blob: d7c6c7977103eb11ca539f9ea7522967af9f5b6b [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);
Matthijs Kooijman214142c2008-05-23 16:17:48 +00001099 if (!LU)
1100 continue;
1101 unsigned Opcode = getOpcode(LU);
Dan Gohmaneee962e2008-04-10 18:43:06 +00001102 // Check for operations that have the property that if
1103 // both their operands have low zero bits, the result
1104 // will have low zero bits.
1105 if (Opcode == Instruction::Add ||
1106 Opcode == Instruction::Sub ||
1107 Opcode == Instruction::And ||
1108 Opcode == Instruction::Or ||
1109 Opcode == Instruction::Mul) {
1110 Value *LL = LU->getOperand(0);
1111 Value *LR = LU->getOperand(1);
1112 // Find a recurrence.
1113 if (LL == I)
1114 L = LR;
1115 else if (LR == I)
1116 L = LL;
1117 else
1118 break;
1119 // Ok, we have a PHI of the form L op= R. Check for low
1120 // zero bits.
1121 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1122 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1123 Mask2 = APInt::getLowBitsSet(BitWidth,
1124 KnownZero2.countTrailingOnes());
1125 KnownOne2.clear();
1126 KnownZero2.clear();
1127 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1128 KnownZero = Mask &
1129 APInt::getLowBitsSet(BitWidth,
1130 KnownZero2.countTrailingOnes());
1131 break;
1132 }
1133 }
1134 }
1135 break;
1136 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001137 case Instruction::Call:
1138 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1139 switch (II->getIntrinsicID()) {
1140 default: break;
1141 case Intrinsic::ctpop:
1142 case Intrinsic::ctlz:
1143 case Intrinsic::cttz: {
1144 unsigned LowBits = Log2_32(BitWidth)+1;
1145 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1146 break;
1147 }
1148 }
1149 }
1150 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +00001151 }
1152}
1153
Reid Spencere7816b52007-03-08 01:52:58 +00001154/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1155/// this predicate to simplify operations downstream. Mask is known to be zero
1156/// for bits that V cannot have.
Dan Gohmaneee962e2008-04-10 18:43:06 +00001157bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1158 unsigned Depth) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001159 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001160 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1161 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1162 return (KnownZero & Mask) == Mask;
1163}
1164
Chris Lattner255d8912006-02-11 09:31:47 +00001165/// ShrinkDemandedConstant - Check to see if the specified operand of the
1166/// specified instruction is a constant integer. If so, check to see if there
1167/// are any bits set in the constant that are not demanded. If so, shrink the
1168/// constant and return true.
1169static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001170 APInt Demanded) {
1171 assert(I && "No instruction?");
1172 assert(OpNo < I->getNumOperands() && "Operand index too large");
1173
1174 // If the operand is not a constant integer, nothing to do.
1175 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1176 if (!OpC) return false;
1177
1178 // If there are no bits set that aren't demanded, nothing to do.
1179 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1180 if ((~Demanded & OpC->getValue()) == 0)
1181 return false;
1182
1183 // This instruction is producing bits that are not demanded. Shrink the RHS.
1184 Demanded &= OpC->getValue();
1185 I->setOperand(OpNo, ConstantInt::get(Demanded));
1186 return true;
1187}
1188
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001189// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1190// set of known zero and one bits, compute the maximum and minimum values that
1191// could have the specified known zero and known one bits, returning them in
1192// min/max.
1193static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +00001194 const APInt& KnownZero,
1195 const APInt& KnownOne,
1196 APInt& Min, APInt& Max) {
1197 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1198 assert(KnownZero.getBitWidth() == BitWidth &&
1199 KnownOne.getBitWidth() == BitWidth &&
1200 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1201 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001202 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001203
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001204 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1205 // bit if it is unknown.
1206 Min = KnownOne;
1207 Max = KnownOne|UnknownBits;
1208
Zhou Sheng4acf1552007-03-28 05:15:57 +00001209 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001210 Min.set(BitWidth-1);
1211 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001212 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001213}
1214
1215// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1216// a set of known zero and one bits, compute the maximum and minimum values that
1217// could have the specified known zero and known one bits, returning them in
1218// min/max.
1219static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001220 const APInt &KnownZero,
1221 const APInt &KnownOne,
1222 APInt &Min, APInt &Max) {
1223 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +00001224 assert(KnownZero.getBitWidth() == BitWidth &&
1225 KnownOne.getBitWidth() == BitWidth &&
1226 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1227 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001228 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001229
1230 // The minimum value is when the unknown bits are all zeros.
1231 Min = KnownOne;
1232 // The maximum value is when the unknown bits are all ones.
1233 Max = KnownOne|UnknownBits;
1234}
Chris Lattner255d8912006-02-11 09:31:47 +00001235
Reid Spencer8cb68342007-03-12 17:25:59 +00001236/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1237/// value based on the demanded bits. When this function is called, it is known
1238/// that only the bits set in DemandedMask of the result of V are ever used
1239/// downstream. Consequently, depending on the mask and V, it may be possible
1240/// to replace V with a constant or one of its operands. In such cases, this
1241/// function does the replacement and returns true. In all other cases, it
1242/// returns false after analyzing the expression and setting KnownOne and known
1243/// to be one in the expression. KnownZero contains all the bits that are known
1244/// to be zero in the expression. These are provided to potentially allow the
1245/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1246/// the expression. KnownOne and KnownZero always follow the invariant that
1247/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1248/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1249/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1250/// and KnownOne must all be the same.
1251bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1252 APInt& KnownZero, APInt& KnownOne,
1253 unsigned Depth) {
1254 assert(V != 0 && "Null pointer of Value???");
1255 assert(Depth <= 6 && "Limit Search Depth");
1256 uint32_t BitWidth = DemandedMask.getBitWidth();
1257 const IntegerType *VTy = cast<IntegerType>(V->getType());
1258 assert(VTy->getBitWidth() == BitWidth &&
1259 KnownZero.getBitWidth() == BitWidth &&
1260 KnownOne.getBitWidth() == BitWidth &&
1261 "Value *V, DemandedMask, KnownZero and KnownOne \
1262 must have same BitWidth");
1263 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1264 // We know all of the bits for a constant!
1265 KnownOne = CI->getValue() & DemandedMask;
1266 KnownZero = ~KnownOne & DemandedMask;
1267 return false;
1268 }
1269
Zhou Sheng96704452007-03-14 03:21:24 +00001270 KnownZero.clear();
1271 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001272 if (!V->hasOneUse()) { // Other users may use these bits.
1273 if (Depth != 0) { // Not at the root.
1274 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1275 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1276 return false;
1277 }
1278 // If this is the root being simplified, allow it to have multiple uses,
1279 // just set the DemandedMask to all bits.
1280 DemandedMask = APInt::getAllOnesValue(BitWidth);
1281 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1282 if (V != UndefValue::get(VTy))
1283 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1284 return false;
1285 } else if (Depth == 6) { // Limit search depth.
1286 return false;
1287 }
1288
1289 Instruction *I = dyn_cast<Instruction>(V);
1290 if (!I) return false; // Only analyze instructions.
1291
Reid Spencer8cb68342007-03-12 17:25:59 +00001292 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1293 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1294 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001295 default:
1296 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1297 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001298 case Instruction::And:
1299 // If either the LHS or the RHS are Zero, the result is zero.
1300 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1301 RHSKnownZero, RHSKnownOne, Depth+1))
1302 return true;
1303 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1304 "Bits known to be one AND zero?");
1305
1306 // If something is known zero on the RHS, the bits aren't demanded on the
1307 // LHS.
1308 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1309 LHSKnownZero, LHSKnownOne, Depth+1))
1310 return true;
1311 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1312 "Bits known to be one AND zero?");
1313
1314 // If all of the demanded bits are known 1 on one side, return the other.
1315 // These bits cannot contribute to the result of the 'and'.
1316 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1317 (DemandedMask & ~LHSKnownZero))
1318 return UpdateValueUsesWith(I, I->getOperand(0));
1319 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1320 (DemandedMask & ~RHSKnownZero))
1321 return UpdateValueUsesWith(I, I->getOperand(1));
1322
1323 // If all of the demanded bits in the inputs are known zeros, return zero.
1324 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1325 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1326
1327 // If the RHS is a constant, see if we can simplify it.
1328 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1329 return UpdateValueUsesWith(I, I);
1330
1331 // Output known-1 bits are only known if set in both the LHS & RHS.
1332 RHSKnownOne &= LHSKnownOne;
1333 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1334 RHSKnownZero |= LHSKnownZero;
1335 break;
1336 case Instruction::Or:
1337 // If either the LHS or the RHS are One, the result is One.
1338 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1339 RHSKnownZero, RHSKnownOne, Depth+1))
1340 return true;
1341 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1342 "Bits known to be one AND zero?");
1343 // If something is known one on the RHS, the bits aren't demanded on the
1344 // LHS.
1345 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1346 LHSKnownZero, LHSKnownOne, Depth+1))
1347 return true;
1348 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1349 "Bits known to be one AND zero?");
1350
1351 // If all of the demanded bits are known zero on one side, return the other.
1352 // These bits cannot contribute to the result of the 'or'.
1353 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1354 (DemandedMask & ~LHSKnownOne))
1355 return UpdateValueUsesWith(I, I->getOperand(0));
1356 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1357 (DemandedMask & ~RHSKnownOne))
1358 return UpdateValueUsesWith(I, I->getOperand(1));
1359
1360 // If all of the potentially set bits on one side are known to be set on
1361 // the other side, just use the 'other' side.
1362 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1363 (DemandedMask & (~RHSKnownZero)))
1364 return UpdateValueUsesWith(I, I->getOperand(0));
1365 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1366 (DemandedMask & (~LHSKnownZero)))
1367 return UpdateValueUsesWith(I, I->getOperand(1));
1368
1369 // If the RHS is a constant, see if we can simplify it.
1370 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1371 return UpdateValueUsesWith(I, I);
1372
1373 // Output known-0 bits are only known if clear in both the LHS & RHS.
1374 RHSKnownZero &= LHSKnownZero;
1375 // Output known-1 are known to be set if set in either the LHS | RHS.
1376 RHSKnownOne |= LHSKnownOne;
1377 break;
1378 case Instruction::Xor: {
1379 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1380 RHSKnownZero, RHSKnownOne, Depth+1))
1381 return true;
1382 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1383 "Bits known to be one AND zero?");
1384 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1385 LHSKnownZero, LHSKnownOne, Depth+1))
1386 return true;
1387 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1388 "Bits known to be one AND zero?");
1389
1390 // If all of the demanded bits are known zero on one side, return the other.
1391 // These bits cannot contribute to the result of the 'xor'.
1392 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1393 return UpdateValueUsesWith(I, I->getOperand(0));
1394 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1395 return UpdateValueUsesWith(I, I->getOperand(1));
1396
1397 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1398 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1399 (RHSKnownOne & LHSKnownOne);
1400 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1401 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1402 (RHSKnownOne & LHSKnownZero);
1403
1404 // If all of the demanded bits are known to be zero on one side or the
1405 // other, turn this into an *inclusive* or.
1406 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1407 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1408 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001409 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001410 I->getName());
1411 InsertNewInstBefore(Or, *I);
1412 return UpdateValueUsesWith(I, Or);
1413 }
1414
1415 // If all of the demanded bits on one side are known, and all of the set
1416 // bits on that side are also known to be set on the other side, turn this
1417 // into an AND, as we know the bits will be cleared.
1418 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1419 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1420 // all known
1421 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1422 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1423 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001424 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +00001425 InsertNewInstBefore(And, *I);
1426 return UpdateValueUsesWith(I, And);
1427 }
1428 }
1429
1430 // If the RHS is a constant, see if we can simplify it.
1431 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1432 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1433 return UpdateValueUsesWith(I, I);
1434
1435 RHSKnownZero = KnownZeroOut;
1436 RHSKnownOne = KnownOneOut;
1437 break;
1438 }
1439 case Instruction::Select:
1440 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1441 RHSKnownZero, RHSKnownOne, Depth+1))
1442 return true;
1443 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1444 LHSKnownZero, LHSKnownOne, Depth+1))
1445 return true;
1446 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1447 "Bits known to be one AND zero?");
1448 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1449 "Bits known to be one AND zero?");
1450
1451 // If the operands are constants, see if we can simplify them.
1452 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1453 return UpdateValueUsesWith(I, I);
1454 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1455 return UpdateValueUsesWith(I, I);
1456
1457 // Only known if known in both the LHS and RHS.
1458 RHSKnownOne &= LHSKnownOne;
1459 RHSKnownZero &= LHSKnownZero;
1460 break;
1461 case Instruction::Trunc: {
1462 uint32_t truncBf =
1463 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001464 DemandedMask.zext(truncBf);
1465 RHSKnownZero.zext(truncBf);
1466 RHSKnownOne.zext(truncBf);
1467 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1468 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001469 return true;
1470 DemandedMask.trunc(BitWidth);
1471 RHSKnownZero.trunc(BitWidth);
1472 RHSKnownOne.trunc(BitWidth);
1473 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1474 "Bits known to be one AND zero?");
1475 break;
1476 }
1477 case Instruction::BitCast:
1478 if (!I->getOperand(0)->getType()->isInteger())
1479 return false;
1480
1481 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1482 RHSKnownZero, RHSKnownOne, Depth+1))
1483 return true;
1484 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1485 "Bits known to be one AND zero?");
1486 break;
1487 case Instruction::ZExt: {
1488 // Compute the bits in the result that are not present in the input.
1489 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001490 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001491
Zhou Shengd48653a2007-03-29 04:45:55 +00001492 DemandedMask.trunc(SrcBitWidth);
1493 RHSKnownZero.trunc(SrcBitWidth);
1494 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001495 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1496 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001497 return true;
1498 DemandedMask.zext(BitWidth);
1499 RHSKnownZero.zext(BitWidth);
1500 RHSKnownOne.zext(BitWidth);
1501 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1502 "Bits known to be one AND zero?");
1503 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001504 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001505 break;
1506 }
1507 case Instruction::SExt: {
1508 // Compute the bits in the result that are not present in the input.
1509 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001510 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001511
Reid Spencer8cb68342007-03-12 17:25:59 +00001512 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001513 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001514
Zhou Sheng01542f32007-03-29 02:26:30 +00001515 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001516 // If any of the sign extended bits are demanded, we know that the sign
1517 // bit is demanded.
1518 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001519 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001520
Zhou Shengd48653a2007-03-29 04:45:55 +00001521 InputDemandedBits.trunc(SrcBitWidth);
1522 RHSKnownZero.trunc(SrcBitWidth);
1523 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001524 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1525 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001526 return true;
1527 InputDemandedBits.zext(BitWidth);
1528 RHSKnownZero.zext(BitWidth);
1529 RHSKnownOne.zext(BitWidth);
1530 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1531 "Bits known to be one AND zero?");
1532
1533 // If the sign bit of the input is known set or clear, then we know the
1534 // top bits of the result.
1535
1536 // If the input sign bit is known zero, or if the NewBits are not demanded
1537 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001538 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001539 {
1540 // Convert to ZExt cast
1541 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1542 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001543 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001544 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001545 }
1546 break;
1547 }
1548 case Instruction::Add: {
1549 // Figure out what the input bits are. If the top bits of the and result
1550 // are not demanded, then the add doesn't demand them from its input
1551 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001552 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001553
1554 // If there is a constant on the RHS, there are a variety of xformations
1555 // we can do.
1556 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1557 // If null, this should be simplified elsewhere. Some of the xforms here
1558 // won't work if the RHS is zero.
1559 if (RHS->isZero())
1560 break;
1561
1562 // If the top bit of the output is demanded, demand everything from the
1563 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001564 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001565
1566 // Find information about known zero/one bits in the input.
1567 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1568 LHSKnownZero, LHSKnownOne, Depth+1))
1569 return true;
1570
1571 // If the RHS of the add has bits set that can't affect the input, reduce
1572 // the constant.
1573 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1574 return UpdateValueUsesWith(I, I);
1575
1576 // Avoid excess work.
1577 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1578 break;
1579
1580 // Turn it into OR if input bits are zero.
1581 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1582 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001583 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001584 I->getName());
1585 InsertNewInstBefore(Or, *I);
1586 return UpdateValueUsesWith(I, Or);
1587 }
1588
1589 // We can say something about the output known-zero and known-one bits,
1590 // depending on potential carries from the input constant and the
1591 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1592 // bits set and the RHS constant is 0x01001, then we know we have a known
1593 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1594
1595 // To compute this, we first compute the potential carry bits. These are
1596 // the bits which may be modified. I'm not aware of a better way to do
1597 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001598 const APInt& RHSVal = RHS->getValue();
1599 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001600
1601 // Now that we know which bits have carries, compute the known-1/0 sets.
1602
1603 // Bits are known one if they are known zero in one operand and one in the
1604 // other, and there is no input carry.
1605 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1606 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1607
1608 // Bits are known zero if they are known zero in both operands and there
1609 // is no input carry.
1610 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1611 } else {
1612 // If the high-bits of this ADD are not demanded, then it does not demand
1613 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001614 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001615 // Right fill the mask of bits for this ADD to demand the most
1616 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001617 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001618 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1619 LHSKnownZero, LHSKnownOne, Depth+1))
1620 return true;
1621 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1622 LHSKnownZero, LHSKnownOne, Depth+1))
1623 return true;
1624 }
1625 }
1626 break;
1627 }
1628 case Instruction::Sub:
1629 // If the high-bits of this SUB are not demanded, then it does not demand
1630 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001631 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001632 // Right fill the mask of bits for this SUB to demand the most
1633 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001634 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001635 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001636 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1637 LHSKnownZero, LHSKnownOne, Depth+1))
1638 return true;
1639 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1640 LHSKnownZero, LHSKnownOne, Depth+1))
1641 return true;
1642 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001643 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1644 // the known zeros and ones.
1645 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001646 break;
1647 case Instruction::Shl:
1648 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001649 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001650 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1651 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001652 RHSKnownZero, RHSKnownOne, Depth+1))
1653 return true;
1654 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1655 "Bits known to be one AND zero?");
1656 RHSKnownZero <<= ShiftAmt;
1657 RHSKnownOne <<= ShiftAmt;
1658 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001659 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001660 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001661 }
1662 break;
1663 case Instruction::LShr:
1664 // For a logical shift right
1665 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001666 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001667
Reid Spencer8cb68342007-03-12 17:25:59 +00001668 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001669 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1670 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001671 RHSKnownZero, RHSKnownOne, Depth+1))
1672 return true;
1673 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1674 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001675 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1676 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001677 if (ShiftAmt) {
1678 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001679 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001680 RHSKnownZero |= HighBits; // high bits known zero.
1681 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001682 }
1683 break;
1684 case Instruction::AShr:
1685 // If this is an arithmetic shift right and only the low-bit is set, we can
1686 // always convert this into a logical shr, even if the shift amount is
1687 // variable. The low bit of the shift cannot be an input sign bit unless
1688 // the shift amount is >= the size of the datatype, which is undefined.
1689 if (DemandedMask == 1) {
1690 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001691 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001692 I->getOperand(0), I->getOperand(1), I->getName());
1693 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1694 return UpdateValueUsesWith(I, NewVal);
1695 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001696
1697 // If the sign bit is the only bit demanded by this ashr, then there is no
1698 // need to do it, the shift doesn't change the high bit.
1699 if (DemandedMask.isSignBit())
1700 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001701
1702 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001703 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001704
Reid Spencer8cb68342007-03-12 17:25:59 +00001705 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001706 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001707 // If any of the "high bits" are demanded, we should set the sign bit as
1708 // demanded.
1709 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1710 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001711 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001712 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001713 RHSKnownZero, RHSKnownOne, Depth+1))
1714 return true;
1715 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1716 "Bits known to be one AND zero?");
1717 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001718 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001719 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1720 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1721
1722 // Handle the sign bits.
1723 APInt SignBit(APInt::getSignBit(BitWidth));
1724 // Adjust to where it is now in the mask.
1725 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1726
1727 // If the input sign bit is known to be zero, or if none of the top bits
1728 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001729 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001730 (HighBits & ~DemandedMask) == HighBits) {
1731 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001732 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001733 I->getOperand(0), SA, I->getName());
1734 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1735 return UpdateValueUsesWith(I, NewVal);
1736 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1737 RHSKnownOne |= HighBits;
1738 }
1739 }
1740 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001741 case Instruction::SRem:
1742 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1743 APInt RA = Rem->getValue();
1744 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001745 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001746 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1747 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1748 LHSKnownZero, LHSKnownOne, Depth+1))
1749 return true;
1750
1751 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1752 LHSKnownZero |= ~LowBits;
1753 else if (LHSKnownOne[BitWidth-1])
1754 LHSKnownOne |= ~LowBits;
1755
1756 KnownZero |= LHSKnownZero & DemandedMask;
1757 KnownOne |= LHSKnownOne & DemandedMask;
1758
1759 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1760 }
1761 }
1762 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001763 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001764 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1765 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001766 if (RA.isPowerOf2()) {
1767 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001768 APInt Mask2 = LowBits & DemandedMask;
1769 KnownZero |= ~LowBits & DemandedMask;
1770 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1771 KnownZero, KnownOne, Depth+1))
1772 return true;
1773
1774 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001775 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001776 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001777 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001778
1779 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1780 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001781 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1782 KnownZero2, KnownOne2, Depth+1))
1783 return true;
1784
Dan Gohman23e8b712008-04-28 17:02:21 +00001785 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001786 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001787 KnownZero2, KnownOne2, Depth+1))
1788 return true;
1789
1790 Leaders = std::max(Leaders,
1791 KnownZero2.countLeadingOnes());
1792 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001793 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001794 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001795 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001796
1797 // If the client is only demanding bits that we know, return the known
1798 // constant.
1799 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1800 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1801 return false;
1802}
1803
Chris Lattner867b99f2006-10-05 06:55:50 +00001804
1805/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1806/// 64 or fewer elements. DemandedElts contains the set of elements that are
1807/// actually used by the caller. This method analyzes which elements of the
1808/// operand are undef and returns that information in UndefElts.
1809///
1810/// If the information about demanded elements can be used to simplify the
1811/// operation, the operation is simplified, then the resultant value is
1812/// returned. This returns null if no change was made.
1813Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1814 uint64_t &UndefElts,
1815 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001816 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001817 assert(VWidth <= 64 && "Vector too wide to analyze!");
1818 uint64_t EltMask = ~0ULL >> (64-VWidth);
1819 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1820 "Invalid DemandedElts!");
1821
1822 if (isa<UndefValue>(V)) {
1823 // If the entire vector is undefined, just return this info.
1824 UndefElts = EltMask;
1825 return 0;
1826 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1827 UndefElts = EltMask;
1828 return UndefValue::get(V->getType());
1829 }
1830
1831 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001832 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1833 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001834 Constant *Undef = UndefValue::get(EltTy);
1835
1836 std::vector<Constant*> Elts;
1837 for (unsigned i = 0; i != VWidth; ++i)
1838 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1839 Elts.push_back(Undef);
1840 UndefElts |= (1ULL << i);
1841 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1842 Elts.push_back(Undef);
1843 UndefElts |= (1ULL << i);
1844 } else { // Otherwise, defined.
1845 Elts.push_back(CP->getOperand(i));
1846 }
1847
1848 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001849 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001850 return NewCP != CP ? NewCP : 0;
1851 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001852 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001853 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001854 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001855 Constant *Zero = Constant::getNullValue(EltTy);
1856 Constant *Undef = UndefValue::get(EltTy);
1857 std::vector<Constant*> Elts;
1858 for (unsigned i = 0; i != VWidth; ++i)
1859 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1860 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001861 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001862 }
1863
1864 if (!V->hasOneUse()) { // Other users may use these bits.
1865 if (Depth != 0) { // Not at the root.
1866 // TODO: Just compute the UndefElts information recursively.
1867 return false;
1868 }
1869 return false;
1870 } else if (Depth == 10) { // Limit search depth.
1871 return false;
1872 }
1873
1874 Instruction *I = dyn_cast<Instruction>(V);
1875 if (!I) return false; // Only analyze instructions.
1876
1877 bool MadeChange = false;
1878 uint64_t UndefElts2;
1879 Value *TmpV;
1880 switch (I->getOpcode()) {
1881 default: break;
1882
1883 case Instruction::InsertElement: {
1884 // If this is a variable index, we don't know which element it overwrites.
1885 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001886 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001887 if (Idx == 0) {
1888 // Note that we can't propagate undef elt info, because we don't know
1889 // which elt is getting updated.
1890 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1891 UndefElts2, Depth+1);
1892 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1893 break;
1894 }
1895
1896 // If this is inserting an element that isn't demanded, remove this
1897 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001898 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001899 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1900 return AddSoonDeadInstToWorklist(*I, 0);
1901
1902 // Otherwise, the element inserted overwrites whatever was there, so the
1903 // input demanded set is simpler than the output set.
1904 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1905 DemandedElts & ~(1ULL << IdxNo),
1906 UndefElts, Depth+1);
1907 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1908
1909 // The inserted element is defined.
1910 UndefElts |= 1ULL << IdxNo;
1911 break;
1912 }
Chris Lattner69878332007-04-14 22:29:23 +00001913 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001914 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001915 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1916 if (!VTy) break;
1917 unsigned InVWidth = VTy->getNumElements();
1918 uint64_t InputDemandedElts = 0;
1919 unsigned Ratio;
1920
1921 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001922 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001923 // elements as are demanded of us.
1924 Ratio = 1;
1925 InputDemandedElts = DemandedElts;
1926 } else if (VWidth > InVWidth) {
1927 // Untested so far.
1928 break;
1929
1930 // If there are more elements in the result than there are in the source,
1931 // then an input element is live if any of the corresponding output
1932 // elements are live.
1933 Ratio = VWidth/InVWidth;
1934 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1935 if (DemandedElts & (1ULL << OutIdx))
1936 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1937 }
1938 } else {
1939 // Untested so far.
1940 break;
1941
1942 // If there are more elements in the source than there are in the result,
1943 // then an input element is live if the corresponding output element is
1944 // live.
1945 Ratio = InVWidth/VWidth;
1946 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1947 if (DemandedElts & (1ULL << InIdx/Ratio))
1948 InputDemandedElts |= 1ULL << InIdx;
1949 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001950
Chris Lattner69878332007-04-14 22:29:23 +00001951 // div/rem demand all inputs, because they don't want divide by zero.
1952 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1953 UndefElts2, Depth+1);
1954 if (TmpV) {
1955 I->setOperand(0, TmpV);
1956 MadeChange = true;
1957 }
1958
1959 UndefElts = UndefElts2;
1960 if (VWidth > InVWidth) {
1961 assert(0 && "Unimp");
1962 // If there are more elements in the result than there are in the source,
1963 // then an output element is undef if the corresponding input element is
1964 // undef.
1965 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1966 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1967 UndefElts |= 1ULL << OutIdx;
1968 } else if (VWidth < InVWidth) {
1969 assert(0 && "Unimp");
1970 // If there are more elements in the source than there are in the result,
1971 // then a result element is undef if all of the corresponding input
1972 // elements are undef.
1973 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1974 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1975 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1976 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1977 }
1978 break;
1979 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001980 case Instruction::And:
1981 case Instruction::Or:
1982 case Instruction::Xor:
1983 case Instruction::Add:
1984 case Instruction::Sub:
1985 case Instruction::Mul:
1986 // div/rem demand all inputs, because they don't want divide by zero.
1987 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1988 UndefElts, Depth+1);
1989 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1990 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1991 UndefElts2, Depth+1);
1992 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1993
1994 // Output elements are undefined if both are undefined. Consider things
1995 // like undef&0. The result is known zero, not undef.
1996 UndefElts &= UndefElts2;
1997 break;
1998
1999 case Instruction::Call: {
2000 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2001 if (!II) break;
2002 switch (II->getIntrinsicID()) {
2003 default: break;
2004
2005 // Binary vector operations that work column-wise. A dest element is a
2006 // function of the corresponding input elements from the two inputs.
2007 case Intrinsic::x86_sse_sub_ss:
2008 case Intrinsic::x86_sse_mul_ss:
2009 case Intrinsic::x86_sse_min_ss:
2010 case Intrinsic::x86_sse_max_ss:
2011 case Intrinsic::x86_sse2_sub_sd:
2012 case Intrinsic::x86_sse2_mul_sd:
2013 case Intrinsic::x86_sse2_min_sd:
2014 case Intrinsic::x86_sse2_max_sd:
2015 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2016 UndefElts, Depth+1);
2017 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2018 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2019 UndefElts2, Depth+1);
2020 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2021
2022 // If only the low elt is demanded and this is a scalarizable intrinsic,
2023 // scalarize it now.
2024 if (DemandedElts == 1) {
2025 switch (II->getIntrinsicID()) {
2026 default: break;
2027 case Intrinsic::x86_sse_sub_ss:
2028 case Intrinsic::x86_sse_mul_ss:
2029 case Intrinsic::x86_sse2_sub_sd:
2030 case Intrinsic::x86_sse2_mul_sd:
2031 // TODO: Lower MIN/MAX/ABS/etc
2032 Value *LHS = II->getOperand(1);
2033 Value *RHS = II->getOperand(2);
2034 // Extract the element as scalars.
2035 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2036 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2037
2038 switch (II->getIntrinsicID()) {
2039 default: assert(0 && "Case stmts out of sync!");
2040 case Intrinsic::x86_sse_sub_ss:
2041 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002042 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002043 II->getName()), *II);
2044 break;
2045 case Intrinsic::x86_sse_mul_ss:
2046 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002047 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002048 II->getName()), *II);
2049 break;
2050 }
2051
2052 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00002053 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2054 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00002055 InsertNewInstBefore(New, *II);
2056 AddSoonDeadInstToWorklist(*II, 0);
2057 return New;
2058 }
2059 }
2060
2061 // Output elements are undefined if both are undefined. Consider things
2062 // like undef&0. The result is known zero, not undef.
2063 UndefElts &= UndefElts2;
2064 break;
2065 }
2066 break;
2067 }
2068 }
2069 return MadeChange ? I : 0;
2070}
2071
Dan Gohman45b4e482008-05-19 22:14:15 +00002072/// ComputeNumSignBits - Return the number of times the sign bit of the
2073/// register is replicated into the other bits. We know that at least 1 bit
2074/// is always equal to the sign bit (itself), but other cases can give us
2075/// information. For example, immediately after an "ashr X, 2", we know that
2076/// the top 3 bits are all equal to each other, so we return 3.
2077///
2078unsigned InstCombiner::ComputeNumSignBits(Value *V, unsigned Depth) const{
2079 const IntegerType *Ty = cast<IntegerType>(V->getType());
2080 unsigned TyBits = Ty->getBitWidth();
2081 unsigned Tmp, Tmp2;
Dan Gohmana332f172008-05-23 02:28:01 +00002082 unsigned FirstAnswer = 1;
Dan Gohman45b4e482008-05-19 22:14:15 +00002083
2084 if (Depth == 6)
2085 return 1; // Limit search depth.
2086
2087 User *U = dyn_cast<User>(V);
2088 switch (getOpcode(V)) {
2089 default: break;
2090 case Instruction::SExt:
2091 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
2092 return ComputeNumSignBits(U->getOperand(0), Depth+1) + Tmp;
2093
2094 case Instruction::AShr:
2095 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
Dan Gohmanf35c8822008-05-20 21:01:12 +00002096 // ashr X, C -> adds C sign bits.
Dan Gohman45b4e482008-05-19 22:14:15 +00002097 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2098 Tmp += C->getZExtValue();
2099 if (Tmp > TyBits) Tmp = TyBits;
2100 }
2101 return Tmp;
2102 case Instruction::Shl:
2103 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2104 // shl destroys sign bits.
2105 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2106 if (C->getZExtValue() >= TyBits || // Bad shift.
2107 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2108 return Tmp - C->getZExtValue();
2109 }
2110 break;
2111 case Instruction::And:
2112 case Instruction::Or:
Dan Gohmana332f172008-05-23 02:28:01 +00002113 case Instruction::Xor: // NOT is handled here.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002114 // Logical binary ops preserve the number of sign bits at the worst.
2115 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2116 if (Tmp != 1) {
2117 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
Dan Gohmana332f172008-05-23 02:28:01 +00002118 FirstAnswer = std::min(Tmp, Tmp2);
2119 // We computed what we know about the sign bits as our first
2120 // answer. Now proceed to the generic code that uses
2121 // ComputeMaskedBits, and pick whichever answer is better.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002122 }
Dan Gohmana332f172008-05-23 02:28:01 +00002123 break;
Dan Gohman45b4e482008-05-19 22:14:15 +00002124
2125 case Instruction::Select:
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002126 Tmp = ComputeNumSignBits(U->getOperand(1), Depth+1);
Dan Gohman45b4e482008-05-19 22:14:15 +00002127 if (Tmp == 1) return 1; // Early out.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002128 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth+1);
Dan Gohman45b4e482008-05-19 22:14:15 +00002129 return std::min(Tmp, Tmp2);
2130
2131 case Instruction::Add:
2132 // Add can have at most one carry bit. Thus we know that the output
2133 // is, at worst, one more bit than the inputs.
2134 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2135 if (Tmp == 1) return 1; // Early out.
2136
2137 // Special case decrementing a value (ADD X, -1):
2138 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2139 if (CRHS->isAllOnesValue()) {
2140 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2141 APInt Mask = APInt::getAllOnesValue(TyBits);
2142 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2143
2144 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2145 // sign bits set.
2146 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2147 return TyBits;
2148
2149 // If we are subtracting one from a positive number, there is no carry
2150 // out of the result.
2151 if (KnownZero.isNegative())
2152 return Tmp;
2153 }
2154
2155 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2156 if (Tmp2 == 1) return 1;
2157 return std::min(Tmp, Tmp2)-1;
2158 break;
2159
2160 case Instruction::Sub:
2161 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2162 if (Tmp2 == 1) return 1;
2163
2164 // Handle NEG.
2165 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2166 if (CLHS->isNullValue()) {
2167 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2168 APInt Mask = APInt::getAllOnesValue(TyBits);
2169 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2170 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2171 // sign bits set.
2172 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2173 return TyBits;
2174
2175 // If the input is known to be positive (the sign bit is known clear),
2176 // the output of the NEG has the same number of sign bits as the input.
2177 if (KnownZero.isNegative())
2178 return Tmp2;
2179
2180 // Otherwise, we treat this like a SUB.
2181 }
2182
2183 // Sub can have at most one carry bit. Thus we know that the output
2184 // is, at worst, one more bit than the inputs.
2185 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2186 if (Tmp == 1) return 1; // Early out.
2187 return std::min(Tmp, Tmp2)-1;
2188 break;
2189 case Instruction::Trunc:
2190 // FIXME: it's tricky to do anything useful for this, but it is an important
2191 // case for targets like X86.
2192 break;
2193 }
2194
2195 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2196 // use this information.
2197 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2198 APInt Mask = APInt::getAllOnesValue(TyBits);
2199 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
2200
2201 if (KnownZero.isNegative()) { // sign bit is 0
2202 Mask = KnownZero;
2203 } else if (KnownOne.isNegative()) { // sign bit is 1;
2204 Mask = KnownOne;
2205 } else {
2206 // Nothing known.
Dan Gohmana332f172008-05-23 02:28:01 +00002207 return FirstAnswer;
Dan Gohman45b4e482008-05-19 22:14:15 +00002208 }
2209
2210 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2211 // the number of identical bits in the top of the input value.
2212 Mask = ~Mask;
2213 Mask <<= Mask.getBitWidth()-TyBits;
2214 // Return # leading zeros. We use 'min' here in case Val was zero before
2215 // shifting. We don't want to return '64' as for an i32 "0".
Dan Gohmana332f172008-05-23 02:28:01 +00002216 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
Dan Gohman45b4e482008-05-19 22:14:15 +00002217}
2218
2219
Chris Lattner564a7272003-08-13 19:01:45 +00002220/// AssociativeOpt - Perform an optimization on an associative operator. This
2221/// function is designed to check a chain of associative operators for a
2222/// potential to apply a certain optimization. Since the optimization may be
2223/// applicable if the expression was reassociated, this checks the chain, then
2224/// reassociates the expression as necessary to expose the optimization
2225/// opportunity. This makes use of a special Functor, which must define
2226/// 'shouldApply' and 'apply' methods.
2227///
2228template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00002229static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00002230 unsigned Opcode = Root.getOpcode();
2231 Value *LHS = Root.getOperand(0);
2232
2233 // Quick check, see if the immediate LHS matches...
2234 if (F.shouldApply(LHS))
2235 return F.apply(Root);
2236
2237 // Otherwise, if the LHS is not of the same opcode as the root, return.
2238 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002239 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002240 // Should we apply this transform to the RHS?
2241 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2242
2243 // If not to the RHS, check to see if we should apply to the LHS...
2244 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2245 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2246 ShouldApply = true;
2247 }
2248
2249 // If the functor wants to apply the optimization to the RHS of LHSI,
2250 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2251 if (ShouldApply) {
2252 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002253
Chris Lattner564a7272003-08-13 19:01:45 +00002254 // Now all of the instructions are in the current basic block, go ahead
2255 // and perform the reassociation.
2256 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2257
2258 // First move the selected RHS to the LHS of the root...
2259 Root.setOperand(0, LHSI->getOperand(1));
2260
2261 // Make what used to be the LHS of the root be the user of the root...
2262 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002263 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002264 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2265 return 0;
2266 }
Chris Lattner65725312004-04-16 18:08:07 +00002267 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002268 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002269 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2270 BasicBlock::iterator ARI = &Root; ++ARI;
2271 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2272 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002273
2274 // Now propagate the ExtraOperand down the chain of instructions until we
2275 // get to LHSI.
2276 while (TmpLHSI != LHSI) {
2277 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002278 // Move the instruction to immediately before the chain we are
2279 // constructing to avoid breaking dominance properties.
2280 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2281 BB->getInstList().insert(ARI, NextLHSI);
2282 ARI = NextLHSI;
2283
Chris Lattner564a7272003-08-13 19:01:45 +00002284 Value *NextOp = NextLHSI->getOperand(1);
2285 NextLHSI->setOperand(1, ExtraOperand);
2286 TmpLHSI = NextLHSI;
2287 ExtraOperand = NextOp;
2288 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002289
Chris Lattner564a7272003-08-13 19:01:45 +00002290 // Now that the instructions are reassociated, have the functor perform
2291 // the transformation...
2292 return F.apply(Root);
2293 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002294
Chris Lattner564a7272003-08-13 19:01:45 +00002295 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2296 }
2297 return 0;
2298}
2299
Dan Gohman844731a2008-05-13 00:00:25 +00002300namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002301
Nick Lewycky02d639f2008-05-23 04:34:58 +00002302// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00002303struct AddRHS {
2304 Value *RHS;
2305 AddRHS(Value *rhs) : RHS(rhs) {}
2306 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2307 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00002308 return BinaryOperator::CreateShl(Add.getOperand(0),
2309 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002310 }
2311};
2312
2313// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2314// iff C1&C2 == 0
2315struct AddMaskingAnd {
2316 Constant *C2;
2317 AddMaskingAnd(Constant *c) : C2(c) {}
2318 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002319 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002320 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002321 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002322 }
2323 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002324 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002325 }
2326};
2327
Dan Gohman844731a2008-05-13 00:00:25 +00002328}
2329
Chris Lattner6e7ba452005-01-01 16:22:27 +00002330static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002331 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002332 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002333 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002334 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002335
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002336 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00002337 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002338 }
2339
Chris Lattner2eefe512004-04-09 19:05:30 +00002340 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002341 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2342 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002343
Chris Lattner2eefe512004-04-09 19:05:30 +00002344 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2345 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002346 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2347 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002348 }
2349
2350 Value *Op0 = SO, *Op1 = ConstOperand;
2351 if (!ConstIsRHS)
2352 std::swap(Op0, Op1);
2353 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002354 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002355 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002356 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002357 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002358 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002359 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002360 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002361 abort();
2362 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002363 return IC->InsertNewInstBefore(New, I);
2364}
2365
2366// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2367// constant as the other operand, try to fold the binary operator into the
2368// select arguments. This also works for Cast instructions, which obviously do
2369// not have a second operand.
2370static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2371 InstCombiner *IC) {
2372 // Don't modify shared select instructions
2373 if (!SI->hasOneUse()) return 0;
2374 Value *TV = SI->getOperand(1);
2375 Value *FV = SI->getOperand(2);
2376
2377 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002378 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002379 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002380
Chris Lattner6e7ba452005-01-01 16:22:27 +00002381 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2382 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2383
Gabor Greif051a9502008-04-06 20:25:17 +00002384 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2385 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002386 }
2387 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002388}
2389
Chris Lattner4e998b22004-09-29 05:07:12 +00002390
2391/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2392/// node as operand #0, see if we can fold the instruction into the PHI (which
2393/// is only possible if all operands to the PHI are constants).
2394Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2395 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002396 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002397 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002398
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002399 // Check to see if all of the operands of the PHI are constants. If there is
2400 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002401 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002402 BasicBlock *NonConstBB = 0;
2403 for (unsigned i = 0; i != NumPHIValues; ++i)
2404 if (!isa<Constant>(PN->getIncomingValue(i))) {
2405 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002406 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002407 NonConstBB = PN->getIncomingBlock(i);
2408
2409 // If the incoming non-constant value is in I's block, we have an infinite
2410 // loop.
2411 if (NonConstBB == I.getParent())
2412 return 0;
2413 }
2414
2415 // If there is exactly one non-constant value, we can insert a copy of the
2416 // operation in that block. However, if this is a critical edge, we would be
2417 // inserting the computation one some other paths (e.g. inside a loop). Only
2418 // do this if the pred block is unconditionally branching into the phi block.
2419 if (NonConstBB) {
2420 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2421 if (!BI || !BI->isUnconditional()) return 0;
2422 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002423
2424 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002425 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002426 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002427 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002428 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002429
2430 // Next, add all of the operands to the PHI.
2431 if (I.getNumOperands() == 2) {
2432 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002433 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002434 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002435 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002436 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2437 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2438 else
2439 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002440 } else {
2441 assert(PN->getIncomingBlock(i) == NonConstBB);
2442 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002443 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002444 PN->getIncomingValue(i), C, "phitmp",
2445 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002446 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002447 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002448 CI->getPredicate(),
2449 PN->getIncomingValue(i), C, "phitmp",
2450 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002451 else
2452 assert(0 && "Unknown binop!");
2453
Chris Lattnerdbab3862007-03-02 21:28:56 +00002454 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002455 }
2456 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002457 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002458 } else {
2459 CastInst *CI = cast<CastInst>(&I);
2460 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002461 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002462 Value *InV;
2463 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002464 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002465 } else {
2466 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002467 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002468 I.getType(), "phitmp",
2469 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002470 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002471 }
2472 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002473 }
2474 }
2475 return ReplaceInstUsesWith(I, NewPN);
2476}
2477
Chris Lattner2454a2e2008-01-29 06:52:45 +00002478
2479/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2480/// value is never equal to -0.0.
2481///
2482/// Note that this function will need to be revisited when we support nondefault
2483/// rounding modes!
2484///
2485static bool CannotBeNegativeZero(const Value *V) {
2486 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2487 return !CFP->getValueAPF().isNegZero();
2488
Chris Lattner2454a2e2008-01-29 06:52:45 +00002489 if (const Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002490 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Chris Lattner2454a2e2008-01-29 06:52:45 +00002491 if (I->getOpcode() == Instruction::Add &&
2492 isa<ConstantFP>(I->getOperand(1)) &&
2493 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2494 return true;
2495
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002496 // sitofp and uitofp turn into +0.0 for zero.
2497 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2498 return true;
2499
Chris Lattner2454a2e2008-01-29 06:52:45 +00002500 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2501 if (II->getIntrinsicID() == Intrinsic::sqrt)
2502 return CannotBeNegativeZero(II->getOperand(1));
2503
2504 if (const CallInst *CI = dyn_cast<CallInst>(I))
2505 if (const Function *F = CI->getCalledFunction()) {
2506 if (F->isDeclaration()) {
2507 switch (F->getNameLen()) {
2508 case 3: // abs(x) != -0.0
2509 if (!strcmp(F->getNameStart(), "abs")) return true;
2510 break;
2511 case 4: // abs[lf](x) != -0.0
2512 if (!strcmp(F->getNameStart(), "absf")) return true;
2513 if (!strcmp(F->getNameStart(), "absl")) return true;
2514 break;
2515 }
2516 }
2517 }
2518 }
2519
2520 return false;
2521}
2522
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002523/// WillNotOverflowSignedAdd - Return true if we can prove that:
2524/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2525/// This basically requires proving that the add in the original type would not
2526/// overflow to change the sign bit or have a carry out.
2527bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2528 // There are different heuristics we can use for this. Here are some simple
2529 // ones.
2530
2531 // Add has the property that adding any two 2's complement numbers can only
2532 // have one carry bit which can change a sign. As such, if LHS and RHS each
2533 // have at least two sign bits, we know that the addition of the two values will
2534 // sign extend fine.
2535 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2536 return true;
2537
2538
2539 // If one of the operands only has one non-zero bit, and if the other operand
2540 // has a known-zero bit in a more significant place than it (not including the
2541 // sign bit) the ripple may go up to and fill the zero, but won't change the
2542 // sign. For example, (X & ~4) + 1.
2543
2544 // TODO: Implement.
2545
2546 return false;
2547}
2548
Chris Lattner2454a2e2008-01-29 06:52:45 +00002549
Chris Lattner7e708292002-06-25 16:13:24 +00002550Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002551 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002552 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002553
Chris Lattner66331a42004-04-10 22:01:55 +00002554 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002555 // X + undef -> undef
2556 if (isa<UndefValue>(RHS))
2557 return ReplaceInstUsesWith(I, RHS);
2558
Chris Lattner66331a42004-04-10 22:01:55 +00002559 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002560 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002561 if (RHSC->isNullValue())
2562 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002563 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002564 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2565 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002566 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002567 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002568
Chris Lattner66331a42004-04-10 22:01:55 +00002569 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002570 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002571 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002572 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002573 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002574 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002575
2576 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2577 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002578 if (!isa<VectorType>(I.getType())) {
2579 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2580 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2581 KnownZero, KnownOne))
2582 return &I;
2583 }
Chris Lattner66331a42004-04-10 22:01:55 +00002584 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002585
2586 if (isa<PHINode>(LHS))
2587 if (Instruction *NV = FoldOpIntoPhi(I))
2588 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002589
Chris Lattner4f637d42006-01-06 17:59:59 +00002590 ConstantInt *XorRHS = 0;
2591 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002592 if (isa<ConstantInt>(RHSC) &&
2593 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002594 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002595 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002596
Zhou Sheng4351c642007-04-02 08:20:41 +00002597 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002598 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2599 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002600 do {
2601 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002602 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2603 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002604 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2605 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002606 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002607 if (!MaskedValueIsZero(XorLHS,
2608 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002609 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002610 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002611 }
2612 }
2613 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002614 C0080Val = APIntOps::lshr(C0080Val, Size);
2615 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2616 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002617
Reid Spencer35c38852007-03-28 01:36:16 +00002618 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002619 // with funny bit widths then this switch statement should be removed. It
2620 // is just here to get the size of the "middle" type back up to something
2621 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002622 const Type *MiddleType = 0;
2623 switch (Size) {
2624 default: break;
2625 case 32: MiddleType = Type::Int32Ty; break;
2626 case 16: MiddleType = Type::Int16Ty; break;
2627 case 8: MiddleType = Type::Int8Ty; break;
2628 }
2629 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002630 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002631 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002632 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002633 }
2634 }
Chris Lattner66331a42004-04-10 22:01:55 +00002635 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002636
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002637 // X + X --> X << 1
Nick Lewycky02d639f2008-05-23 04:34:58 +00002638 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002639 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002640
2641 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2642 if (RHSI->getOpcode() == Instruction::Sub)
2643 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2644 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2645 }
2646 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2647 if (LHSI->getOpcode() == Instruction::Sub)
2648 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2649 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2650 }
Robert Bocchino71698282004-07-27 21:02:21 +00002651 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002652
Chris Lattner5c4afb92002-05-08 22:46:53 +00002653 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002654 // -A + -B --> -(A + B)
2655 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002656 if (LHS->getType()->isIntOrIntVector()) {
2657 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002658 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002659 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002660 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002661 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002662 }
2663
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002664 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002665 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002666
2667 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002668 if (!isa<Constant>(RHS))
2669 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002670 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002671
Misha Brukmanfd939082005-04-21 23:48:37 +00002672
Chris Lattner50af16a2004-11-13 19:50:12 +00002673 ConstantInt *C2;
2674 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2675 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002676 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002677
2678 // X*C1 + X*C2 --> X * (C1+C2)
2679 ConstantInt *C1;
2680 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002681 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002682 }
2683
2684 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002685 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002686 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002687
Chris Lattnere617c9e2007-01-05 02:17:46 +00002688 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002689 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2690 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002691
Chris Lattnerad3448c2003-02-18 19:57:07 +00002692
Chris Lattner564a7272003-08-13 19:01:45 +00002693 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002694 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002695 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2696 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002697
2698 // A+B --> A|B iff A and B have no bits set in common.
2699 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2700 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2701 APInt LHSKnownOne(IT->getBitWidth(), 0);
2702 APInt LHSKnownZero(IT->getBitWidth(), 0);
2703 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2704 if (LHSKnownZero != 0) {
2705 APInt RHSKnownOne(IT->getBitWidth(), 0);
2706 APInt RHSKnownZero(IT->getBitWidth(), 0);
2707 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2708
2709 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002710 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002711 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002712 }
2713 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002714
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002715 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002716 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002717 Value *W, *X, *Y, *Z;
2718 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2719 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2720 if (W != Y) {
2721 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002722 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002723 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002724 std::swap(W, X);
2725 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002726 std::swap(Y, Z);
2727 std::swap(W, X);
2728 }
2729 }
2730
2731 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002732 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002733 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002734 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002735 }
2736 }
2737 }
2738
Chris Lattner6b032052003-10-02 15:11:26 +00002739 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002740 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002741 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002742 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002743
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002744 // (X & FF00) + xx00 -> (X+xx00) & FF00
2745 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002746 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002747 if (Anded == CRHS) {
2748 // See if all bits from the first bit set in the Add RHS up are included
2749 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002750 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002751
2752 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002753 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002754
2755 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002756 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002757
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002758 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2759 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002760 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002761 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002762 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002763 }
2764 }
2765 }
2766
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002767 // Try to fold constant add into select arguments.
2768 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002769 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002770 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002771 }
2772
Reid Spencer1628cec2006-10-26 06:15:43 +00002773 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002774 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002775 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002776 CastInst *CI = dyn_cast<CastInst>(LHS);
2777 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002778 if (!CI) {
2779 CI = dyn_cast<CastInst>(RHS);
2780 Other = LHS;
2781 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002782 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002783 (CI->getType()->getPrimitiveSizeInBits() ==
2784 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002785 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002786 unsigned AS =
2787 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002788 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2789 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002790 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002791 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002792 }
2793 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002794
Chris Lattner42790482007-12-20 01:56:58 +00002795 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002796 {
2797 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2798 Value *Other = RHS;
2799 if (!SI) {
2800 SI = dyn_cast<SelectInst>(RHS);
2801 Other = LHS;
2802 }
Chris Lattner42790482007-12-20 01:56:58 +00002803 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002804 Value *TV = SI->getTrueValue();
2805 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002806 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002807
2808 // Can we fold the add into the argument of the select?
2809 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002810 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2811 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002812 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002813 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2814 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002815 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002816 }
2817 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002818
2819 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2820 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2821 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2822 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002823
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002824 // Check for (add (sext x), y), see if we can merge this into an
2825 // integer add followed by a sext.
2826 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2827 // (add (sext x), cst) --> (sext (add x, cst'))
2828 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2829 Constant *CI =
2830 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2831 if (LHSConv->hasOneUse() &&
2832 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2833 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2834 // Insert the new, smaller add.
2835 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2836 CI, "addconv");
2837 InsertNewInstBefore(NewAdd, I);
2838 return new SExtInst(NewAdd, I.getType());
2839 }
2840 }
2841
2842 // (add (sext x), (sext y)) --> (sext (add int x, y))
2843 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2844 // Only do this if x/y have the same type, if at last one of them has a
2845 // single use (so we don't increase the number of sexts), and if the
2846 // integer add will not overflow.
2847 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2848 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2849 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2850 RHSConv->getOperand(0))) {
2851 // Insert the new integer add.
2852 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2853 RHSConv->getOperand(0),
2854 "addconv");
2855 InsertNewInstBefore(NewAdd, I);
2856 return new SExtInst(NewAdd, I.getType());
2857 }
2858 }
2859 }
2860
2861 // Check for (add double (sitofp x), y), see if we can merge this into an
2862 // integer add followed by a promotion.
2863 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2864 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2865 // ... if the constant fits in the integer value. This is useful for things
2866 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2867 // requires a constant pool load, and generally allows the add to be better
2868 // instcombined.
2869 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2870 Constant *CI =
2871 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2872 if (LHSConv->hasOneUse() &&
2873 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2874 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2875 // Insert the new integer add.
2876 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2877 CI, "addconv");
2878 InsertNewInstBefore(NewAdd, I);
2879 return new SIToFPInst(NewAdd, I.getType());
2880 }
2881 }
2882
2883 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2884 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2885 // Only do this if x/y have the same type, if at last one of them has a
2886 // single use (so we don't increase the number of int->fp conversions),
2887 // and if the integer add will not overflow.
2888 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2889 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2890 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2891 RHSConv->getOperand(0))) {
2892 // Insert the new integer add.
2893 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2894 RHSConv->getOperand(0),
2895 "addconv");
2896 InsertNewInstBefore(NewAdd, I);
2897 return new SIToFPInst(NewAdd, I.getType());
2898 }
2899 }
2900 }
2901
Chris Lattner7e708292002-06-25 16:13:24 +00002902 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002903}
2904
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002905// isSignBit - Return true if the value represented by the constant only has the
2906// highest order bit set.
2907static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002908 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002909 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002910}
2911
Chris Lattner7e708292002-06-25 16:13:24 +00002912Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002913 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002914
Chris Lattner233f7dc2002-08-12 21:17:25 +00002915 if (Op0 == Op1) // sub X, X -> 0
2916 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002917
Chris Lattner233f7dc2002-08-12 21:17:25 +00002918 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002919 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002920 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002921
Chris Lattnere87597f2004-10-16 18:11:37 +00002922 if (isa<UndefValue>(Op0))
2923 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2924 if (isa<UndefValue>(Op1))
2925 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2926
Chris Lattnerd65460f2003-11-05 01:06:05 +00002927 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2928 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002929 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002930 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002931
Chris Lattnerd65460f2003-11-05 01:06:05 +00002932 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002933 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002934 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002935 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002936
Chris Lattner76b7a062007-01-15 07:02:54 +00002937 // -(X >>u 31) -> (X >>s 31)
2938 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002939 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002940 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002941 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002942 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002943 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002944 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002945 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002946 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002947 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002948 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002949 }
2950 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002951 }
2952 else if (SI->getOpcode() == Instruction::AShr) {
2953 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2954 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002955 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002956 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002957 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002958 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002959 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002960 }
2961 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002962 }
2963 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002964 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002965
2966 // Try to fold constant sub into select arguments.
2967 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002968 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002969 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002970
2971 if (isa<PHINode>(Op0))
2972 if (Instruction *NV = FoldOpIntoPhi(I))
2973 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002974 }
2975
Chris Lattner43d84d62005-04-07 16:15:25 +00002976 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2977 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002978 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002979 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002980 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002981 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002982 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002983 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2984 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2985 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002986 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002987 Op1I->getOperand(0));
2988 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002989 }
2990
Chris Lattnerfd059242003-10-15 16:48:29 +00002991 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002992 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2993 // is not used by anyone else...
2994 //
Chris Lattner0517e722004-02-02 20:09:56 +00002995 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002996 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002997 // Swap the two operands of the subexpr...
2998 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2999 Op1I->setOperand(0, IIOp1);
3000 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00003001
Chris Lattnera2881962003-02-18 19:28:33 +00003002 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003003 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003004 }
3005
3006 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
3007 //
3008 if (Op1I->getOpcode() == Instruction::And &&
3009 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
3010 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
3011
Chris Lattnerf523d062004-06-09 05:08:07 +00003012 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003013 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
3014 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00003015 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00003016
Reid Spencerac5209e2006-10-16 23:08:08 +00003017 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00003018 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00003019 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00003020 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00003021 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003022 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00003023 ConstantExpr::getNeg(DivRHS));
3024
Chris Lattnerad3448c2003-02-18 19:57:07 +00003025 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00003026 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00003027 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00003028 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003029 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00003030 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00003031
3032 // X - ((X / Y) * Y) --> X % Y
3033 if (Op1I->getOpcode() == Instruction::Mul)
3034 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
3035 if (Op0 == I->getOperand(0) &&
3036 Op1I->getOperand(1) == I->getOperand(1)) {
3037 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003038 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00003039 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003040 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00003041 }
Chris Lattner40371712002-05-09 01:29:19 +00003042 }
Chris Lattner43d84d62005-04-07 16:15:25 +00003043 }
Chris Lattnera2881962003-02-18 19:28:33 +00003044
Chris Lattner9919e3d2006-12-02 00:13:08 +00003045 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003046 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00003047 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003048 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
3049 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3050 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
3051 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00003052 } else if (Op0I->getOpcode() == Instruction::Sub) {
3053 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003054 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003055 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003056 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003057
Chris Lattner50af16a2004-11-13 19:50:12 +00003058 ConstantInt *C1;
3059 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00003060 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003061 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00003062
Chris Lattner50af16a2004-11-13 19:50:12 +00003063 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
3064 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003065 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00003066 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003067 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003068}
3069
Chris Lattnera0141b92007-07-15 20:42:37 +00003070/// isSignBitCheck - Given an exploded icmp instruction, return true if the
3071/// comparison only checks the sign bit. If it only checks the sign bit, set
3072/// TrueIfSigned if the result of the comparison is true when the input value is
3073/// signed.
3074static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3075 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003076 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003077 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3078 TrueIfSigned = true;
3079 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003080 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3081 TrueIfSigned = true;
3082 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00003083 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3084 TrueIfSigned = false;
3085 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003086 case ICmpInst::ICMP_UGT:
3087 // True if LHS u> RHS and RHS == high-bit-mask - 1
3088 TrueIfSigned = true;
3089 return RHS->getValue() ==
3090 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3091 case ICmpInst::ICMP_UGE:
3092 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3093 TrueIfSigned = true;
3094 return RHS->getValue() ==
3095 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00003096 default:
3097 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00003098 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00003099}
3100
Chris Lattner7e708292002-06-25 16:13:24 +00003101Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003102 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00003103 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003104
Chris Lattnere87597f2004-10-16 18:11:37 +00003105 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
3106 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3107
Chris Lattner233f7dc2002-08-12 21:17:25 +00003108 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00003109 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
3110 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00003111
3112 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00003113 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00003114 if (SI->getOpcode() == Instruction::Shl)
3115 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003116 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00003117 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00003118
Zhou Sheng843f07672007-04-19 05:39:12 +00003119 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00003120 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
3121 if (CI->equalsInt(1)) // X * 1 == X
3122 return ReplaceInstUsesWith(I, Op0);
3123 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003124 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00003125
Zhou Sheng97b52c22007-03-29 01:57:21 +00003126 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003127 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003128 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00003129 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003130 }
Robert Bocchino71698282004-07-27 21:02:21 +00003131 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00003132 if (Op1F->isNullValue())
3133 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00003134
Chris Lattnera2881962003-02-18 19:28:33 +00003135 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3136 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00003137 // We need a better interface for long double here.
3138 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
3139 if (Op1F->isExactlyValue(1.0))
3140 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00003141 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003142
3143 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3144 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00003145 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003146 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003147 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003148 Op1, "tmp");
3149 InsertNewInstBefore(Add, I);
3150 Value *C1C2 = ConstantExpr::getMul(Op1,
3151 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003152 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003153
3154 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003155
3156 // Try to fold constant mul into select arguments.
3157 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003158 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003159 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003160
3161 if (isa<PHINode>(Op0))
3162 if (Instruction *NV = FoldOpIntoPhi(I))
3163 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003164 }
3165
Chris Lattnera4f445b2003-03-10 23:23:04 +00003166 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
3167 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003168 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003169
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003170 // If one of the operands of the multiply is a cast from a boolean value, then
3171 // we know the bool is either zero or one, so this is a 'masking' multiply.
3172 // See if we can simplify things based on how the boolean was originally
3173 // formed.
3174 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00003175 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003176 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003177 BoolCast = CI;
3178 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00003179 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003180 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003181 BoolCast = CI;
3182 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003183 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003184 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3185 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00003186 bool TIS = false;
3187
Reid Spencere4d87aa2006-12-23 06:05:41 +00003188 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00003189 // multiply into a shift/and combination.
3190 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00003191 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
3192 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003193 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00003194 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00003195 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00003196 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00003197 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003198 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00003199 BoolCast->getOperand(0)->getName()+
3200 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003201
3202 // If the multiply type is not the same as the source type, sign extend
3203 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00003204 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00003205 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
3206 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00003207 Instruction::CastOps opcode =
3208 (SrcBits == DstBits ? Instruction::BitCast :
3209 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3210 V = InsertCastBefore(opcode, V, I.getType(), I);
3211 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003212
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003213 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003214 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003215 }
3216 }
3217 }
3218
Chris Lattner7e708292002-06-25 16:13:24 +00003219 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003220}
3221
Reid Spencer1628cec2006-10-26 06:15:43 +00003222/// This function implements the transforms on div instructions that work
3223/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3224/// used by the visitors to those instructions.
3225/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003226Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003227 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003228
Chris Lattner50b2ca42008-02-19 06:12:18 +00003229 // undef / X -> 0 for integer.
3230 // undef / X -> undef for FP (the undef could be a snan).
3231 if (isa<UndefValue>(Op0)) {
3232 if (Op0->getType()->isFPOrFPVector())
3233 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003234 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003235 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003236
3237 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003238 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003239 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003240
Chris Lattner25feae52008-01-28 00:58:18 +00003241 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3242 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00003243 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00003244 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
3245 // the same basic block, then we replace the select with Y, and the
3246 // condition of the select with false (if the cond value is in the same BB).
3247 // If the select has uses other than the div, this allows them to be
3248 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
3249 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003250 if (ST->isNullValue()) {
3251 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3252 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003253 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00003254 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3255 I.setOperand(1, SI->getOperand(2));
3256 else
3257 UpdateValueUsesWith(SI, SI->getOperand(2));
3258 return &I;
3259 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003260
Chris Lattner25feae52008-01-28 00:58:18 +00003261 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3262 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003263 if (ST->isNullValue()) {
3264 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3265 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003266 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00003267 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3268 I.setOperand(1, SI->getOperand(1));
3269 else
3270 UpdateValueUsesWith(SI, SI->getOperand(1));
3271 return &I;
3272 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003273 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003274
Reid Spencer1628cec2006-10-26 06:15:43 +00003275 return 0;
3276}
Misha Brukmanfd939082005-04-21 23:48:37 +00003277
Reid Spencer1628cec2006-10-26 06:15:43 +00003278/// This function implements the transforms common to both integer division
3279/// instructions (udiv and sdiv). It is called by the visitors to those integer
3280/// division instructions.
3281/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003282Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003283 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3284
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003285 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003286 if (Op0 == Op1) {
3287 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3288 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
3289 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3290 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3291 }
3292
3293 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
3294 return ReplaceInstUsesWith(I, CI);
3295 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003296
Reid Spencer1628cec2006-10-26 06:15:43 +00003297 if (Instruction *Common = commonDivTransforms(I))
3298 return Common;
3299
3300 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3301 // div X, 1 == X
3302 if (RHS->equalsInt(1))
3303 return ReplaceInstUsesWith(I, Op0);
3304
3305 // (X / C1) / C2 -> X / (C1*C2)
3306 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3307 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3308 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003309 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3310 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3311 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003312 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003313 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003314 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003315
Reid Spencerbca0e382007-03-23 20:05:17 +00003316 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003317 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3318 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3319 return R;
3320 if (isa<PHINode>(Op0))
3321 if (Instruction *NV = FoldOpIntoPhi(I))
3322 return NV;
3323 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003324 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003325
Chris Lattnera2881962003-02-18 19:28:33 +00003326 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003327 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003328 if (LHS->equalsInt(0))
3329 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3330
Reid Spencer1628cec2006-10-26 06:15:43 +00003331 return 0;
3332}
3333
3334Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3335 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3336
3337 // Handle the integer div common cases
3338 if (Instruction *Common = commonIDivTransforms(I))
3339 return Common;
3340
3341 // X udiv C^2 -> X >> C
3342 // Check to see if this is an unsigned division with an exact power of 2,
3343 // if so, convert to a right shift.
3344 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00003345 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003346 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003347 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003348 }
3349
3350 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003351 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003352 if (RHSI->getOpcode() == Instruction::Shl &&
3353 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003354 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003355 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003356 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003357 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003358 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003359 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003360 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003361 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003362 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003363 }
3364 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003365 }
3366
Reid Spencer1628cec2006-10-26 06:15:43 +00003367 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3368 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003369 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003370 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003371 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003372 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003373 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003374 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003375 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003376 // Construct the "on true" case of the select
3377 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003378 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003379 Op0, TC, SI->getName()+".t");
3380 TSI = InsertNewInstBefore(TSI, I);
3381
3382 // Construct the "on false" case of the select
3383 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003384 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003385 Op0, FC, SI->getName()+".f");
3386 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003387
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003388 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003389 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003390 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003391 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003392 return 0;
3393}
3394
Reid Spencer1628cec2006-10-26 06:15:43 +00003395Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3396 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3397
3398 // Handle the integer div common cases
3399 if (Instruction *Common = commonIDivTransforms(I))
3400 return Common;
3401
3402 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3403 // sdiv X, -1 == -X
3404 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003405 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003406
3407 // -X/C -> X/-C
3408 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003409 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003410 }
3411
3412 // If the sign bits of both operands are zero (i.e. we can prove they are
3413 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003414 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003415 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003416 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003417 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003418 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003419 }
3420 }
3421
3422 return 0;
3423}
3424
3425Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3426 return commonDivTransforms(I);
3427}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003428
Reid Spencer0a783f72006-11-02 01:53:59 +00003429/// This function implements the transforms on rem instructions that work
3430/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3431/// is used by the visitors to those instructions.
3432/// @brief Transforms common to all three rem instructions
3433Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003434 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003435
Chris Lattner50b2ca42008-02-19 06:12:18 +00003436 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003437 if (Constant *LHS = dyn_cast<Constant>(Op0))
3438 if (LHS->isNullValue())
3439 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3440
Chris Lattner50b2ca42008-02-19 06:12:18 +00003441 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3442 if (I.getType()->isFPOrFPVector())
3443 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003444 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003445 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003446 if (isa<UndefValue>(Op1))
3447 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003448
3449 // Handle cases involving: rem X, (select Cond, Y, Z)
3450 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3451 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3452 // the same basic block, then we replace the select with Y, and the
3453 // condition of the select with false (if the cond value is in the same
3454 // BB). If the select has uses other than the div, this allows them to be
3455 // simplified also.
3456 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3457 if (ST->isNullValue()) {
3458 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3459 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003460 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003461 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3462 I.setOperand(1, SI->getOperand(2));
3463 else
3464 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003465 return &I;
3466 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003467 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3468 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3469 if (ST->isNullValue()) {
3470 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3471 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003472 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003473 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3474 I.setOperand(1, SI->getOperand(1));
3475 else
3476 UpdateValueUsesWith(SI, SI->getOperand(1));
3477 return &I;
3478 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003479 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003480
Reid Spencer0a783f72006-11-02 01:53:59 +00003481 return 0;
3482}
3483
3484/// This function implements the transforms common to both integer remainder
3485/// instructions (urem and srem). It is called by the visitors to those integer
3486/// remainder instructions.
3487/// @brief Common integer remainder transforms
3488Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3489 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3490
3491 if (Instruction *common = commonRemTransforms(I))
3492 return common;
3493
Chris Lattner857e8cd2004-12-12 21:48:58 +00003494 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003495 // X % 0 == undef, we don't need to preserve faults!
3496 if (RHS->equalsInt(0))
3497 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3498
Chris Lattnera2881962003-02-18 19:28:33 +00003499 if (RHS->equalsInt(1)) // X % 1 == 0
3500 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3501
Chris Lattner97943922006-02-28 05:49:21 +00003502 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3503 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3504 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3505 return R;
3506 } else if (isa<PHINode>(Op0I)) {
3507 if (Instruction *NV = FoldOpIntoPhi(I))
3508 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003509 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003510
3511 // See if we can fold away this rem instruction.
3512 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3513 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3514 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3515 KnownZero, KnownOne))
3516 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003517 }
Chris Lattnera2881962003-02-18 19:28:33 +00003518 }
3519
Reid Spencer0a783f72006-11-02 01:53:59 +00003520 return 0;
3521}
3522
3523Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3524 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3525
3526 if (Instruction *common = commonIRemTransforms(I))
3527 return common;
3528
3529 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3530 // X urem C^2 -> X and C
3531 // Check to see if this is an unsigned remainder with an exact power of 2,
3532 // if so, convert to a bitwise and.
3533 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003534 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003535 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003536 }
3537
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003538 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003539 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3540 if (RHSI->getOpcode() == Instruction::Shl &&
3541 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003542 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003543 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003544 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003545 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003546 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003547 }
3548 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003549 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003550
Reid Spencer0a783f72006-11-02 01:53:59 +00003551 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3552 // where C1&C2 are powers of two.
3553 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3554 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3555 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3556 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003557 if ((STO->getValue().isPowerOf2()) &&
3558 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003559 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003560 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003561 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003562 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003563 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003564 }
3565 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003566 }
3567
Chris Lattner3f5b8772002-05-06 16:14:14 +00003568 return 0;
3569}
3570
Reid Spencer0a783f72006-11-02 01:53:59 +00003571Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3572 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3573
Dan Gohmancff55092007-11-05 23:16:33 +00003574 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003575 if (Instruction *common = commonIRemTransforms(I))
3576 return common;
3577
3578 if (Value *RHSNeg = dyn_castNegVal(Op1))
3579 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003580 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003581 // X % -Y -> X % Y
3582 AddUsesToWorkList(I);
3583 I.setOperand(1, RHSNeg);
3584 return &I;
3585 }
3586
Dan Gohmancff55092007-11-05 23:16:33 +00003587 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003588 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003589 if (I.getType()->isInteger()) {
3590 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3591 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3592 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003593 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003594 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003595 }
3596
3597 return 0;
3598}
3599
3600Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003601 return commonRemTransforms(I);
3602}
3603
Chris Lattner8b170942002-08-09 23:47:40 +00003604// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003605static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003606 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003607 if (!isSigned)
3608 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3609 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003610}
3611
3612// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003613static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003614 if (!isSigned)
3615 return C->getValue() == 1; // unsigned
3616
3617 // Calculate 1111111111000000000000
3618 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3619 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003620}
3621
Chris Lattner457dd822004-06-09 07:59:58 +00003622// isOneBitSet - Return true if there is exactly one bit set in the specified
3623// constant.
3624static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003625 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003626}
3627
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003628// isHighOnes - Return true if the constant is of the form 1+0+.
3629// This is the same as lowones(~X).
3630static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003631 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003632}
3633
Reid Spencere4d87aa2006-12-23 06:05:41 +00003634/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003635/// are carefully arranged to allow folding of expressions such as:
3636///
3637/// (A < B) | (A > B) --> (A != B)
3638///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003639/// Note that this is only valid if the first and second predicates have the
3640/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003641///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003642/// Three bits are used to represent the condition, as follows:
3643/// 0 A > B
3644/// 1 A == B
3645/// 2 A < B
3646///
3647/// <=> Value Definition
3648/// 000 0 Always false
3649/// 001 1 A > B
3650/// 010 2 A == B
3651/// 011 3 A >= B
3652/// 100 4 A < B
3653/// 101 5 A != B
3654/// 110 6 A <= B
3655/// 111 7 Always true
3656///
3657static unsigned getICmpCode(const ICmpInst *ICI) {
3658 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003659 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003660 case ICmpInst::ICMP_UGT: return 1; // 001
3661 case ICmpInst::ICMP_SGT: return 1; // 001
3662 case ICmpInst::ICMP_EQ: return 2; // 010
3663 case ICmpInst::ICMP_UGE: return 3; // 011
3664 case ICmpInst::ICMP_SGE: return 3; // 011
3665 case ICmpInst::ICMP_ULT: return 4; // 100
3666 case ICmpInst::ICMP_SLT: return 4; // 100
3667 case ICmpInst::ICMP_NE: return 5; // 101
3668 case ICmpInst::ICMP_ULE: return 6; // 110
3669 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003670 // True -> 7
3671 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003672 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003673 return 0;
3674 }
3675}
3676
Reid Spencere4d87aa2006-12-23 06:05:41 +00003677/// getICmpValue - This is the complement of getICmpCode, which turns an
3678/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003679/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003680/// of predicate to use in new icmp instructions.
3681static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3682 switch (code) {
3683 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003684 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003685 case 1:
3686 if (sign)
3687 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3688 else
3689 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3690 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3691 case 3:
3692 if (sign)
3693 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3694 else
3695 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3696 case 4:
3697 if (sign)
3698 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3699 else
3700 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3701 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3702 case 6:
3703 if (sign)
3704 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3705 else
3706 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003707 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003708 }
3709}
3710
Reid Spencere4d87aa2006-12-23 06:05:41 +00003711static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3712 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3713 (ICmpInst::isSignedPredicate(p1) &&
3714 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3715 (ICmpInst::isSignedPredicate(p2) &&
3716 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3717}
3718
3719namespace {
3720// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3721struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003722 InstCombiner &IC;
3723 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003724 ICmpInst::Predicate pred;
3725 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3726 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3727 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003728 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003729 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3730 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003731 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3732 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003733 return false;
3734 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003735 Instruction *apply(Instruction &Log) const {
3736 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3737 if (ICI->getOperand(0) != LHS) {
3738 assert(ICI->getOperand(1) == LHS);
3739 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003740 }
3741
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003742 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003743 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003744 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003745 unsigned Code;
3746 switch (Log.getOpcode()) {
3747 case Instruction::And: Code = LHSCode & RHSCode; break;
3748 case Instruction::Or: Code = LHSCode | RHSCode; break;
3749 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003750 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003751 }
3752
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003753 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3754 ICmpInst::isSignedPredicate(ICI->getPredicate());
3755
3756 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003757 if (Instruction *I = dyn_cast<Instruction>(RV))
3758 return I;
3759 // Otherwise, it's a constant boolean value...
3760 return IC.ReplaceInstUsesWith(Log, RV);
3761 }
3762};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003763} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003764
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003765// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3766// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003767// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003768Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003769 ConstantInt *OpRHS,
3770 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003771 BinaryOperator &TheAnd) {
3772 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003773 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003774 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003775 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003776
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003777 switch (Op->getOpcode()) {
3778 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003779 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003780 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003781 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003782 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003783 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003784 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003785 }
3786 break;
3787 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003788 if (Together == AndRHS) // (X | C) & C --> C
3789 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003790
Chris Lattner6e7ba452005-01-01 16:22:27 +00003791 if (Op->hasOneUse() && Together != OpRHS) {
3792 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003793 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003794 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003795 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003796 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003797 }
3798 break;
3799 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003800 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003801 // Adding a one to a single bit bit-field should be turned into an XOR
3802 // of the bit. First thing to check is to see if this AND is with a
3803 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003804 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003805
3806 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003807 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003808 // Ok, at this point, we know that we are masking the result of the
3809 // ADD down to exactly one bit. If the constant we are adding has
3810 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003811 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003812
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003813 // Check to see if any bits below the one bit set in AndRHSV are set.
3814 if ((AddRHS & (AndRHSV-1)) == 0) {
3815 // If not, the only thing that can effect the output of the AND is
3816 // the bit specified by AndRHSV. If that bit is set, the effect of
3817 // the XOR is to toggle the bit. If it is clear, then the ADD has
3818 // no effect.
3819 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3820 TheAnd.setOperand(0, X);
3821 return &TheAnd;
3822 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003823 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003824 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003825 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003826 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003827 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003828 }
3829 }
3830 }
3831 }
3832 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003833
3834 case Instruction::Shl: {
3835 // We know that the AND will not produce any of the bits shifted in, so if
3836 // the anded constant includes them, clear them now!
3837 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003838 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003839 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003840 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3841 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003842
Zhou Sheng290bec52007-03-29 08:15:12 +00003843 if (CI->getValue() == ShlMask) {
3844 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003845 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3846 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003847 TheAnd.setOperand(1, CI);
3848 return &TheAnd;
3849 }
3850 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003851 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003852 case Instruction::LShr:
3853 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003854 // We know that the AND will not produce any of the bits shifted in, so if
3855 // the anded constant includes them, clear them now! This only applies to
3856 // unsigned shifts, because a signed shr may bring in set bits!
3857 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003858 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003859 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003860 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3861 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003862
Zhou Sheng290bec52007-03-29 08:15:12 +00003863 if (CI->getValue() == ShrMask) {
3864 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003865 return ReplaceInstUsesWith(TheAnd, Op);
3866 } else if (CI != AndRHS) {
3867 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3868 return &TheAnd;
3869 }
3870 break;
3871 }
3872 case Instruction::AShr:
3873 // Signed shr.
3874 // See if this is shifting in some sign extension, then masking it out
3875 // with an and.
3876 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003877 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003878 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003879 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3880 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003881 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003882 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003883 // Make the argument unsigned.
3884 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003885 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003886 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003887 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003888 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003889 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003890 }
3891 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003892 }
3893 return 0;
3894}
3895
Chris Lattner8b170942002-08-09 23:47:40 +00003896
Chris Lattnera96879a2004-09-29 17:40:11 +00003897/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3898/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003899/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3900/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003901/// insert new instructions.
3902Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003903 bool isSigned, bool Inside,
3904 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003905 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003906 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003907 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003908
Chris Lattnera96879a2004-09-29 17:40:11 +00003909 if (Inside) {
3910 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003911 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003912
Reid Spencere4d87aa2006-12-23 06:05:41 +00003913 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003914 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003915 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003916 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3917 return new ICmpInst(pred, V, Hi);
3918 }
3919
3920 // Emit V-Lo <u Hi-Lo
3921 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003922 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003923 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003924 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3925 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003926 }
3927
3928 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003929 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003930
Reid Spencere4e40032007-03-21 23:19:50 +00003931 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003932 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003933 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003934 ICmpInst::Predicate pred = (isSigned ?
3935 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3936 return new ICmpInst(pred, V, Hi);
3937 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003938
Reid Spencere4e40032007-03-21 23:19:50 +00003939 // Emit V-Lo >u Hi-1-Lo
3940 // Note that Hi has already had one subtracted from it, above.
3941 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003942 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003943 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003944 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3945 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003946}
3947
Chris Lattner7203e152005-09-18 07:22:02 +00003948// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3949// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3950// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3951// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003952static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003953 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003954 uint32_t BitWidth = Val->getType()->getBitWidth();
3955 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003956
3957 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003958 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003959 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003960 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003961 return true;
3962}
3963
Chris Lattner7203e152005-09-18 07:22:02 +00003964/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3965/// where isSub determines whether the operator is a sub. If we can fold one of
3966/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003967///
3968/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3969/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3970/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3971///
3972/// return (A +/- B).
3973///
3974Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003975 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003976 Instruction &I) {
3977 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3978 if (!LHSI || LHSI->getNumOperands() != 2 ||
3979 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3980
3981 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3982
3983 switch (LHSI->getOpcode()) {
3984 default: return 0;
3985 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003986 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003987 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003988 if ((Mask->getValue().countLeadingZeros() +
3989 Mask->getValue().countPopulation()) ==
3990 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003991 break;
3992
3993 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3994 // part, we don't need any explicit masks to take them out of A. If that
3995 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003996 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003997 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003998 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003999 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004000 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004001 break;
4002 }
4003 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004004 return 0;
4005 case Instruction::Or:
4006 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004007 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004008 if ((Mask->getValue().countLeadingZeros() +
4009 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00004010 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004011 break;
4012 return 0;
4013 }
4014
4015 Instruction *New;
4016 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004017 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004018 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004019 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004020 return InsertNewInstBefore(New, I);
4021}
4022
Chris Lattner7e708292002-06-25 16:13:24 +00004023Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004024 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004025 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004026
Chris Lattnere87597f2004-10-16 18:11:37 +00004027 if (isa<UndefValue>(Op1)) // X & undef -> 0
4028 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4029
Chris Lattner6e7ba452005-01-01 16:22:27 +00004030 // and X, X = X
4031 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004032 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004033
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004034 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004035 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00004036 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00004037 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4038 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4039 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00004040 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00004041 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00004042 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004043 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004044 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004045 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004046 } else if (isa<ConstantAggregateZero>(Op1)) {
4047 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004048 }
4049 }
Chris Lattner9ca96412006-02-08 03:25:32 +00004050
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004051 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004052 const APInt& AndRHSMask = AndRHS->getValue();
4053 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004054
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004055 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004056 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004057 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004058 Value *Op0LHS = Op0I->getOperand(0);
4059 Value *Op0RHS = Op0I->getOperand(1);
4060 switch (Op0I->getOpcode()) {
4061 case Instruction::Xor:
4062 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004063 // If the mask is only needed on one incoming arm, push it up.
4064 if (Op0I->hasOneUse()) {
4065 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4066 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004067 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004068 Op0RHS->getName()+".masked");
4069 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004070 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004071 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004072 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004073 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004074 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4075 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004076 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004077 Op0LHS->getName()+".masked");
4078 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004079 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004080 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4081 }
4082 }
4083
Chris Lattner6e7ba452005-01-01 16:22:27 +00004084 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004085 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004086 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4087 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4088 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4089 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004090 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004091 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004092 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004093 break;
4094
4095 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004096 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4097 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4098 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4099 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004100 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00004101 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004102 }
4103
Chris Lattner58403262003-07-23 19:25:52 +00004104 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004105 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004106 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004107 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004108 // If this is an integer truncation or change from signed-to-unsigned, and
4109 // if the source is an and/or with immediate, transform it. This
4110 // frequently occurs for bitfield accesses.
4111 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004112 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004113 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004114 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004115 if (CastOp->getOpcode() == Instruction::And) {
4116 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004117 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4118 // This will fold the two constants together, which may allow
4119 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004120 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004121 CastOp->getOperand(0), I.getType(),
4122 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004123 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004124 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00004125 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00004126 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004127 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004128 } else if (CastOp->getOpcode() == Instruction::Or) {
4129 // Change: and (cast (or X, C1) to T), C2
4130 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00004131 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00004132 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4133 return ReplaceInstUsesWith(I, AndRHS);
4134 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004135 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004136 }
Chris Lattner06782f82003-07-23 19:36:21 +00004137 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004138
4139 // Try to fold constant and into select arguments.
4140 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004141 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004142 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004143 if (isa<PHINode>(Op0))
4144 if (Instruction *NV = FoldOpIntoPhi(I))
4145 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004146 }
4147
Chris Lattner8d969642003-03-10 23:06:50 +00004148 Value *Op0NotVal = dyn_castNotVal(Op0);
4149 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004150
Chris Lattner5b62aa72004-06-18 06:07:51 +00004151 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4152 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4153
Misha Brukmancb6267b2004-07-30 12:50:08 +00004154 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004155 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004156 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004157 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004158 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004159 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004160 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004161
4162 {
Chris Lattner003b6202007-06-15 05:58:24 +00004163 Value *A = 0, *B = 0, *C = 0, *D = 0;
4164 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004165 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4166 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004167
4168 // (A|B) & ~(A&B) -> A^B
4169 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4170 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004171 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004172 }
4173 }
4174
4175 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004176 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4177 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004178
4179 // ~(A&B) & (A|B) -> A^B
4180 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4181 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004182 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004183 }
4184 }
Chris Lattner64daab52006-04-01 08:03:55 +00004185
4186 if (Op0->hasOneUse() &&
4187 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4188 if (A == Op1) { // (A^B)&A -> A&(A^B)
4189 I.swapOperands(); // Simplify below
4190 std::swap(Op0, Op1);
4191 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4192 cast<BinaryOperator>(Op0)->swapOperands();
4193 I.swapOperands(); // Simplify below
4194 std::swap(Op0, Op1);
4195 }
4196 }
4197 if (Op1->hasOneUse() &&
4198 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4199 if (B == Op0) { // B&(A^B) -> B&(B^A)
4200 cast<BinaryOperator>(Op1)->swapOperands();
4201 std::swap(A, B);
4202 }
4203 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004204 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004205 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004206 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004207 }
4208 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004209 }
4210
Reid Spencere4d87aa2006-12-23 06:05:41 +00004211 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4212 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4213 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004214 return R;
4215
Chris Lattner955f3312004-09-28 21:48:02 +00004216 Value *LHSVal, *RHSVal;
4217 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004218 ICmpInst::Predicate LHSCC, RHSCC;
4219 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4220 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4221 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
4222 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4223 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4224 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4225 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00004226 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4227
4228 // Don't try to fold ICMP_SLT + ICMP_ULT.
4229 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
4230 ICmpInst::isSignedPredicate(LHSCC) ==
4231 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00004232 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00004233 ICmpInst::Predicate GT;
4234 if (ICmpInst::isSignedPredicate(LHSCC) ||
4235 (ICmpInst::isEquality(LHSCC) &&
4236 ICmpInst::isSignedPredicate(RHSCC)))
4237 GT = ICmpInst::ICMP_SGT;
4238 else
4239 GT = ICmpInst::ICMP_UGT;
4240
Reid Spencere4d87aa2006-12-23 06:05:41 +00004241 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4242 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00004243 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00004244 std::swap(LHS, RHS);
4245 std::swap(LHSCst, RHSCst);
4246 std::swap(LHSCC, RHSCC);
4247 }
4248
Reid Spencere4d87aa2006-12-23 06:05:41 +00004249 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00004250 // comparing a value against two constants and and'ing the result
4251 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004252 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4253 // (from the FoldICmpLogical check above), that the two constants
4254 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00004255 assert(LHSCst != RHSCst && "Compares not folded above?");
4256
4257 switch (LHSCC) {
4258 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004259 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00004260 switch (RHSCC) {
4261 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004262 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4263 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4264 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004265 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004266 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4267 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4268 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00004269 return ReplaceInstUsesWith(I, LHS);
4270 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004271 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00004272 switch (RHSCC) {
4273 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004274 case ICmpInst::ICMP_ULT:
4275 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4276 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4277 break; // (X != 13 & X u< 15) -> no change
4278 case ICmpInst::ICMP_SLT:
4279 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4280 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4281 break; // (X != 13 & X s< 15) -> no change
4282 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4283 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4284 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00004285 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004286 case ICmpInst::ICMP_NE:
4287 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00004288 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004289 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00004290 LHSVal->getName()+".off");
4291 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00004292 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4293 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00004294 }
4295 break; // (X != 13 & X != 15) -> no change
4296 }
4297 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004298 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00004299 switch (RHSCC) {
4300 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004301 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4302 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004303 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004304 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4305 break;
4306 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4307 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00004308 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004309 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4310 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004311 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004312 break;
4313 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00004314 switch (RHSCC) {
4315 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004316 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4317 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004318 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004319 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4320 break;
4321 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4322 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00004323 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004324 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4325 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004326 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004327 break;
4328 case ICmpInst::ICMP_UGT:
4329 switch (RHSCC) {
4330 default: assert(0 && "Unknown integer condition code!");
4331 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4332 return ReplaceInstUsesWith(I, LHS);
4333 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4334 return ReplaceInstUsesWith(I, RHS);
4335 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4336 break;
4337 case ICmpInst::ICMP_NE:
4338 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4339 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4340 break; // (X u> 13 & X != 15) -> no change
4341 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4342 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4343 true, I);
4344 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4345 break;
4346 }
4347 break;
4348 case ICmpInst::ICMP_SGT:
4349 switch (RHSCC) {
4350 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004351 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004352 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4353 return ReplaceInstUsesWith(I, RHS);
4354 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4355 break;
4356 case ICmpInst::ICMP_NE:
4357 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4358 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4359 break; // (X s> 13 & X != 15) -> no change
4360 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4361 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4362 true, I);
4363 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4364 break;
4365 }
4366 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004367 }
4368 }
4369 }
4370
Chris Lattner6fc205f2006-05-05 06:39:07 +00004371 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004372 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4373 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4374 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4375 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004376 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004377 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004378 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4379 I.getType(), TD) &&
4380 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4381 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004382 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004383 Op1C->getOperand(0),
4384 I.getName());
4385 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004386 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004387 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004388 }
Chris Lattnere511b742006-11-14 07:46:50 +00004389
4390 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004391 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4392 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4393 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004394 SI0->getOperand(1) == SI1->getOperand(1) &&
4395 (SI0->hasOneUse() || SI1->hasOneUse())) {
4396 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004397 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004398 SI1->getOperand(0),
4399 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004400 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004401 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004402 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004403 }
4404
Chris Lattner99c65742007-10-24 05:38:08 +00004405 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4406 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4407 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4408 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4409 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4410 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4411 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4412 // If either of the constants are nans, then the whole thing returns
4413 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004414 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004415 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4416 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4417 RHS->getOperand(0));
4418 }
4419 }
4420 }
4421
Chris Lattner7e708292002-06-25 16:13:24 +00004422 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004423}
4424
Chris Lattnerafe91a52006-06-15 19:07:26 +00004425/// CollectBSwapParts - Look to see if the specified value defines a single byte
4426/// in the result. If it does, and if the specified byte hasn't been filled in
4427/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004428static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004429 Instruction *I = dyn_cast<Instruction>(V);
4430 if (I == 0) return true;
4431
4432 // If this is an or instruction, it is an inner node of the bswap.
4433 if (I->getOpcode() == Instruction::Or)
4434 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4435 CollectBSwapParts(I->getOperand(1), ByteValues);
4436
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004437 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004438 // If this is a shift by a constant int, and it is "24", then its operand
4439 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004440 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004441 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004442 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004443 8*(ByteValues.size()-1))
4444 return true;
4445
4446 unsigned DestNo;
4447 if (I->getOpcode() == Instruction::Shl) {
4448 // X << 24 defines the top byte with the lowest of the input bytes.
4449 DestNo = ByteValues.size()-1;
4450 } else {
4451 // X >>u 24 defines the low byte with the highest of the input bytes.
4452 DestNo = 0;
4453 }
4454
4455 // If the destination byte value is already defined, the values are or'd
4456 // together, which isn't a bswap (unless it's an or of the same bits).
4457 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4458 return true;
4459 ByteValues[DestNo] = I->getOperand(0);
4460 return false;
4461 }
4462
4463 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4464 // don't have this.
4465 Value *Shift = 0, *ShiftLHS = 0;
4466 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4467 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4468 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4469 return true;
4470 Instruction *SI = cast<Instruction>(Shift);
4471
4472 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004473 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4474 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004475 return true;
4476
4477 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4478 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004479 if (AndAmt->getValue().getActiveBits() > 64)
4480 return true;
4481 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004482 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004483 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004484 break;
4485 // Unknown mask for bswap.
4486 if (DestByte == ByteValues.size()) return true;
4487
Reid Spencerb83eb642006-10-20 07:07:24 +00004488 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004489 unsigned SrcByte;
4490 if (SI->getOpcode() == Instruction::Shl)
4491 SrcByte = DestByte - ShiftBytes;
4492 else
4493 SrcByte = DestByte + ShiftBytes;
4494
4495 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4496 if (SrcByte != ByteValues.size()-DestByte-1)
4497 return true;
4498
4499 // If the destination byte value is already defined, the values are or'd
4500 // together, which isn't a bswap (unless it's an or of the same bits).
4501 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4502 return true;
4503 ByteValues[DestByte] = SI->getOperand(0);
4504 return false;
4505}
4506
4507/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4508/// If so, insert the new bswap intrinsic and return it.
4509Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004510 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4511 if (!ITy || ITy->getBitWidth() % 16)
4512 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004513
4514 /// ByteValues - For each byte of the result, we keep track of which value
4515 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004516 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004517 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004518
4519 // Try to find all the pieces corresponding to the bswap.
4520 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4521 CollectBSwapParts(I.getOperand(1), ByteValues))
4522 return 0;
4523
4524 // Check to see if all of the bytes come from the same value.
4525 Value *V = ByteValues[0];
4526 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4527
4528 // Check to make sure that all of the bytes come from the same value.
4529 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4530 if (ByteValues[i] != V)
4531 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004532 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004533 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004534 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004535 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004536}
4537
4538
Chris Lattner7e708292002-06-25 16:13:24 +00004539Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004540 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004541 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004542
Chris Lattner42593e62007-03-24 23:56:43 +00004543 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004544 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004545
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004546 // or X, X = X
4547 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004548 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004549
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004550 // See if we can simplify any instructions used by the instruction whose sole
4551 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004552 if (!isa<VectorType>(I.getType())) {
4553 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4554 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4555 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4556 KnownZero, KnownOne))
4557 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004558 } else if (isa<ConstantAggregateZero>(Op1)) {
4559 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4560 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4561 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4562 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004563 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004564
4565
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004566
Chris Lattner3f5b8772002-05-06 16:14:14 +00004567 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004568 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004569 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004570 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4571 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004572 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004573 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004574 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004575 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004576 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004577 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004578
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004579 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4580 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004581 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004582 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004583 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004584 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004585 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004586 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004587
4588 // Try to fold constant and into select arguments.
4589 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004590 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004591 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004592 if (isa<PHINode>(Op0))
4593 if (Instruction *NV = FoldOpIntoPhi(I))
4594 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004595 }
4596
Chris Lattner4f637d42006-01-06 17:59:59 +00004597 Value *A = 0, *B = 0;
4598 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004599
4600 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4601 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4602 return ReplaceInstUsesWith(I, Op1);
4603 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4604 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4605 return ReplaceInstUsesWith(I, Op0);
4606
Chris Lattner6423d4c2006-07-10 20:25:24 +00004607 // (A | B) | C and A | (B | C) -> bswap if possible.
4608 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004609 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004610 match(Op1, m_Or(m_Value(), m_Value())) ||
4611 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4612 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004613 if (Instruction *BSwap = MatchBSwap(I))
4614 return BSwap;
4615 }
4616
Chris Lattner6e4c6492005-05-09 04:58:36 +00004617 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4618 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004619 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004620 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004621 InsertNewInstBefore(NOr, I);
4622 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004623 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004624 }
4625
4626 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4627 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004628 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004629 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004630 InsertNewInstBefore(NOr, I);
4631 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004632 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004633 }
4634
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004635 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004636 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004637 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4638 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004639 Value *V1 = 0, *V2 = 0, *V3 = 0;
4640 C1 = dyn_cast<ConstantInt>(C);
4641 C2 = dyn_cast<ConstantInt>(D);
4642 if (C1 && C2) { // (A & C1)|(B & C2)
4643 // If we have: ((V + N) & C1) | (V & C2)
4644 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4645 // replace with V+N.
4646 if (C1->getValue() == ~C2->getValue()) {
4647 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4648 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4649 // Add commutes, try both ways.
4650 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4651 return ReplaceInstUsesWith(I, A);
4652 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4653 return ReplaceInstUsesWith(I, A);
4654 }
4655 // Or commutes, try both ways.
4656 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4657 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4658 // Add commutes, try both ways.
4659 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4660 return ReplaceInstUsesWith(I, B);
4661 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4662 return ReplaceInstUsesWith(I, B);
4663 }
4664 }
Chris Lattner044e5332007-04-08 08:01:49 +00004665 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004666 }
4667
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004668 // Check to see if we have any common things being and'ed. If so, find the
4669 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004670 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4671 if (A == B) // (A & C)|(A & D) == A & (C|D)
4672 V1 = A, V2 = C, V3 = D;
4673 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4674 V1 = A, V2 = B, V3 = C;
4675 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4676 V1 = C, V2 = A, V3 = D;
4677 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4678 V1 = C, V2 = A, V3 = B;
4679
4680 if (V1) {
4681 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004682 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4683 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004684 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004685 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004686 }
Chris Lattnere511b742006-11-14 07:46:50 +00004687
4688 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004689 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4690 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4691 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004692 SI0->getOperand(1) == SI1->getOperand(1) &&
4693 (SI0->hasOneUse() || SI1->hasOneUse())) {
4694 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004695 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004696 SI1->getOperand(0),
4697 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004698 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004699 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004700 }
4701 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004702
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004703 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4704 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004705 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004706 } else {
4707 A = 0;
4708 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004709 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004710 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4711 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004712 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004713
Misha Brukmancb6267b2004-07-30 12:50:08 +00004714 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004715 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004716 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004717 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004718 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004719 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004720 }
Chris Lattnera2881962003-02-18 19:28:33 +00004721
Reid Spencere4d87aa2006-12-23 06:05:41 +00004722 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4723 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4724 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004725 return R;
4726
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004727 Value *LHSVal, *RHSVal;
4728 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004729 ICmpInst::Predicate LHSCC, RHSCC;
4730 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4731 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4732 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4733 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4734 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4735 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4736 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004737 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4738 // We can't fold (ugt x, C) | (sgt x, C2).
4739 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004740 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004741 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004742 bool NeedsSwap;
4743 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004744 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004745 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004746 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004747
4748 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004749 std::swap(LHS, RHS);
4750 std::swap(LHSCst, RHSCst);
4751 std::swap(LHSCC, RHSCC);
4752 }
4753
Reid Spencere4d87aa2006-12-23 06:05:41 +00004754 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004755 // comparing a value against two constants and or'ing the result
4756 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004757 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4758 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004759 // equal.
4760 assert(LHSCst != RHSCst && "Compares not folded above?");
4761
4762 switch (LHSCC) {
4763 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004764 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004765 switch (RHSCC) {
4766 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004767 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004768 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4769 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004770 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004771 LHSVal->getName()+".off");
4772 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004773 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004774 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004775 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004776 break; // (X == 13 | X == 15) -> no change
4777 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4778 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004779 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004780 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4781 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4782 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004783 return ReplaceInstUsesWith(I, RHS);
4784 }
4785 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004786 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004787 switch (RHSCC) {
4788 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004789 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4790 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4791 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004792 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004793 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4794 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4795 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004796 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004797 }
4798 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004799 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004800 switch (RHSCC) {
4801 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004802 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004803 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004804 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004805 // If RHSCst is [us]MAXINT, it is always false. Not handling
4806 // this can cause overflow.
4807 if (RHSCst->isMaxValue(false))
4808 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004809 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4810 false, I);
4811 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4812 break;
4813 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4814 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004815 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004816 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4817 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004818 }
4819 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004820 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004821 switch (RHSCC) {
4822 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004823 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4824 break;
4825 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004826 // If RHSCst is [us]MAXINT, it is always false. Not handling
4827 // this can cause overflow.
4828 if (RHSCst->isMaxValue(true))
4829 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004830 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4831 false, I);
4832 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4833 break;
4834 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4835 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4836 return ReplaceInstUsesWith(I, RHS);
4837 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4838 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004839 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004840 break;
4841 case ICmpInst::ICMP_UGT:
4842 switch (RHSCC) {
4843 default: assert(0 && "Unknown integer condition code!");
4844 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4845 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4846 return ReplaceInstUsesWith(I, LHS);
4847 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4848 break;
4849 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4850 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004851 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004852 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4853 break;
4854 }
4855 break;
4856 case ICmpInst::ICMP_SGT:
4857 switch (RHSCC) {
4858 default: assert(0 && "Unknown integer condition code!");
4859 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4860 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4861 return ReplaceInstUsesWith(I, LHS);
4862 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4863 break;
4864 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4865 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004866 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004867 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4868 break;
4869 }
4870 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004871 }
4872 }
4873 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004874
4875 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004876 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004877 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004878 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004879 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4880 !isa<ICmpInst>(Op1C->getOperand(0))) {
4881 const Type *SrcTy = Op0C->getOperand(0)->getType();
4882 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4883 // Only do this if the casts both really cause code to be
4884 // generated.
4885 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4886 I.getType(), TD) &&
4887 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4888 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004889 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004890 Op1C->getOperand(0),
4891 I.getName());
4892 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004893 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004894 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004895 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004896 }
Chris Lattner99c65742007-10-24 05:38:08 +00004897 }
4898
4899
4900 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4901 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4902 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4903 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004904 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4905 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004906 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4907 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4908 // If either of the constants are nans, then the whole thing returns
4909 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004910 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004911 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4912
4913 // Otherwise, no need to compare the two constants, compare the
4914 // rest.
4915 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4916 RHS->getOperand(0));
4917 }
4918 }
4919 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004920
Chris Lattner7e708292002-06-25 16:13:24 +00004921 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004922}
4923
Dan Gohman844731a2008-05-13 00:00:25 +00004924namespace {
4925
Chris Lattnerc317d392004-02-16 01:20:27 +00004926// XorSelf - Implements: X ^ X --> 0
4927struct XorSelf {
4928 Value *RHS;
4929 XorSelf(Value *rhs) : RHS(rhs) {}
4930 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4931 Instruction *apply(BinaryOperator &Xor) const {
4932 return &Xor;
4933 }
4934};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004935
Dan Gohman844731a2008-05-13 00:00:25 +00004936}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004937
Chris Lattner7e708292002-06-25 16:13:24 +00004938Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004939 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004940 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004941
Evan Chengd34af782008-03-25 20:07:13 +00004942 if (isa<UndefValue>(Op1)) {
4943 if (isa<UndefValue>(Op0))
4944 // Handle undef ^ undef -> 0 special case. This is a common
4945 // idiom (misuse).
4946 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004947 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004948 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004949
Chris Lattnerc317d392004-02-16 01:20:27 +00004950 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4951 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004952 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004953 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004954 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004955
4956 // See if we can simplify any instructions used by the instruction whose sole
4957 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004958 if (!isa<VectorType>(I.getType())) {
4959 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4960 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4961 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4962 KnownZero, KnownOne))
4963 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004964 } else if (isa<ConstantAggregateZero>(Op1)) {
4965 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004966 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004967
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004968 // Is this a ~ operation?
4969 if (Value *NotOp = dyn_castNotVal(&I)) {
4970 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4971 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4972 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4973 if (Op0I->getOpcode() == Instruction::And ||
4974 Op0I->getOpcode() == Instruction::Or) {
4975 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4976 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4977 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004978 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004979 Op0I->getOperand(1)->getName()+".not");
4980 InsertNewInstBefore(NotY, I);
4981 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004982 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004983 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004984 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004985 }
4986 }
4987 }
4988 }
4989
4990
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004991 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004992 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4993 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4994 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004995 return new ICmpInst(ICI->getInversePredicate(),
4996 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004997
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004998 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4999 return new FCmpInst(FCI->getInversePredicate(),
5000 FCI->getOperand(0), FCI->getOperand(1));
5001 }
5002
Reid Spencere4d87aa2006-12-23 06:05:41 +00005003 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005004 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005005 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5006 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00005007 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5008 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005009 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005010 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005011 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005012
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005013 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005014 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005015 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005016 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00005017 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005018 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00005019 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005020 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00005021 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005022 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005023 // (X + C) ^ signbit -> (X + C + signbit)
5024 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005025 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005026
Chris Lattner7c4049c2004-01-12 19:35:11 +00005027 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005028 } else if (Op0I->getOpcode() == Instruction::Or) {
5029 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005030 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00005031 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5032 // Anything in both C1 and C2 is known to be zero, remove it from
5033 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005034 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005035 NewRHS = ConstantExpr::getAnd(NewRHS,
5036 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005037 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005038 I.setOperand(0, Op0I->getOperand(0));
5039 I.setOperand(1, NewRHS);
5040 return &I;
5041 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005042 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005043 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005044 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005045
5046 // Try to fold constant and into select arguments.
5047 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005048 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005049 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005050 if (isa<PHINode>(Op0))
5051 if (Instruction *NV = FoldOpIntoPhi(I))
5052 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005053 }
5054
Chris Lattner8d969642003-03-10 23:06:50 +00005055 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005056 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005057 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005058
Chris Lattner8d969642003-03-10 23:06:50 +00005059 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005060 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005061 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005062
Chris Lattner318bf792007-03-18 22:51:34 +00005063
5064 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5065 if (Op1I) {
5066 Value *A, *B;
5067 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5068 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005069 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005070 I.swapOperands();
5071 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005072 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005073 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005074 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005075 }
Chris Lattner318bf792007-03-18 22:51:34 +00005076 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
5077 if (Op0 == A) // A^(A^B) == B
5078 return ReplaceInstUsesWith(I, B);
5079 else if (Op0 == B) // A^(B^A) == B
5080 return ReplaceInstUsesWith(I, A);
5081 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005082 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005083 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005084 std::swap(A, B);
5085 }
Chris Lattner318bf792007-03-18 22:51:34 +00005086 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005087 I.swapOperands(); // Simplified below.
5088 std::swap(Op0, Op1);
5089 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005090 }
Chris Lattner318bf792007-03-18 22:51:34 +00005091 }
5092
5093 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5094 if (Op0I) {
5095 Value *A, *B;
5096 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5097 if (A == Op1) // (B|A)^B == (A|B)^B
5098 std::swap(A, B);
5099 if (B == Op1) { // (A|B)^B == A & ~B
5100 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005101 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5102 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005103 }
Chris Lattner318bf792007-03-18 22:51:34 +00005104 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
5105 if (Op1 == A) // (A^B)^A == B
5106 return ReplaceInstUsesWith(I, B);
5107 else if (Op1 == B) // (B^A)^A == B
5108 return ReplaceInstUsesWith(I, A);
5109 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5110 if (A == Op1) // (A&B)^A -> (B&A)^A
5111 std::swap(A, B);
5112 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005113 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005114 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005115 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5116 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005117 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005118 }
Chris Lattner318bf792007-03-18 22:51:34 +00005119 }
5120
5121 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5122 if (Op0I && Op1I && Op0I->isShift() &&
5123 Op0I->getOpcode() == Op1I->getOpcode() &&
5124 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5125 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5126 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005127 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005128 Op1I->getOperand(0),
5129 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005130 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005131 Op1I->getOperand(1));
5132 }
5133
5134 if (Op0I && Op1I) {
5135 Value *A, *B, *C, *D;
5136 // (A & B)^(A | B) -> A ^ B
5137 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5138 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5139 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005140 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005141 }
5142 // (A | B)^(A & B) -> A ^ B
5143 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5144 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5145 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005146 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005147 }
5148
5149 // (A & B)^(C & D)
5150 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5151 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5152 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5153 // (X & Y)^(X & Y) -> (Y^Z) & X
5154 Value *X = 0, *Y = 0, *Z = 0;
5155 if (A == C)
5156 X = A, Y = B, Z = D;
5157 else if (A == D)
5158 X = A, Y = B, Z = C;
5159 else if (B == C)
5160 X = B, Y = A, Z = D;
5161 else if (B == D)
5162 X = B, Y = A, Z = C;
5163
5164 if (X) {
5165 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005166 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5167 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005168 }
5169 }
5170 }
5171
Reid Spencere4d87aa2006-12-23 06:05:41 +00005172 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5173 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5174 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005175 return R;
5176
Chris Lattner6fc205f2006-05-05 06:39:07 +00005177 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005178 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005179 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005180 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5181 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005182 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005183 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005184 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5185 I.getType(), TD) &&
5186 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5187 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005188 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005189 Op1C->getOperand(0),
5190 I.getName());
5191 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005192 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005193 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005194 }
Chris Lattner99c65742007-10-24 05:38:08 +00005195 }
Chris Lattner7e708292002-06-25 16:13:24 +00005196 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005197}
5198
Chris Lattnera96879a2004-09-29 17:40:11 +00005199/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5200/// overflowed for this type.
5201static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005202 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005203 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005204
Reid Spencere4e40032007-03-21 23:19:50 +00005205 if (IsSigned)
5206 if (In2->getValue().isNegative())
5207 return Result->getValue().sgt(In1->getValue());
5208 else
5209 return Result->getValue().slt(In1->getValue());
5210 else
5211 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005212}
5213
Chris Lattner574da9b2005-01-13 20:14:25 +00005214/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5215/// code necessary to compute the offset from the base pointer (without adding
5216/// in the base pointer). Return the result as a signed integer of intptr size.
5217static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5218 TargetData &TD = IC.getTargetData();
5219 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005220 const Type *IntPtrTy = TD.getIntPtrType();
5221 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005222
5223 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005224 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005225 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005226
Chris Lattner574da9b2005-01-13 20:14:25 +00005227 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5228 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00005229 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005230 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5231 if (OpC->isZero()) continue;
5232
5233 // Handle a struct index, which adds its field offset to the pointer.
5234 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5235 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5236
5237 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5238 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005239 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005240 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005241 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005242 ConstantInt::get(IntPtrTy, Size),
5243 GEP->getName()+".offs"), I);
5244 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005245 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005246
5247 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5248 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5249 Scale = ConstantExpr::getMul(OC, Scale);
5250 if (Constant *RC = dyn_cast<Constant>(Result))
5251 Result = ConstantExpr::getAdd(RC, Scale);
5252 else {
5253 // Emit an add instruction.
5254 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005255 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005256 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005257 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005258 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005259 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005260 // Convert to correct type.
5261 if (Op->getType() != IntPtrTy) {
5262 if (Constant *OpC = dyn_cast<Constant>(Op))
5263 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5264 else
5265 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5266 Op->getName()+".c"), I);
5267 }
5268 if (Size != 1) {
5269 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5270 if (Constant *OpC = dyn_cast<Constant>(Op))
5271 Op = ConstantExpr::getMul(OpC, Scale);
5272 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005273 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005274 GEP->getName()+".idx"), I);
5275 }
5276
5277 // Emit an add instruction.
5278 if (isa<Constant>(Op) && isa<Constant>(Result))
5279 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5280 cast<Constant>(Result));
5281 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005282 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005283 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005284 }
5285 return Result;
5286}
5287
Chris Lattner10c0d912008-04-22 02:53:33 +00005288
5289/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5290/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5291/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5292/// complex, and scales are involved. The above expression would also be legal
5293/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5294/// later form is less amenable to optimization though, and we are allowed to
5295/// generate the first by knowing that pointer arithmetic doesn't overflow.
5296///
5297/// If we can't emit an optimized form for this expression, this returns null.
5298///
5299static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5300 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005301 TargetData &TD = IC.getTargetData();
5302 gep_type_iterator GTI = gep_type_begin(GEP);
5303
5304 // Check to see if this gep only has a single variable index. If so, and if
5305 // any constant indices are a multiple of its scale, then we can compute this
5306 // in terms of the scale of the variable index. For example, if the GEP
5307 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5308 // because the expression will cross zero at the same point.
5309 unsigned i, e = GEP->getNumOperands();
5310 int64_t Offset = 0;
5311 for (i = 1; i != e; ++i, ++GTI) {
5312 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5313 // Compute the aggregate offset of constant indices.
5314 if (CI->isZero()) continue;
5315
5316 // Handle a struct index, which adds its field offset to the pointer.
5317 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5318 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5319 } else {
5320 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5321 Offset += Size*CI->getSExtValue();
5322 }
5323 } else {
5324 // Found our variable index.
5325 break;
5326 }
5327 }
5328
5329 // If there are no variable indices, we must have a constant offset, just
5330 // evaluate it the general way.
5331 if (i == e) return 0;
5332
5333 Value *VariableIdx = GEP->getOperand(i);
5334 // Determine the scale factor of the variable element. For example, this is
5335 // 4 if the variable index is into an array of i32.
5336 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5337
5338 // Verify that there are no other variable indices. If so, emit the hard way.
5339 for (++i, ++GTI; i != e; ++i, ++GTI) {
5340 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5341 if (!CI) return 0;
5342
5343 // Compute the aggregate offset of constant indices.
5344 if (CI->isZero()) continue;
5345
5346 // Handle a struct index, which adds its field offset to the pointer.
5347 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5348 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5349 } else {
5350 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5351 Offset += Size*CI->getSExtValue();
5352 }
5353 }
5354
5355 // Okay, we know we have a single variable index, which must be a
5356 // pointer/array/vector index. If there is no offset, life is simple, return
5357 // the index.
5358 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5359 if (Offset == 0) {
5360 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5361 // we don't need to bother extending: the extension won't affect where the
5362 // computation crosses zero.
5363 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5364 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5365 VariableIdx->getNameStart(), &I);
5366 return VariableIdx;
5367 }
5368
5369 // Otherwise, there is an index. The computation we will do will be modulo
5370 // the pointer size, so get it.
5371 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5372
5373 Offset &= PtrSizeMask;
5374 VariableScale &= PtrSizeMask;
5375
5376 // To do this transformation, any constant index must be a multiple of the
5377 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5378 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5379 // multiple of the variable scale.
5380 int64_t NewOffs = Offset / (int64_t)VariableScale;
5381 if (Offset != NewOffs*(int64_t)VariableScale)
5382 return 0;
5383
5384 // Okay, we can do this evaluation. Start by converting the index to intptr.
5385 const Type *IntPtrTy = TD.getIntPtrType();
5386 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005387 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005388 true /*SExt*/,
5389 VariableIdx->getNameStart(), &I);
5390 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005391 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005392}
5393
5394
Reid Spencere4d87aa2006-12-23 06:05:41 +00005395/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005396/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005397Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5398 ICmpInst::Predicate Cond,
5399 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005400 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005401
Chris Lattner10c0d912008-04-22 02:53:33 +00005402 // Look through bitcasts.
5403 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5404 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005405
Chris Lattner574da9b2005-01-13 20:14:25 +00005406 Value *PtrBase = GEPLHS->getOperand(0);
5407 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005408 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005409 // This transformation (ignoring the base and scales) is valid because we
5410 // know pointers can't overflow. See if we can output an optimized form.
5411 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5412
5413 // If not, synthesize the offset the hard way.
5414 if (Offset == 0)
5415 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005416 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5417 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005418 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005419 // If the base pointers are different, but the indices are the same, just
5420 // compare the base pointer.
5421 if (PtrBase != GEPRHS->getOperand(0)) {
5422 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005423 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005424 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005425 if (IndicesTheSame)
5426 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5427 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5428 IndicesTheSame = false;
5429 break;
5430 }
5431
5432 // If all indices are the same, just compare the base pointers.
5433 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005434 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5435 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005436
5437 // Otherwise, the base pointers are different and the indices are
5438 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005439 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005440 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005441
Chris Lattnere9d782b2005-01-13 22:25:21 +00005442 // If one of the GEPs has all zero indices, recurse.
5443 bool AllZeros = true;
5444 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5445 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5446 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5447 AllZeros = false;
5448 break;
5449 }
5450 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005451 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5452 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005453
5454 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005455 AllZeros = true;
5456 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5457 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5458 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5459 AllZeros = false;
5460 break;
5461 }
5462 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005463 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005464
Chris Lattner4401c9c2005-01-14 00:20:05 +00005465 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5466 // If the GEPs only differ by one index, compare it.
5467 unsigned NumDifferences = 0; // Keep track of # differences.
5468 unsigned DiffOperand = 0; // The operand that differs.
5469 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5470 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005471 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5472 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005473 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005474 NumDifferences = 2;
5475 break;
5476 } else {
5477 if (NumDifferences++) break;
5478 DiffOperand = i;
5479 }
5480 }
5481
5482 if (NumDifferences == 0) // SAME GEP?
5483 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005484 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005485 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005486
Chris Lattner4401c9c2005-01-14 00:20:05 +00005487 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005488 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5489 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005490 // Make sure we do a signed comparison here.
5491 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005492 }
5493 }
5494
Reid Spencere4d87aa2006-12-23 06:05:41 +00005495 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005496 // the result to fold to a constant!
5497 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5498 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5499 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5500 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5501 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005502 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005503 }
5504 }
5505 return 0;
5506}
5507
Chris Lattnera5406232008-05-19 20:18:56 +00005508/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5509///
5510Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5511 Instruction *LHSI,
5512 Constant *RHSC) {
5513 if (!isa<ConstantFP>(RHSC)) return 0;
5514 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5515
5516 // Get the width of the mantissa. We don't want to hack on conversions that
5517 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005518 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005519 if (MantissaWidth == -1) return 0; // Unknown.
5520
5521 // Check to see that the input is converted from an integer type that is small
5522 // enough that preserves all bits. TODO: check here for "known" sign bits.
5523 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5524 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5525
5526 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5527 if (isa<UIToFPInst>(LHSI))
5528 ++InputSize;
5529
5530 // If the conversion would lose info, don't hack on this.
5531 if ((int)InputSize > MantissaWidth)
5532 return 0;
5533
5534 // Otherwise, we can potentially simplify the comparison. We know that it
5535 // will always come through as an integer value and we know the constant is
5536 // not a NAN (it would have been previously simplified).
5537 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5538
5539 ICmpInst::Predicate Pred;
5540 switch (I.getPredicate()) {
5541 default: assert(0 && "Unexpected predicate!");
5542 case FCmpInst::FCMP_UEQ:
5543 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5544 case FCmpInst::FCMP_UGT:
5545 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5546 case FCmpInst::FCMP_UGE:
5547 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5548 case FCmpInst::FCMP_ULT:
5549 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5550 case FCmpInst::FCMP_ULE:
5551 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5552 case FCmpInst::FCMP_UNE:
5553 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5554 case FCmpInst::FCMP_ORD:
5555 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5556 case FCmpInst::FCMP_UNO:
5557 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5558 }
5559
5560 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5561
5562 // Now we know that the APFloat is a normal number, zero or inf.
5563
Chris Lattner85162782008-05-20 03:50:52 +00005564 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005565 // comparing an i8 to 300.0.
5566 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5567
5568 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5569 // and large values.
5570 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5571 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5572 APFloat::rmNearestTiesToEven);
5573 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5574 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5575 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5576 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5577 }
5578
5579 // See if the RHS value is < SignedMin.
5580 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5581 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5582 APFloat::rmNearestTiesToEven);
5583 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5584 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5585 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5586 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5587 }
5588
5589 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5590 // it may still be fractional. See if it is fractional by casting the FP
5591 // value to the integer value and back, checking for equality. Don't do this
5592 // for zero, because -0.0 is not fractional.
5593 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5594 if (!RHS.isZero() &&
5595 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5596 // If we had a comparison against a fractional value, we have to adjust
5597 // the compare predicate and sometimes the value. RHSC is rounded towards
5598 // zero at this point.
5599 switch (Pred) {
5600 default: assert(0 && "Unexpected integer comparison!");
5601 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5602 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5603 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5604 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5605 case ICmpInst::ICMP_SLE:
5606 // (float)int <= 4.4 --> int <= 4
5607 // (float)int <= -4.4 --> int < -4
5608 if (RHS.isNegative())
5609 Pred = ICmpInst::ICMP_SLT;
5610 break;
5611 case ICmpInst::ICMP_SLT:
5612 // (float)int < -4.4 --> int < -4
5613 // (float)int < 4.4 --> int <= 4
5614 if (!RHS.isNegative())
5615 Pred = ICmpInst::ICMP_SLE;
5616 break;
5617 case ICmpInst::ICMP_SGT:
5618 // (float)int > 4.4 --> int > 4
5619 // (float)int > -4.4 --> int >= -4
5620 if (RHS.isNegative())
5621 Pred = ICmpInst::ICMP_SGE;
5622 break;
5623 case ICmpInst::ICMP_SGE:
5624 // (float)int >= -4.4 --> int >= -4
5625 // (float)int >= 4.4 --> int > 4
5626 if (!RHS.isNegative())
5627 Pred = ICmpInst::ICMP_SGT;
5628 break;
5629 }
5630 }
5631
5632 // Lower this FP comparison into an appropriate integer version of the
5633 // comparison.
5634 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5635}
5636
Reid Spencere4d87aa2006-12-23 06:05:41 +00005637Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5638 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005639 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005640
Chris Lattner58e97462007-01-14 19:42:17 +00005641 // Fold trivial predicates.
5642 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5643 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5644 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5645 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5646
5647 // Simplify 'fcmp pred X, X'
5648 if (Op0 == Op1) {
5649 switch (I.getPredicate()) {
5650 default: assert(0 && "Unknown predicate!");
5651 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5652 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5653 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5654 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5655 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5656 case FCmpInst::FCMP_OLT: // True if ordered and less than
5657 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5658 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5659
5660 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5661 case FCmpInst::FCMP_ULT: // True if unordered or less than
5662 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5663 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5664 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5665 I.setPredicate(FCmpInst::FCMP_UNO);
5666 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5667 return &I;
5668
5669 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5670 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5671 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5672 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5673 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5674 I.setPredicate(FCmpInst::FCMP_ORD);
5675 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5676 return &I;
5677 }
5678 }
5679
Reid Spencere4d87aa2006-12-23 06:05:41 +00005680 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005681 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005682
Reid Spencere4d87aa2006-12-23 06:05:41 +00005683 // Handle fcmp with constant RHS
5684 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005685 // If the constant is a nan, see if we can fold the comparison based on it.
5686 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5687 if (CFP->getValueAPF().isNaN()) {
5688 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5689 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005690 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5691 "Comparison must be either ordered or unordered!");
5692 // True if unordered.
5693 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005694 }
5695 }
5696
Reid Spencere4d87aa2006-12-23 06:05:41 +00005697 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5698 switch (LHSI->getOpcode()) {
5699 case Instruction::PHI:
5700 if (Instruction *NV = FoldOpIntoPhi(I))
5701 return NV;
5702 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005703 case Instruction::SIToFP:
5704 case Instruction::UIToFP:
5705 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5706 return NV;
5707 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005708 case Instruction::Select:
5709 // If either operand of the select is a constant, we can fold the
5710 // comparison into the select arms, which will cause one to be
5711 // constant folded and the select turned into a bitwise or.
5712 Value *Op1 = 0, *Op2 = 0;
5713 if (LHSI->hasOneUse()) {
5714 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5715 // Fold the known value into the constant operand.
5716 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5717 // Insert a new FCmp of the other select operand.
5718 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5719 LHSI->getOperand(2), RHSC,
5720 I.getName()), I);
5721 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5722 // Fold the known value into the constant operand.
5723 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5724 // Insert a new FCmp of the other select operand.
5725 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5726 LHSI->getOperand(1), RHSC,
5727 I.getName()), I);
5728 }
5729 }
5730
5731 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005732 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005733 break;
5734 }
5735 }
5736
5737 return Changed ? &I : 0;
5738}
5739
5740Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5741 bool Changed = SimplifyCompare(I);
5742 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5743 const Type *Ty = Op0->getType();
5744
5745 // icmp X, X
5746 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005747 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005748 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005749
5750 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005751 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005752
Reid Spencere4d87aa2006-12-23 06:05:41 +00005753 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005754 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005755 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5756 isa<ConstantPointerNull>(Op0)) &&
5757 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005758 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005759 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005760 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005761
Reid Spencere4d87aa2006-12-23 06:05:41 +00005762 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005763 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005764 switch (I.getPredicate()) {
5765 default: assert(0 && "Invalid icmp instruction!");
5766 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005767 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005768 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005769 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005770 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005771 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005772 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005773
Reid Spencere4d87aa2006-12-23 06:05:41 +00005774 case ICmpInst::ICMP_UGT:
5775 case ICmpInst::ICMP_SGT:
5776 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005777 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005778 case ICmpInst::ICMP_ULT:
5779 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005780 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005781 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005782 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005783 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005784 case ICmpInst::ICMP_UGE:
5785 case ICmpInst::ICMP_SGE:
5786 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005787 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005788 case ICmpInst::ICMP_ULE:
5789 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005790 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005791 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005792 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005793 }
5794 }
Chris Lattner8b170942002-08-09 23:47:40 +00005795 }
5796
Chris Lattner2be51ae2004-06-09 04:24:29 +00005797 // See if we are doing a comparison between a constant and an instruction that
5798 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005799 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005800 Value *A, *B;
5801
Chris Lattnerb6566012008-01-05 01:18:20 +00005802 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5803 if (I.isEquality() && CI->isNullValue() &&
5804 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5805 // (icmp cond A B) if cond is equality
5806 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005807 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005808
Reid Spencere4d87aa2006-12-23 06:05:41 +00005809 switch (I.getPredicate()) {
5810 default: break;
5811 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5812 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005813 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005814 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5815 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5816 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5817 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005818 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5819 if (CI->isMinValue(true))
5820 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5821 ConstantInt::getAllOnesValue(Op0->getType()));
5822
Reid Spencere4d87aa2006-12-23 06:05:41 +00005823 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005824
Reid Spencere4d87aa2006-12-23 06:05:41 +00005825 case ICmpInst::ICMP_SLT:
5826 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005827 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005828 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5829 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5830 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5831 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5832 break;
5833
5834 case ICmpInst::ICMP_UGT:
5835 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005836 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005837 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5838 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5839 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5840 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005841
5842 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5843 if (CI->isMaxValue(true))
5844 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5845 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005846 break;
5847
5848 case ICmpInst::ICMP_SGT:
5849 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005850 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005851 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5852 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5853 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5854 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5855 break;
5856
5857 case ICmpInst::ICMP_ULE:
5858 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005859 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005860 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5861 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5862 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5863 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5864 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005865
Reid Spencere4d87aa2006-12-23 06:05:41 +00005866 case ICmpInst::ICMP_SLE:
5867 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005868 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005869 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5870 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5871 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5872 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5873 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005874
Reid Spencere4d87aa2006-12-23 06:05:41 +00005875 case ICmpInst::ICMP_UGE:
5876 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005877 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005878 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5879 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5880 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5881 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5882 break;
5883
5884 case ICmpInst::ICMP_SGE:
5885 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005886 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005887 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5888 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5889 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5890 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5891 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005892 }
5893
Reid Spencere4d87aa2006-12-23 06:05:41 +00005894 // If we still have a icmp le or icmp ge instruction, turn it into the
5895 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005896 // already been handled above, this requires little checking.
5897 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005898 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005899 default: break;
5900 case ICmpInst::ICMP_ULE:
5901 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5902 case ICmpInst::ICMP_SLE:
5903 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5904 case ICmpInst::ICMP_UGE:
5905 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5906 case ICmpInst::ICMP_SGE:
5907 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005908 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005909
5910 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005911 // in the input. If this comparison is a normal comparison, it demands all
5912 // bits, if it is a sign bit comparison, it only demands the sign bit.
5913
5914 bool UnusedBit;
5915 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5916
Reid Spencer0460fb32007-03-22 20:36:03 +00005917 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5918 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005919 if (SimplifyDemandedBits(Op0,
5920 isSignBit ? APInt::getSignBit(BitWidth)
5921 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005922 KnownZero, KnownOne, 0))
5923 return &I;
5924
5925 // Given the known and unknown bits, compute a range that the LHS could be
5926 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005927 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005928 // Compute the Min, Max and RHS values based on the known bits. For the
5929 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005930 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5931 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005932 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005933 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5934 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005935 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005936 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5937 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005938 }
5939 switch (I.getPredicate()) { // LE/GE have been folded already.
5940 default: assert(0 && "Unknown icmp opcode!");
5941 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005942 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005943 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005944 break;
5945 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005946 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005947 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005948 break;
5949 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005950 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005951 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005952 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005953 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005954 break;
5955 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005956 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005957 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005958 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005959 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005960 break;
5961 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005962 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005963 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005964 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005965 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005966 break;
5967 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005968 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005969 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005970 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005971 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005972 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005973 }
5974 }
5975
Reid Spencere4d87aa2006-12-23 06:05:41 +00005976 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005977 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005978 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005979 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005980 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5981 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005982 }
5983
Chris Lattner01deb9d2007-04-03 17:43:25 +00005984 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005985 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5986 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5987 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005988 case Instruction::GetElementPtr:
5989 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005990 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005991 bool isAllZeros = true;
5992 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5993 if (!isa<Constant>(LHSI->getOperand(i)) ||
5994 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5995 isAllZeros = false;
5996 break;
5997 }
5998 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005999 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00006000 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6001 }
6002 break;
6003
Chris Lattner6970b662005-04-23 15:31:55 +00006004 case Instruction::PHI:
6005 if (Instruction *NV = FoldOpIntoPhi(I))
6006 return NV;
6007 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006008 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006009 // If either operand of the select is a constant, we can fold the
6010 // comparison into the select arms, which will cause one to be
6011 // constant folded and the select turned into a bitwise or.
6012 Value *Op1 = 0, *Op2 = 0;
6013 if (LHSI->hasOneUse()) {
6014 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6015 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006016 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6017 // Insert a new ICmp of the other select operand.
6018 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6019 LHSI->getOperand(2), RHSC,
6020 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006021 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6022 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006023 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6024 // Insert a new ICmp of the other select operand.
6025 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6026 LHSI->getOperand(1), RHSC,
6027 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006028 }
6029 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006030
Chris Lattner6970b662005-04-23 15:31:55 +00006031 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006032 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006033 break;
6034 }
Chris Lattner4802d902007-04-06 18:57:34 +00006035 case Instruction::Malloc:
6036 // If we have (malloc != null), and if the malloc has a single use, we
6037 // can assume it is successful and remove the malloc.
6038 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6039 AddToWorkList(LHSI);
6040 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006041 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006042 }
6043 break;
6044 }
Chris Lattner6970b662005-04-23 15:31:55 +00006045 }
6046
Reid Spencere4d87aa2006-12-23 06:05:41 +00006047 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006048 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006049 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006050 return NI;
6051 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006052 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6053 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006054 return NI;
6055
Reid Spencere4d87aa2006-12-23 06:05:41 +00006056 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006057 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6058 // now.
6059 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6060 if (isa<PointerType>(Op0->getType()) &&
6061 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006062 // We keep moving the cast from the left operand over to the right
6063 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006064 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006065
Chris Lattner57d86372007-01-06 01:45:59 +00006066 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6067 // so eliminate it as well.
6068 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6069 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006070
Chris Lattnerde90b762003-11-03 04:25:02 +00006071 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006072 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006073 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006074 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006075 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006076 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006077 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006078 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006079 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006080 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006081 }
Chris Lattner57d86372007-01-06 01:45:59 +00006082 }
6083
6084 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006085 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006086 // This comes up when you have code like
6087 // int X = A < B;
6088 // if (X) ...
6089 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006090 // with a constant or another cast from the same type.
6091 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006092 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006093 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006094 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006095
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006096 // ~x < ~y --> y < x
6097 { Value *A, *B;
6098 if (match(Op0, m_Not(m_Value(A))) &&
6099 match(Op1, m_Not(m_Value(B))))
6100 return new ICmpInst(I.getPredicate(), B, A);
6101 }
6102
Chris Lattner65b72ba2006-09-18 04:22:48 +00006103 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006104 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006105
6106 // -x == -y --> x == y
6107 if (match(Op0, m_Neg(m_Value(A))) &&
6108 match(Op1, m_Neg(m_Value(B))))
6109 return new ICmpInst(I.getPredicate(), A, B);
6110
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006111 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6112 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6113 Value *OtherVal = A == Op1 ? B : A;
6114 return new ICmpInst(I.getPredicate(), OtherVal,
6115 Constant::getNullValue(A->getType()));
6116 }
6117
6118 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6119 // A^c1 == C^c2 --> A == C^(c1^c2)
6120 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6121 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6122 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006123 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006124 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006125 return new ICmpInst(I.getPredicate(), A,
6126 InsertNewInstBefore(Xor, I));
6127 }
6128
6129 // A^B == A^D -> B == D
6130 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6131 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6132 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6133 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6134 }
6135 }
6136
6137 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6138 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006139 // A == (A^B) -> B == 0
6140 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006141 return new ICmpInst(I.getPredicate(), OtherVal,
6142 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006143 }
6144 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006145 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006146 return new ICmpInst(I.getPredicate(), B,
6147 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006148 }
6149 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006150 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006151 return new ICmpInst(I.getPredicate(), B,
6152 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00006153 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00006154
Chris Lattner9c2328e2006-11-14 06:06:06 +00006155 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6156 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6157 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6158 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6159 Value *X = 0, *Y = 0, *Z = 0;
6160
6161 if (A == C) {
6162 X = B; Y = D; Z = A;
6163 } else if (A == D) {
6164 X = B; Y = C; Z = A;
6165 } else if (B == C) {
6166 X = A; Y = D; Z = B;
6167 } else if (B == D) {
6168 X = A; Y = C; Z = B;
6169 }
6170
6171 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006172 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6173 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006174 I.setOperand(0, Op1);
6175 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6176 return &I;
6177 }
6178 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006179 }
Chris Lattner7e708292002-06-25 16:13:24 +00006180 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006181}
6182
Chris Lattner562ef782007-06-20 23:46:26 +00006183
6184/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6185/// and CmpRHS are both known to be integer constants.
6186Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6187 ConstantInt *DivRHS) {
6188 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6189 const APInt &CmpRHSV = CmpRHS->getValue();
6190
6191 // FIXME: If the operand types don't match the type of the divide
6192 // then don't attempt this transform. The code below doesn't have the
6193 // logic to deal with a signed divide and an unsigned compare (and
6194 // vice versa). This is because (x /s C1) <s C2 produces different
6195 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6196 // (x /u C1) <u C2. Simply casting the operands and result won't
6197 // work. :( The if statement below tests that condition and bails
6198 // if it finds it.
6199 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6200 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6201 return 0;
6202 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006203 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00006204
6205 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6206 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6207 // C2 (CI). By solving for X we can turn this into a range check
6208 // instead of computing a divide.
6209 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6210
6211 // Determine if the product overflows by seeing if the product is
6212 // not equal to the divide. Make sure we do the same kind of divide
6213 // as in the LHS instruction that we're folding.
6214 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6215 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6216
6217 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006218 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006219
Chris Lattner1dbfd482007-06-21 18:11:19 +00006220 // Figure out the interval that is being checked. For example, a comparison
6221 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6222 // Compute this interval based on the constants involved and the signedness of
6223 // the compare/divide. This computes a half-open interval, keeping track of
6224 // whether either value in the interval overflows. After analysis each
6225 // overflow variable is set to 0 if it's corresponding bound variable is valid
6226 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6227 int LoOverflow = 0, HiOverflow = 0;
6228 ConstantInt *LoBound = 0, *HiBound = 0;
6229
6230
Chris Lattner562ef782007-06-20 23:46:26 +00006231 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006232 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006233 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006234 HiOverflow = LoOverflow = ProdOV;
6235 if (!HiOverflow)
6236 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006237 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006238 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006239 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006240 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6241 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006242 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006243 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6244 HiOverflow = LoOverflow = ProdOV;
6245 if (!HiOverflow)
6246 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006247 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006248 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006249 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
6250 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00006251 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006252 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006253 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006254 }
Dan Gohman76491272008-02-13 22:09:18 +00006255 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006256 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006257 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006258 LoBound = AddOne(DivRHS);
6259 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006260 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6261 HiOverflow = 1; // [INTMIN+1, overflow)
6262 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6263 }
Dan Gohman76491272008-02-13 22:09:18 +00006264 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006265 // e.g. X/-5 op 3 --> [-19, -14)
6266 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006267 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006268 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00006269 HiBound = AddOne(Prod);
6270 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006271 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006272 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006273 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006274 HiBound = Subtract(Prod, DivRHS);
6275 }
6276
Chris Lattner1dbfd482007-06-21 18:11:19 +00006277 // Dividing by a negative swaps the condition. LT <-> GT
6278 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006279 }
6280
6281 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006282 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006283 default: assert(0 && "Unhandled icmp opcode!");
6284 case ICmpInst::ICMP_EQ:
6285 if (LoOverflow && HiOverflow)
6286 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6287 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006288 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006289 ICmpInst::ICMP_UGE, X, LoBound);
6290 else if (LoOverflow)
6291 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6292 ICmpInst::ICMP_ULT, X, HiBound);
6293 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006294 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006295 case ICmpInst::ICMP_NE:
6296 if (LoOverflow && HiOverflow)
6297 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6298 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006299 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006300 ICmpInst::ICMP_ULT, X, LoBound);
6301 else if (LoOverflow)
6302 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6303 ICmpInst::ICMP_UGE, X, HiBound);
6304 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006305 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006306 case ICmpInst::ICMP_ULT:
6307 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006308 if (LoOverflow == +1) // Low bound is greater than input range.
6309 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6310 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006311 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006312 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006313 case ICmpInst::ICMP_UGT:
6314 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006315 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006316 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006317 else if (HiOverflow == -1) // High bound less than input range.
6318 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6319 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006320 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6321 else
6322 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6323 }
6324}
6325
6326
Chris Lattner01deb9d2007-04-03 17:43:25 +00006327/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6328///
6329Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6330 Instruction *LHSI,
6331 ConstantInt *RHS) {
6332 const APInt &RHSV = RHS->getValue();
6333
6334 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00006335 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006336 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6337 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6338 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006339 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6340 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006341 Value *CompareVal = LHSI->getOperand(0);
6342
6343 // If the sign bit of the XorCST is not set, there is no change to
6344 // the operation, just stop using the Xor.
6345 if (!XorCST->getValue().isNegative()) {
6346 ICI.setOperand(0, CompareVal);
6347 AddToWorkList(LHSI);
6348 return &ICI;
6349 }
6350
6351 // Was the old condition true if the operand is positive?
6352 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6353
6354 // If so, the new one isn't.
6355 isTrueIfPositive ^= true;
6356
6357 if (isTrueIfPositive)
6358 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6359 else
6360 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6361 }
6362 }
6363 break;
6364 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6365 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6366 LHSI->getOperand(0)->hasOneUse()) {
6367 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6368
6369 // If the LHS is an AND of a truncating cast, we can widen the
6370 // and/compare to be the input width without changing the value
6371 // produced, eliminating a cast.
6372 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6373 // We can do this transformation if either the AND constant does not
6374 // have its sign bit set or if it is an equality comparison.
6375 // Extending a relational comparison when we're checking the sign
6376 // bit would not work.
6377 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006378 (ICI.isEquality() ||
6379 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006380 uint32_t BitWidth =
6381 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6382 APInt NewCST = AndCST->getValue();
6383 NewCST.zext(BitWidth);
6384 APInt NewCI = RHSV;
6385 NewCI.zext(BitWidth);
6386 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006387 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006388 ConstantInt::get(NewCST),LHSI->getName());
6389 InsertNewInstBefore(NewAnd, ICI);
6390 return new ICmpInst(ICI.getPredicate(), NewAnd,
6391 ConstantInt::get(NewCI));
6392 }
6393 }
6394
6395 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6396 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6397 // happens a LOT in code produced by the C front-end, for bitfield
6398 // access.
6399 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6400 if (Shift && !Shift->isShift())
6401 Shift = 0;
6402
6403 ConstantInt *ShAmt;
6404 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6405 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6406 const Type *AndTy = AndCST->getType(); // Type of the and.
6407
6408 // We can fold this as long as we can't shift unknown bits
6409 // into the mask. This can only happen with signed shift
6410 // rights, as they sign-extend.
6411 if (ShAmt) {
6412 bool CanFold = Shift->isLogicalShift();
6413 if (!CanFold) {
6414 // To test for the bad case of the signed shr, see if any
6415 // of the bits shifted in could be tested after the mask.
6416 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6417 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6418
6419 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6420 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6421 AndCST->getValue()) == 0)
6422 CanFold = true;
6423 }
6424
6425 if (CanFold) {
6426 Constant *NewCst;
6427 if (Shift->getOpcode() == Instruction::Shl)
6428 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6429 else
6430 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6431
6432 // Check to see if we are shifting out any of the bits being
6433 // compared.
6434 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6435 // If we shifted bits out, the fold is not going to work out.
6436 // As a special case, check to see if this means that the
6437 // result is always true or false now.
6438 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6439 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6440 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6441 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6442 } else {
6443 ICI.setOperand(1, NewCst);
6444 Constant *NewAndCST;
6445 if (Shift->getOpcode() == Instruction::Shl)
6446 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6447 else
6448 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6449 LHSI->setOperand(1, NewAndCST);
6450 LHSI->setOperand(0, Shift->getOperand(0));
6451 AddToWorkList(Shift); // Shift is dead.
6452 AddUsesToWorkList(ICI);
6453 return &ICI;
6454 }
6455 }
6456 }
6457
6458 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6459 // preferable because it allows the C<<Y expression to be hoisted out
6460 // of a loop if Y is invariant and X is not.
6461 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6462 ICI.isEquality() && !Shift->isArithmeticShift() &&
6463 isa<Instruction>(Shift->getOperand(0))) {
6464 // Compute C << Y.
6465 Value *NS;
6466 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006467 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006468 Shift->getOperand(1), "tmp");
6469 } else {
6470 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006471 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006472 Shift->getOperand(1), "tmp");
6473 }
6474 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6475
6476 // Compute X & (C << Y).
6477 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006478 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006479 InsertNewInstBefore(NewAnd, ICI);
6480
6481 ICI.setOperand(0, NewAnd);
6482 return &ICI;
6483 }
6484 }
6485 break;
6486
Chris Lattnera0141b92007-07-15 20:42:37 +00006487 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6488 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6489 if (!ShAmt) break;
6490
6491 uint32_t TypeBits = RHSV.getBitWidth();
6492
6493 // Check that the shift amount is in range. If not, don't perform
6494 // undefined shifts. When the shift is visited it will be
6495 // simplified.
6496 if (ShAmt->uge(TypeBits))
6497 break;
6498
6499 if (ICI.isEquality()) {
6500 // If we are comparing against bits always shifted out, the
6501 // comparison cannot succeed.
6502 Constant *Comp =
6503 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6504 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6505 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6506 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6507 return ReplaceInstUsesWith(ICI, Cst);
6508 }
6509
6510 if (LHSI->hasOneUse()) {
6511 // Otherwise strength reduce the shift into an and.
6512 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6513 Constant *Mask =
6514 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006515
Chris Lattnera0141b92007-07-15 20:42:37 +00006516 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006517 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006518 Mask, LHSI->getName()+".mask");
6519 Value *And = InsertNewInstBefore(AndI, ICI);
6520 return new ICmpInst(ICI.getPredicate(), And,
6521 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006522 }
6523 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006524
6525 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6526 bool TrueIfSigned = false;
6527 if (LHSI->hasOneUse() &&
6528 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6529 // (X << 31) <s 0 --> (X&1) != 0
6530 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6531 (TypeBits-ShAmt->getZExtValue()-1));
6532 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006533 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006534 Mask, LHSI->getName()+".mask");
6535 Value *And = InsertNewInstBefore(AndI, ICI);
6536
6537 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6538 And, Constant::getNullValue(And->getType()));
6539 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006540 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006541 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006542
6543 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006544 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006545 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006546 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006547 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006548
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006549 // Check that the shift amount is in range. If not, don't perform
6550 // undefined shifts. When the shift is visited it will be
6551 // simplified.
6552 uint32_t TypeBits = RHSV.getBitWidth();
6553 if (ShAmt->uge(TypeBits))
6554 break;
6555
6556 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006557
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006558 // If we are comparing against bits always shifted out, the
6559 // comparison cannot succeed.
6560 APInt Comp = RHSV << ShAmtVal;
6561 if (LHSI->getOpcode() == Instruction::LShr)
6562 Comp = Comp.lshr(ShAmtVal);
6563 else
6564 Comp = Comp.ashr(ShAmtVal);
6565
6566 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6567 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6568 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6569 return ReplaceInstUsesWith(ICI, Cst);
6570 }
6571
6572 // Otherwise, check to see if the bits shifted out are known to be zero.
6573 // If so, we can compare against the unshifted value:
6574 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006575 if (LHSI->hasOneUse() &&
6576 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006577 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6578 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6579 ConstantExpr::getShl(RHS, ShAmt));
6580 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006581
Evan Chengf30752c2008-04-23 00:38:06 +00006582 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006583 // Otherwise strength reduce the shift into an and.
6584 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6585 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006586
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006587 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006588 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006589 Mask, LHSI->getName()+".mask");
6590 Value *And = InsertNewInstBefore(AndI, ICI);
6591 return new ICmpInst(ICI.getPredicate(), And,
6592 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006593 }
6594 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006595 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006596
6597 case Instruction::SDiv:
6598 case Instruction::UDiv:
6599 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6600 // Fold this div into the comparison, producing a range check.
6601 // Determine, based on the divide type, what the range is being
6602 // checked. If there is an overflow on the low or high side, remember
6603 // it, otherwise compute the range [low, hi) bounding the new value.
6604 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006605 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6606 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6607 DivRHS))
6608 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006609 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006610
6611 case Instruction::Add:
6612 // Fold: icmp pred (add, X, C1), C2
6613
6614 if (!ICI.isEquality()) {
6615 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6616 if (!LHSC) break;
6617 const APInt &LHSV = LHSC->getValue();
6618
6619 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6620 .subtract(LHSV);
6621
6622 if (ICI.isSignedPredicate()) {
6623 if (CR.getLower().isSignBit()) {
6624 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6625 ConstantInt::get(CR.getUpper()));
6626 } else if (CR.getUpper().isSignBit()) {
6627 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6628 ConstantInt::get(CR.getLower()));
6629 }
6630 } else {
6631 if (CR.getLower().isMinValue()) {
6632 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6633 ConstantInt::get(CR.getUpper()));
6634 } else if (CR.getUpper().isMinValue()) {
6635 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6636 ConstantInt::get(CR.getLower()));
6637 }
6638 }
6639 }
6640 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006641 }
6642
6643 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6644 if (ICI.isEquality()) {
6645 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6646
6647 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6648 // the second operand is a constant, simplify a bit.
6649 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6650 switch (BO->getOpcode()) {
6651 case Instruction::SRem:
6652 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6653 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6654 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6655 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6656 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006657 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006658 BO->getName());
6659 InsertNewInstBefore(NewRem, ICI);
6660 return new ICmpInst(ICI.getPredicate(), NewRem,
6661 Constant::getNullValue(BO->getType()));
6662 }
6663 }
6664 break;
6665 case Instruction::Add:
6666 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6667 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6668 if (BO->hasOneUse())
6669 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6670 Subtract(RHS, BOp1C));
6671 } else if (RHSV == 0) {
6672 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6673 // efficiently invertible, or if the add has just this one use.
6674 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6675
6676 if (Value *NegVal = dyn_castNegVal(BOp1))
6677 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6678 else if (Value *NegVal = dyn_castNegVal(BOp0))
6679 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6680 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006681 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006682 InsertNewInstBefore(Neg, ICI);
6683 Neg->takeName(BO);
6684 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6685 }
6686 }
6687 break;
6688 case Instruction::Xor:
6689 // For the xor case, we can xor two constants together, eliminating
6690 // the explicit xor.
6691 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6692 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6693 ConstantExpr::getXor(RHS, BOC));
6694
6695 // FALLTHROUGH
6696 case Instruction::Sub:
6697 // Replace (([sub|xor] A, B) != 0) with (A != B)
6698 if (RHSV == 0)
6699 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6700 BO->getOperand(1));
6701 break;
6702
6703 case Instruction::Or:
6704 // If bits are being or'd in that are not present in the constant we
6705 // are comparing against, then the comparison could never succeed!
6706 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6707 Constant *NotCI = ConstantExpr::getNot(RHS);
6708 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6709 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6710 isICMP_NE));
6711 }
6712 break;
6713
6714 case Instruction::And:
6715 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6716 // If bits are being compared against that are and'd out, then the
6717 // comparison can never succeed!
6718 if ((RHSV & ~BOC->getValue()) != 0)
6719 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6720 isICMP_NE));
6721
6722 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6723 if (RHS == BOC && RHSV.isPowerOf2())
6724 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6725 ICmpInst::ICMP_NE, LHSI,
6726 Constant::getNullValue(RHS->getType()));
6727
6728 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6729 if (isSignBit(BOC)) {
6730 Value *X = BO->getOperand(0);
6731 Constant *Zero = Constant::getNullValue(X->getType());
6732 ICmpInst::Predicate pred = isICMP_NE ?
6733 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6734 return new ICmpInst(pred, X, Zero);
6735 }
6736
6737 // ((X & ~7) == 0) --> X < 8
6738 if (RHSV == 0 && isHighOnes(BOC)) {
6739 Value *X = BO->getOperand(0);
6740 Constant *NegX = ConstantExpr::getNeg(BOC);
6741 ICmpInst::Predicate pred = isICMP_NE ?
6742 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6743 return new ICmpInst(pred, X, NegX);
6744 }
6745 }
6746 default: break;
6747 }
6748 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6749 // Handle icmp {eq|ne} <intrinsic>, intcst.
6750 if (II->getIntrinsicID() == Intrinsic::bswap) {
6751 AddToWorkList(II);
6752 ICI.setOperand(0, II->getOperand(1));
6753 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6754 return &ICI;
6755 }
6756 }
6757 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006758 // If the LHS is a cast from an integral value of the same size,
6759 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006760 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6761 Value *CastOp = Cast->getOperand(0);
6762 const Type *SrcTy = CastOp->getType();
6763 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6764 if (SrcTy->isInteger() &&
6765 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6766 // If this is an unsigned comparison, try to make the comparison use
6767 // smaller constant values.
6768 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6769 // X u< 128 => X s> -1
6770 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6771 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6772 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6773 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6774 // X u> 127 => X s< 0
6775 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6776 Constant::getNullValue(SrcTy));
6777 }
6778 }
6779 }
6780 }
6781 return 0;
6782}
6783
6784/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6785/// We only handle extending casts so far.
6786///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006787Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6788 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006789 Value *LHSCIOp = LHSCI->getOperand(0);
6790 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006791 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006792 Value *RHSCIOp;
6793
Chris Lattner8c756c12007-05-05 22:41:33 +00006794 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6795 // integer type is the same size as the pointer type.
6796 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6797 getTargetData().getPointerSizeInBits() ==
6798 cast<IntegerType>(DestTy)->getBitWidth()) {
6799 Value *RHSOp = 0;
6800 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006801 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006802 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6803 RHSOp = RHSC->getOperand(0);
6804 // If the pointer types don't match, insert a bitcast.
6805 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006806 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006807 }
6808
6809 if (RHSOp)
6810 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6811 }
6812
6813 // The code below only handles extension cast instructions, so far.
6814 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006815 if (LHSCI->getOpcode() != Instruction::ZExt &&
6816 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006817 return 0;
6818
Reid Spencere4d87aa2006-12-23 06:05:41 +00006819 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6820 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006821
Reid Spencere4d87aa2006-12-23 06:05:41 +00006822 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006823 // Not an extension from the same type?
6824 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006825 if (RHSCIOp->getType() != LHSCIOp->getType())
6826 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006827
Nick Lewycky4189a532008-01-28 03:48:02 +00006828 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006829 // and the other is a zext), then we can't handle this.
6830 if (CI->getOpcode() != LHSCI->getOpcode())
6831 return 0;
6832
Nick Lewycky4189a532008-01-28 03:48:02 +00006833 // Deal with equality cases early.
6834 if (ICI.isEquality())
6835 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6836
6837 // A signed comparison of sign extended values simplifies into a
6838 // signed comparison.
6839 if (isSignedCmp && isSignedExt)
6840 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6841
6842 // The other three cases all fold into an unsigned comparison.
6843 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006844 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006845
Reid Spencere4d87aa2006-12-23 06:05:41 +00006846 // If we aren't dealing with a constant on the RHS, exit early
6847 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6848 if (!CI)
6849 return 0;
6850
6851 // Compute the constant that would happen if we truncated to SrcTy then
6852 // reextended to DestTy.
6853 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6854 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6855
6856 // If the re-extended constant didn't change...
6857 if (Res2 == CI) {
6858 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6859 // For example, we might have:
6860 // %A = sext short %X to uint
6861 // %B = icmp ugt uint %A, 1330
6862 // It is incorrect to transform this into
6863 // %B = icmp ugt short %X, 1330
6864 // because %A may have negative value.
6865 //
6866 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6867 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006868 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006869 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6870 else
6871 return 0;
6872 }
6873
6874 // The re-extended constant changed so the constant cannot be represented
6875 // in the shorter type. Consequently, we cannot emit a simple comparison.
6876
6877 // First, handle some easy cases. We know the result cannot be equal at this
6878 // point so handle the ICI.isEquality() cases
6879 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006880 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006881 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006882 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006883
6884 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6885 // should have been folded away previously and not enter in here.
6886 Value *Result;
6887 if (isSignedCmp) {
6888 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006889 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006890 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006891 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006892 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006893 } else {
6894 // We're performing an unsigned comparison.
6895 if (isSignedExt) {
6896 // We're performing an unsigned comp with a sign extended value.
6897 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006898 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006899 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6900 NegOne, ICI.getName()), ICI);
6901 } else {
6902 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006903 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006904 }
6905 }
6906
6907 // Finally, return the value computed.
6908 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6909 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6910 return ReplaceInstUsesWith(ICI, Result);
6911 } else {
6912 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6913 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6914 "ICmp should be folded!");
6915 if (Constant *CI = dyn_cast<Constant>(Result))
6916 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6917 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006918 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006919 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006920}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006921
Reid Spencer832254e2007-02-02 02:16:23 +00006922Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6923 return commonShiftTransforms(I);
6924}
6925
6926Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6927 return commonShiftTransforms(I);
6928}
6929
6930Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006931 if (Instruction *R = commonShiftTransforms(I))
6932 return R;
6933
6934 Value *Op0 = I.getOperand(0);
6935
6936 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6937 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6938 if (CSI->isAllOnesValue())
6939 return ReplaceInstUsesWith(I, CSI);
6940
6941 // See if we can turn a signed shr into an unsigned shr.
6942 if (MaskedValueIsZero(Op0,
6943 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006944 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006945
6946 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006947}
6948
6949Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6950 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006951 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006952
6953 // shl X, 0 == X and shr X, 0 == X
6954 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006955 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006956 Op0 == Constant::getNullValue(Op0->getType()))
6957 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006958
Reid Spencere4d87aa2006-12-23 06:05:41 +00006959 if (isa<UndefValue>(Op0)) {
6960 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006961 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006962 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006963 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6964 }
6965 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006966 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6967 return ReplaceInstUsesWith(I, Op0);
6968 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006969 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006970 }
6971
Chris Lattner2eefe512004-04-09 19:05:30 +00006972 // Try to fold constant and into select arguments.
6973 if (isa<Constant>(Op0))
6974 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006975 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006976 return R;
6977
Reid Spencerb83eb642006-10-20 07:07:24 +00006978 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006979 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6980 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006981 return 0;
6982}
6983
Reid Spencerb83eb642006-10-20 07:07:24 +00006984Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006985 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006986 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006987
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006988 // See if we can simplify any instructions used by the instruction whose sole
6989 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006990 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6991 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6992 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006993 KnownZero, KnownOne))
6994 return &I;
6995
Chris Lattner4d5542c2006-01-06 07:12:35 +00006996 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6997 // of a signed value.
6998 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006999 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007000 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00007001 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7002 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007003 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007004 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007005 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007006 }
7007
7008 // ((X*C1) << C2) == (X * (C1 << C2))
7009 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7010 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7011 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007012 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007013 ConstantExpr::getShl(BOOp, Op1));
7014
7015 // Try to fold constant and into select arguments.
7016 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7017 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7018 return R;
7019 if (isa<PHINode>(Op0))
7020 if (Instruction *NV = FoldOpIntoPhi(I))
7021 return NV;
7022
Chris Lattner8999dd32007-12-22 09:07:47 +00007023 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7024 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7025 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7026 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7027 // place. Don't try to do this transformation in this case. Also, we
7028 // require that the input operand is a shift-by-constant so that we have
7029 // confidence that the shifts will get folded together. We could do this
7030 // xform in more cases, but it is unlikely to be profitable.
7031 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7032 isa<ConstantInt>(TrOp->getOperand(1))) {
7033 // Okay, we'll do this xform. Make the shift of shift.
7034 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007035 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007036 I.getName());
7037 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7038
7039 // For logical shifts, the truncation has the effect of making the high
7040 // part of the register be zeros. Emulate this by inserting an AND to
7041 // clear the top bits as needed. This 'and' will usually be zapped by
7042 // other xforms later if dead.
7043 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7044 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7045 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7046
7047 // The mask we constructed says what the trunc would do if occurring
7048 // between the shifts. We want to know the effect *after* the second
7049 // shift. We know that it is a logical shift by a constant, so adjust the
7050 // mask as appropriate.
7051 if (I.getOpcode() == Instruction::Shl)
7052 MaskV <<= Op1->getZExtValue();
7053 else {
7054 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7055 MaskV = MaskV.lshr(Op1->getZExtValue());
7056 }
7057
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007058 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007059 TI->getName());
7060 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7061
7062 // Return the value truncated to the interesting size.
7063 return new TruncInst(And, I.getType());
7064 }
7065 }
7066
Chris Lattner4d5542c2006-01-06 07:12:35 +00007067 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007068 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7069 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7070 Value *V1, *V2;
7071 ConstantInt *CC;
7072 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007073 default: break;
7074 case Instruction::Add:
7075 case Instruction::And:
7076 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007077 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007078 // These operators commute.
7079 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007080 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7081 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007082 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007083 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007084 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007085 Op0BO->getName());
7086 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007087 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007088 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007089 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007090 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007091 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007092 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007093 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007094 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007095
Chris Lattner150f12a2005-09-18 06:30:59 +00007096 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007097 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007098 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007099 match(Op0BOOp1,
7100 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00007101 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
7102 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007103 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007104 Op0BO->getOperand(0), Op1,
7105 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007106 InsertNewInstBefore(YS, I); // (Y << C)
7107 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007108 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007109 V1->getName()+".mask");
7110 InsertNewInstBefore(XM, I); // X & (CC << C)
7111
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007112 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007113 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007114 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007115
Reid Spencera07cb7d2007-02-02 14:41:37 +00007116 // FALL THROUGH.
7117 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007118 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007119 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7120 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007121 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007122 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007123 Op0BO->getOperand(1), Op1,
7124 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007125 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007126 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007127 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007128 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007129 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007130 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007131 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007132 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007133 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007134
Chris Lattner13d4ab42006-05-31 21:14:00 +00007135 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007136 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7137 match(Op0BO->getOperand(0),
7138 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007139 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007140 cast<BinaryOperator>(Op0BO->getOperand(0))
7141 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007142 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007143 Op0BO->getOperand(1), Op1,
7144 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007145 InsertNewInstBefore(YS, I); // (Y << C)
7146 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007147 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007148 V1->getName()+".mask");
7149 InsertNewInstBefore(XM, I); // X & (CC << C)
7150
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007151 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007152 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007153
Chris Lattner11021cb2005-09-18 05:12:10 +00007154 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007155 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007156 }
7157
7158
7159 // If the operand is an bitwise operator with a constant RHS, and the
7160 // shift is the only use, we can pull it out of the shift.
7161 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7162 bool isValid = true; // Valid only for And, Or, Xor
7163 bool highBitSet = false; // Transform if high bit of constant set?
7164
7165 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007166 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007167 case Instruction::Add:
7168 isValid = isLeftShift;
7169 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007170 case Instruction::Or:
7171 case Instruction::Xor:
7172 highBitSet = false;
7173 break;
7174 case Instruction::And:
7175 highBitSet = true;
7176 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007177 }
7178
7179 // If this is a signed shift right, and the high bit is modified
7180 // by the logical operation, do not perform the transformation.
7181 // The highBitSet boolean indicates the value of the high bit of
7182 // the constant which would cause it to be modified for this
7183 // operation.
7184 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007185 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007186 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007187
7188 if (isValid) {
7189 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7190
7191 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007192 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007193 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007194 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007195
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007196 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007197 NewRHS);
7198 }
7199 }
7200 }
7201 }
7202
Chris Lattnerad0124c2006-01-06 07:52:12 +00007203 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007204 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7205 if (ShiftOp && !ShiftOp->isShift())
7206 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007207
Reid Spencerb83eb642006-10-20 07:07:24 +00007208 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007209 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007210 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7211 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007212 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7213 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7214 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007215
Zhou Sheng4351c642007-04-02 08:20:41 +00007216 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00007217 if (AmtSum > TypeBits)
7218 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007219
7220 const IntegerType *Ty = cast<IntegerType>(I.getType());
7221
7222 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007223 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007224 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007225 ConstantInt::get(Ty, AmtSum));
7226 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7227 I.getOpcode() == Instruction::AShr) {
7228 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007229 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007230 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7231 I.getOpcode() == Instruction::LShr) {
7232 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7233 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007234 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007235 InsertNewInstBefore(Shift, I);
7236
Zhou Shenge9e03f62007-03-28 15:02:20 +00007237 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007238 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007239 }
7240
Chris Lattnerb87056f2007-02-05 00:57:54 +00007241 // Okay, if we get here, one shift must be left, and the other shift must be
7242 // right. See if the amounts are equal.
7243 if (ShiftAmt1 == ShiftAmt2) {
7244 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7245 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007246 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007247 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007248 }
7249 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7250 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007251 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007252 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007253 }
7254 // We can simplify ((X << C) >>s C) into a trunc + sext.
7255 // NOTE: we could do this for any C, but that would make 'unusual' integer
7256 // types. For now, just stick to ones well-supported by the code
7257 // generators.
7258 const Type *SExtType = 0;
7259 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007260 case 1 :
7261 case 8 :
7262 case 16 :
7263 case 32 :
7264 case 64 :
7265 case 128:
7266 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7267 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007268 default: break;
7269 }
7270 if (SExtType) {
7271 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7272 InsertNewInstBefore(NewTrunc, I);
7273 return new SExtInst(NewTrunc, Ty);
7274 }
7275 // Otherwise, we can't handle it yet.
7276 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007277 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007278
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007279 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007280 if (I.getOpcode() == Instruction::Shl) {
7281 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7282 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007283 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007284 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007285 InsertNewInstBefore(Shift, I);
7286
Reid Spencer55702aa2007-03-25 21:11:44 +00007287 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007288 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007289 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007290
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007291 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007292 if (I.getOpcode() == Instruction::LShr) {
7293 assert(ShiftOp->getOpcode() == Instruction::Shl);
7294 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007295 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007296 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007297
Reid Spencerd5e30f02007-03-26 17:18:58 +00007298 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007299 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007300 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007301
7302 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7303 } else {
7304 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007305 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007306
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007307 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007308 if (I.getOpcode() == Instruction::Shl) {
7309 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7310 ShiftOp->getOpcode() == Instruction::AShr);
7311 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007312 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007313 ConstantInt::get(Ty, ShiftDiff));
7314 InsertNewInstBefore(Shift, I);
7315
Reid Spencer55702aa2007-03-25 21:11:44 +00007316 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007317 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007318 }
7319
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007320 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007321 if (I.getOpcode() == Instruction::LShr) {
7322 assert(ShiftOp->getOpcode() == Instruction::Shl);
7323 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007324 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007325 InsertNewInstBefore(Shift, I);
7326
Reid Spencer68d27cf2007-03-26 23:45:51 +00007327 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007328 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007329 }
7330
7331 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007332 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007333 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007334 return 0;
7335}
7336
Chris Lattnera1be5662002-05-02 17:06:02 +00007337
Chris Lattnercfd65102005-10-29 04:36:15 +00007338/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7339/// expression. If so, decompose it, returning some value X, such that Val is
7340/// X*Scale+Offset.
7341///
7342static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007343 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007344 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007345 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007346 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007347 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007348 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007349 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7350 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7351 if (I->getOpcode() == Instruction::Shl) {
7352 // This is a value scaled by '1 << the shift amt'.
7353 Scale = 1U << RHS->getZExtValue();
7354 Offset = 0;
7355 return I->getOperand(0);
7356 } else if (I->getOpcode() == Instruction::Mul) {
7357 // This value is scaled by 'RHS'.
7358 Scale = RHS->getZExtValue();
7359 Offset = 0;
7360 return I->getOperand(0);
7361 } else if (I->getOpcode() == Instruction::Add) {
7362 // We have X+C. Check to see if we really have (X*C2)+C1,
7363 // where C1 is divisible by C2.
7364 unsigned SubScale;
7365 Value *SubVal =
7366 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7367 Offset += RHS->getZExtValue();
7368 Scale = SubScale;
7369 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007370 }
7371 }
7372 }
7373
7374 // Otherwise, we can't look past this.
7375 Scale = 1;
7376 Offset = 0;
7377 return Val;
7378}
7379
7380
Chris Lattnerb3f83972005-10-24 06:03:58 +00007381/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7382/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007383Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007384 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007385 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007386
Chris Lattnerb53c2382005-10-24 06:22:12 +00007387 // Remove any uses of AI that are dead.
7388 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007389
Chris Lattnerb53c2382005-10-24 06:22:12 +00007390 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7391 Instruction *User = cast<Instruction>(*UI++);
7392 if (isInstructionTriviallyDead(User)) {
7393 while (UI != E && *UI == User)
7394 ++UI; // If this instruction uses AI more than once, don't break UI.
7395
Chris Lattnerb53c2382005-10-24 06:22:12 +00007396 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007397 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007398 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007399 }
7400 }
7401
Chris Lattnerb3f83972005-10-24 06:03:58 +00007402 // Get the type really allocated and the type casted to.
7403 const Type *AllocElTy = AI.getAllocatedType();
7404 const Type *CastElTy = PTy->getElementType();
7405 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007406
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007407 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7408 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007409 if (CastElTyAlign < AllocElTyAlign) return 0;
7410
Chris Lattner39387a52005-10-24 06:35:18 +00007411 // If the allocation has multiple uses, only promote it if we are strictly
7412 // increasing the alignment of the resultant allocation. If we keep it the
7413 // same, we open the door to infinite loops of various kinds.
7414 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7415
Duncan Sands514ab342007-11-01 20:53:16 +00007416 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7417 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007418 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007419
Chris Lattner455fcc82005-10-29 03:19:53 +00007420 // See if we can satisfy the modulus by pulling a scale out of the array
7421 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007422 unsigned ArraySizeScale;
7423 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007424 Value *NumElements = // See if the array size is a decomposable linear expr.
7425 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7426
Chris Lattner455fcc82005-10-29 03:19:53 +00007427 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7428 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007429 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7430 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007431
Chris Lattner455fcc82005-10-29 03:19:53 +00007432 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7433 Value *Amt = 0;
7434 if (Scale == 1) {
7435 Amt = NumElements;
7436 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007437 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007438 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7439 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007440 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007441 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007442 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007443 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007444 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007445 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007446 }
7447
Jeff Cohen86796be2007-04-04 16:58:57 +00007448 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7449 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007450 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007451 Amt = InsertNewInstBefore(Tmp, AI);
7452 }
7453
Chris Lattnerb3f83972005-10-24 06:03:58 +00007454 AllocationInst *New;
7455 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007456 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007457 else
Chris Lattner6934a042007-02-11 01:23:03 +00007458 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007459 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007460 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007461
7462 // If the allocation has multiple uses, insert a cast and change all things
7463 // that used it to use the new cast. This will also hack on CI, but it will
7464 // die soon.
7465 if (!AI.hasOneUse()) {
7466 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007467 // New is the allocation instruction, pointer typed. AI is the original
7468 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7469 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007470 InsertNewInstBefore(NewCast, AI);
7471 AI.replaceAllUsesWith(NewCast);
7472 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007473 return ReplaceInstUsesWith(CI, New);
7474}
7475
Chris Lattner70074e02006-05-13 02:06:03 +00007476/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007477/// and return it as type Ty without inserting any new casts and without
7478/// changing the computed value. This is used by code that tries to decide
7479/// whether promoting or shrinking integer operations to wider or smaller types
7480/// will allow us to eliminate a truncate or extend.
7481///
7482/// This is a truncation operation if Ty is smaller than V->getType(), or an
7483/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00007484bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7485 unsigned CastOpc,
7486 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007487 // We can always evaluate constants in another type.
7488 if (isa<ConstantInt>(V))
7489 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007490
7491 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007492 if (!I) return false;
7493
7494 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007495
Chris Lattner951626b2007-08-02 06:11:14 +00007496 // If this is an extension or truncate, we can often eliminate it.
7497 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7498 // If this is a cast from the destination type, we can trivially eliminate
7499 // it, and this will remove a cast overall.
7500 if (I->getOperand(0)->getType() == Ty) {
7501 // If the first operand is itself a cast, and is eliminable, do not count
7502 // this as an eliminable cast. We would prefer to eliminate those two
7503 // casts first.
7504 if (!isa<CastInst>(I->getOperand(0)))
7505 ++NumCastsRemoved;
7506 return true;
7507 }
7508 }
7509
7510 // We can't extend or shrink something that has multiple uses: doing so would
7511 // require duplicating the instruction in general, which isn't profitable.
7512 if (!I->hasOneUse()) return false;
7513
Chris Lattner70074e02006-05-13 02:06:03 +00007514 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007515 case Instruction::Add:
7516 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00007517 case Instruction::And:
7518 case Instruction::Or:
7519 case Instruction::Xor:
7520 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007521 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7522 NumCastsRemoved) &&
7523 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7524 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007525
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007526 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007527 // A multiply can be truncated by truncating its operands.
7528 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7529 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7530 NumCastsRemoved) &&
7531 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7532 NumCastsRemoved);
7533
Chris Lattner46b96052006-11-29 07:18:39 +00007534 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007535 // If we are truncating the result of this SHL, and if it's a shift of a
7536 // constant amount, we can always perform a SHL in a smaller type.
7537 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007538 uint32_t BitWidth = Ty->getBitWidth();
7539 if (BitWidth < OrigTy->getBitWidth() &&
7540 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007541 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7542 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007543 }
7544 break;
7545 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007546 // If this is a truncate of a logical shr, we can truncate it to a smaller
7547 // lshr iff we know that the bits we would otherwise be shifting in are
7548 // already zeros.
7549 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007550 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7551 uint32_t BitWidth = Ty->getBitWidth();
7552 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007553 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007554 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7555 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007556 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7557 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007558 }
7559 }
Chris Lattner46b96052006-11-29 07:18:39 +00007560 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007561 case Instruction::ZExt:
7562 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007563 case Instruction::Trunc:
7564 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007565 // can safely replace it. Note that replacing it does not reduce the number
7566 // of casts in the input.
7567 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007568 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00007569
Reid Spencer3da59db2006-11-27 01:05:10 +00007570 break;
7571 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007572 // TODO: Can handle more cases here.
7573 break;
7574 }
7575
7576 return false;
7577}
7578
7579/// EvaluateInDifferentType - Given an expression that
7580/// CanEvaluateInDifferentType returns true for, actually insert the code to
7581/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007582Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007583 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007584 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007585 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007586
7587 // Otherwise, it must be an instruction.
7588 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007589 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007590 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007591 case Instruction::Add:
7592 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007593 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007594 case Instruction::And:
7595 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007596 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007597 case Instruction::AShr:
7598 case Instruction::LShr:
7599 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007600 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007601 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007602 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00007603 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00007604 break;
7605 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007606 case Instruction::Trunc:
7607 case Instruction::ZExt:
7608 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007609 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007610 // just return the source. There's no need to insert it because it is not
7611 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007612 if (I->getOperand(0)->getType() == Ty)
7613 return I->getOperand(0);
7614
Chris Lattner951626b2007-08-02 06:11:14 +00007615 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007616 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00007617 Ty, I->getName());
7618 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007619 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007620 // TODO: Can handle more cases here.
7621 assert(0 && "Unreachable!");
7622 break;
7623 }
7624
7625 return InsertNewInstBefore(Res, *I);
7626}
7627
Reid Spencer3da59db2006-11-27 01:05:10 +00007628/// @brief Implement the transforms common to all CastInst visitors.
7629Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007630 Value *Src = CI.getOperand(0);
7631
Dan Gohman23d9d272007-05-11 21:10:54 +00007632 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007633 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007634 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007635 if (Instruction::CastOps opc =
7636 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7637 // The first cast (CSrc) is eliminable so we need to fix up or replace
7638 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007639 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007640 }
7641 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007642
Reid Spencer3da59db2006-11-27 01:05:10 +00007643 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007644 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7645 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7646 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007647
7648 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007649 if (isa<PHINode>(Src))
7650 if (Instruction *NV = FoldOpIntoPhi(CI))
7651 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007652
Reid Spencer3da59db2006-11-27 01:05:10 +00007653 return 0;
7654}
7655
Chris Lattnerd3e28342007-04-27 17:44:50 +00007656/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7657Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7658 Value *Src = CI.getOperand(0);
7659
Chris Lattnerd3e28342007-04-27 17:44:50 +00007660 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007661 // If casting the result of a getelementptr instruction with no offset, turn
7662 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007663 if (GEP->hasAllZeroIndices()) {
7664 // Changing the cast operand is usually not a good idea but it is safe
7665 // here because the pointer operand is being replaced with another
7666 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007667 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007668 CI.setOperand(0, GEP->getOperand(0));
7669 return &CI;
7670 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007671
7672 // If the GEP has a single use, and the base pointer is a bitcast, and the
7673 // GEP computes a constant offset, see if we can convert these three
7674 // instructions into fewer. This typically happens with unions and other
7675 // non-type-safe code.
7676 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7677 if (GEP->hasAllConstantIndices()) {
7678 // We are guaranteed to get a constant from EmitGEPOffset.
7679 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7680 int64_t Offset = OffsetV->getSExtValue();
7681
7682 // Get the base pointer input of the bitcast, and the type it points to.
7683 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7684 const Type *GEPIdxTy =
7685 cast<PointerType>(OrigBase->getType())->getElementType();
7686 if (GEPIdxTy->isSized()) {
7687 SmallVector<Value*, 8> NewIndices;
7688
Chris Lattnerc42e2262007-05-05 01:59:31 +00007689 // Start with the index over the outer type. Note that the type size
7690 // might be zero (even if the offset isn't zero) if the indexed type
7691 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007692 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007693 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007694 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007695 FirstIdx = Offset/TySize;
7696 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007697
Chris Lattnerc42e2262007-05-05 01:59:31 +00007698 // Handle silly modulus not returning values values [0..TySize).
7699 if (Offset < 0) {
7700 --FirstIdx;
7701 Offset += TySize;
7702 assert(Offset >= 0);
7703 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007704 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007705 }
7706
7707 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007708
7709 // Index into the types. If we fail, set OrigBase to null.
7710 while (Offset) {
7711 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7712 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007713 if (Offset < (int64_t)SL->getSizeInBytes()) {
7714 unsigned Elt = SL->getElementContainingOffset(Offset);
7715 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007716
Chris Lattner6b6aef82007-05-15 00:16:00 +00007717 Offset -= SL->getElementOffset(Elt);
7718 GEPIdxTy = STy->getElementType(Elt);
7719 } else {
7720 // Otherwise, we can't index into this, bail out.
7721 Offset = 0;
7722 OrigBase = 0;
7723 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007724 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7725 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007726 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007727 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7728 Offset %= EltSize;
7729 } else {
7730 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7731 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007732 GEPIdxTy = STy->getElementType();
7733 } else {
7734 // Otherwise, we can't index into this, bail out.
7735 Offset = 0;
7736 OrigBase = 0;
7737 }
7738 }
7739 if (OrigBase) {
7740 // If we were able to index down into an element, create the GEP
7741 // and bitcast the result. This eliminates one bitcast, potentially
7742 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007743 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7744 NewIndices.begin(),
7745 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007746 InsertNewInstBefore(NGEP, CI);
7747 NGEP->takeName(GEP);
7748
Chris Lattner9bc14642007-04-28 00:57:34 +00007749 if (isa<BitCastInst>(CI))
7750 return new BitCastInst(NGEP, CI.getType());
7751 assert(isa<PtrToIntInst>(CI));
7752 return new PtrToIntInst(NGEP, CI.getType());
7753 }
7754 }
7755 }
7756 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007757 }
7758
7759 return commonCastTransforms(CI);
7760}
7761
7762
7763
Chris Lattnerc739cd62007-03-03 05:27:34 +00007764/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7765/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007766/// cases.
7767/// @brief Implement the transforms common to CastInst with integer operands
7768Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7769 if (Instruction *Result = commonCastTransforms(CI))
7770 return Result;
7771
7772 Value *Src = CI.getOperand(0);
7773 const Type *SrcTy = Src->getType();
7774 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007775 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7776 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007777
Reid Spencer3da59db2006-11-27 01:05:10 +00007778 // See if we can simplify any instructions used by the LHS whose sole
7779 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007780 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7781 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007782 KnownZero, KnownOne))
7783 return &CI;
7784
7785 // If the source isn't an instruction or has more than one use then we
7786 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007787 Instruction *SrcI = dyn_cast<Instruction>(Src);
7788 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007789 return 0;
7790
Chris Lattnerc739cd62007-03-03 05:27:34 +00007791 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007792 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007793 if (!isa<BitCastInst>(CI) &&
7794 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007795 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007796 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007797 // eliminates the cast, so it is always a win. If this is a zero-extension,
7798 // we need to do an AND to maintain the clear top-part of the computation,
7799 // so we require that the input have eliminated at least one cast. If this
7800 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007801 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007802 bool DoXForm;
7803 switch (CI.getOpcode()) {
7804 default:
7805 // All the others use floating point so we shouldn't actually
7806 // get here because of the check above.
7807 assert(0 && "Unknown cast type");
7808 case Instruction::Trunc:
7809 DoXForm = true;
7810 break;
7811 case Instruction::ZExt:
7812 DoXForm = NumCastsRemoved >= 1;
7813 break;
7814 case Instruction::SExt:
7815 DoXForm = NumCastsRemoved >= 2;
7816 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007817 }
7818
7819 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007820 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7821 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007822 assert(Res->getType() == DestTy);
7823 switch (CI.getOpcode()) {
7824 default: assert(0 && "Unknown cast type!");
7825 case Instruction::Trunc:
7826 case Instruction::BitCast:
7827 // Just replace this cast with the result.
7828 return ReplaceInstUsesWith(CI, Res);
7829 case Instruction::ZExt: {
7830 // We need to emit an AND to clear the high bits.
7831 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007832 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7833 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007834 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007835 }
7836 case Instruction::SExt:
7837 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007838 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007839 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7840 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007841 }
7842 }
7843 }
7844
7845 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7846 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7847
7848 switch (SrcI->getOpcode()) {
7849 case Instruction::Add:
7850 case Instruction::Mul:
7851 case Instruction::And:
7852 case Instruction::Or:
7853 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007854 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007855 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7856 // Don't insert two casts if they cannot be eliminated. We allow
7857 // two casts to be inserted if the sizes are the same. This could
7858 // only be converting signedness, which is a noop.
7859 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007860 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7861 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007862 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007863 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7864 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007865 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007866 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007867 }
7868 }
7869
7870 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7871 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7872 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007873 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007874 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007875 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007876 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007877 }
7878 break;
7879 case Instruction::SDiv:
7880 case Instruction::UDiv:
7881 case Instruction::SRem:
7882 case Instruction::URem:
7883 // If we are just changing the sign, rewrite.
7884 if (DestBitSize == SrcBitSize) {
7885 // Don't insert two casts if they cannot be eliminated. We allow
7886 // two casts to be inserted if the sizes are the same. This could
7887 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007888 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7889 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007890 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7891 Op0, DestTy, SrcI);
7892 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7893 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007894 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007895 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7896 }
7897 }
7898 break;
7899
7900 case Instruction::Shl:
7901 // Allow changing the sign of the source operand. Do not allow
7902 // changing the size of the shift, UNLESS the shift amount is a
7903 // constant. We must not change variable sized shifts to a smaller
7904 // size, because it is undefined to shift more bits out than exist
7905 // in the value.
7906 if (DestBitSize == SrcBitSize ||
7907 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007908 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7909 Instruction::BitCast : Instruction::Trunc);
7910 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007911 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007912 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007913 }
7914 break;
7915 case Instruction::AShr:
7916 // If this is a signed shr, and if all bits shifted in are about to be
7917 // truncated off, turn it into an unsigned shr to allow greater
7918 // simplifications.
7919 if (DestBitSize < SrcBitSize &&
7920 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007921 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007922 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7923 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007924 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007925 }
7926 }
7927 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007928 }
7929 return 0;
7930}
7931
Chris Lattner8a9f5712007-04-11 06:57:46 +00007932Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007933 if (Instruction *Result = commonIntCastTransforms(CI))
7934 return Result;
7935
7936 Value *Src = CI.getOperand(0);
7937 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007938 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7939 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007940
7941 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7942 switch (SrcI->getOpcode()) {
7943 default: break;
7944 case Instruction::LShr:
7945 // We can shrink lshr to something smaller if we know the bits shifted in
7946 // are already zeros.
7947 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007948 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007949
7950 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007951 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007952 Value* SrcIOp0 = SrcI->getOperand(0);
7953 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007954 if (ShAmt >= DestBitWidth) // All zeros.
7955 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7956
7957 // Okay, we can shrink this. Truncate the input, then return a new
7958 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007959 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7960 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7961 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007962 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007963 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007964 } else { // This is a variable shr.
7965
7966 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7967 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7968 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007969 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007970 Value *One = ConstantInt::get(SrcI->getType(), 1);
7971
Reid Spencer832254e2007-02-02 02:16:23 +00007972 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007973 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007974 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007975 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007976 SrcI->getOperand(0),
7977 "tmp"), CI);
7978 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007979 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007980 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007981 }
7982 break;
7983 }
7984 }
7985
7986 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007987}
7988
Evan Chengb98a10e2008-03-24 00:21:34 +00007989/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7990/// in order to eliminate the icmp.
7991Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7992 bool DoXform) {
7993 // If we are just checking for a icmp eq of a single bit and zext'ing it
7994 // to an integer, then shift the bit to the appropriate place and then
7995 // cast to integer to avoid the comparison.
7996 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7997 const APInt &Op1CV = Op1C->getValue();
7998
7999 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8000 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8001 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8002 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8003 if (!DoXform) return ICI;
8004
8005 Value *In = ICI->getOperand(0);
8006 Value *Sh = ConstantInt::get(In->getType(),
8007 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008008 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008009 In->getName()+".lobit"),
8010 CI);
8011 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008012 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008013 false/*ZExt*/, "tmp", &CI);
8014
8015 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8016 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008017 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008018 In->getName()+".not"),
8019 CI);
8020 }
8021
8022 return ReplaceInstUsesWith(CI, In);
8023 }
8024
8025
8026
8027 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8028 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8029 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8030 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8031 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8032 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8033 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8034 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8035 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8036 // This only works for EQ and NE
8037 ICI->isEquality()) {
8038 // If Op1C some other power of two, convert:
8039 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8040 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8041 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8042 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8043
8044 APInt KnownZeroMask(~KnownZero);
8045 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8046 if (!DoXform) return ICI;
8047
8048 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8049 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8050 // (X&4) == 2 --> false
8051 // (X&4) != 2 --> true
8052 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8053 Res = ConstantExpr::getZExt(Res, CI.getType());
8054 return ReplaceInstUsesWith(CI, Res);
8055 }
8056
8057 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8058 Value *In = ICI->getOperand(0);
8059 if (ShiftAmt) {
8060 // Perform a logical shr by shiftamt.
8061 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008062 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008063 ConstantInt::get(In->getType(), ShiftAmt),
8064 In->getName()+".lobit"), CI);
8065 }
8066
8067 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8068 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008069 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008070 InsertNewInstBefore(cast<Instruction>(In), CI);
8071 }
8072
8073 if (CI.getType() == In->getType())
8074 return ReplaceInstUsesWith(CI, In);
8075 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008076 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008077 }
8078 }
8079 }
8080
8081 return 0;
8082}
8083
Chris Lattner8a9f5712007-04-11 06:57:46 +00008084Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008085 // If one of the common conversion will work ..
8086 if (Instruction *Result = commonIntCastTransforms(CI))
8087 return Result;
8088
8089 Value *Src = CI.getOperand(0);
8090
8091 // If this is a cast of a cast
8092 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008093 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8094 // types and if the sizes are just right we can convert this into a logical
8095 // 'and' which will be much cheaper than the pair of casts.
8096 if (isa<TruncInst>(CSrc)) {
8097 // Get the sizes of the types involved
8098 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008099 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8100 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8101 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008102 // If we're actually extending zero bits and the trunc is a no-op
8103 if (MidSize < DstSize && SrcSize == DstSize) {
8104 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00008105 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00008106 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00008107 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008108 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00008109 // Unfortunately, if the type changed, we need to cast it back.
8110 if (And->getType() != CI.getType()) {
8111 And->setName(CSrc->getName()+".mask");
8112 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008113 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00008114 }
8115 return And;
8116 }
8117 }
8118 }
8119
Evan Chengb98a10e2008-03-24 00:21:34 +00008120 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8121 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008122
Evan Chengb98a10e2008-03-24 00:21:34 +00008123 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8124 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8125 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8126 // of the (zext icmp) will be transformed.
8127 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8128 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8129 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8130 (transformZExtICmp(LHS, CI, false) ||
8131 transformZExtICmp(RHS, CI, false))) {
8132 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8133 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008134 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008135 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008136 }
8137
Reid Spencer3da59db2006-11-27 01:05:10 +00008138 return 0;
8139}
8140
Chris Lattner8a9f5712007-04-11 06:57:46 +00008141Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008142 if (Instruction *I = commonIntCastTransforms(CI))
8143 return I;
8144
Chris Lattner8a9f5712007-04-11 06:57:46 +00008145 Value *Src = CI.getOperand(0);
8146
8147 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
8148 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
8149 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
8150 // If we are just checking for a icmp eq of a single bit and zext'ing it
8151 // to an integer, then shift the bit to the appropriate place and then
8152 // cast to integer to avoid the comparison.
8153 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8154 const APInt &Op1CV = Op1C->getValue();
8155
8156 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8157 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8158 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8159 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
8160 Value *In = ICI->getOperand(0);
8161 Value *Sh = ConstantInt::get(In->getType(),
8162 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008163 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00008164 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008165 CI);
8166 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008167 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008168 true/*SExt*/, "tmp", &CI);
8169
8170 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008171 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00008172 In->getName()+".not"), CI);
8173
8174 return ReplaceInstUsesWith(CI, In);
8175 }
8176 }
8177 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00008178
8179 // See if the value being truncated is already sign extended. If so, just
8180 // eliminate the trunc/sext pair.
8181 if (getOpcode(Src) == Instruction::Trunc) {
8182 Value *Op = cast<User>(Src)->getOperand(0);
8183 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8184 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8185 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8186 unsigned NumSignBits = ComputeNumSignBits(Op);
8187
8188 if (OpBits == DestBits) {
8189 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8190 // bits, it is already ready.
8191 if (NumSignBits > DestBits-MidBits)
8192 return ReplaceInstUsesWith(CI, Op);
8193 } else if (OpBits < DestBits) {
8194 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8195 // bits, just sext from i32.
8196 if (NumSignBits > OpBits-MidBits)
8197 return new SExtInst(Op, CI.getType(), "tmp");
8198 } else {
8199 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8200 // bits, just truncate to i32.
8201 if (NumSignBits > OpBits-MidBits)
8202 return new TruncInst(Op, CI.getType(), "tmp");
8203 }
8204 }
Chris Lattner8a9f5712007-04-11 06:57:46 +00008205
Chris Lattnerba417832007-04-11 06:12:58 +00008206 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008207}
8208
Chris Lattnerb7530652008-01-27 05:29:54 +00008209/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8210/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008211static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008212 APFloat F = CFP->getValueAPF();
8213 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00008214 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008215 return 0;
8216}
8217
8218/// LookThroughFPExtensions - If this is an fp extension instruction, look
8219/// through it until we get the source value.
8220static Value *LookThroughFPExtensions(Value *V) {
8221 if (Instruction *I = dyn_cast<Instruction>(V))
8222 if (I->getOpcode() == Instruction::FPExt)
8223 return LookThroughFPExtensions(I->getOperand(0));
8224
8225 // If this value is a constant, return the constant in the smallest FP type
8226 // that can accurately represent it. This allows us to turn
8227 // (float)((double)X+2.0) into x+2.0f.
8228 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8229 if (CFP->getType() == Type::PPC_FP128Ty)
8230 return V; // No constant folding of this.
8231 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008232 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008233 return V;
8234 if (CFP->getType() == Type::DoubleTy)
8235 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008236 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008237 return V;
8238 // Don't try to shrink to various long double types.
8239 }
8240
8241 return V;
8242}
8243
8244Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8245 if (Instruction *I = commonCastTransforms(CI))
8246 return I;
8247
8248 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8249 // smaller than the destination type, we can eliminate the truncate by doing
8250 // the add as the smaller type. This applies to add/sub/mul/div as well as
8251 // many builtins (sqrt, etc).
8252 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8253 if (OpI && OpI->hasOneUse()) {
8254 switch (OpI->getOpcode()) {
8255 default: break;
8256 case Instruction::Add:
8257 case Instruction::Sub:
8258 case Instruction::Mul:
8259 case Instruction::FDiv:
8260 case Instruction::FRem:
8261 const Type *SrcTy = OpI->getType();
8262 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8263 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8264 if (LHSTrunc->getType() != SrcTy &&
8265 RHSTrunc->getType() != SrcTy) {
8266 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8267 // If the source types were both smaller than the destination type of
8268 // the cast, do this xform.
8269 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8270 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8271 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8272 CI.getType(), CI);
8273 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8274 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008275 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008276 }
8277 }
8278 break;
8279 }
8280 }
8281 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008282}
8283
8284Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8285 return commonCastTransforms(CI);
8286}
8287
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008288Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8289 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
8290 // mantissa to accurately represent all values of X. For example, do not
8291 // do this with i64->float->i64.
8292 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8293 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8294 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00008295 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008296 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8297
8298 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008299}
8300
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008301Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8302 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
8303 // mantissa to accurately represent all values of X. For example, do not
8304 // do this with i64->float->i64.
8305 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8306 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8307 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00008308 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008309 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8310
8311 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008312}
8313
8314Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8315 return commonCastTransforms(CI);
8316}
8317
8318Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8319 return commonCastTransforms(CI);
8320}
8321
8322Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008323 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008324}
8325
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008326Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8327 if (Instruction *I = commonCastTransforms(CI))
8328 return I;
8329
8330 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8331 if (!DestPointee->isSized()) return 0;
8332
8333 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8334 ConstantInt *Cst;
8335 Value *X;
8336 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8337 m_ConstantInt(Cst)))) {
8338 // If the source and destination operands have the same type, see if this
8339 // is a single-index GEP.
8340 if (X->getType() == CI.getType()) {
8341 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00008342 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008343
8344 // Convert the constant to intptr type.
8345 APInt Offset = Cst->getValue();
8346 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8347
8348 // If Offset is evenly divisible by Size, we can do this xform.
8349 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8350 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008351 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008352 }
8353 }
8354 // TODO: Could handle other cases, e.g. where add is indexing into field of
8355 // struct etc.
8356 } else if (CI.getOperand(0)->hasOneUse() &&
8357 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8358 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8359 // "inttoptr+GEP" instead of "add+intptr".
8360
8361 // Get the size of the pointee type.
8362 uint64_t Size = TD->getABITypeSize(DestPointee);
8363
8364 // Convert the constant to intptr type.
8365 APInt Offset = Cst->getValue();
8366 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8367
8368 // If Offset is evenly divisible by Size, we can do this xform.
8369 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8370 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8371
8372 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8373 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008374 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008375 }
8376 }
8377 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008378}
8379
Chris Lattnerd3e28342007-04-27 17:44:50 +00008380Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008381 // If the operands are integer typed then apply the integer transforms,
8382 // otherwise just apply the common ones.
8383 Value *Src = CI.getOperand(0);
8384 const Type *SrcTy = Src->getType();
8385 const Type *DestTy = CI.getType();
8386
Chris Lattner42a75512007-01-15 02:27:26 +00008387 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008388 if (Instruction *Result = commonIntCastTransforms(CI))
8389 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008390 } else if (isa<PointerType>(SrcTy)) {
8391 if (Instruction *I = commonPointerCastTransforms(CI))
8392 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008393 } else {
8394 if (Instruction *Result = commonCastTransforms(CI))
8395 return Result;
8396 }
8397
8398
8399 // Get rid of casts from one type to the same type. These are useless and can
8400 // be replaced by the operand.
8401 if (DestTy == Src->getType())
8402 return ReplaceInstUsesWith(CI, Src);
8403
Reid Spencer3da59db2006-11-27 01:05:10 +00008404 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008405 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8406 const Type *DstElTy = DstPTy->getElementType();
8407 const Type *SrcElTy = SrcPTy->getElementType();
8408
Nate Begeman83ad90a2008-03-31 00:22:16 +00008409 // If the address spaces don't match, don't eliminate the bitcast, which is
8410 // required for changing types.
8411 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8412 return 0;
8413
Chris Lattnerd3e28342007-04-27 17:44:50 +00008414 // If we are casting a malloc or alloca to a pointer to a type of the same
8415 // size, rewrite the allocation instruction to allocate the "right" type.
8416 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8417 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8418 return V;
8419
Chris Lattnerd717c182007-05-05 22:32:24 +00008420 // If the source and destination are pointers, and this cast is equivalent
8421 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008422 // This can enhance SROA and other transforms that want type-safe pointers.
8423 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8424 unsigned NumZeros = 0;
8425 while (SrcElTy != DstElTy &&
8426 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8427 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8428 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8429 ++NumZeros;
8430 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008431
Chris Lattnerd3e28342007-04-27 17:44:50 +00008432 // If we found a path from the src to dest, create the getelementptr now.
8433 if (SrcElTy == DstElTy) {
8434 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008435 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8436 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008437 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008438 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008439
Reid Spencer3da59db2006-11-27 01:05:10 +00008440 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8441 if (SVI->hasOneUse()) {
8442 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8443 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008444 if (isa<VectorType>(DestTy) &&
8445 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00008446 SVI->getType()->getNumElements()) {
8447 CastInst *Tmp;
8448 // If either of the operands is a cast from CI.getType(), then
8449 // evaluating the shuffle in the casted destination's type will allow
8450 // us to eliminate at least one cast.
8451 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8452 Tmp->getOperand(0)->getType() == DestTy) ||
8453 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8454 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008455 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8456 SVI->getOperand(0), DestTy, &CI);
8457 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8458 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008459 // Return a new shuffle vector. Use the same element ID's, as we
8460 // know the vector types match #elts.
8461 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008462 }
8463 }
8464 }
8465 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008466 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008467}
8468
Chris Lattnere576b912004-04-09 23:46:01 +00008469/// GetSelectFoldableOperands - We want to turn code that looks like this:
8470/// %C = or %A, %B
8471/// %D = select %cond, %C, %A
8472/// into:
8473/// %C = select %cond, %B, 0
8474/// %D = or %A, %C
8475///
8476/// Assuming that the specified instruction is an operand to the select, return
8477/// a bitmask indicating which operands of this instruction are foldable if they
8478/// equal the other incoming value of the select.
8479///
8480static unsigned GetSelectFoldableOperands(Instruction *I) {
8481 switch (I->getOpcode()) {
8482 case Instruction::Add:
8483 case Instruction::Mul:
8484 case Instruction::And:
8485 case Instruction::Or:
8486 case Instruction::Xor:
8487 return 3; // Can fold through either operand.
8488 case Instruction::Sub: // Can only fold on the amount subtracted.
8489 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008490 case Instruction::LShr:
8491 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008492 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008493 default:
8494 return 0; // Cannot fold
8495 }
8496}
8497
8498/// GetSelectFoldableConstant - For the same transformation as the previous
8499/// function, return the identity constant that goes into the select.
8500static Constant *GetSelectFoldableConstant(Instruction *I) {
8501 switch (I->getOpcode()) {
8502 default: assert(0 && "This cannot happen!"); abort();
8503 case Instruction::Add:
8504 case Instruction::Sub:
8505 case Instruction::Or:
8506 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008507 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008508 case Instruction::LShr:
8509 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008510 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008511 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008512 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008513 case Instruction::Mul:
8514 return ConstantInt::get(I->getType(), 1);
8515 }
8516}
8517
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008518/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8519/// have the same opcode and only one use each. Try to simplify this.
8520Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8521 Instruction *FI) {
8522 if (TI->getNumOperands() == 1) {
8523 // If this is a non-volatile load or a cast from the same type,
8524 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008525 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008526 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8527 return 0;
8528 } else {
8529 return 0; // unknown unary op.
8530 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008531
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008532 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008533 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8534 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008535 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008536 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008537 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008538 }
8539
Reid Spencer832254e2007-02-02 02:16:23 +00008540 // Only handle binary operators here.
8541 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008542 return 0;
8543
8544 // Figure out if the operations have any operands in common.
8545 Value *MatchOp, *OtherOpT, *OtherOpF;
8546 bool MatchIsOpZero;
8547 if (TI->getOperand(0) == FI->getOperand(0)) {
8548 MatchOp = TI->getOperand(0);
8549 OtherOpT = TI->getOperand(1);
8550 OtherOpF = FI->getOperand(1);
8551 MatchIsOpZero = true;
8552 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8553 MatchOp = TI->getOperand(1);
8554 OtherOpT = TI->getOperand(0);
8555 OtherOpF = FI->getOperand(0);
8556 MatchIsOpZero = false;
8557 } else if (!TI->isCommutative()) {
8558 return 0;
8559 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8560 MatchOp = TI->getOperand(0);
8561 OtherOpT = TI->getOperand(1);
8562 OtherOpF = FI->getOperand(0);
8563 MatchIsOpZero = true;
8564 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8565 MatchOp = TI->getOperand(1);
8566 OtherOpT = TI->getOperand(0);
8567 OtherOpF = FI->getOperand(1);
8568 MatchIsOpZero = true;
8569 } else {
8570 return 0;
8571 }
8572
8573 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008574 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8575 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008576 InsertNewInstBefore(NewSI, SI);
8577
8578 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8579 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008580 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008581 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008582 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008583 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008584 assert(0 && "Shouldn't get here");
8585 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008586}
8587
Chris Lattner3d69f462004-03-12 05:52:32 +00008588Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008589 Value *CondVal = SI.getCondition();
8590 Value *TrueVal = SI.getTrueValue();
8591 Value *FalseVal = SI.getFalseValue();
8592
8593 // select true, X, Y -> X
8594 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008595 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008596 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008597
8598 // select C, X, X -> X
8599 if (TrueVal == FalseVal)
8600 return ReplaceInstUsesWith(SI, TrueVal);
8601
Chris Lattnere87597f2004-10-16 18:11:37 +00008602 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8603 return ReplaceInstUsesWith(SI, FalseVal);
8604 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8605 return ReplaceInstUsesWith(SI, TrueVal);
8606 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8607 if (isa<Constant>(TrueVal))
8608 return ReplaceInstUsesWith(SI, TrueVal);
8609 else
8610 return ReplaceInstUsesWith(SI, FalseVal);
8611 }
8612
Reid Spencer4fe16d62007-01-11 18:21:29 +00008613 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008614 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008615 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008616 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008617 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008618 } else {
8619 // Change: A = select B, false, C --> A = and !B, C
8620 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008621 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008622 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008623 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008624 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008625 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008626 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008627 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008628 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008629 } else {
8630 // Change: A = select B, C, true --> A = or !B, C
8631 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008632 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008633 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008634 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008635 }
8636 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008637
8638 // select a, b, a -> a&b
8639 // select a, a, b -> a|b
8640 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008641 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008642 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008643 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008644 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008645
Chris Lattner2eefe512004-04-09 19:05:30 +00008646 // Selecting between two integer constants?
8647 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8648 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008649 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008650 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008651 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008652 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008653 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008654 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008655 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008656 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008657 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008658 }
Chris Lattnerba417832007-04-11 06:12:58 +00008659
8660 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008661
Reid Spencere4d87aa2006-12-23 06:05:41 +00008662 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008663
Reid Spencere4d87aa2006-12-23 06:05:41 +00008664 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008665 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008666 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008667 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008668 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008669 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008670 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008671 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008672 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008673 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008674 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008675 InsertNewInstBefore(SRA, SI);
8676
Reid Spencer3da59db2006-11-27 01:05:10 +00008677 // Finally, convert to the type of the select RHS. We figure out
8678 // if this requires a SExt, Trunc or BitCast based on the sizes.
8679 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008680 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8681 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008682 if (SRASize < SISize)
8683 opc = Instruction::SExt;
8684 else if (SRASize > SISize)
8685 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008686 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008687 }
8688 }
8689
8690
8691 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008692 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008693 // non-constant value, eliminate this whole mess. This corresponds to
8694 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008695 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008696 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008697 cast<Constant>(IC->getOperand(1))->isNullValue())
8698 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8699 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008700 isa<ConstantInt>(ICA->getOperand(1)) &&
8701 (ICA->getOperand(1) == TrueValC ||
8702 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008703 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8704 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008705 // know whether we have a icmp_ne or icmp_eq and whether the
8706 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008707 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008708 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008709 Value *V = ICA;
8710 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008711 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008712 Instruction::Xor, V, ICA->getOperand(1)), SI);
8713 return ReplaceInstUsesWith(SI, V);
8714 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008715 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008716 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008717
8718 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008719 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8720 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008721 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008722 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8723 // This is not safe in general for floating point:
8724 // consider X== -0, Y== +0.
8725 // It becomes safe if either operand is a nonzero constant.
8726 ConstantFP *CFPt, *CFPf;
8727 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8728 !CFPt->getValueAPF().isZero()) ||
8729 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8730 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008731 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008732 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008733 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008734 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008735 return ReplaceInstUsesWith(SI, TrueVal);
8736 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8737
Reid Spencere4d87aa2006-12-23 06:05:41 +00008738 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008739 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008740 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8741 // This is not safe in general for floating point:
8742 // consider X== -0, Y== +0.
8743 // It becomes safe if either operand is a nonzero constant.
8744 ConstantFP *CFPt, *CFPf;
8745 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8746 !CFPt->getValueAPF().isZero()) ||
8747 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8748 !CFPf->getValueAPF().isZero()))
8749 return ReplaceInstUsesWith(SI, FalseVal);
8750 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008751 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008752 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8753 return ReplaceInstUsesWith(SI, TrueVal);
8754 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8755 }
8756 }
8757
8758 // See if we are selecting two values based on a comparison of the two values.
8759 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8760 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8761 // Transform (X == Y) ? X : Y -> Y
8762 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8763 return ReplaceInstUsesWith(SI, FalseVal);
8764 // Transform (X != Y) ? X : Y -> X
8765 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8766 return ReplaceInstUsesWith(SI, TrueVal);
8767 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8768
8769 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8770 // Transform (X == Y) ? Y : X -> X
8771 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8772 return ReplaceInstUsesWith(SI, FalseVal);
8773 // Transform (X != Y) ? Y : X -> Y
8774 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008775 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008776 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8777 }
8778 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008779
Chris Lattner87875da2005-01-13 22:52:24 +00008780 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8781 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8782 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008783 Instruction *AddOp = 0, *SubOp = 0;
8784
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008785 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8786 if (TI->getOpcode() == FI->getOpcode())
8787 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8788 return IV;
8789
8790 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8791 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008792 if (TI->getOpcode() == Instruction::Sub &&
8793 FI->getOpcode() == Instruction::Add) {
8794 AddOp = FI; SubOp = TI;
8795 } else if (FI->getOpcode() == Instruction::Sub &&
8796 TI->getOpcode() == Instruction::Add) {
8797 AddOp = TI; SubOp = FI;
8798 }
8799
8800 if (AddOp) {
8801 Value *OtherAddOp = 0;
8802 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8803 OtherAddOp = AddOp->getOperand(1);
8804 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8805 OtherAddOp = AddOp->getOperand(0);
8806 }
8807
8808 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008809 // So at this point we know we have (Y -> OtherAddOp):
8810 // select C, (add X, Y), (sub X, Z)
8811 Value *NegVal; // Compute -Z
8812 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8813 NegVal = ConstantExpr::getNeg(C);
8814 } else {
8815 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008816 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008817 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008818
8819 Value *NewTrueOp = OtherAddOp;
8820 Value *NewFalseOp = NegVal;
8821 if (AddOp != TI)
8822 std::swap(NewTrueOp, NewFalseOp);
8823 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008824 SelectInst::Create(CondVal, NewTrueOp,
8825 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008826
8827 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008828 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008829 }
8830 }
8831 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008832
Chris Lattnere576b912004-04-09 23:46:01 +00008833 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008834 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008835 // See the comment above GetSelectFoldableOperands for a description of the
8836 // transformation we are doing here.
8837 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8838 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8839 !isa<Constant>(FalseVal))
8840 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8841 unsigned OpToFold = 0;
8842 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8843 OpToFold = 1;
8844 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8845 OpToFold = 2;
8846 }
8847
8848 if (OpToFold) {
8849 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008850 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008851 SelectInst::Create(SI.getCondition(),
8852 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008853 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008854 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008855 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008856 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008857 else {
8858 assert(0 && "Unknown instruction!!");
8859 }
8860 }
8861 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008862
Chris Lattnere576b912004-04-09 23:46:01 +00008863 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8864 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8865 !isa<Constant>(TrueVal))
8866 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8867 unsigned OpToFold = 0;
8868 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8869 OpToFold = 1;
8870 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8871 OpToFold = 2;
8872 }
8873
8874 if (OpToFold) {
8875 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008876 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008877 SelectInst::Create(SI.getCondition(), C,
8878 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008879 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008880 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008881 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008882 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008883 else
Chris Lattnere576b912004-04-09 23:46:01 +00008884 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008885 }
8886 }
8887 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008888
8889 if (BinaryOperator::isNot(CondVal)) {
8890 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8891 SI.setOperand(1, FalseVal);
8892 SI.setOperand(2, TrueVal);
8893 return &SI;
8894 }
8895
Chris Lattner3d69f462004-03-12 05:52:32 +00008896 return 0;
8897}
8898
Dan Gohmaneee962e2008-04-10 18:43:06 +00008899/// EnforceKnownAlignment - If the specified pointer points to an object that
8900/// we control, modify the object's alignment to PrefAlign. This isn't
8901/// often possible though. If alignment is important, a more reliable approach
8902/// is to simply align all global variables and allocation instructions to
8903/// their preferred alignment from the beginning.
8904///
8905static unsigned EnforceKnownAlignment(Value *V,
8906 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008907
Dan Gohmaneee962e2008-04-10 18:43:06 +00008908 User *U = dyn_cast<User>(V);
8909 if (!U) return Align;
8910
8911 switch (getOpcode(U)) {
8912 default: break;
8913 case Instruction::BitCast:
8914 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8915 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008916 // If all indexes are zero, it is just the alignment of the base pointer.
8917 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008918 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8919 if (!isa<Constant>(U->getOperand(i)) ||
8920 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008921 AllZeroOperands = false;
8922 break;
8923 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008924
8925 if (AllZeroOperands) {
8926 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008927 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008928 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008929 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008930 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008931 }
8932
8933 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8934 // If there is a large requested alignment and we can, bump up the alignment
8935 // of the global.
8936 if (!GV->isDeclaration()) {
8937 GV->setAlignment(PrefAlign);
8938 Align = PrefAlign;
8939 }
8940 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8941 // If there is a requested alignment and if this is an alloca, round up. We
8942 // don't do this for malloc, because some systems can't respect the request.
8943 if (isa<AllocaInst>(AI)) {
8944 AI->setAlignment(PrefAlign);
8945 Align = PrefAlign;
8946 }
8947 }
8948
8949 return Align;
8950}
8951
8952/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8953/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8954/// and it is more than the alignment of the ultimate object, see if we can
8955/// increase the alignment of the ultimate object, making this check succeed.
8956unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8957 unsigned PrefAlign) {
8958 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8959 sizeof(PrefAlign) * CHAR_BIT;
8960 APInt Mask = APInt::getAllOnesValue(BitWidth);
8961 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8962 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8963 unsigned TrailZ = KnownZero.countTrailingOnes();
8964 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8965
8966 if (PrefAlign > Align)
8967 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8968
8969 // We don't need to make any adjustment.
8970 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008971}
8972
Chris Lattnerf497b022008-01-13 23:50:23 +00008973Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008974 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8975 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008976 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8977 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8978
8979 if (CopyAlign < MinAlign) {
8980 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8981 return MI;
8982 }
8983
8984 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8985 // load/store.
8986 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8987 if (MemOpLength == 0) return 0;
8988
Chris Lattner37ac6082008-01-14 00:28:35 +00008989 // Source and destination pointer types are always "i8*" for intrinsic. See
8990 // if the size is something we can handle with a single primitive load/store.
8991 // A single load+store correctly handles overlapping memory in the memmove
8992 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008993 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008994 if (Size == 0) return MI; // Delete this mem transfer.
8995
8996 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008997 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008998
Chris Lattner37ac6082008-01-14 00:28:35 +00008999 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009000 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009001
9002 // Memcpy forces the use of i8* for the source and destination. That means
9003 // that if you're using memcpy to move one double around, you'll get a cast
9004 // from double* to i8*. We'd much rather use a double load+store rather than
9005 // an i64 load+store, here because this improves the odds that the source or
9006 // dest address will be promotable. See if we can find a better type than the
9007 // integer datatype.
9008 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9009 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9010 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9011 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9012 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009013 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009014 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9015 if (STy->getNumElements() == 1)
9016 SrcETy = STy->getElementType(0);
9017 else
9018 break;
9019 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9020 if (ATy->getNumElements() == 1)
9021 SrcETy = ATy->getElementType();
9022 else
9023 break;
9024 } else
9025 break;
9026 }
9027
Dan Gohman8f8e2692008-05-23 01:52:21 +00009028 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009029 NewPtrTy = PointerType::getUnqual(SrcETy);
9030 }
9031 }
9032
9033
Chris Lattnerf497b022008-01-13 23:50:23 +00009034 // If the memcpy/memmove provides better alignment info than we can
9035 // infer, use it.
9036 SrcAlign = std::max(SrcAlign, CopyAlign);
9037 DstAlign = std::max(DstAlign, CopyAlign);
9038
9039 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9040 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009041 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9042 InsertNewInstBefore(L, *MI);
9043 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9044
9045 // Set the size of the copy to 0, it will be deleted on the next iteration.
9046 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9047 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009048}
Chris Lattner3d69f462004-03-12 05:52:32 +00009049
Chris Lattner69ea9d22008-04-30 06:39:11 +00009050Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9051 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9052 if (MI->getAlignment()->getZExtValue() < Alignment) {
9053 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9054 return MI;
9055 }
9056
9057 // Extract the length and alignment and fill if they are constant.
9058 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9059 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9060 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9061 return 0;
9062 uint64_t Len = LenC->getZExtValue();
9063 Alignment = MI->getAlignment()->getZExtValue();
9064
9065 // If the length is zero, this is a no-op
9066 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9067
9068 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9069 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9070 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9071
9072 Value *Dest = MI->getDest();
9073 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9074
9075 // Alignment 0 is identity for alignment 1 for memset, but not store.
9076 if (Alignment == 0) Alignment = 1;
9077
9078 // Extract the fill value and store.
9079 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9080 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9081 Alignment), *MI);
9082
9083 // Set the size of the copy to 0, it will be deleted on the next iteration.
9084 MI->setLength(Constant::getNullValue(LenC->getType()));
9085 return MI;
9086 }
9087
9088 return 0;
9089}
9090
9091
Chris Lattner8b0ea312006-01-13 20:11:04 +00009092/// visitCallInst - CallInst simplification. This mostly only handles folding
9093/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9094/// the heavy lifting.
9095///
Chris Lattner9fe38862003-06-19 17:00:31 +00009096Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00009097 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9098 if (!II) return visitCallSite(&CI);
9099
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009100 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9101 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009102 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009103 bool Changed = false;
9104
9105 // memmove/cpy/set of zero bytes is a noop.
9106 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9107 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9108
Chris Lattner35b9e482004-10-12 04:52:52 +00009109 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009110 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009111 // Replace the instruction with just byte operations. We would
9112 // transform other cases to loads/stores, but we don't know if
9113 // alignment is sufficient.
9114 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009115 }
9116
Chris Lattner35b9e482004-10-12 04:52:52 +00009117 // If we have a memmove and the source operation is a constant global,
9118 // then the source and dest pointers can't alias, so we can change this
9119 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009120 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009121 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9122 if (GVSrc->isConstant()) {
9123 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00009124 Intrinsic::ID MemCpyID;
9125 if (CI.getOperand(3)->getType() == Type::Int32Ty)
9126 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00009127 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00009128 MemCpyID = Intrinsic::memcpy_i64;
9129 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00009130 Changed = true;
9131 }
Chris Lattner95a959d2006-03-06 20:18:44 +00009132 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009133
Chris Lattner95a959d2006-03-06 20:18:44 +00009134 // If we can determine a pointer alignment that is bigger than currently
9135 // set, update the alignment.
9136 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009137 if (Instruction *I = SimplifyMemTransfer(MI))
9138 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009139 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9140 if (Instruction *I = SimplifyMemSet(MSI))
9141 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009142 }
9143
Chris Lattner8b0ea312006-01-13 20:11:04 +00009144 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00009145 } else {
9146 switch (II->getIntrinsicID()) {
9147 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00009148 case Intrinsic::ppc_altivec_lvx:
9149 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009150 case Intrinsic::x86_sse_loadu_ps:
9151 case Intrinsic::x86_sse2_loadu_pd:
9152 case Intrinsic::x86_sse2_loadu_dq:
9153 // Turn PPC lvx -> load if the pointer is known aligned.
9154 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009155 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00009156 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9157 PointerType::getUnqual(II->getType()),
9158 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009159 return new LoadInst(Ptr);
9160 }
9161 break;
9162 case Intrinsic::ppc_altivec_stvx:
9163 case Intrinsic::ppc_altivec_stvxl:
9164 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009165 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009166 const Type *OpPtrTy =
9167 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009168 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009169 return new StoreInst(II->getOperand(1), Ptr);
9170 }
9171 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009172 case Intrinsic::x86_sse_storeu_ps:
9173 case Intrinsic::x86_sse2_storeu_pd:
9174 case Intrinsic::x86_sse2_storeu_dq:
9175 case Intrinsic::x86_sse2_storel_dq:
9176 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009177 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009178 const Type *OpPtrTy =
9179 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009180 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009181 return new StoreInst(II->getOperand(2), Ptr);
9182 }
9183 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00009184
9185 case Intrinsic::x86_sse_cvttss2si: {
9186 // These intrinsics only demands the 0th element of its input vector. If
9187 // we can simplify the input based on that, do so now.
9188 uint64_t UndefElts;
9189 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9190 UndefElts)) {
9191 II->setOperand(1, V);
9192 return II;
9193 }
9194 break;
9195 }
9196
Chris Lattnere2ed0572006-04-06 19:19:17 +00009197 case Intrinsic::ppc_altivec_vperm:
9198 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009199 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00009200 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9201
9202 // Check that all of the elements are integer constants or undefs.
9203 bool AllEltsOk = true;
9204 for (unsigned i = 0; i != 16; ++i) {
9205 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9206 !isa<UndefValue>(Mask->getOperand(i))) {
9207 AllEltsOk = false;
9208 break;
9209 }
9210 }
9211
9212 if (AllEltsOk) {
9213 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00009214 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9215 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009216 Value *Result = UndefValue::get(Op0->getType());
9217
9218 // Only extract each element once.
9219 Value *ExtractedElts[32];
9220 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9221
9222 for (unsigned i = 0; i != 16; ++i) {
9223 if (isa<UndefValue>(Mask->getOperand(i)))
9224 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00009225 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00009226 Idx &= 31; // Match the hardware behavior.
9227
9228 if (ExtractedElts[Idx] == 0) {
9229 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00009230 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009231 InsertNewInstBefore(Elt, CI);
9232 ExtractedElts[Idx] = Elt;
9233 }
9234
9235 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009236 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9237 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009238 InsertNewInstBefore(cast<Instruction>(Result), CI);
9239 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009240 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009241 }
9242 }
9243 break;
9244
Chris Lattnera728ddc2006-01-13 21:28:09 +00009245 case Intrinsic::stackrestore: {
9246 // If the save is right next to the restore, remove the restore. This can
9247 // happen when variable allocas are DCE'd.
9248 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9249 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9250 BasicBlock::iterator BI = SS;
9251 if (&*++BI == II)
9252 return EraseInstFromFunction(CI);
9253 }
9254 }
9255
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009256 // Scan down this block to see if there is another stack restore in the
9257 // same block without an intervening call/alloca.
9258 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00009259 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009260 bool CannotRemove = false;
9261 for (++BI; &*BI != TI; ++BI) {
9262 if (isa<AllocaInst>(BI)) {
9263 CannotRemove = true;
9264 break;
9265 }
9266 if (isa<CallInst>(BI)) {
9267 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00009268 CannotRemove = true;
9269 break;
9270 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009271 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00009272 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009273 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009274 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009275
9276 // If the stack restore is in a return/unwind block and if there are no
9277 // allocas or calls between the restore and the return, nuke the restore.
9278 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9279 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009280 break;
9281 }
9282 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009283 }
9284
Chris Lattner8b0ea312006-01-13 20:11:04 +00009285 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009286}
9287
9288// InvokeInst simplification
9289//
9290Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009291 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009292}
9293
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009294/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9295/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009296static bool isSafeToEliminateVarargsCast(const CallSite CS,
9297 const CastInst * const CI,
9298 const TargetData * const TD,
9299 const int ix) {
9300 if (!CI->isLosslessCast())
9301 return false;
9302
9303 // The size of ByVal arguments is derived from the type, so we
9304 // can't change to a type with a different size. If the size were
9305 // passed explicitly we could avoid this check.
9306 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9307 return true;
9308
9309 const Type* SrcTy =
9310 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9311 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9312 if (!SrcTy->isSized() || !DstTy->isSized())
9313 return false;
9314 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9315 return false;
9316 return true;
9317}
9318
Chris Lattnera44d8a22003-10-07 22:32:43 +00009319// visitCallSite - Improvements for call and invoke instructions.
9320//
9321Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009322 bool Changed = false;
9323
9324 // If the callee is a constexpr cast of a function, attempt to move the cast
9325 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009326 if (transformConstExprCastCall(CS)) return 0;
9327
Chris Lattner6c266db2003-10-07 22:54:13 +00009328 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009329
Chris Lattner08b22ec2005-05-13 07:09:09 +00009330 if (Function *CalleeF = dyn_cast<Function>(Callee))
9331 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9332 Instruction *OldCall = CS.getInstruction();
9333 // If the call and callee calling conventions don't match, this call must
9334 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009335 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009336 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9337 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009338 if (!OldCall->use_empty())
9339 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9340 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9341 return EraseInstFromFunction(*OldCall);
9342 return 0;
9343 }
9344
Chris Lattner17be6352004-10-18 02:59:09 +00009345 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9346 // This instruction is not reachable, just remove it. We insert a store to
9347 // undef so that we know that this code is not reachable, despite the fact
9348 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009349 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009350 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009351 CS.getInstruction());
9352
9353 if (!CS.getInstruction()->use_empty())
9354 CS.getInstruction()->
9355 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9356
9357 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9358 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009359 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9360 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009361 }
Chris Lattner17be6352004-10-18 02:59:09 +00009362 return EraseInstFromFunction(*CS.getInstruction());
9363 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009364
Duncan Sandscdb6d922007-09-17 10:26:40 +00009365 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9366 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9367 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9368 return transformCallThroughTrampoline(CS);
9369
Chris Lattner6c266db2003-10-07 22:54:13 +00009370 const PointerType *PTy = cast<PointerType>(Callee->getType());
9371 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9372 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009373 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009374 // See if we can optimize any arguments passed through the varargs area of
9375 // the call.
9376 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009377 E = CS.arg_end(); I != E; ++I, ++ix) {
9378 CastInst *CI = dyn_cast<CastInst>(*I);
9379 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9380 *I = CI->getOperand(0);
9381 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009382 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009383 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009384 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009385
Duncan Sandsf0c33542007-12-19 21:13:37 +00009386 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009387 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009388 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009389 Changed = true;
9390 }
9391
Chris Lattner6c266db2003-10-07 22:54:13 +00009392 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009393}
9394
Chris Lattner9fe38862003-06-19 17:00:31 +00009395// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9396// attempt to move the cast to the arguments of the call/invoke.
9397//
9398bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9399 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9400 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009401 if (CE->getOpcode() != Instruction::BitCast ||
9402 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009403 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009404 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009405 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00009406 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00009407
9408 // Okay, this is a cast from a function to a different type. Unless doing so
9409 // would cause a type conversion of one of our arguments, change this call to
9410 // be a direct call with arguments casted to the appropriate types.
9411 //
9412 const FunctionType *FT = Callee->getFunctionType();
9413 const Type *OldRetTy = Caller->getType();
9414
Devang Patel75e6f022008-03-11 18:04:06 +00009415 if (isa<StructType>(FT->getReturnType()))
9416 return false; // TODO: Handle multiple return values.
9417
Chris Lattnerf78616b2004-01-14 06:06:08 +00009418 // Check to see if we are changing the return type...
9419 if (OldRetTy != FT->getReturnType()) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009420 if (Callee->isDeclaration() &&
Chris Lattner46013f42007-01-06 19:53:32 +00009421 // Conversion is ok if changing from pointer to int of same size.
9422 !(isa<PointerType>(FT->getReturnType()) &&
9423 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00009424 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009425
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009426 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009427 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00009428 FT->getReturnType() != Type::VoidTy &&
9429 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009430 return false; // Cannot transform this return value.
9431
Chris Lattner58d74912008-03-12 17:45:29 +00009432 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9433 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00009434 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9435 return false; // Attribute not compatible with transformed value.
9436 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009437
Chris Lattnerf78616b2004-01-14 06:06:08 +00009438 // If the callsite is an invoke instruction, and the return value is used by
9439 // a PHI node in a successor, we cannot change the return type of the call
9440 // because there is no place to put the cast instruction (without breaking
9441 // the critical edge). Bail out in this case.
9442 if (!Caller->use_empty())
9443 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9444 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9445 UI != E; ++UI)
9446 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9447 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009448 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009449 return false;
9450 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009451
9452 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9453 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009454
Chris Lattner9fe38862003-06-19 17:00:31 +00009455 CallSite::arg_iterator AI = CS.arg_begin();
9456 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9457 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009458 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009459
9460 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009461 return false; // Cannot transform this parameter value.
9462
Chris Lattner58d74912008-03-12 17:45:29 +00009463 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9464 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009465
Reid Spencer3da59db2006-11-27 01:05:10 +00009466 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009467 // Some conversions are safe even if we do not have a body.
9468 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00009469 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00009470 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00009471 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009472 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9473 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00009474 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00009475 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009476 }
9477
9478 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009479 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009480 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009481
Chris Lattner58d74912008-03-12 17:45:29 +00009482 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9483 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009484 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009485 // won't be dropping them. Check that these extra arguments have attributes
9486 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009487 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9488 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009489 break;
Chris Lattner58d74912008-03-12 17:45:29 +00009490 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00009491 if (PAttrs & ParamAttr::VarArgsIncompatible)
9492 return false;
9493 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009494
Chris Lattner9fe38862003-06-19 17:00:31 +00009495 // Okay, we decided that this is a safe thing to do: go ahead and start
9496 // inserting cast instructions as necessary...
9497 std::vector<Value*> Args;
9498 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00009499 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009500 attrVec.reserve(NumCommonArgs);
9501
9502 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009503 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009504
9505 // If the return value is not being used, the type may not be compatible
9506 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00009507 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009508
9509 // Add the new return attributes.
9510 if (RAttrs)
9511 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009512
9513 AI = CS.arg_begin();
9514 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9515 const Type *ParamTy = FT->getParamType(i);
9516 if ((*AI)->getType() == ParamTy) {
9517 Args.push_back(*AI);
9518 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009519 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009520 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009521 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009522 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009523 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009524
9525 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009526 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009527 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009528 }
9529
9530 // If the function takes more arguments than the call was taking, add them
9531 // now...
9532 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9533 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9534
9535 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009536 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009537 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009538 cerr << "WARNING: While resolving call to function '"
9539 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009540 } else {
9541 // Add all of the arguments in their promoted form to the arg list...
9542 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9543 const Type *PTy = getPromotedType((*AI)->getType());
9544 if (PTy != (*AI)->getType()) {
9545 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009546 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9547 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009548 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009549 InsertNewInstBefore(Cast, *Caller);
9550 Args.push_back(Cast);
9551 } else {
9552 Args.push_back(*AI);
9553 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009554
Duncan Sandse1e520f2008-01-13 08:02:44 +00009555 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009556 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009557 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9558 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009559 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009560 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009561
9562 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009563 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009564
Chris Lattner58d74912008-03-12 17:45:29 +00009565 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009566
Chris Lattner9fe38862003-06-19 17:00:31 +00009567 Instruction *NC;
9568 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009569 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009570 Args.begin(), Args.end(),
9571 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009572 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009573 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009574 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009575 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9576 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009577 CallInst *CI = cast<CallInst>(Caller);
9578 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009579 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009580 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009581 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009582 }
9583
Chris Lattner6934a042007-02-11 01:23:03 +00009584 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009585 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009586 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009587 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009588 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009589 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009590 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009591
9592 // If this is an invoke instruction, we should insert it after the first
9593 // non-phi, instruction in the normal successor block.
9594 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009595 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009596 InsertNewInstBefore(NC, *I);
9597 } else {
9598 // Otherwise, it's a call, just insert cast right after the call instr
9599 InsertNewInstBefore(NC, *Caller);
9600 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009601 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009602 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009603 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009604 }
9605 }
9606
9607 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9608 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009609 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009610 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009611 return true;
9612}
9613
Duncan Sandscdb6d922007-09-17 10:26:40 +00009614// transformCallThroughTrampoline - Turn a call to a function created by the
9615// init_trampoline intrinsic into a direct call to the underlying function.
9616//
9617Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9618 Value *Callee = CS.getCalledValue();
9619 const PointerType *PTy = cast<PointerType>(Callee->getType());
9620 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009621 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009622
9623 // If the call already has the 'nest' attribute somewhere then give up -
9624 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009625 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009626 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009627
9628 IntrinsicInst *Tramp =
9629 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9630
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009631 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009632 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9633 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9634
Chris Lattner58d74912008-03-12 17:45:29 +00009635 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9636 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009637 unsigned NestIdx = 1;
9638 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009639 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009640
9641 // Look for a parameter marked with the 'nest' attribute.
9642 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9643 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009644 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009645 // Record the parameter type and any other attributes.
9646 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009647 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009648 break;
9649 }
9650
9651 if (NestTy) {
9652 Instruction *Caller = CS.getInstruction();
9653 std::vector<Value*> NewArgs;
9654 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9655
Chris Lattner58d74912008-03-12 17:45:29 +00009656 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9657 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009658
Duncan Sandscdb6d922007-09-17 10:26:40 +00009659 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009660 // mean appending it. Likewise for attributes.
9661
9662 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009663 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9664 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009665
Duncan Sandscdb6d922007-09-17 10:26:40 +00009666 {
9667 unsigned Idx = 1;
9668 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9669 do {
9670 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009671 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009672 Value *NestVal = Tramp->getOperand(3);
9673 if (NestVal->getType() != NestTy)
9674 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9675 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009676 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009677 }
9678
9679 if (I == E)
9680 break;
9681
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009682 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009683 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009684 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009685 NewAttrs.push_back
9686 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009687
9688 ++Idx, ++I;
9689 } while (1);
9690 }
9691
9692 // The trampoline may have been bitcast to a bogus type (FTy).
9693 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009694 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009695
Duncan Sandscdb6d922007-09-17 10:26:40 +00009696 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009697 NewTypes.reserve(FTy->getNumParams()+1);
9698
Duncan Sandscdb6d922007-09-17 10:26:40 +00009699 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009700 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009701 {
9702 unsigned Idx = 1;
9703 FunctionType::param_iterator I = FTy->param_begin(),
9704 E = FTy->param_end();
9705
9706 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009707 if (Idx == NestIdx)
9708 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009709 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009710
9711 if (I == E)
9712 break;
9713
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009714 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009715 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009716
9717 ++Idx, ++I;
9718 } while (1);
9719 }
9720
9721 // Replace the trampoline call with a direct call. Let the generic
9722 // code sort out any function type mismatches.
9723 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009724 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009725 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9726 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009727 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009728
9729 Instruction *NewCaller;
9730 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009731 NewCaller = InvokeInst::Create(NewCallee,
9732 II->getNormalDest(), II->getUnwindDest(),
9733 NewArgs.begin(), NewArgs.end(),
9734 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009735 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009736 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009737 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009738 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9739 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009740 if (cast<CallInst>(Caller)->isTailCall())
9741 cast<CallInst>(NewCaller)->setTailCall();
9742 cast<CallInst>(NewCaller)->
9743 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009744 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009745 }
9746 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9747 Caller->replaceAllUsesWith(NewCaller);
9748 Caller->eraseFromParent();
9749 RemoveFromWorkList(Caller);
9750 return 0;
9751 }
9752 }
9753
9754 // Replace the trampoline call with a direct call. Since there is no 'nest'
9755 // parameter, there is no need to adjust the argument list. Let the generic
9756 // code sort out any function type mismatches.
9757 Constant *NewCallee =
9758 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9759 CS.setCalledFunction(NewCallee);
9760 return CS.getInstruction();
9761}
9762
Chris Lattner7da52b22006-11-01 04:51:18 +00009763/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9764/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9765/// and a single binop.
9766Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9767 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009768 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9769 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009770 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009771 Value *LHSVal = FirstInst->getOperand(0);
9772 Value *RHSVal = FirstInst->getOperand(1);
9773
9774 const Type *LHSType = LHSVal->getType();
9775 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009776
9777 // Scan to see if all operands are the same opcode, all have one use, and all
9778 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009779 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009780 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009781 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009782 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009783 // types or GEP's with different index types.
9784 I->getOperand(0)->getType() != LHSType ||
9785 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009786 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009787
9788 // If they are CmpInst instructions, check their predicates
9789 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9790 if (cast<CmpInst>(I)->getPredicate() !=
9791 cast<CmpInst>(FirstInst)->getPredicate())
9792 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009793
9794 // Keep track of which operand needs a phi node.
9795 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9796 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009797 }
9798
Chris Lattner53738a42006-11-08 19:42:28 +00009799 // Otherwise, this is safe to transform, determine if it is profitable.
9800
9801 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9802 // Indexes are often folded into load/store instructions, so we don't want to
9803 // hide them behind a phi.
9804 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9805 return 0;
9806
Chris Lattner7da52b22006-11-01 04:51:18 +00009807 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009808 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009809 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009810 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009811 NewLHS = PHINode::Create(LHSType,
9812 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009813 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9814 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009815 InsertNewInstBefore(NewLHS, PN);
9816 LHSVal = NewLHS;
9817 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009818
9819 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009820 NewRHS = PHINode::Create(RHSType,
9821 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009822 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9823 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009824 InsertNewInstBefore(NewRHS, PN);
9825 RHSVal = NewRHS;
9826 }
9827
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009828 // Add all operands to the new PHIs.
9829 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9830 if (NewLHS) {
9831 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9832 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9833 }
9834 if (NewRHS) {
9835 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9836 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9837 }
9838 }
9839
Chris Lattner7da52b22006-11-01 04:51:18 +00009840 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009841 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009842 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009843 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009844 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009845 else {
9846 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009847 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009848 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009849}
9850
Chris Lattner76c73142006-11-01 07:13:54 +00009851/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9852/// of the block that defines it. This means that it must be obvious the value
9853/// of the load is not changed from the point of the load to the end of the
9854/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009855///
9856/// Finally, it is safe, but not profitable, to sink a load targetting a
9857/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9858/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009859static bool isSafeToSinkLoad(LoadInst *L) {
9860 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9861
9862 for (++BBI; BBI != E; ++BBI)
9863 if (BBI->mayWriteToMemory())
9864 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009865
9866 // Check for non-address taken alloca. If not address-taken already, it isn't
9867 // profitable to do this xform.
9868 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9869 bool isAddressTaken = false;
9870 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9871 UI != E; ++UI) {
9872 if (isa<LoadInst>(UI)) continue;
9873 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9874 // If storing TO the alloca, then the address isn't taken.
9875 if (SI->getOperand(1) == AI) continue;
9876 }
9877 isAddressTaken = true;
9878 break;
9879 }
9880
9881 if (!isAddressTaken)
9882 return false;
9883 }
9884
Chris Lattner76c73142006-11-01 07:13:54 +00009885 return true;
9886}
9887
Chris Lattner9fe38862003-06-19 17:00:31 +00009888
Chris Lattnerbac32862004-11-14 19:13:23 +00009889// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9890// operator and they all are only used by the PHI, PHI together their
9891// inputs, and do the operation once, to the result of the PHI.
9892Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9893 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9894
9895 // Scan the instruction, looking for input operations that can be folded away.
9896 // If all input operands to the phi are the same instruction (e.g. a cast from
9897 // the same type or "+42") we can pull the operation through the PHI, reducing
9898 // code size and simplifying code.
9899 Constant *ConstantOp = 0;
9900 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009901 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009902 if (isa<CastInst>(FirstInst)) {
9903 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009904 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009905 // Can fold binop, compare or shift here if the RHS is a constant,
9906 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009907 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009908 if (ConstantOp == 0)
9909 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009910 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9911 isVolatile = LI->isVolatile();
9912 // We can't sink the load if the loaded value could be modified between the
9913 // load and the PHI.
9914 if (LI->getParent() != PN.getIncomingBlock(0) ||
9915 !isSafeToSinkLoad(LI))
9916 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009917 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009918 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009919 return FoldPHIArgBinOpIntoPHI(PN);
9920 // Can't handle general GEPs yet.
9921 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009922 } else {
9923 return 0; // Cannot fold this operation.
9924 }
9925
9926 // Check to see if all arguments are the same operation.
9927 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9928 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9929 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009930 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009931 return 0;
9932 if (CastSrcTy) {
9933 if (I->getOperand(0)->getType() != CastSrcTy)
9934 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009935 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009936 // We can't sink the load if the loaded value could be modified between
9937 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009938 if (LI->isVolatile() != isVolatile ||
9939 LI->getParent() != PN.getIncomingBlock(i) ||
9940 !isSafeToSinkLoad(LI))
9941 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009942
9943 // If the PHI is volatile and its block has multiple successors, sinking
9944 // it would remove a load of the volatile value from the path through the
9945 // other successor.
9946 if (isVolatile &&
9947 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9948 return 0;
9949
9950
Chris Lattnerbac32862004-11-14 19:13:23 +00009951 } else if (I->getOperand(1) != ConstantOp) {
9952 return 0;
9953 }
9954 }
9955
9956 // Okay, they are all the same operation. Create a new PHI node of the
9957 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009958 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9959 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009960 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009961
9962 Value *InVal = FirstInst->getOperand(0);
9963 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009964
9965 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009966 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9967 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9968 if (NewInVal != InVal)
9969 InVal = 0;
9970 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9971 }
9972
9973 Value *PhiVal;
9974 if (InVal) {
9975 // The new PHI unions all of the same values together. This is really
9976 // common, so we handle it intelligently here for compile-time speed.
9977 PhiVal = InVal;
9978 delete NewPN;
9979 } else {
9980 InsertNewInstBefore(NewPN, PN);
9981 PhiVal = NewPN;
9982 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009983
Chris Lattnerbac32862004-11-14 19:13:23 +00009984 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009985 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009986 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009987 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009988 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009989 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009990 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009991 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009992 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9993
9994 // If this was a volatile load that we are merging, make sure to loop through
9995 // and mark all the input loads as non-volatile. If we don't do this, we will
9996 // insert a new volatile load and the old ones will not be deletable.
9997 if (isVolatile)
9998 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9999 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10000
10001 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010002}
Chris Lattnera1be5662002-05-02 17:06:02 +000010003
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010004/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10005/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010006static bool DeadPHICycle(PHINode *PN,
10007 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010008 if (PN->use_empty()) return true;
10009 if (!PN->hasOneUse()) return false;
10010
10011 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010012 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010013 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010014
10015 // Don't scan crazily complex things.
10016 if (PotentiallyDeadPHIs.size() == 16)
10017 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010018
10019 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10020 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010021
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010022 return false;
10023}
10024
Chris Lattnercf5008a2007-11-06 21:52:06 +000010025/// PHIsEqualValue - Return true if this phi node is always equal to
10026/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10027/// z = some value; x = phi (y, z); y = phi (x, z)
10028static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10029 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10030 // See if we already saw this PHI node.
10031 if (!ValueEqualPHIs.insert(PN))
10032 return true;
10033
10034 // Don't scan crazily complex things.
10035 if (ValueEqualPHIs.size() == 16)
10036 return false;
10037
10038 // Scan the operands to see if they are either phi nodes or are equal to
10039 // the value.
10040 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10041 Value *Op = PN->getIncomingValue(i);
10042 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10043 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10044 return false;
10045 } else if (Op != NonPhiInVal)
10046 return false;
10047 }
10048
10049 return true;
10050}
10051
10052
Chris Lattner473945d2002-05-06 18:06:38 +000010053// PHINode simplification
10054//
Chris Lattner7e708292002-06-25 16:13:24 +000010055Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010056 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010057 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010058
Owen Anderson7e057142006-07-10 22:03:18 +000010059 if (Value *V = PN.hasConstantValue())
10060 return ReplaceInstUsesWith(PN, V);
10061
Owen Anderson7e057142006-07-10 22:03:18 +000010062 // If all PHI operands are the same operation, pull them through the PHI,
10063 // reducing code size.
10064 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10065 PN.getIncomingValue(0)->hasOneUse())
10066 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10067 return Result;
10068
10069 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10070 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10071 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010072 if (PN.hasOneUse()) {
10073 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10074 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010075 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010076 PotentiallyDeadPHIs.insert(&PN);
10077 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10078 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10079 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010080
10081 // If this phi has a single use, and if that use just computes a value for
10082 // the next iteration of a loop, delete the phi. This occurs with unused
10083 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10084 // common case here is good because the only other things that catch this
10085 // are induction variable analysis (sometimes) and ADCE, which is only run
10086 // late.
10087 if (PHIUser->hasOneUse() &&
10088 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10089 PHIUser->use_back() == &PN) {
10090 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10091 }
10092 }
Owen Anderson7e057142006-07-10 22:03:18 +000010093
Chris Lattnercf5008a2007-11-06 21:52:06 +000010094 // We sometimes end up with phi cycles that non-obviously end up being the
10095 // same value, for example:
10096 // z = some value; x = phi (y, z); y = phi (x, z)
10097 // where the phi nodes don't necessarily need to be in the same block. Do a
10098 // quick check to see if the PHI node only contains a single non-phi value, if
10099 // so, scan to see if the phi cycle is actually equal to that value.
10100 {
10101 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10102 // Scan for the first non-phi operand.
10103 while (InValNo != NumOperandVals &&
10104 isa<PHINode>(PN.getIncomingValue(InValNo)))
10105 ++InValNo;
10106
10107 if (InValNo != NumOperandVals) {
10108 Value *NonPhiInVal = PN.getOperand(InValNo);
10109
10110 // Scan the rest of the operands to see if there are any conflicts, if so
10111 // there is no need to recursively scan other phis.
10112 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10113 Value *OpVal = PN.getIncomingValue(InValNo);
10114 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10115 break;
10116 }
10117
10118 // If we scanned over all operands, then we have one unique value plus
10119 // phi values. Scan PHI nodes to see if they all merge in each other or
10120 // the value.
10121 if (InValNo == NumOperandVals) {
10122 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10123 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10124 return ReplaceInstUsesWith(PN, NonPhiInVal);
10125 }
10126 }
10127 }
Chris Lattner60921c92003-12-19 05:58:40 +000010128 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010129}
10130
Reid Spencer17212df2006-12-12 09:18:51 +000010131static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10132 Instruction *InsertPoint,
10133 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010134 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10135 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010136 // We must cast correctly to the pointer type. Ensure that we
10137 // sign extend the integer value if it is smaller as this is
10138 // used for address computation.
10139 Instruction::CastOps opcode =
10140 (VTySize < PtrSize ? Instruction::SExt :
10141 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10142 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010143}
10144
Chris Lattnera1be5662002-05-02 17:06:02 +000010145
Chris Lattner7e708292002-06-25 16:13:24 +000010146Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010147 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010148 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010149 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010150 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010151 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010152
Chris Lattnere87597f2004-10-16 18:11:37 +000010153 if (isa<UndefValue>(GEP.getOperand(0)))
10154 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10155
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010156 bool HasZeroPointerIndex = false;
10157 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10158 HasZeroPointerIndex = C->isNullValue();
10159
10160 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010161 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010162
Chris Lattner28977af2004-04-05 01:30:19 +000010163 // Eliminate unneeded casts for indices.
10164 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010165
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010166 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010167 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010168 if (isa<SequentialType>(*GTI)) {
10169 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010170 if (CI->getOpcode() == Instruction::ZExt ||
10171 CI->getOpcode() == Instruction::SExt) {
10172 const Type *SrcTy = CI->getOperand(0)->getType();
10173 // We can eliminate a cast from i32 to i64 iff the target
10174 // is a 32-bit pointer target.
10175 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10176 MadeChange = true;
10177 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +000010178 }
10179 }
10180 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010181 // If we are using a wider index than needed for this platform, shrink it
10182 // to what we need. If the incoming value needs a cast instruction,
10183 // insert it. This explicit cast can make subsequent optimizations more
10184 // obvious.
10185 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010186 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010187 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010188 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +000010189 MadeChange = true;
10190 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010191 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10192 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010193 GEP.setOperand(i, Op);
10194 MadeChange = true;
10195 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010196 }
Chris Lattner28977af2004-04-05 01:30:19 +000010197 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010198 }
Chris Lattner28977af2004-04-05 01:30:19 +000010199 if (MadeChange) return &GEP;
10200
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010201 // If this GEP instruction doesn't move the pointer, and if the input operand
10202 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10203 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +000010204 if (GEP.hasAllZeroIndices()) {
10205 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10206 // If the bitcast is of an allocation, and the allocation will be
10207 // converted to match the type of the cast, don't touch this.
10208 if (isa<AllocationInst>(BCI->getOperand(0))) {
10209 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +000010210 if (Instruction *I = visitBitCast(*BCI)) {
10211 if (I != BCI) {
10212 I->takeName(BCI);
10213 BCI->getParent()->getInstList().insert(BCI, I);
10214 ReplaceInstUsesWith(*BCI, I);
10215 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010216 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +000010217 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010218 }
10219 return new BitCastInst(BCI->getOperand(0), GEP.getType());
10220 }
10221 }
10222
Chris Lattner90ac28c2002-08-02 19:29:35 +000010223 // Combine Indices - If the source pointer to this getelementptr instruction
10224 // is a getelementptr instruction, combine the indices of the two
10225 // getelementptr instructions into a single instruction.
10226 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010227 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010228 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010229 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010230
10231 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010232 // Note that if our source is a gep chain itself that we wait for that
10233 // chain to be resolved before we perform this transformation. This
10234 // avoids us creating a TON of code in some cases.
10235 //
10236 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10237 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10238 return 0; // Wait until our source is folded to completion.
10239
Chris Lattner72588fc2007-02-15 22:48:32 +000010240 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010241
10242 // Find out whether the last index in the source GEP is a sequential idx.
10243 bool EndsWithSequential = false;
10244 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10245 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010246 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010247
Chris Lattner90ac28c2002-08-02 19:29:35 +000010248 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010249 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010250 // Replace: gep (gep %P, long B), long A, ...
10251 // With: T = long A+B; gep %P, T, ...
10252 //
Chris Lattner620ce142004-05-07 22:09:22 +000010253 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010254 if (SO1 == Constant::getNullValue(SO1->getType())) {
10255 Sum = GO1;
10256 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10257 Sum = SO1;
10258 } else {
10259 // If they aren't the same type, convert both to an integer of the
10260 // target's pointer size.
10261 if (SO1->getType() != GO1->getType()) {
10262 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010263 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010264 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010265 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010266 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010267 unsigned PS = TD->getPointerSizeInBits();
10268 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010269 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010270 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010271
Duncan Sands514ab342007-11-01 20:53:16 +000010272 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010273 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010274 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010275 } else {
10276 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010277 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10278 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010279 }
10280 }
10281 }
Chris Lattner620ce142004-05-07 22:09:22 +000010282 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10283 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10284 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010285 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010286 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010287 }
Chris Lattner28977af2004-04-05 01:30:19 +000010288 }
Chris Lattner620ce142004-05-07 22:09:22 +000010289
10290 // Recycle the GEP we already have if possible.
10291 if (SrcGEPOperands.size() == 2) {
10292 GEP.setOperand(0, SrcGEPOperands[0]);
10293 GEP.setOperand(1, Sum);
10294 return &GEP;
10295 } else {
10296 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10297 SrcGEPOperands.end()-1);
10298 Indices.push_back(Sum);
10299 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10300 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010301 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010302 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010303 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010304 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010305 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10306 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010307 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10308 }
10309
10310 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010311 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10312 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010313
Chris Lattner620ce142004-05-07 22:09:22 +000010314 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010315 // GEP of global variable. If all of the indices for this GEP are
10316 // constants, we can promote this to a constexpr instead of an instruction.
10317
10318 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010319 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010320 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10321 for (; I != E && isa<Constant>(*I); ++I)
10322 Indices.push_back(cast<Constant>(*I));
10323
10324 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010325 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10326 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010327
10328 // Replace all uses of the GEP with the new constexpr...
10329 return ReplaceInstUsesWith(GEP, CE);
10330 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010331 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010332 if (!isa<PointerType>(X->getType())) {
10333 // Not interesting. Source pointer must be a cast from pointer.
10334 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010335 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10336 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010337 //
10338 // This occurs when the program declares an array extern like "int X[];"
10339 //
10340 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10341 const PointerType *XTy = cast<PointerType>(X->getType());
10342 if (const ArrayType *XATy =
10343 dyn_cast<ArrayType>(XTy->getElementType()))
10344 if (const ArrayType *CATy =
10345 dyn_cast<ArrayType>(CPTy->getElementType()))
10346 if (CATy->getElementType() == XATy->getElementType()) {
10347 // At this point, we know that the cast source type is a pointer
10348 // to an array of the same type as the destination pointer
10349 // array. Because the array type is never stepped over (there
10350 // is a leading zero) we can fold the cast into this GEP.
10351 GEP.setOperand(0, X);
10352 return &GEP;
10353 }
10354 } else if (GEP.getNumOperands() == 2) {
10355 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010356 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10357 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010358 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10359 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10360 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +000010361 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10362 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010363 Value *Idx[2];
10364 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10365 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010366 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010367 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010368 // V and GEP are both pointer types --> BitCast
10369 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010370 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010371
10372 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010373 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010374 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010375 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010376
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010377 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010378 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +000010379 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010380
10381 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10382 // allow either a mul, shift, or constant here.
10383 Value *NewIdx = 0;
10384 ConstantInt *Scale = 0;
10385 if (ArrayEltSize == 1) {
10386 NewIdx = GEP.getOperand(1);
10387 Scale = ConstantInt::get(NewIdx->getType(), 1);
10388 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010389 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010390 Scale = CI;
10391 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10392 if (Inst->getOpcode() == Instruction::Shl &&
10393 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010394 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10395 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10396 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010397 NewIdx = Inst->getOperand(0);
10398 } else if (Inst->getOpcode() == Instruction::Mul &&
10399 isa<ConstantInt>(Inst->getOperand(1))) {
10400 Scale = cast<ConstantInt>(Inst->getOperand(1));
10401 NewIdx = Inst->getOperand(0);
10402 }
10403 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010404
Chris Lattner7835cdd2005-09-13 18:36:04 +000010405 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010406 // out, perform the transformation. Note, we don't know whether Scale is
10407 // signed or not. We'll use unsigned version of division/modulo
10408 // operation after making sure Scale doesn't have the sign bit set.
10409 if (Scale && Scale->getSExtValue() >= 0LL &&
10410 Scale->getZExtValue() % ArrayEltSize == 0) {
10411 Scale = ConstantInt::get(Scale->getType(),
10412 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010413 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010414 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010415 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010416 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010417 NewIdx = InsertNewInstBefore(Sc, GEP);
10418 }
10419
10420 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010421 Value *Idx[2];
10422 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10423 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010424 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010425 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010426 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10427 // The NewGEP must be pointer typed, so must the old one -> BitCast
10428 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010429 }
10430 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010431 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010432 }
10433
Chris Lattner8a2a3112001-12-14 16:52:21 +000010434 return 0;
10435}
10436
Chris Lattner0864acf2002-11-04 16:18:53 +000010437Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10438 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010439 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010440 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10441 const Type *NewTy =
10442 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010443 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010444
10445 // Create and insert the replacement instruction...
10446 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010447 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010448 else {
10449 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010450 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010451 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010452
10453 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010454
Chris Lattner0864acf2002-11-04 16:18:53 +000010455 // Scan to the end of the allocation instructions, to skip over a block of
10456 // allocas if possible...
10457 //
10458 BasicBlock::iterator It = New;
10459 while (isa<AllocationInst>(*It)) ++It;
10460
10461 // Now that I is pointing to the first non-allocation-inst in the block,
10462 // insert our getelementptr instruction...
10463 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010464 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010465 Value *Idx[2];
10466 Idx[0] = NullIdx;
10467 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010468 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10469 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010470
10471 // Now make everything use the getelementptr instead of the original
10472 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010473 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010474 } else if (isa<UndefValue>(AI.getArraySize())) {
10475 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010476 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010477 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010478
10479 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10480 // Note that we only do this for alloca's, because malloc should allocate and
10481 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +000010482 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +000010483 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +000010484 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10485
Chris Lattner0864acf2002-11-04 16:18:53 +000010486 return 0;
10487}
10488
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010489Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10490 Value *Op = FI.getOperand(0);
10491
Chris Lattner17be6352004-10-18 02:59:09 +000010492 // free undef -> unreachable.
10493 if (isa<UndefValue>(Op)) {
10494 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010495 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010496 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010497 return EraseInstFromFunction(FI);
10498 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010499
Chris Lattner6160e852004-02-28 04:57:37 +000010500 // If we have 'free null' delete the instruction. This can happen in stl code
10501 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010502 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010503 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010504
10505 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10506 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10507 FI.setOperand(0, CI->getOperand(0));
10508 return &FI;
10509 }
10510
10511 // Change free (gep X, 0,0,0,0) into free(X)
10512 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10513 if (GEPI->hasAllZeroIndices()) {
10514 AddToWorkList(GEPI);
10515 FI.setOperand(0, GEPI->getOperand(0));
10516 return &FI;
10517 }
10518 }
10519
10520 // Change free(malloc) into nothing, if the malloc has a single use.
10521 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10522 if (MI->hasOneUse()) {
10523 EraseInstFromFunction(FI);
10524 return EraseInstFromFunction(*MI);
10525 }
Chris Lattner6160e852004-02-28 04:57:37 +000010526
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010527 return 0;
10528}
10529
10530
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010531/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010532static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010533 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010534 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010535 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010536
Devang Patel99db6ad2007-10-18 19:52:32 +000010537 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10538 // Instead of loading constant c string, use corresponding integer value
10539 // directly if string length is small enough.
10540 const std::string &Str = CE->getOperand(0)->getStringValue();
10541 if (!Str.empty()) {
10542 unsigned len = Str.length();
10543 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10544 unsigned numBits = Ty->getPrimitiveSizeInBits();
10545 // Replace LI with immediate integer store.
10546 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010547 APInt StrVal(numBits, 0);
10548 APInt SingleChar(numBits, 0);
10549 if (TD->isLittleEndian()) {
10550 for (signed i = len-1; i >= 0; i--) {
10551 SingleChar = (uint64_t) Str[i];
10552 StrVal = (StrVal << 8) | SingleChar;
10553 }
10554 } else {
10555 for (unsigned i = 0; i < len; i++) {
10556 SingleChar = (uint64_t) Str[i];
10557 StrVal = (StrVal << 8) | SingleChar;
10558 }
10559 // Append NULL at the end.
10560 SingleChar = 0;
10561 StrVal = (StrVal << 8) | SingleChar;
10562 }
10563 Value *NL = ConstantInt::get(StrVal);
10564 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010565 }
10566 }
10567 }
10568
Chris Lattnerb89e0712004-07-13 01:49:43 +000010569 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010570 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010571 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010572
Reid Spencer42230162007-01-22 05:51:25 +000010573 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010574 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010575 // If the source is an array, the code below will not succeed. Check to
10576 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10577 // constants.
10578 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10579 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10580 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010581 Value *Idxs[2];
10582 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10583 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010584 SrcTy = cast<PointerType>(CastOp->getType());
10585 SrcPTy = SrcTy->getElementType();
10586 }
10587
Reid Spencer42230162007-01-22 05:51:25 +000010588 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010589 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010590 // Do not allow turning this into a load of an integer, which is then
10591 // casted to a pointer, this pessimizes pointer analysis a lot.
10592 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010593 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10594 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010595
Chris Lattnerf9527852005-01-31 04:50:46 +000010596 // Okay, we are casting from one integer or pointer type to another of
10597 // the same size. Instead of casting the pointer before the load, cast
10598 // the result of the loaded value.
10599 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10600 CI->getName(),
10601 LI.isVolatile()),LI);
10602 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010603 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010604 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010605 }
10606 }
10607 return 0;
10608}
10609
Chris Lattnerc10aced2004-09-19 18:43:46 +000010610/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010611/// from this value cannot trap. If it is not obviously safe to load from the
10612/// specified pointer, we do a quick local scan of the basic block containing
10613/// ScanFrom, to determine if the address is already accessed.
10614static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010615 // If it is an alloca it is always safe to load from.
10616 if (isa<AllocaInst>(V)) return true;
10617
Duncan Sands46318cd2007-09-19 10:25:38 +000010618 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010619 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010620 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010621 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010622
10623 // Otherwise, be a little bit agressive by scanning the local block where we
10624 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010625 // from/to. If so, the previous load or store would have already trapped,
10626 // so there is no harm doing an extra load (also, CSE will later eliminate
10627 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010628 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10629
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010630 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010631 --BBI;
10632
10633 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10634 if (LI->getOperand(0) == V) return true;
10635 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10636 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010637
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010638 }
Chris Lattner8a375202004-09-19 19:18:10 +000010639 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010640}
10641
Chris Lattner8d2e8882007-08-11 18:48:48 +000010642/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10643/// until we find the underlying object a pointer is referring to or something
10644/// we don't understand. Note that the returned pointer may be offset from the
10645/// input, because we ignore GEP indices.
10646static Value *GetUnderlyingObject(Value *Ptr) {
10647 while (1) {
10648 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10649 if (CE->getOpcode() == Instruction::BitCast ||
10650 CE->getOpcode() == Instruction::GetElementPtr)
10651 Ptr = CE->getOperand(0);
10652 else
10653 return Ptr;
10654 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10655 Ptr = BCI->getOperand(0);
10656 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10657 Ptr = GEP->getOperand(0);
10658 } else {
10659 return Ptr;
10660 }
10661 }
10662}
10663
Chris Lattner833b8a42003-06-26 05:06:25 +000010664Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10665 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010666
Dan Gohman9941f742007-07-20 16:34:21 +000010667 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010668 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10669 if (KnownAlign >
10670 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10671 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010672 LI.setAlignment(KnownAlign);
10673
Chris Lattner37366c12005-05-01 04:24:53 +000010674 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010675 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010676 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010677 return Res;
10678
10679 // None of the following transforms are legal for volatile loads.
10680 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010681
Chris Lattner62f254d2005-09-12 22:00:15 +000010682 if (&LI.getParent()->front() != &LI) {
10683 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010684 // If the instruction immediately before this is a store to the same
10685 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010686 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10687 if (SI->getOperand(1) == LI.getOperand(0))
10688 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010689 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10690 if (LIB->getOperand(0) == LI.getOperand(0))
10691 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010692 }
Chris Lattner37366c12005-05-01 04:24:53 +000010693
Christopher Lambb15147e2007-12-29 07:56:53 +000010694 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10695 const Value *GEPI0 = GEPI->getOperand(0);
10696 // TODO: Consider a target hook for valid address spaces for this xform.
10697 if (isa<ConstantPointerNull>(GEPI0) &&
10698 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010699 // Insert a new store to null instruction before the load to indicate
10700 // that this code is not reachable. We do this instead of inserting
10701 // an unreachable instruction directly because we cannot modify the
10702 // CFG.
10703 new StoreInst(UndefValue::get(LI.getType()),
10704 Constant::getNullValue(Op->getType()), &LI);
10705 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10706 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010707 }
Chris Lattner37366c12005-05-01 04:24:53 +000010708
Chris Lattnere87597f2004-10-16 18:11:37 +000010709 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010710 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010711 // TODO: Consider a target hook for valid address spaces for this xform.
10712 if (isa<UndefValue>(C) || (C->isNullValue() &&
10713 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010714 // Insert a new store to null instruction before the load to indicate that
10715 // this code is not reachable. We do this instead of inserting an
10716 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010717 new StoreInst(UndefValue::get(LI.getType()),
10718 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010719 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010720 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010721
Chris Lattnere87597f2004-10-16 18:11:37 +000010722 // Instcombine load (constant global) into the value loaded.
10723 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010724 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010725 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010726
Chris Lattnere87597f2004-10-16 18:11:37 +000010727 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010728 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010729 if (CE->getOpcode() == Instruction::GetElementPtr) {
10730 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010731 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010732 if (Constant *V =
10733 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010734 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010735 if (CE->getOperand(0)->isNullValue()) {
10736 // Insert a new store to null instruction before the load to indicate
10737 // that this code is not reachable. We do this instead of inserting
10738 // an unreachable instruction directly because we cannot modify the
10739 // CFG.
10740 new StoreInst(UndefValue::get(LI.getType()),
10741 Constant::getNullValue(Op->getType()), &LI);
10742 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10743 }
10744
Reid Spencer3da59db2006-11-27 01:05:10 +000010745 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010746 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010747 return Res;
10748 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010749 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010750 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010751
10752 // If this load comes from anywhere in a constant global, and if the global
10753 // is all undef or zero, we know what it loads.
10754 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10755 if (GV->isConstant() && GV->hasInitializer()) {
10756 if (GV->getInitializer()->isNullValue())
10757 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10758 else if (isa<UndefValue>(GV->getInitializer()))
10759 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10760 }
10761 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010762
Chris Lattner37366c12005-05-01 04:24:53 +000010763 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010764 // Change select and PHI nodes to select values instead of addresses: this
10765 // helps alias analysis out a lot, allows many others simplifications, and
10766 // exposes redundancy in the code.
10767 //
10768 // Note that we cannot do the transformation unless we know that the
10769 // introduced loads cannot trap! Something like this is valid as long as
10770 // the condition is always false: load (select bool %C, int* null, int* %G),
10771 // but it would not be valid if we transformed it to load from null
10772 // unconditionally.
10773 //
10774 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10775 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010776 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10777 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010778 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010779 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010780 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010781 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010782 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010783 }
10784
Chris Lattner684fe212004-09-23 15:46:00 +000010785 // load (select (cond, null, P)) -> load P
10786 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10787 if (C->isNullValue()) {
10788 LI.setOperand(0, SI->getOperand(2));
10789 return &LI;
10790 }
10791
10792 // load (select (cond, P, null)) -> load P
10793 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10794 if (C->isNullValue()) {
10795 LI.setOperand(0, SI->getOperand(1));
10796 return &LI;
10797 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010798 }
10799 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010800 return 0;
10801}
10802
Reid Spencer55af2b52007-01-19 21:20:31 +000010803/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010804/// when possible.
10805static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10806 User *CI = cast<User>(SI.getOperand(1));
10807 Value *CastOp = CI->getOperand(0);
10808
10809 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10810 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10811 const Type *SrcPTy = SrcTy->getElementType();
10812
Reid Spencer42230162007-01-22 05:51:25 +000010813 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010814 // If the source is an array, the code below will not succeed. Check to
10815 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10816 // constants.
10817 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10818 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10819 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010820 Value* Idxs[2];
10821 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10822 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010823 SrcTy = cast<PointerType>(CastOp->getType());
10824 SrcPTy = SrcTy->getElementType();
10825 }
10826
Reid Spencer67f827c2007-01-20 23:35:48 +000010827 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10828 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10829 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010830
10831 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010832 // the same size. Instead of casting the pointer before
10833 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010834 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010835 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010836 Instruction::CastOps opcode = Instruction::BitCast;
10837 const Type* CastSrcTy = SIOp0->getType();
10838 const Type* CastDstTy = SrcPTy;
10839 if (isa<PointerType>(CastDstTy)) {
10840 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010841 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010842 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010843 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010844 opcode = Instruction::PtrToInt;
10845 }
10846 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010847 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010848 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010849 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010850 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010851 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010852 return new StoreInst(NewCast, CastOp);
10853 }
10854 }
10855 }
10856 return 0;
10857}
10858
Chris Lattner2f503e62005-01-31 05:36:43 +000010859Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10860 Value *Val = SI.getOperand(0);
10861 Value *Ptr = SI.getOperand(1);
10862
10863 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010864 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010865 ++NumCombined;
10866 return 0;
10867 }
Chris Lattner836692d2007-01-15 06:51:56 +000010868
10869 // If the RHS is an alloca with a single use, zapify the store, making the
10870 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010871 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010872 if (isa<AllocaInst>(Ptr)) {
10873 EraseInstFromFunction(SI);
10874 ++NumCombined;
10875 return 0;
10876 }
10877
10878 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10879 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10880 GEP->getOperand(0)->hasOneUse()) {
10881 EraseInstFromFunction(SI);
10882 ++NumCombined;
10883 return 0;
10884 }
10885 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010886
Dan Gohman9941f742007-07-20 16:34:21 +000010887 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010888 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10889 if (KnownAlign >
10890 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10891 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010892 SI.setAlignment(KnownAlign);
10893
Chris Lattner9ca96412006-02-08 03:25:32 +000010894 // Do really simple DSE, to catch cases where there are several consequtive
10895 // stores to the same location, separated by a few arithmetic operations. This
10896 // situation often occurs with bitfield accesses.
10897 BasicBlock::iterator BBI = &SI;
10898 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10899 --ScanInsts) {
10900 --BBI;
10901
10902 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10903 // Prev store isn't volatile, and stores to the same location?
10904 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10905 ++NumDeadStore;
10906 ++BBI;
10907 EraseInstFromFunction(*PrevSI);
10908 continue;
10909 }
10910 break;
10911 }
10912
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010913 // If this is a load, we have to stop. However, if the loaded value is from
10914 // the pointer we're loading and is producing the pointer we're storing,
10915 // then *this* store is dead (X = load P; store X -> P).
10916 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010917 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010918 EraseInstFromFunction(SI);
10919 ++NumCombined;
10920 return 0;
10921 }
10922 // Otherwise, this is a load from some other location. Stores before it
10923 // may not be dead.
10924 break;
10925 }
10926
Chris Lattner9ca96412006-02-08 03:25:32 +000010927 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010928 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010929 break;
10930 }
10931
10932
10933 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010934
10935 // store X, null -> turns into 'unreachable' in SimplifyCFG
10936 if (isa<ConstantPointerNull>(Ptr)) {
10937 if (!isa<UndefValue>(Val)) {
10938 SI.setOperand(0, UndefValue::get(Val->getType()));
10939 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010940 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010941 ++NumCombined;
10942 }
10943 return 0; // Do not modify these!
10944 }
10945
10946 // store undef, Ptr -> noop
10947 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010948 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010949 ++NumCombined;
10950 return 0;
10951 }
10952
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010953 // If the pointer destination is a cast, see if we can fold the cast into the
10954 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010955 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010956 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10957 return Res;
10958 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010959 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010960 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10961 return Res;
10962
Chris Lattner408902b2005-09-12 23:23:25 +000010963
10964 // If this store is the last instruction in the basic block, and if the block
10965 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010966 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010967 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010968 if (BI->isUnconditional())
10969 if (SimplifyStoreAtEndOfBlock(SI))
10970 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010971
Chris Lattner2f503e62005-01-31 05:36:43 +000010972 return 0;
10973}
10974
Chris Lattner3284d1f2007-04-15 00:07:55 +000010975/// SimplifyStoreAtEndOfBlock - Turn things like:
10976/// if () { *P = v1; } else { *P = v2 }
10977/// into a phi node with a store in the successor.
10978///
Chris Lattner31755a02007-04-15 01:02:18 +000010979/// Simplify things like:
10980/// *P = v1; if () { *P = v2; }
10981/// into a phi node with a store in the successor.
10982///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010983bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10984 BasicBlock *StoreBB = SI.getParent();
10985
10986 // Check to see if the successor block has exactly two incoming edges. If
10987 // so, see if the other predecessor contains a store to the same location.
10988 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010989 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010990
10991 // Determine whether Dest has exactly two predecessors and, if so, compute
10992 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010993 pred_iterator PI = pred_begin(DestBB);
10994 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010995 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010996 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010997 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010998 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010999 return false;
11000
11001 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011002 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011003 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011004 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011005 }
Chris Lattner31755a02007-04-15 01:02:18 +000011006 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011007 return false;
11008
11009
Chris Lattner31755a02007-04-15 01:02:18 +000011010 // Verify that the other block ends in a branch and is not otherwise empty.
11011 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011012 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011013 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011014 return false;
11015
Chris Lattner31755a02007-04-15 01:02:18 +000011016 // If the other block ends in an unconditional branch, check for the 'if then
11017 // else' case. there is an instruction before the branch.
11018 StoreInst *OtherStore = 0;
11019 if (OtherBr->isUnconditional()) {
11020 // If this isn't a store, or isn't a store to the same location, bail out.
11021 --BBI;
11022 OtherStore = dyn_cast<StoreInst>(BBI);
11023 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11024 return false;
11025 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011026 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011027 // destinations is StoreBB, then we have the if/then case.
11028 if (OtherBr->getSuccessor(0) != StoreBB &&
11029 OtherBr->getSuccessor(1) != StoreBB)
11030 return false;
11031
11032 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011033 // if/then triangle. See if there is a store to the same ptr as SI that
11034 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011035 for (;; --BBI) {
11036 // Check to see if we find the matching store.
11037 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11038 if (OtherStore->getOperand(1) != SI.getOperand(1))
11039 return false;
11040 break;
11041 }
Chris Lattnerd717c182007-05-05 22:32:24 +000011042 // If we find something that may be using the stored value, or if we run
11043 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000011044 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
11045 BBI == OtherBB->begin())
11046 return false;
11047 }
11048
11049 // In order to eliminate the store in OtherBr, we have to
11050 // make sure nothing reads the stored value in StoreBB.
11051 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11052 // FIXME: This should really be AA driven.
11053 if (isa<LoadInst>(I) || I->mayWriteToMemory())
11054 return false;
11055 }
11056 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011057
Chris Lattner31755a02007-04-15 01:02:18 +000011058 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011059 Value *MergedVal = OtherStore->getOperand(0);
11060 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011061 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011062 PN->reserveOperandSpace(2);
11063 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011064 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11065 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011066 }
11067
11068 // Advance to a place where it is safe to insert the new store and
11069 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011070 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011071 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
Dan Gohman02dea8b2008-05-23 21:05:58 +000011738 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000011739
Chris Lattner4bc5f802005-08-08 19:11:57 +000011740 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011741 ++NumSunkInst;
11742 return true;
11743}
11744
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011745
11746/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11747/// all reachable code to the worklist.
11748///
11749/// This has a couple of tricks to make the code faster and more powerful. In
11750/// particular, we constant fold and DCE instructions as we go, to avoid adding
11751/// them to the worklist (this significantly speeds up instcombine on code where
11752/// many instructions are dead or constant). Additionally, if we find a branch
11753/// whose condition is a known constant, we only visit the reachable successors.
11754///
11755static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011756 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011757 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011758 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011759 std::vector<BasicBlock*> Worklist;
11760 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011761
Chris Lattner2c7718a2007-03-23 19:17:18 +000011762 while (!Worklist.empty()) {
11763 BB = Worklist.back();
11764 Worklist.pop_back();
11765
11766 // We have now visited this block! If we've already been here, ignore it.
11767 if (!Visited.insert(BB)) continue;
11768
11769 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11770 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011771
Chris Lattner2c7718a2007-03-23 19:17:18 +000011772 // DCE instruction if trivially dead.
11773 if (isInstructionTriviallyDead(Inst)) {
11774 ++NumDeadInst;
11775 DOUT << "IC: DCE: " << *Inst;
11776 Inst->eraseFromParent();
11777 continue;
11778 }
11779
11780 // ConstantProp instruction if trivially constant.
11781 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11782 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11783 Inst->replaceAllUsesWith(C);
11784 ++NumConstProp;
11785 Inst->eraseFromParent();
11786 continue;
11787 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011788
Chris Lattner2c7718a2007-03-23 19:17:18 +000011789 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011790 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011791
11792 // Recursively visit successors. If this is a branch or switch on a
11793 // constant, only visit the reachable successor.
11794 TerminatorInst *TI = BB->getTerminator();
11795 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11796 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11797 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011798 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011799 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011800 continue;
11801 }
11802 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11803 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11804 // See if this is an explicit destination.
11805 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11806 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011807 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011808 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011809 continue;
11810 }
11811
11812 // Otherwise it is the default destination.
11813 Worklist.push_back(SI->getSuccessor(0));
11814 continue;
11815 }
11816 }
11817
11818 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11819 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011820 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011821}
11822
Chris Lattnerec9c3582007-03-03 02:04:50 +000011823bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011824 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011825 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011826
11827 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11828 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011829
Chris Lattnerb3d59702005-07-07 20:40:38 +000011830 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011831 // Do a depth-first traversal of the function, populate the worklist with
11832 // the reachable instructions. Ignore blocks that are not reachable. Keep
11833 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011834 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011835 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011836
Chris Lattnerb3d59702005-07-07 20:40:38 +000011837 // Do a quick scan over the function. If we find any blocks that are
11838 // unreachable, remove any instructions inside of them. This prevents
11839 // the instcombine code from having to deal with some bad special cases.
11840 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11841 if (!Visited.count(BB)) {
11842 Instruction *Term = BB->getTerminator();
11843 while (Term != BB->begin()) { // Remove instrs bottom-up
11844 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011845
Bill Wendlingb7427032006-11-26 09:46:52 +000011846 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011847 ++NumDeadInst;
11848
11849 if (!I->use_empty())
11850 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11851 I->eraseFromParent();
11852 }
11853 }
11854 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011855
Chris Lattnerdbab3862007-03-02 21:28:56 +000011856 while (!Worklist.empty()) {
11857 Instruction *I = RemoveOneFromWorkList();
11858 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011859
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011860 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011861 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011862 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011863 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011864 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011865 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011866
Bill Wendlingb7427032006-11-26 09:46:52 +000011867 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011868
11869 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011870 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011871 continue;
11872 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011873
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011874 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011875 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011876 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011877
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011878 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011879 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011880 ReplaceInstUsesWith(*I, C);
11881
Chris Lattner62b14df2002-09-02 04:59:56 +000011882 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011883 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011884 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011885 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011886 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011887
Chris Lattnerea1c4542004-12-08 23:43:58 +000011888 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011889 // FIXME: Remove GetResultInst test when first class support for aggregates
11890 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011891 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011892 BasicBlock *BB = I->getParent();
11893 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11894 if (UserParent != BB) {
11895 bool UserIsSuccessor = false;
11896 // See if the user is one of our successors.
11897 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11898 if (*SI == UserParent) {
11899 UserIsSuccessor = true;
11900 break;
11901 }
11902
11903 // If the user is one of our immediate successors, and if that successor
11904 // only has us as a predecessors (we'd have to split the critical edge
11905 // otherwise), we can keep going.
11906 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11907 next(pred_begin(UserParent)) == pred_end(UserParent))
11908 // Okay, the CFG is simple enough, try to sink this instruction.
11909 Changed |= TryToSinkInstruction(I, UserParent);
11910 }
11911 }
11912
Chris Lattner8a2a3112001-12-14 16:52:21 +000011913 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011914#ifndef NDEBUG
11915 std::string OrigI;
11916#endif
11917 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011918 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011919 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011920 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011921 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011922 DOUT << "IC: Old = " << *I
11923 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011924
Chris Lattnerf523d062004-06-09 05:08:07 +000011925 // Everything uses the new instruction now.
11926 I->replaceAllUsesWith(Result);
11927
11928 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011929 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011930 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011931
Chris Lattner6934a042007-02-11 01:23:03 +000011932 // Move the name to the new instruction first.
11933 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011934
11935 // Insert the new instruction into the basic block...
11936 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011937 BasicBlock::iterator InsertPos = I;
11938
11939 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11940 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11941 ++InsertPos;
11942
11943 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011944
Chris Lattner00d51312004-05-01 23:27:23 +000011945 // Make sure that we reprocess all operands now that we reduced their
11946 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011947 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011948
Chris Lattnerf523d062004-06-09 05:08:07 +000011949 // Instructions can end up on the worklist more than once. Make sure
11950 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011951 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011952
11953 // Erase the old instruction.
11954 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011955 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011956#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011957 DOUT << "IC: Mod = " << OrigI
11958 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011959#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011960
Chris Lattner90ac28c2002-08-02 19:29:35 +000011961 // If the instruction was modified, it's possible that it is now dead.
11962 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011963 if (isInstructionTriviallyDead(I)) {
11964 // Make sure we process all operands now that we are reducing their
11965 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011966 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011967
Chris Lattner00d51312004-05-01 23:27:23 +000011968 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011969 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011970 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011971 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011972 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011973 AddToWorkList(I);
11974 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011975 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011976 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011977 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011978 }
11979 }
11980
Chris Lattnerec9c3582007-03-03 02:04:50 +000011981 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011982
11983 // Do an explicit clear, this shrinks the map if needed.
11984 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011985 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011986}
11987
Chris Lattnerec9c3582007-03-03 02:04:50 +000011988
11989bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011990 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11991
Chris Lattnerec9c3582007-03-03 02:04:50 +000011992 bool EverMadeChange = false;
11993
11994 // Iterate while there is work to do.
11995 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011996 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011997 EverMadeChange = true;
11998 return EverMadeChange;
11999}
12000
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012001FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012002 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012003}
Brian Gaeked0fde302003-11-11 22:41:34 +000012004