blob: 5199578b1f81667321d9d4805f092b71e7d8f273 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000047#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000048#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000051#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000052#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000053#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000054#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000055#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000059#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000060#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000061#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000062using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000063using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065STATISTIC(NumCombined , "Number of insts combined");
66STATISTIC(NumConstProp, "Number of constant folds");
67STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000070
Chris Lattner0e5f4992006-12-19 21:40:18 +000071namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000072 class VISIBILITY_HIDDEN InstCombiner
73 : public FunctionPass,
74 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000075 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000076 std::vector<Instruction*> Worklist;
77 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000078 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000079 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000080 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000081 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000082 InstCombiner() : FunctionPass((intptr_t)&ID) {}
83
Chris Lattnerdbab3862007-03-02 21:28:56 +000084 /// AddToWorkList - Add the specified instruction to the worklist if it
85 /// isn't already in it.
86 void AddToWorkList(Instruction *I) {
87 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88 Worklist.push_back(I);
89 }
90
91 // RemoveFromWorkList - remove I from the worklist if it exists.
92 void RemoveFromWorkList(Instruction *I) {
93 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94 if (It == WorklistMap.end()) return; // Not in worklist.
95
96 // Don't bother moving everything down, just null out the slot.
97 Worklist[It->second] = 0;
98
99 WorklistMap.erase(It);
100 }
101
102 Instruction *RemoveOneFromWorkList() {
103 Instruction *I = Worklist.back();
104 Worklist.pop_back();
105 WorklistMap.erase(I);
106 return I;
107 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000108
Chris Lattnerdbab3862007-03-02 21:28:56 +0000109
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000110 /// AddUsersToWorkList - When an instruction is simplified, add all users of
111 /// the instruction to the work lists because they might get more simplified
112 /// now.
113 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000114 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000115 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000116 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000117 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000118 }
119
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000120 /// AddUsesToWorkList - When an instruction is simplified, add operands to
121 /// the work lists because they might get more simplified now.
122 ///
123 void AddUsesToWorkList(Instruction &I) {
124 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000126 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000127 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000128
129 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130 /// dead. Add all of its operands to the worklist, turning them into
131 /// undef's to reduce the number of uses of those instructions.
132 ///
133 /// Return the specified operand before it is turned into an undef.
134 ///
135 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136 Value *R = I.getOperand(op);
137
138 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000140 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000141 // Set the operand to undef to drop the use.
142 I.setOperand(i, UndefValue::get(Op->getType()));
143 }
144
145 return R;
146 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000147
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000148 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000149 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000150
151 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000152
Chris Lattner97e52e42002-04-28 21:27:06 +0000153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000154 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000155 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000156 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000157 }
158
Chris Lattner28977af2004-04-05 01:30:19 +0000159 TargetData &getTargetData() const { return *TD; }
160
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000161 // Visitation implementation - Implement instruction combining for different
162 // instruction types. The semantics are as follows:
163 // Return Value:
164 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000165 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000166 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000167 //
Chris Lattner7e708292002-06-25 16:13:24 +0000168 Instruction *visitAdd(BinaryOperator &I);
169 Instruction *visitSub(BinaryOperator &I);
170 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000171 Instruction *visitURem(BinaryOperator &I);
172 Instruction *visitSRem(BinaryOperator &I);
173 Instruction *visitFRem(BinaryOperator &I);
174 Instruction *commonRemTransforms(BinaryOperator &I);
175 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000176 Instruction *commonDivTransforms(BinaryOperator &I);
177 Instruction *commonIDivTransforms(BinaryOperator &I);
178 Instruction *visitUDiv(BinaryOperator &I);
179 Instruction *visitSDiv(BinaryOperator &I);
180 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000181 Instruction *visitAnd(BinaryOperator &I);
182 Instruction *visitOr (BinaryOperator &I);
183 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000184 Instruction *visitShl(BinaryOperator &I);
185 Instruction *visitAShr(BinaryOperator &I);
186 Instruction *visitLShr(BinaryOperator &I);
187 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000188 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
189 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000190 Instruction *visitFCmpInst(FCmpInst &I);
191 Instruction *visitICmpInst(ICmpInst &I);
192 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000193 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
194 Instruction *LHS,
195 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000196 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
197 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000198
Reid Spencere4d87aa2006-12-23 06:05:41 +0000199 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
200 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000201 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000202 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000203 Instruction *commonCastTransforms(CastInst &CI);
204 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000205 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000206 Instruction *visitTrunc(TruncInst &CI);
207 Instruction *visitZExt(ZExtInst &CI);
208 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000209 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000210 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000211 Instruction *visitFPToUI(FPToUIInst &FI);
212 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000213 Instruction *visitUIToFP(CastInst &CI);
214 Instruction *visitSIToFP(CastInst &CI);
215 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000216 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000217 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000218 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
219 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000220 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000221 Instruction *visitCallInst(CallInst &CI);
222 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000223 Instruction *visitPHINode(PHINode &PN);
224 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000225 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000226 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000227 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000228 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000229 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000230 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000231 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000232 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000233 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000234
235 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000236 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000237
Chris Lattner9fe38862003-06-19 17:00:31 +0000238 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000239 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000240 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000241 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000242 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
243 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000244 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000245
Chris Lattner28977af2004-04-05 01:30:19 +0000246 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000247 // InsertNewInstBefore - insert an instruction New before instruction Old
248 // in the program. Add the new instruction to the worklist.
249 //
Chris Lattner955f3312004-09-28 21:48:02 +0000250 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000251 assert(New && New->getParent() == 0 &&
252 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000253 BasicBlock *BB = Old.getParent();
254 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000255 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000256 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000257 }
258
Chris Lattner0c967662004-09-24 15:21:34 +0000259 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
260 /// This also adds the cast to the worklist. Finally, this returns the
261 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000262 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
263 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000264 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000265
Chris Lattnere2ed0572006-04-06 19:19:17 +0000266 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000267 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000268
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000269 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000270 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000271 return C;
272 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000273
274 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
275 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
276 }
277
Chris Lattner0c967662004-09-24 15:21:34 +0000278
Chris Lattner8b170942002-08-09 23:47:40 +0000279 // ReplaceInstUsesWith - This method is to be used when an instruction is
280 // found to be dead, replacable with another preexisting expression. Here
281 // we add all uses of I to the worklist, replace all uses of I with the new
282 // value, then return I, so that the inst combiner will know that I was
283 // modified.
284 //
285 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000286 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000287 if (&I != V) {
288 I.replaceAllUsesWith(V);
289 return &I;
290 } else {
291 // If we are replacing the instruction with itself, this must be in a
292 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000293 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000294 return &I;
295 }
Chris Lattner8b170942002-08-09 23:47:40 +0000296 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000297
Chris Lattner6dce1a72006-02-07 06:56:34 +0000298 // UpdateValueUsesWith - This method is to be used when an value is
299 // found to be replacable with another preexisting expression or was
300 // updated. Here we add all uses of I to the worklist, replace all uses of
301 // I with the new value (unless the instruction was just updated), then
302 // return true, so that the inst combiner will know that I was modified.
303 //
304 bool UpdateValueUsesWith(Value *Old, Value *New) {
305 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
306 if (Old != New)
307 Old->replaceAllUsesWith(New);
308 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000309 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000310 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000311 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000312 return true;
313 }
314
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000315 // EraseInstFromFunction - When dealing with an instruction that has side
316 // effects or produces a void value, we can't rely on DCE to delete the
317 // instruction. Instead, visit methods should return the value returned by
318 // this function.
319 Instruction *EraseInstFromFunction(Instruction &I) {
320 assert(I.use_empty() && "Cannot erase instruction that is used!");
321 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000322 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000323 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000324 return 0; // Don't do anything with FI
325 }
326
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000327 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000328 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
329 /// InsertBefore instruction. This is specialized a bit to avoid inserting
330 /// casts that are known to not do anything...
331 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000332 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
333 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000334 Instruction *InsertBefore);
335
Reid Spencere4d87aa2006-12-23 06:05:41 +0000336 /// SimplifyCommutative - This performs a few simplifications for
337 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000338 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000339
Reid Spencere4d87aa2006-12-23 06:05:41 +0000340 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
341 /// most-complex to least-complex order.
342 bool SimplifyCompare(CmpInst &I);
343
Reid Spencer2ec619a2007-03-23 21:24:59 +0000344 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
345 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000346 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
347 APInt& KnownZero, APInt& KnownOne,
348 unsigned Depth = 0);
349
Chris Lattner867b99f2006-10-05 06:55:50 +0000350 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
351 uint64_t &UndefElts, unsigned Depth = 0);
352
Chris Lattner4e998b22004-09-29 05:07:12 +0000353 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
354 // PHI node as operand #0, see if we can fold the instruction into the PHI
355 // (which is only possible if all operands to the PHI are constants).
356 Instruction *FoldOpIntoPhi(Instruction &I);
357
Chris Lattnerbac32862004-11-14 19:13:23 +0000358 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
359 // operator and they all are only used by the PHI, PHI together their
360 // inputs, and do the operation once, to the result of the PHI.
361 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000362 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
363
364
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000365 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
366 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000367
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000368 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000369 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000370 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000371 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000372 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000373 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000374 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000375 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000376 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000377
Chris Lattnerafe91a52006-06-15 19:07:26 +0000378
Reid Spencerc55b2432006-12-13 18:21:21 +0000379 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000380
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000381 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Dan Gohman45b4e482008-05-19 22:14:15 +0000382 APInt& KnownOne, unsigned Depth = 0) const;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000383 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
Dan Gohman45b4e482008-05-19 22:14:15 +0000384 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000385 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
386 unsigned CastOpc,
387 int &NumCastsRemoved);
388 unsigned GetOrEnforceKnownAlignment(Value *V,
389 unsigned PrefAlign = 0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000390 };
391}
392
Dan Gohman844731a2008-05-13 00:00:25 +0000393char InstCombiner::ID = 0;
394static RegisterPass<InstCombiner>
395X("instcombine", "Combine redundant instructions");
396
Chris Lattner4f98c562003-03-10 21:43:22 +0000397// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000398// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000399static unsigned getComplexity(Value *V) {
400 if (isa<Instruction>(V)) {
401 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000402 return 3;
403 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000404 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000405 if (isa<Argument>(V)) return 3;
406 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000407}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000408
Chris Lattnerc8802d22003-03-11 00:12:48 +0000409// isOnlyUse - Return true if this instruction will be deleted if we stop using
410// it.
411static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000412 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000413}
414
Chris Lattner4cb170c2004-02-23 06:38:22 +0000415// getPromotedType - Return the specified type promoted as it would be to pass
416// though a va_arg area...
417static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000418 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
419 if (ITy->getBitWidth() < 32)
420 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000421 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000422 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000423}
424
Reid Spencer3da59db2006-11-27 01:05:10 +0000425/// getBitCastOperand - If the specified operand is a CastInst or a constant
426/// expression bitcast, return the operand value, otherwise return null.
427static Value *getBitCastOperand(Value *V) {
428 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000429 return I->getOperand(0);
430 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000431 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000432 return CE->getOperand(0);
433 return 0;
434}
435
Reid Spencer3da59db2006-11-27 01:05:10 +0000436/// This function is a wrapper around CastInst::isEliminableCastPair. It
437/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000438static Instruction::CastOps
439isEliminableCastPair(
440 const CastInst *CI, ///< The first cast instruction
441 unsigned opcode, ///< The opcode of the second cast instruction
442 const Type *DstTy, ///< The target type for the second cast instruction
443 TargetData *TD ///< The target data for pointer size
444) {
445
446 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
447 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000448
Reid Spencer3da59db2006-11-27 01:05:10 +0000449 // Get the opcodes of the two Cast instructions
450 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
451 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000452
Reid Spencer3da59db2006-11-27 01:05:10 +0000453 return Instruction::CastOps(
454 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
455 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000456}
457
458/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
459/// in any code being generated. It does not require codegen if V is simple
460/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000461static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
462 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000463 if (V->getType() == Ty || isa<Constant>(V)) return false;
464
Chris Lattner01575b72006-05-25 23:24:33 +0000465 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000466 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000467 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000468 return false;
469 return true;
470}
471
472/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
473/// InsertBefore instruction. This is specialized a bit to avoid inserting
474/// casts that are known to not do anything...
475///
Reid Spencer17212df2006-12-12 09:18:51 +0000476Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
477 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000478 Instruction *InsertBefore) {
479 if (V->getType() == DestTy) return V;
480 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000481 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000482
Reid Spencer17212df2006-12-12 09:18:51 +0000483 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000484}
485
Chris Lattner4f98c562003-03-10 21:43:22 +0000486// SimplifyCommutative - This performs a few simplifications for commutative
487// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000488//
Chris Lattner4f98c562003-03-10 21:43:22 +0000489// 1. Order operands such that they are listed from right (least complex) to
490// left (most complex). This puts constants before unary operators before
491// binary operators.
492//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000493// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
494// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000495//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000496bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000497 bool Changed = false;
498 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
499 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000500
Chris Lattner4f98c562003-03-10 21:43:22 +0000501 if (!I.isAssociative()) return Changed;
502 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000503 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
504 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
505 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000506 Constant *Folded = ConstantExpr::get(I.getOpcode(),
507 cast<Constant>(I.getOperand(1)),
508 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000509 I.setOperand(0, Op->getOperand(0));
510 I.setOperand(1, Folded);
511 return true;
512 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
513 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
514 isOnlyUse(Op) && isOnlyUse(Op1)) {
515 Constant *C1 = cast<Constant>(Op->getOperand(1));
516 Constant *C2 = cast<Constant>(Op1->getOperand(1));
517
518 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000519 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000520 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000521 Op1->getOperand(0),
522 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000523 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000524 I.setOperand(0, New);
525 I.setOperand(1, Folded);
526 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000527 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000528 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000529 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000530}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000531
Reid Spencere4d87aa2006-12-23 06:05:41 +0000532/// SimplifyCompare - For a CmpInst this function just orders the operands
533/// so that theyare listed from right (least complex) to left (most complex).
534/// This puts constants before unary operators before binary operators.
535bool InstCombiner::SimplifyCompare(CmpInst &I) {
536 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
537 return false;
538 I.swapOperands();
539 // Compare instructions are not associative so there's nothing else we can do.
540 return true;
541}
542
Chris Lattner8d969642003-03-10 23:06:50 +0000543// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
544// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000545//
Chris Lattner8d969642003-03-10 23:06:50 +0000546static inline Value *dyn_castNegVal(Value *V) {
547 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000548 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000549
Chris Lattner0ce85802004-12-14 20:08:06 +0000550 // Constants can be considered to be negated values if they can be folded.
551 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
552 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000553
554 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
555 if (C->getType()->getElementType()->isInteger())
556 return ConstantExpr::getNeg(C);
557
Chris Lattner8d969642003-03-10 23:06:50 +0000558 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000559}
560
Chris Lattner8d969642003-03-10 23:06:50 +0000561static inline Value *dyn_castNotVal(Value *V) {
562 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000563 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000564
565 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000566 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000567 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000568 return 0;
569}
570
Chris Lattnerc8802d22003-03-11 00:12:48 +0000571// dyn_castFoldableMul - If this value is a multiply that can be folded into
572// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000573// non-constant operand of the multiply, and set CST to point to the multiplier.
574// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000575//
Chris Lattner50af16a2004-11-13 19:50:12 +0000576static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000577 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000578 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000579 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000580 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000581 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000582 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000583 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000584 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000585 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000586 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000587 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000588 return I->getOperand(0);
589 }
590 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000591 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000592}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000593
Chris Lattner574da9b2005-01-13 20:14:25 +0000594/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
595/// expression, return it.
596static User *dyn_castGetElementPtr(Value *V) {
597 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
598 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
599 if (CE->getOpcode() == Instruction::GetElementPtr)
600 return cast<User>(V);
601 return false;
602}
603
Dan Gohmaneee962e2008-04-10 18:43:06 +0000604/// getOpcode - If this is an Instruction or a ConstantExpr, return the
605/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000606static unsigned getOpcode(const Value *V) {
607 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000608 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000609 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000610 return CE->getOpcode();
611 // Use UserOp1 to mean there's no opcode.
612 return Instruction::UserOp1;
613}
614
Reid Spencer7177c3a2007-03-25 05:33:51 +0000615/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000616static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000617 APInt Val(C->getValue());
618 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000619}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000620/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000621static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000622 APInt Val(C->getValue());
623 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000624}
625/// Add - Add two ConstantInts together
626static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
627 return ConstantInt::get(C1->getValue() + C2->getValue());
628}
629/// And - Bitwise AND two ConstantInts together
630static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
631 return ConstantInt::get(C1->getValue() & C2->getValue());
632}
633/// Subtract - Subtract one ConstantInt from another
634static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
635 return ConstantInt::get(C1->getValue() - C2->getValue());
636}
637/// Multiply - Multiply two ConstantInts together
638static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
639 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000640}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000641/// MultiplyOverflows - True if the multiply can not be expressed in an int
642/// this size.
643static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
644 uint32_t W = C1->getBitWidth();
645 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
646 if (sign) {
647 LHSExt.sext(W * 2);
648 RHSExt.sext(W * 2);
649 } else {
650 LHSExt.zext(W * 2);
651 RHSExt.zext(W * 2);
652 }
653
654 APInt MulExt = LHSExt * RHSExt;
655
656 if (sign) {
657 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
658 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
659 return MulExt.slt(Min) || MulExt.sgt(Max);
660 } else
661 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
662}
Chris Lattner955f3312004-09-28 21:48:02 +0000663
Chris Lattner68d5ff22006-02-09 07:38:58 +0000664/// ComputeMaskedBits - Determine which of the bits specified in Mask are
665/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000666/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
667/// processing.
668/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
669/// we cannot optimize based on the assumption that it is zero without changing
670/// it to be an explicit zero. If we don't change it to zero, other code could
671/// optimized based on the contradictory assumption that it is non-zero.
672/// Because instcombine aggressively folds operations with undef args anyway,
673/// this won't lose us code quality.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000674void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
675 APInt& KnownZero, APInt& KnownOne,
Dan Gohman45b4e482008-05-19 22:14:15 +0000676 unsigned Depth) const {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000677 assert(V && "No Value?");
678 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000679 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000680 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
681 "Not integer or pointer type!");
682 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
683 (!isa<IntegerType>(V->getType()) ||
684 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000685 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000686 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000687 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Dan Gohman45b4e482008-05-19 22:14:15 +0000688
Reid Spencer3e7594f2007-03-08 01:46:38 +0000689 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
690 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000691 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000692 KnownZero = ~KnownOne & Mask;
693 return;
694 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000695 // Null is all-zeros.
696 if (isa<ConstantPointerNull>(V)) {
697 KnownOne.clear();
698 KnownZero = Mask;
699 return;
700 }
701 // The address of an aligned GlobalValue has trailing zeros.
702 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
703 unsigned Align = GV->getAlignment();
704 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
705 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
706 if (Align > 0)
707 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
708 CountTrailingZeros_32(Align));
709 else
710 KnownZero.clear();
711 KnownOne.clear();
712 return;
713 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000714
Dan Gohman23e8b712008-04-28 17:02:21 +0000715 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
716
Reid Spencer3e7594f2007-03-08 01:46:38 +0000717 if (Depth == 6 || Mask == 0)
718 return; // Limit search depth.
719
Dan Gohmaneee962e2008-04-10 18:43:06 +0000720 User *I = dyn_cast<User>(V);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000721 if (!I) return;
722
723 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000724 switch (getOpcode(I)) {
725 default: break;
Reid Spencer2b812072007-03-25 02:03:12 +0000726 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000727 // If either the LHS or the RHS are Zero, the result is zero.
728 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000729 APInt Mask2(Mask & ~KnownZero);
730 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000731 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
732 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
733
734 // Output known-1 bits are only known if set in both the LHS & RHS.
735 KnownOne &= KnownOne2;
736 // Output known-0 are known to be clear if zero in either the LHS | RHS.
737 KnownZero |= KnownZero2;
738 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000739 }
740 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000741 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000742 APInt Mask2(Mask & ~KnownOne);
743 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000744 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
745 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
746
747 // Output known-0 bits are only known if clear in both the LHS & RHS.
748 KnownZero &= KnownZero2;
749 // Output known-1 are known to be set if set in either the LHS | RHS.
750 KnownOne |= KnownOne2;
751 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000752 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000753 case Instruction::Xor: {
754 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
755 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
756 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
757 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
758
759 // Output known-0 bits are known if clear or set in both the LHS & RHS.
760 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
761 // Output known-1 are known to be set if set in only one of the LHS, RHS.
762 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
763 KnownZero = KnownZeroOut;
764 return;
765 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000766 case Instruction::Mul: {
767 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
768 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
769 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
770 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
771 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
772
773 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohman23e8b712008-04-28 17:02:21 +0000774 // Also compute a conserative estimate for high known-0 bits.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000775 // More trickiness is possible, but this is sufficient for the
776 // interesting case of alignment computation.
777 KnownOne.clear();
778 unsigned TrailZ = KnownZero.countTrailingOnes() +
779 KnownZero2.countTrailingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +0000780 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
Dan Gohman42ac9292008-05-07 00:35:55 +0000781 KnownZero2.countLeadingOnes(),
782 BitWidth) - BitWidth;
Dan Gohman23e8b712008-04-28 17:02:21 +0000783
Dan Gohmaneee962e2008-04-10 18:43:06 +0000784 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000785 LeadZ = std::min(LeadZ, BitWidth);
786 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
787 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000788 KnownZero &= Mask;
789 return;
790 }
Dan Gohman23e8b712008-04-28 17:02:21 +0000791 case Instruction::UDiv: {
792 // For the purposes of computing leading zeros we can conservatively
793 // treat a udiv as a logical right shift by the power of 2 known to
Dan Gohman1d9cd502008-05-02 21:30:02 +0000794 // be less than the denominator.
Dan Gohman23e8b712008-04-28 17:02:21 +0000795 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
796 ComputeMaskedBits(I->getOperand(0),
797 AllOnes, KnownZero2, KnownOne2, Depth+1);
798 unsigned LeadZ = KnownZero2.countLeadingOnes();
799
800 KnownOne2.clear();
801 KnownZero2.clear();
802 ComputeMaskedBits(I->getOperand(1),
803 AllOnes, KnownZero2, KnownOne2, Depth+1);
Dan Gohman1d9cd502008-05-02 21:30:02 +0000804 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
805 if (RHSUnknownLeadingOnes != BitWidth)
806 LeadZ = std::min(BitWidth,
807 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000808
809 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
810 return;
811 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000812 case Instruction::Select:
813 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
814 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
815 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
816 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
817
818 // Only known if known in both the LHS and RHS.
819 KnownOne &= KnownOne2;
820 KnownZero &= KnownZero2;
821 return;
822 case Instruction::FPTrunc:
823 case Instruction::FPExt:
824 case Instruction::FPToUI:
825 case Instruction::FPToSI:
826 case Instruction::SIToFP:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000827 case Instruction::UIToFP:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000828 return; // Can't work with floating point.
829 case Instruction::PtrToInt:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000830 case Instruction::IntToPtr:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000831 // We can't handle these if we don't know the pointer size.
832 if (!TD) return;
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000833 // FALL THROUGH and handle them the same as zext/trunc.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000834 case Instruction::ZExt:
Zhou Sheng771dbf72007-03-13 02:23:10 +0000835 case Instruction::Trunc: {
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000836 // Note that we handle pointer operands here because of inttoptr/ptrtoint
837 // which fall through here.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000838 const Type *SrcTy = I->getOperand(0)->getType();
839 uint32_t SrcBitWidth = TD ?
840 TD->getTypeSizeInBits(SrcTy) :
841 SrcTy->getPrimitiveSizeInBits();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000842 APInt MaskIn(Mask);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000843 MaskIn.zextOrTrunc(SrcBitWidth);
844 KnownZero.zextOrTrunc(SrcBitWidth);
845 KnownOne.zextOrTrunc(SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000846 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000847 KnownZero.zextOrTrunc(BitWidth);
848 KnownOne.zextOrTrunc(BitWidth);
849 // Any top bits are known to be zero.
850 if (BitWidth > SrcBitWidth)
851 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000852 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000853 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000854 case Instruction::BitCast: {
855 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000856 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000857 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
858 return;
859 }
860 break;
861 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000862 case Instruction::SExt: {
863 // Compute the bits in the result that are not present in the input.
864 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000865 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000866
Zhou Shengaa305ab2007-03-28 02:19:03 +0000867 APInt MaskIn(Mask);
868 MaskIn.trunc(SrcBitWidth);
869 KnownZero.trunc(SrcBitWidth);
870 KnownOne.trunc(SrcBitWidth);
871 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000872 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000873 KnownZero.zext(BitWidth);
874 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000875
876 // If the sign bit of the input is known set or clear, then we know the
877 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000878 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000879 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000880 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000881 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000882 return;
883 }
884 case Instruction::Shl:
885 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
886 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000887 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000888 APInt Mask2(Mask.lshr(ShiftAmt));
889 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000890 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000891 KnownZero <<= ShiftAmt;
892 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000893 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000894 return;
895 }
896 break;
897 case Instruction::LShr:
898 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
899 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
900 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000901 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000902
903 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000904 APInt Mask2(Mask.shl(ShiftAmt));
905 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000906 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
907 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
908 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000909 // high bits known zero.
910 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000911 return;
912 }
913 break;
914 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000915 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000916 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
917 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000918 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000919
920 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000921 APInt Mask2(Mask.shl(ShiftAmt));
922 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000923 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
924 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
925 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
926
Zhou Shengaa305ab2007-03-28 02:19:03 +0000927 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
928 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000929 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000930 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000931 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000932 return;
933 }
934 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000935 case Instruction::Sub: {
936 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
937 // We know that the top bits of C-X are clear if X contains less bits
938 // than C (i.e. no wrap-around can happen). For example, 20-X is
939 // positive if we can prove that X is >= 0 and < 16.
940 if (!CLHS->getValue().isNegative()) {
941 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
942 // NLZ can't be BitWidth with no sign bit
943 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000944 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
945 Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000946
Dan Gohman23e8b712008-04-28 17:02:21 +0000947 // If all of the MaskV bits are known to be zero, then we know the
948 // output top bits are zero, because we now know that the output is
949 // from [0-C].
950 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohmaneee962e2008-04-10 18:43:06 +0000951 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
952 // Top bits known zero.
953 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000954 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000955 }
956 }
957 }
958 // fall through
Duncan Sands1d57a752008-03-21 08:32:17 +0000959 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000960 // Output known-0 bits are known if clear or set in both the low clear bits
961 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
962 // low 3 bits clear.
Dan Gohman23e8b712008-04-28 17:02:21 +0000963 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
964 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
965 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
966 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
967
968 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
969 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
970 KnownZeroOut = std::min(KnownZeroOut,
971 KnownZero2.countTrailingOnes());
972
973 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000974 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000975 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000976 case Instruction::SRem:
977 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
978 APInt RA = Rem->getValue();
979 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +0000980 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000981 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
982 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
983
984 // The sign of a remainder is equal to the sign of the first
985 // operand (zero being positive).
986 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
987 KnownZero2 |= ~LowBits;
988 else if (KnownOne2[BitWidth-1])
989 KnownOne2 |= ~LowBits;
990
991 KnownZero |= KnownZero2 & Mask;
992 KnownOne |= KnownOne2 & Mask;
993
994 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
995 }
996 }
997 break;
Dan Gohman23e8b712008-04-28 17:02:21 +0000998 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000999 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1000 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001001 if (RA.isPowerOf2()) {
1002 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001003 APInt Mask2 = LowBits & Mask;
1004 KnownZero |= ~LowBits & Mask;
1005 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1006 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001007 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001008 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001009 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001010
1011 // Since the result is less than or equal to either operand, any leading
1012 // zero bits in either operand must also exist in the result.
1013 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1014 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1015 Depth+1);
1016 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1017 Depth+1);
1018
1019 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1020 KnownZero2.countLeadingOnes());
1021 KnownOne.clear();
1022 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001023 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001024 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00001025
1026 case Instruction::Alloca:
1027 case Instruction::Malloc: {
1028 AllocationInst *AI = cast<AllocationInst>(V);
1029 unsigned Align = AI->getAlignment();
1030 if (Align == 0 && TD) {
1031 if (isa<AllocaInst>(AI))
1032 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1033 else if (isa<MallocInst>(AI)) {
1034 // Malloc returns maximally aligned memory.
1035 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1036 Align =
1037 std::max(Align,
1038 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1039 Align =
1040 std::max(Align,
1041 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1042 }
1043 }
1044
1045 if (Align > 0)
1046 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1047 CountTrailingZeros_32(Align));
1048 break;
1049 }
1050 case Instruction::GetElementPtr: {
1051 // Analyze all of the subscripts of this getelementptr instruction
1052 // to determine if we can prove known low zero bits.
1053 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1054 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1055 ComputeMaskedBits(I->getOperand(0), LocalMask,
1056 LocalKnownZero, LocalKnownOne, Depth+1);
1057 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1058
1059 gep_type_iterator GTI = gep_type_begin(I);
1060 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1061 Value *Index = I->getOperand(i);
1062 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1063 // Handle struct member offset arithmetic.
1064 if (!TD) return;
1065 const StructLayout *SL = TD->getStructLayout(STy);
1066 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1067 uint64_t Offset = SL->getElementOffset(Idx);
1068 TrailZ = std::min(TrailZ,
1069 CountTrailingZeros_64(Offset));
1070 } else {
1071 // Handle array index arithmetic.
1072 const Type *IndexedTy = GTI.getIndexedType();
1073 if (!IndexedTy->isSized()) return;
1074 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1075 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1076 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1077 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1078 ComputeMaskedBits(Index, LocalMask,
1079 LocalKnownZero, LocalKnownOne, Depth+1);
1080 TrailZ = std::min(TrailZ,
1081 CountTrailingZeros_64(TypeSize) +
1082 LocalKnownZero.countTrailingOnes());
1083 }
1084 }
1085
1086 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1087 break;
1088 }
1089 case Instruction::PHI: {
1090 PHINode *P = cast<PHINode>(I);
1091 // Handle the case of a simple two-predecessor recurrence PHI.
1092 // There's a lot more that could theoretically be done here, but
1093 // this is sufficient to catch some interesting cases.
1094 if (P->getNumIncomingValues() == 2) {
1095 for (unsigned i = 0; i != 2; ++i) {
1096 Value *L = P->getIncomingValue(i);
1097 Value *R = P->getIncomingValue(!i);
1098 User *LU = dyn_cast<User>(L);
Matthijs Kooijman214142c2008-05-23 16:17:48 +00001099 if (!LU)
1100 continue;
1101 unsigned Opcode = getOpcode(LU);
Dan Gohmaneee962e2008-04-10 18:43:06 +00001102 // Check for operations that have the property that if
1103 // both their operands have low zero bits, the result
1104 // will have low zero bits.
1105 if (Opcode == Instruction::Add ||
1106 Opcode == Instruction::Sub ||
1107 Opcode == Instruction::And ||
1108 Opcode == Instruction::Or ||
1109 Opcode == Instruction::Mul) {
1110 Value *LL = LU->getOperand(0);
1111 Value *LR = LU->getOperand(1);
1112 // Find a recurrence.
1113 if (LL == I)
1114 L = LR;
1115 else if (LR == I)
1116 L = LL;
1117 else
1118 break;
1119 // Ok, we have a PHI of the form L op= R. Check for low
1120 // zero bits.
1121 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1122 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1123 Mask2 = APInt::getLowBitsSet(BitWidth,
1124 KnownZero2.countTrailingOnes());
1125 KnownOne2.clear();
1126 KnownZero2.clear();
1127 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1128 KnownZero = Mask &
1129 APInt::getLowBitsSet(BitWidth,
1130 KnownZero2.countTrailingOnes());
1131 break;
1132 }
1133 }
1134 }
1135 break;
1136 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001137 case Instruction::Call:
1138 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1139 switch (II->getIntrinsicID()) {
1140 default: break;
1141 case Intrinsic::ctpop:
1142 case Intrinsic::ctlz:
1143 case Intrinsic::cttz: {
1144 unsigned LowBits = Log2_32(BitWidth)+1;
1145 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1146 break;
1147 }
1148 }
1149 }
1150 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +00001151 }
1152}
1153
Reid Spencere7816b52007-03-08 01:52:58 +00001154/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1155/// this predicate to simplify operations downstream. Mask is known to be zero
1156/// for bits that V cannot have.
Dan Gohmaneee962e2008-04-10 18:43:06 +00001157bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1158 unsigned Depth) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001159 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001160 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1161 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1162 return (KnownZero & Mask) == Mask;
1163}
1164
Chris Lattner255d8912006-02-11 09:31:47 +00001165/// ShrinkDemandedConstant - Check to see if the specified operand of the
1166/// specified instruction is a constant integer. If so, check to see if there
1167/// are any bits set in the constant that are not demanded. If so, shrink the
1168/// constant and return true.
1169static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001170 APInt Demanded) {
1171 assert(I && "No instruction?");
1172 assert(OpNo < I->getNumOperands() && "Operand index too large");
1173
1174 // If the operand is not a constant integer, nothing to do.
1175 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1176 if (!OpC) return false;
1177
1178 // If there are no bits set that aren't demanded, nothing to do.
1179 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1180 if ((~Demanded & OpC->getValue()) == 0)
1181 return false;
1182
1183 // This instruction is producing bits that are not demanded. Shrink the RHS.
1184 Demanded &= OpC->getValue();
1185 I->setOperand(OpNo, ConstantInt::get(Demanded));
1186 return true;
1187}
1188
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001189// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1190// set of known zero and one bits, compute the maximum and minimum values that
1191// could have the specified known zero and known one bits, returning them in
1192// min/max.
1193static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +00001194 const APInt& KnownZero,
1195 const APInt& KnownOne,
1196 APInt& Min, APInt& Max) {
1197 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1198 assert(KnownZero.getBitWidth() == BitWidth &&
1199 KnownOne.getBitWidth() == BitWidth &&
1200 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1201 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001202 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001203
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001204 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1205 // bit if it is unknown.
1206 Min = KnownOne;
1207 Max = KnownOne|UnknownBits;
1208
Zhou Sheng4acf1552007-03-28 05:15:57 +00001209 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001210 Min.set(BitWidth-1);
1211 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001212 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001213}
1214
1215// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1216// a set of known zero and one bits, compute the maximum and minimum values that
1217// could have the specified known zero and known one bits, returning them in
1218// min/max.
1219static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001220 const APInt &KnownZero,
1221 const APInt &KnownOne,
1222 APInt &Min, APInt &Max) {
1223 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +00001224 assert(KnownZero.getBitWidth() == BitWidth &&
1225 KnownOne.getBitWidth() == BitWidth &&
1226 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1227 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001228 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001229
1230 // The minimum value is when the unknown bits are all zeros.
1231 Min = KnownOne;
1232 // The maximum value is when the unknown bits are all ones.
1233 Max = KnownOne|UnknownBits;
1234}
Chris Lattner255d8912006-02-11 09:31:47 +00001235
Reid Spencer8cb68342007-03-12 17:25:59 +00001236/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1237/// value based on the demanded bits. When this function is called, it is known
1238/// that only the bits set in DemandedMask of the result of V are ever used
1239/// downstream. Consequently, depending on the mask and V, it may be possible
1240/// to replace V with a constant or one of its operands. In such cases, this
1241/// function does the replacement and returns true. In all other cases, it
1242/// returns false after analyzing the expression and setting KnownOne and known
1243/// to be one in the expression. KnownZero contains all the bits that are known
1244/// to be zero in the expression. These are provided to potentially allow the
1245/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1246/// the expression. KnownOne and KnownZero always follow the invariant that
1247/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1248/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1249/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1250/// and KnownOne must all be the same.
1251bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1252 APInt& KnownZero, APInt& KnownOne,
1253 unsigned Depth) {
1254 assert(V != 0 && "Null pointer of Value???");
1255 assert(Depth <= 6 && "Limit Search Depth");
1256 uint32_t BitWidth = DemandedMask.getBitWidth();
1257 const IntegerType *VTy = cast<IntegerType>(V->getType());
1258 assert(VTy->getBitWidth() == BitWidth &&
1259 KnownZero.getBitWidth() == BitWidth &&
1260 KnownOne.getBitWidth() == BitWidth &&
1261 "Value *V, DemandedMask, KnownZero and KnownOne \
1262 must have same BitWidth");
1263 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1264 // We know all of the bits for a constant!
1265 KnownOne = CI->getValue() & DemandedMask;
1266 KnownZero = ~KnownOne & DemandedMask;
1267 return false;
1268 }
1269
Zhou Sheng96704452007-03-14 03:21:24 +00001270 KnownZero.clear();
1271 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001272 if (!V->hasOneUse()) { // Other users may use these bits.
1273 if (Depth != 0) { // Not at the root.
1274 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1275 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1276 return false;
1277 }
1278 // If this is the root being simplified, allow it to have multiple uses,
1279 // just set the DemandedMask to all bits.
1280 DemandedMask = APInt::getAllOnesValue(BitWidth);
1281 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1282 if (V != UndefValue::get(VTy))
1283 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1284 return false;
1285 } else if (Depth == 6) { // Limit search depth.
1286 return false;
1287 }
1288
1289 Instruction *I = dyn_cast<Instruction>(V);
1290 if (!I) return false; // Only analyze instructions.
1291
Reid Spencer8cb68342007-03-12 17:25:59 +00001292 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1293 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1294 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001295 default:
1296 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1297 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001298 case Instruction::And:
1299 // If either the LHS or the RHS are Zero, the result is zero.
1300 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1301 RHSKnownZero, RHSKnownOne, Depth+1))
1302 return true;
1303 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1304 "Bits known to be one AND zero?");
1305
1306 // If something is known zero on the RHS, the bits aren't demanded on the
1307 // LHS.
1308 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1309 LHSKnownZero, LHSKnownOne, Depth+1))
1310 return true;
1311 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1312 "Bits known to be one AND zero?");
1313
1314 // If all of the demanded bits are known 1 on one side, return the other.
1315 // These bits cannot contribute to the result of the 'and'.
1316 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1317 (DemandedMask & ~LHSKnownZero))
1318 return UpdateValueUsesWith(I, I->getOperand(0));
1319 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1320 (DemandedMask & ~RHSKnownZero))
1321 return UpdateValueUsesWith(I, I->getOperand(1));
1322
1323 // If all of the demanded bits in the inputs are known zeros, return zero.
1324 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1325 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1326
1327 // If the RHS is a constant, see if we can simplify it.
1328 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1329 return UpdateValueUsesWith(I, I);
1330
1331 // Output known-1 bits are only known if set in both the LHS & RHS.
1332 RHSKnownOne &= LHSKnownOne;
1333 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1334 RHSKnownZero |= LHSKnownZero;
1335 break;
1336 case Instruction::Or:
1337 // If either the LHS or the RHS are One, the result is One.
1338 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1339 RHSKnownZero, RHSKnownOne, Depth+1))
1340 return true;
1341 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1342 "Bits known to be one AND zero?");
1343 // If something is known one on the RHS, the bits aren't demanded on the
1344 // LHS.
1345 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1346 LHSKnownZero, LHSKnownOne, Depth+1))
1347 return true;
1348 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1349 "Bits known to be one AND zero?");
1350
1351 // If all of the demanded bits are known zero on one side, return the other.
1352 // These bits cannot contribute to the result of the 'or'.
1353 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1354 (DemandedMask & ~LHSKnownOne))
1355 return UpdateValueUsesWith(I, I->getOperand(0));
1356 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1357 (DemandedMask & ~RHSKnownOne))
1358 return UpdateValueUsesWith(I, I->getOperand(1));
1359
1360 // If all of the potentially set bits on one side are known to be set on
1361 // the other side, just use the 'other' side.
1362 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1363 (DemandedMask & (~RHSKnownZero)))
1364 return UpdateValueUsesWith(I, I->getOperand(0));
1365 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1366 (DemandedMask & (~LHSKnownZero)))
1367 return UpdateValueUsesWith(I, I->getOperand(1));
1368
1369 // If the RHS is a constant, see if we can simplify it.
1370 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1371 return UpdateValueUsesWith(I, I);
1372
1373 // Output known-0 bits are only known if clear in both the LHS & RHS.
1374 RHSKnownZero &= LHSKnownZero;
1375 // Output known-1 are known to be set if set in either the LHS | RHS.
1376 RHSKnownOne |= LHSKnownOne;
1377 break;
1378 case Instruction::Xor: {
1379 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1380 RHSKnownZero, RHSKnownOne, Depth+1))
1381 return true;
1382 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1383 "Bits known to be one AND zero?");
1384 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1385 LHSKnownZero, LHSKnownOne, Depth+1))
1386 return true;
1387 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1388 "Bits known to be one AND zero?");
1389
1390 // If all of the demanded bits are known zero on one side, return the other.
1391 // These bits cannot contribute to the result of the 'xor'.
1392 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1393 return UpdateValueUsesWith(I, I->getOperand(0));
1394 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1395 return UpdateValueUsesWith(I, I->getOperand(1));
1396
1397 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1398 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1399 (RHSKnownOne & LHSKnownOne);
1400 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1401 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1402 (RHSKnownOne & LHSKnownZero);
1403
1404 // If all of the demanded bits are known to be zero on one side or the
1405 // other, turn this into an *inclusive* or.
1406 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1407 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1408 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001409 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001410 I->getName());
1411 InsertNewInstBefore(Or, *I);
1412 return UpdateValueUsesWith(I, Or);
1413 }
1414
1415 // If all of the demanded bits on one side are known, and all of the set
1416 // bits on that side are also known to be set on the other side, turn this
1417 // into an AND, as we know the bits will be cleared.
1418 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1419 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1420 // all known
1421 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1422 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1423 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001424 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +00001425 InsertNewInstBefore(And, *I);
1426 return UpdateValueUsesWith(I, And);
1427 }
1428 }
1429
1430 // If the RHS is a constant, see if we can simplify it.
1431 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1432 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1433 return UpdateValueUsesWith(I, I);
1434
1435 RHSKnownZero = KnownZeroOut;
1436 RHSKnownOne = KnownOneOut;
1437 break;
1438 }
1439 case Instruction::Select:
1440 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1441 RHSKnownZero, RHSKnownOne, Depth+1))
1442 return true;
1443 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1444 LHSKnownZero, LHSKnownOne, Depth+1))
1445 return true;
1446 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1447 "Bits known to be one AND zero?");
1448 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1449 "Bits known to be one AND zero?");
1450
1451 // If the operands are constants, see if we can simplify them.
1452 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1453 return UpdateValueUsesWith(I, I);
1454 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1455 return UpdateValueUsesWith(I, I);
1456
1457 // Only known if known in both the LHS and RHS.
1458 RHSKnownOne &= LHSKnownOne;
1459 RHSKnownZero &= LHSKnownZero;
1460 break;
1461 case Instruction::Trunc: {
1462 uint32_t truncBf =
1463 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001464 DemandedMask.zext(truncBf);
1465 RHSKnownZero.zext(truncBf);
1466 RHSKnownOne.zext(truncBf);
1467 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1468 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001469 return true;
1470 DemandedMask.trunc(BitWidth);
1471 RHSKnownZero.trunc(BitWidth);
1472 RHSKnownOne.trunc(BitWidth);
1473 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1474 "Bits known to be one AND zero?");
1475 break;
1476 }
1477 case Instruction::BitCast:
1478 if (!I->getOperand(0)->getType()->isInteger())
1479 return false;
1480
1481 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1482 RHSKnownZero, RHSKnownOne, Depth+1))
1483 return true;
1484 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1485 "Bits known to be one AND zero?");
1486 break;
1487 case Instruction::ZExt: {
1488 // Compute the bits in the result that are not present in the input.
1489 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001490 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001491
Zhou Shengd48653a2007-03-29 04:45:55 +00001492 DemandedMask.trunc(SrcBitWidth);
1493 RHSKnownZero.trunc(SrcBitWidth);
1494 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001495 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1496 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001497 return true;
1498 DemandedMask.zext(BitWidth);
1499 RHSKnownZero.zext(BitWidth);
1500 RHSKnownOne.zext(BitWidth);
1501 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1502 "Bits known to be one AND zero?");
1503 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001504 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001505 break;
1506 }
1507 case Instruction::SExt: {
1508 // Compute the bits in the result that are not present in the input.
1509 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001510 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001511
Reid Spencer8cb68342007-03-12 17:25:59 +00001512 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001513 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001514
Zhou Sheng01542f32007-03-29 02:26:30 +00001515 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001516 // If any of the sign extended bits are demanded, we know that the sign
1517 // bit is demanded.
1518 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001519 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001520
Zhou Shengd48653a2007-03-29 04:45:55 +00001521 InputDemandedBits.trunc(SrcBitWidth);
1522 RHSKnownZero.trunc(SrcBitWidth);
1523 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001524 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1525 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001526 return true;
1527 InputDemandedBits.zext(BitWidth);
1528 RHSKnownZero.zext(BitWidth);
1529 RHSKnownOne.zext(BitWidth);
1530 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1531 "Bits known to be one AND zero?");
1532
1533 // If the sign bit of the input is known set or clear, then we know the
1534 // top bits of the result.
1535
1536 // If the input sign bit is known zero, or if the NewBits are not demanded
1537 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001538 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001539 {
1540 // Convert to ZExt cast
1541 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1542 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001543 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001544 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001545 }
1546 break;
1547 }
1548 case Instruction::Add: {
1549 // Figure out what the input bits are. If the top bits of the and result
1550 // are not demanded, then the add doesn't demand them from its input
1551 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001552 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001553
1554 // If there is a constant on the RHS, there are a variety of xformations
1555 // we can do.
1556 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1557 // If null, this should be simplified elsewhere. Some of the xforms here
1558 // won't work if the RHS is zero.
1559 if (RHS->isZero())
1560 break;
1561
1562 // If the top bit of the output is demanded, demand everything from the
1563 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001564 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001565
1566 // Find information about known zero/one bits in the input.
1567 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1568 LHSKnownZero, LHSKnownOne, Depth+1))
1569 return true;
1570
1571 // If the RHS of the add has bits set that can't affect the input, reduce
1572 // the constant.
1573 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1574 return UpdateValueUsesWith(I, I);
1575
1576 // Avoid excess work.
1577 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1578 break;
1579
1580 // Turn it into OR if input bits are zero.
1581 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1582 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001583 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001584 I->getName());
1585 InsertNewInstBefore(Or, *I);
1586 return UpdateValueUsesWith(I, Or);
1587 }
1588
1589 // We can say something about the output known-zero and known-one bits,
1590 // depending on potential carries from the input constant and the
1591 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1592 // bits set and the RHS constant is 0x01001, then we know we have a known
1593 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1594
1595 // To compute this, we first compute the potential carry bits. These are
1596 // the bits which may be modified. I'm not aware of a better way to do
1597 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001598 const APInt& RHSVal = RHS->getValue();
1599 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001600
1601 // Now that we know which bits have carries, compute the known-1/0 sets.
1602
1603 // Bits are known one if they are known zero in one operand and one in the
1604 // other, and there is no input carry.
1605 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1606 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1607
1608 // Bits are known zero if they are known zero in both operands and there
1609 // is no input carry.
1610 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1611 } else {
1612 // If the high-bits of this ADD are not demanded, then it does not demand
1613 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001614 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001615 // Right fill the mask of bits for this ADD to demand the most
1616 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001617 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001618 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1619 LHSKnownZero, LHSKnownOne, Depth+1))
1620 return true;
1621 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1622 LHSKnownZero, LHSKnownOne, Depth+1))
1623 return true;
1624 }
1625 }
1626 break;
1627 }
1628 case Instruction::Sub:
1629 // If the high-bits of this SUB are not demanded, then it does not demand
1630 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001631 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001632 // Right fill the mask of bits for this SUB to demand the most
1633 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001634 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001635 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001636 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1637 LHSKnownZero, LHSKnownOne, Depth+1))
1638 return true;
1639 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1640 LHSKnownZero, LHSKnownOne, Depth+1))
1641 return true;
1642 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001643 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1644 // the known zeros and ones.
1645 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001646 break;
1647 case Instruction::Shl:
1648 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001649 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001650 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1651 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001652 RHSKnownZero, RHSKnownOne, Depth+1))
1653 return true;
1654 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1655 "Bits known to be one AND zero?");
1656 RHSKnownZero <<= ShiftAmt;
1657 RHSKnownOne <<= ShiftAmt;
1658 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001659 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001660 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001661 }
1662 break;
1663 case Instruction::LShr:
1664 // For a logical shift right
1665 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001666 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001667
Reid Spencer8cb68342007-03-12 17:25:59 +00001668 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001669 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1670 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001671 RHSKnownZero, RHSKnownOne, Depth+1))
1672 return true;
1673 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1674 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001675 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1676 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001677 if (ShiftAmt) {
1678 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001679 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001680 RHSKnownZero |= HighBits; // high bits known zero.
1681 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001682 }
1683 break;
1684 case Instruction::AShr:
1685 // If this is an arithmetic shift right and only the low-bit is set, we can
1686 // always convert this into a logical shr, even if the shift amount is
1687 // variable. The low bit of the shift cannot be an input sign bit unless
1688 // the shift amount is >= the size of the datatype, which is undefined.
1689 if (DemandedMask == 1) {
1690 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001691 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001692 I->getOperand(0), I->getOperand(1), I->getName());
1693 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1694 return UpdateValueUsesWith(I, NewVal);
1695 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001696
1697 // If the sign bit is the only bit demanded by this ashr, then there is no
1698 // need to do it, the shift doesn't change the high bit.
1699 if (DemandedMask.isSignBit())
1700 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001701
1702 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001703 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001704
Reid Spencer8cb68342007-03-12 17:25:59 +00001705 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001706 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001707 // If any of the "high bits" are demanded, we should set the sign bit as
1708 // demanded.
1709 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1710 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001711 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001712 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001713 RHSKnownZero, RHSKnownOne, Depth+1))
1714 return true;
1715 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1716 "Bits known to be one AND zero?");
1717 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001718 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001719 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1720 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1721
1722 // Handle the sign bits.
1723 APInt SignBit(APInt::getSignBit(BitWidth));
1724 // Adjust to where it is now in the mask.
1725 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1726
1727 // If the input sign bit is known to be zero, or if none of the top bits
1728 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001729 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001730 (HighBits & ~DemandedMask) == HighBits) {
1731 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001732 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001733 I->getOperand(0), SA, I->getName());
1734 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1735 return UpdateValueUsesWith(I, NewVal);
1736 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1737 RHSKnownOne |= HighBits;
1738 }
1739 }
1740 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001741 case Instruction::SRem:
1742 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1743 APInt RA = Rem->getValue();
1744 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001745 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001746 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1747 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1748 LHSKnownZero, LHSKnownOne, Depth+1))
1749 return true;
1750
1751 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1752 LHSKnownZero |= ~LowBits;
1753 else if (LHSKnownOne[BitWidth-1])
1754 LHSKnownOne |= ~LowBits;
1755
1756 KnownZero |= LHSKnownZero & DemandedMask;
1757 KnownOne |= LHSKnownOne & DemandedMask;
1758
1759 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1760 }
1761 }
1762 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001763 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001764 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1765 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001766 if (RA.isPowerOf2()) {
1767 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001768 APInt Mask2 = LowBits & DemandedMask;
1769 KnownZero |= ~LowBits & DemandedMask;
1770 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1771 KnownZero, KnownOne, Depth+1))
1772 return true;
1773
1774 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001775 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001776 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001777 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001778
1779 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1780 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001781 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1782 KnownZero2, KnownOne2, Depth+1))
1783 return true;
1784
Dan Gohman23e8b712008-04-28 17:02:21 +00001785 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001786 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001787 KnownZero2, KnownOne2, Depth+1))
1788 return true;
1789
1790 Leaders = std::max(Leaders,
1791 KnownZero2.countLeadingOnes());
1792 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001793 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001794 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001795 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001796
1797 // If the client is only demanding bits that we know, return the known
1798 // constant.
1799 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1800 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1801 return false;
1802}
1803
Chris Lattner867b99f2006-10-05 06:55:50 +00001804
1805/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1806/// 64 or fewer elements. DemandedElts contains the set of elements that are
1807/// actually used by the caller. This method analyzes which elements of the
1808/// operand are undef and returns that information in UndefElts.
1809///
1810/// If the information about demanded elements can be used to simplify the
1811/// operation, the operation is simplified, then the resultant value is
1812/// returned. This returns null if no change was made.
1813Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1814 uint64_t &UndefElts,
1815 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001816 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001817 assert(VWidth <= 64 && "Vector too wide to analyze!");
1818 uint64_t EltMask = ~0ULL >> (64-VWidth);
1819 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1820 "Invalid DemandedElts!");
1821
1822 if (isa<UndefValue>(V)) {
1823 // If the entire vector is undefined, just return this info.
1824 UndefElts = EltMask;
1825 return 0;
1826 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1827 UndefElts = EltMask;
1828 return UndefValue::get(V->getType());
1829 }
1830
1831 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001832 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1833 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001834 Constant *Undef = UndefValue::get(EltTy);
1835
1836 std::vector<Constant*> Elts;
1837 for (unsigned i = 0; i != VWidth; ++i)
1838 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1839 Elts.push_back(Undef);
1840 UndefElts |= (1ULL << i);
1841 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1842 Elts.push_back(Undef);
1843 UndefElts |= (1ULL << i);
1844 } else { // Otherwise, defined.
1845 Elts.push_back(CP->getOperand(i));
1846 }
1847
1848 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001849 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001850 return NewCP != CP ? NewCP : 0;
1851 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001852 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001853 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001854 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001855 Constant *Zero = Constant::getNullValue(EltTy);
1856 Constant *Undef = UndefValue::get(EltTy);
1857 std::vector<Constant*> Elts;
1858 for (unsigned i = 0; i != VWidth; ++i)
1859 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1860 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001861 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001862 }
1863
1864 if (!V->hasOneUse()) { // Other users may use these bits.
1865 if (Depth != 0) { // Not at the root.
1866 // TODO: Just compute the UndefElts information recursively.
1867 return false;
1868 }
1869 return false;
1870 } else if (Depth == 10) { // Limit search depth.
1871 return false;
1872 }
1873
1874 Instruction *I = dyn_cast<Instruction>(V);
1875 if (!I) return false; // Only analyze instructions.
1876
1877 bool MadeChange = false;
1878 uint64_t UndefElts2;
1879 Value *TmpV;
1880 switch (I->getOpcode()) {
1881 default: break;
1882
1883 case Instruction::InsertElement: {
1884 // If this is a variable index, we don't know which element it overwrites.
1885 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001886 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001887 if (Idx == 0) {
1888 // Note that we can't propagate undef elt info, because we don't know
1889 // which elt is getting updated.
1890 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1891 UndefElts2, Depth+1);
1892 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1893 break;
1894 }
1895
1896 // If this is inserting an element that isn't demanded, remove this
1897 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001898 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001899 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1900 return AddSoonDeadInstToWorklist(*I, 0);
1901
1902 // Otherwise, the element inserted overwrites whatever was there, so the
1903 // input demanded set is simpler than the output set.
1904 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1905 DemandedElts & ~(1ULL << IdxNo),
1906 UndefElts, Depth+1);
1907 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1908
1909 // The inserted element is defined.
1910 UndefElts |= 1ULL << IdxNo;
1911 break;
1912 }
Chris Lattner69878332007-04-14 22:29:23 +00001913 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001914 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001915 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1916 if (!VTy) break;
1917 unsigned InVWidth = VTy->getNumElements();
1918 uint64_t InputDemandedElts = 0;
1919 unsigned Ratio;
1920
1921 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001922 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001923 // elements as are demanded of us.
1924 Ratio = 1;
1925 InputDemandedElts = DemandedElts;
1926 } else if (VWidth > InVWidth) {
1927 // Untested so far.
1928 break;
1929
1930 // If there are more elements in the result than there are in the source,
1931 // then an input element is live if any of the corresponding output
1932 // elements are live.
1933 Ratio = VWidth/InVWidth;
1934 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1935 if (DemandedElts & (1ULL << OutIdx))
1936 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1937 }
1938 } else {
1939 // Untested so far.
1940 break;
1941
1942 // If there are more elements in the source than there are in the result,
1943 // then an input element is live if the corresponding output element is
1944 // live.
1945 Ratio = InVWidth/VWidth;
1946 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1947 if (DemandedElts & (1ULL << InIdx/Ratio))
1948 InputDemandedElts |= 1ULL << InIdx;
1949 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001950
Chris Lattner69878332007-04-14 22:29:23 +00001951 // div/rem demand all inputs, because they don't want divide by zero.
1952 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1953 UndefElts2, Depth+1);
1954 if (TmpV) {
1955 I->setOperand(0, TmpV);
1956 MadeChange = true;
1957 }
1958
1959 UndefElts = UndefElts2;
1960 if (VWidth > InVWidth) {
1961 assert(0 && "Unimp");
1962 // If there are more elements in the result than there are in the source,
1963 // then an output element is undef if the corresponding input element is
1964 // undef.
1965 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1966 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1967 UndefElts |= 1ULL << OutIdx;
1968 } else if (VWidth < InVWidth) {
1969 assert(0 && "Unimp");
1970 // If there are more elements in the source than there are in the result,
1971 // then a result element is undef if all of the corresponding input
1972 // elements are undef.
1973 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1974 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1975 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1976 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1977 }
1978 break;
1979 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001980 case Instruction::And:
1981 case Instruction::Or:
1982 case Instruction::Xor:
1983 case Instruction::Add:
1984 case Instruction::Sub:
1985 case Instruction::Mul:
1986 // div/rem demand all inputs, because they don't want divide by zero.
1987 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1988 UndefElts, Depth+1);
1989 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1990 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1991 UndefElts2, Depth+1);
1992 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1993
1994 // Output elements are undefined if both are undefined. Consider things
1995 // like undef&0. The result is known zero, not undef.
1996 UndefElts &= UndefElts2;
1997 break;
1998
1999 case Instruction::Call: {
2000 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2001 if (!II) break;
2002 switch (II->getIntrinsicID()) {
2003 default: break;
2004
2005 // Binary vector operations that work column-wise. A dest element is a
2006 // function of the corresponding input elements from the two inputs.
2007 case Intrinsic::x86_sse_sub_ss:
2008 case Intrinsic::x86_sse_mul_ss:
2009 case Intrinsic::x86_sse_min_ss:
2010 case Intrinsic::x86_sse_max_ss:
2011 case Intrinsic::x86_sse2_sub_sd:
2012 case Intrinsic::x86_sse2_mul_sd:
2013 case Intrinsic::x86_sse2_min_sd:
2014 case Intrinsic::x86_sse2_max_sd:
2015 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2016 UndefElts, Depth+1);
2017 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2018 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2019 UndefElts2, Depth+1);
2020 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2021
2022 // If only the low elt is demanded and this is a scalarizable intrinsic,
2023 // scalarize it now.
2024 if (DemandedElts == 1) {
2025 switch (II->getIntrinsicID()) {
2026 default: break;
2027 case Intrinsic::x86_sse_sub_ss:
2028 case Intrinsic::x86_sse_mul_ss:
2029 case Intrinsic::x86_sse2_sub_sd:
2030 case Intrinsic::x86_sse2_mul_sd:
2031 // TODO: Lower MIN/MAX/ABS/etc
2032 Value *LHS = II->getOperand(1);
2033 Value *RHS = II->getOperand(2);
2034 // Extract the element as scalars.
2035 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2036 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2037
2038 switch (II->getIntrinsicID()) {
2039 default: assert(0 && "Case stmts out of sync!");
2040 case Intrinsic::x86_sse_sub_ss:
2041 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002042 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002043 II->getName()), *II);
2044 break;
2045 case Intrinsic::x86_sse_mul_ss:
2046 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002047 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002048 II->getName()), *II);
2049 break;
2050 }
2051
2052 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00002053 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2054 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00002055 InsertNewInstBefore(New, *II);
2056 AddSoonDeadInstToWorklist(*II, 0);
2057 return New;
2058 }
2059 }
2060
2061 // Output elements are undefined if both are undefined. Consider things
2062 // like undef&0. The result is known zero, not undef.
2063 UndefElts &= UndefElts2;
2064 break;
2065 }
2066 break;
2067 }
2068 }
2069 return MadeChange ? I : 0;
2070}
2071
Dan Gohman45b4e482008-05-19 22:14:15 +00002072/// ComputeNumSignBits - Return the number of times the sign bit of the
2073/// register is replicated into the other bits. We know that at least 1 bit
2074/// is always equal to the sign bit (itself), but other cases can give us
2075/// information. For example, immediately after an "ashr X, 2", we know that
2076/// the top 3 bits are all equal to each other, so we return 3.
2077///
2078unsigned InstCombiner::ComputeNumSignBits(Value *V, unsigned Depth) const{
2079 const IntegerType *Ty = cast<IntegerType>(V->getType());
2080 unsigned TyBits = Ty->getBitWidth();
2081 unsigned Tmp, Tmp2;
Dan Gohmana332f172008-05-23 02:28:01 +00002082 unsigned FirstAnswer = 1;
Dan Gohman45b4e482008-05-19 22:14:15 +00002083
2084 if (Depth == 6)
2085 return 1; // Limit search depth.
2086
2087 User *U = dyn_cast<User>(V);
2088 switch (getOpcode(V)) {
2089 default: break;
2090 case Instruction::SExt:
2091 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
2092 return ComputeNumSignBits(U->getOperand(0), Depth+1) + Tmp;
2093
2094 case Instruction::AShr:
2095 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
Dan Gohmanf35c8822008-05-20 21:01:12 +00002096 // ashr X, C -> adds C sign bits.
Dan Gohman45b4e482008-05-19 22:14:15 +00002097 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2098 Tmp += C->getZExtValue();
2099 if (Tmp > TyBits) Tmp = TyBits;
2100 }
2101 return Tmp;
2102 case Instruction::Shl:
2103 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2104 // shl destroys sign bits.
2105 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2106 if (C->getZExtValue() >= TyBits || // Bad shift.
2107 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2108 return Tmp - C->getZExtValue();
2109 }
2110 break;
2111 case Instruction::And:
2112 case Instruction::Or:
Dan Gohmana332f172008-05-23 02:28:01 +00002113 case Instruction::Xor: // NOT is handled here.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002114 // Logical binary ops preserve the number of sign bits at the worst.
2115 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2116 if (Tmp != 1) {
2117 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
Dan Gohmana332f172008-05-23 02:28:01 +00002118 FirstAnswer = std::min(Tmp, Tmp2);
2119 // We computed what we know about the sign bits as our first
2120 // answer. Now proceed to the generic code that uses
2121 // ComputeMaskedBits, and pick whichever answer is better.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002122 }
Dan Gohmana332f172008-05-23 02:28:01 +00002123 break;
Dan Gohman45b4e482008-05-19 22:14:15 +00002124
2125 case Instruction::Select:
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002126 Tmp = ComputeNumSignBits(U->getOperand(1), Depth+1);
Dan Gohman45b4e482008-05-19 22:14:15 +00002127 if (Tmp == 1) return 1; // Early out.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002128 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth+1);
Dan Gohman45b4e482008-05-19 22:14:15 +00002129 return std::min(Tmp, Tmp2);
2130
2131 case Instruction::Add:
2132 // Add can have at most one carry bit. Thus we know that the output
2133 // is, at worst, one more bit than the inputs.
2134 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2135 if (Tmp == 1) return 1; // Early out.
2136
2137 // Special case decrementing a value (ADD X, -1):
2138 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2139 if (CRHS->isAllOnesValue()) {
2140 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2141 APInt Mask = APInt::getAllOnesValue(TyBits);
2142 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2143
2144 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2145 // sign bits set.
2146 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2147 return TyBits;
2148
2149 // If we are subtracting one from a positive number, there is no carry
2150 // out of the result.
2151 if (KnownZero.isNegative())
2152 return Tmp;
2153 }
2154
2155 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2156 if (Tmp2 == 1) return 1;
2157 return std::min(Tmp, Tmp2)-1;
2158 break;
2159
2160 case Instruction::Sub:
2161 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2162 if (Tmp2 == 1) return 1;
2163
2164 // Handle NEG.
2165 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2166 if (CLHS->isNullValue()) {
2167 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2168 APInt Mask = APInt::getAllOnesValue(TyBits);
2169 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2170 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2171 // sign bits set.
2172 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2173 return TyBits;
2174
2175 // If the input is known to be positive (the sign bit is known clear),
2176 // the output of the NEG has the same number of sign bits as the input.
2177 if (KnownZero.isNegative())
2178 return Tmp2;
2179
2180 // Otherwise, we treat this like a SUB.
2181 }
2182
2183 // Sub can have at most one carry bit. Thus we know that the output
2184 // is, at worst, one more bit than the inputs.
2185 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2186 if (Tmp == 1) return 1; // Early out.
2187 return std::min(Tmp, Tmp2)-1;
2188 break;
2189 case Instruction::Trunc:
2190 // FIXME: it's tricky to do anything useful for this, but it is an important
2191 // case for targets like X86.
2192 break;
2193 }
2194
2195 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2196 // use this information.
2197 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2198 APInt Mask = APInt::getAllOnesValue(TyBits);
2199 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
2200
2201 if (KnownZero.isNegative()) { // sign bit is 0
2202 Mask = KnownZero;
2203 } else if (KnownOne.isNegative()) { // sign bit is 1;
2204 Mask = KnownOne;
2205 } else {
2206 // Nothing known.
Dan Gohmana332f172008-05-23 02:28:01 +00002207 return FirstAnswer;
Dan Gohman45b4e482008-05-19 22:14:15 +00002208 }
2209
2210 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2211 // the number of identical bits in the top of the input value.
2212 Mask = ~Mask;
2213 Mask <<= Mask.getBitWidth()-TyBits;
2214 // Return # leading zeros. We use 'min' here in case Val was zero before
2215 // shifting. We don't want to return '64' as for an i32 "0".
Dan Gohmana332f172008-05-23 02:28:01 +00002216 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
Dan Gohman45b4e482008-05-19 22:14:15 +00002217}
2218
2219
Chris Lattner564a7272003-08-13 19:01:45 +00002220/// AssociativeOpt - Perform an optimization on an associative operator. This
2221/// function is designed to check a chain of associative operators for a
2222/// potential to apply a certain optimization. Since the optimization may be
2223/// applicable if the expression was reassociated, this checks the chain, then
2224/// reassociates the expression as necessary to expose the optimization
2225/// opportunity. This makes use of a special Functor, which must define
2226/// 'shouldApply' and 'apply' methods.
2227///
2228template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00002229static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00002230 unsigned Opcode = Root.getOpcode();
2231 Value *LHS = Root.getOperand(0);
2232
2233 // Quick check, see if the immediate LHS matches...
2234 if (F.shouldApply(LHS))
2235 return F.apply(Root);
2236
2237 // Otherwise, if the LHS is not of the same opcode as the root, return.
2238 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002239 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002240 // Should we apply this transform to the RHS?
2241 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2242
2243 // If not to the RHS, check to see if we should apply to the LHS...
2244 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2245 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2246 ShouldApply = true;
2247 }
2248
2249 // If the functor wants to apply the optimization to the RHS of LHSI,
2250 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2251 if (ShouldApply) {
2252 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002253
Chris Lattner564a7272003-08-13 19:01:45 +00002254 // Now all of the instructions are in the current basic block, go ahead
2255 // and perform the reassociation.
2256 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2257
2258 // First move the selected RHS to the LHS of the root...
2259 Root.setOperand(0, LHSI->getOperand(1));
2260
2261 // Make what used to be the LHS of the root be the user of the root...
2262 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002263 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002264 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2265 return 0;
2266 }
Chris Lattner65725312004-04-16 18:08:07 +00002267 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002268 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002269 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2270 BasicBlock::iterator ARI = &Root; ++ARI;
2271 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2272 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002273
2274 // Now propagate the ExtraOperand down the chain of instructions until we
2275 // get to LHSI.
2276 while (TmpLHSI != LHSI) {
2277 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002278 // Move the instruction to immediately before the chain we are
2279 // constructing to avoid breaking dominance properties.
2280 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2281 BB->getInstList().insert(ARI, NextLHSI);
2282 ARI = NextLHSI;
2283
Chris Lattner564a7272003-08-13 19:01:45 +00002284 Value *NextOp = NextLHSI->getOperand(1);
2285 NextLHSI->setOperand(1, ExtraOperand);
2286 TmpLHSI = NextLHSI;
2287 ExtraOperand = NextOp;
2288 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002289
Chris Lattner564a7272003-08-13 19:01:45 +00002290 // Now that the instructions are reassociated, have the functor perform
2291 // the transformation...
2292 return F.apply(Root);
2293 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002294
Chris Lattner564a7272003-08-13 19:01:45 +00002295 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2296 }
2297 return 0;
2298}
2299
Dan Gohman844731a2008-05-13 00:00:25 +00002300namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002301
Nick Lewycky02d639f2008-05-23 04:34:58 +00002302// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00002303struct AddRHS {
2304 Value *RHS;
2305 AddRHS(Value *rhs) : RHS(rhs) {}
2306 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2307 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00002308 return BinaryOperator::CreateShl(Add.getOperand(0),
2309 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002310 }
2311};
2312
2313// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2314// iff C1&C2 == 0
2315struct AddMaskingAnd {
2316 Constant *C2;
2317 AddMaskingAnd(Constant *c) : C2(c) {}
2318 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002319 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002320 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002321 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002322 }
2323 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002324 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002325 }
2326};
2327
Dan Gohman844731a2008-05-13 00:00:25 +00002328}
2329
Chris Lattner6e7ba452005-01-01 16:22:27 +00002330static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002331 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002332 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002333 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002334 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002335
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002336 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00002337 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002338 }
2339
Chris Lattner2eefe512004-04-09 19:05:30 +00002340 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002341 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2342 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002343
Chris Lattner2eefe512004-04-09 19:05:30 +00002344 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2345 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002346 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2347 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002348 }
2349
2350 Value *Op0 = SO, *Op1 = ConstOperand;
2351 if (!ConstIsRHS)
2352 std::swap(Op0, Op1);
2353 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002354 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002355 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002356 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002357 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002358 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002359 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002360 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002361 abort();
2362 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002363 return IC->InsertNewInstBefore(New, I);
2364}
2365
2366// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2367// constant as the other operand, try to fold the binary operator into the
2368// select arguments. This also works for Cast instructions, which obviously do
2369// not have a second operand.
2370static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2371 InstCombiner *IC) {
2372 // Don't modify shared select instructions
2373 if (!SI->hasOneUse()) return 0;
2374 Value *TV = SI->getOperand(1);
2375 Value *FV = SI->getOperand(2);
2376
2377 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002378 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002379 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002380
Chris Lattner6e7ba452005-01-01 16:22:27 +00002381 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2382 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2383
Gabor Greif051a9502008-04-06 20:25:17 +00002384 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2385 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002386 }
2387 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002388}
2389
Chris Lattner4e998b22004-09-29 05:07:12 +00002390
2391/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2392/// node as operand #0, see if we can fold the instruction into the PHI (which
2393/// is only possible if all operands to the PHI are constants).
2394Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2395 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002396 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002397 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002398
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002399 // Check to see if all of the operands of the PHI are constants. If there is
2400 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002401 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002402 BasicBlock *NonConstBB = 0;
2403 for (unsigned i = 0; i != NumPHIValues; ++i)
2404 if (!isa<Constant>(PN->getIncomingValue(i))) {
2405 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002406 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002407 NonConstBB = PN->getIncomingBlock(i);
2408
2409 // If the incoming non-constant value is in I's block, we have an infinite
2410 // loop.
2411 if (NonConstBB == I.getParent())
2412 return 0;
2413 }
2414
2415 // If there is exactly one non-constant value, we can insert a copy of the
2416 // operation in that block. However, if this is a critical edge, we would be
2417 // inserting the computation one some other paths (e.g. inside a loop). Only
2418 // do this if the pred block is unconditionally branching into the phi block.
2419 if (NonConstBB) {
2420 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2421 if (!BI || !BI->isUnconditional()) return 0;
2422 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002423
2424 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002425 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002426 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002427 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002428 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002429
2430 // Next, add all of the operands to the PHI.
2431 if (I.getNumOperands() == 2) {
2432 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002433 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002434 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002435 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002436 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2437 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2438 else
2439 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002440 } else {
2441 assert(PN->getIncomingBlock(i) == NonConstBB);
2442 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002443 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002444 PN->getIncomingValue(i), C, "phitmp",
2445 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002446 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002447 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002448 CI->getPredicate(),
2449 PN->getIncomingValue(i), C, "phitmp",
2450 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002451 else
2452 assert(0 && "Unknown binop!");
2453
Chris Lattnerdbab3862007-03-02 21:28:56 +00002454 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002455 }
2456 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002457 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002458 } else {
2459 CastInst *CI = cast<CastInst>(&I);
2460 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002461 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002462 Value *InV;
2463 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002464 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002465 } else {
2466 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002467 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002468 I.getType(), "phitmp",
2469 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002470 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002471 }
2472 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002473 }
2474 }
2475 return ReplaceInstUsesWith(I, NewPN);
2476}
2477
Chris Lattner2454a2e2008-01-29 06:52:45 +00002478
2479/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2480/// value is never equal to -0.0.
2481///
2482/// Note that this function will need to be revisited when we support nondefault
2483/// rounding modes!
2484///
2485static bool CannotBeNegativeZero(const Value *V) {
2486 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2487 return !CFP->getValueAPF().isNegZero();
2488
Chris Lattner2454a2e2008-01-29 06:52:45 +00002489 if (const Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002490 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Chris Lattner2454a2e2008-01-29 06:52:45 +00002491 if (I->getOpcode() == Instruction::Add &&
2492 isa<ConstantFP>(I->getOperand(1)) &&
2493 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2494 return true;
2495
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002496 // sitofp and uitofp turn into +0.0 for zero.
2497 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2498 return true;
2499
Chris Lattner2454a2e2008-01-29 06:52:45 +00002500 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2501 if (II->getIntrinsicID() == Intrinsic::sqrt)
2502 return CannotBeNegativeZero(II->getOperand(1));
2503
2504 if (const CallInst *CI = dyn_cast<CallInst>(I))
2505 if (const Function *F = CI->getCalledFunction()) {
2506 if (F->isDeclaration()) {
2507 switch (F->getNameLen()) {
2508 case 3: // abs(x) != -0.0
2509 if (!strcmp(F->getNameStart(), "abs")) return true;
2510 break;
2511 case 4: // abs[lf](x) != -0.0
2512 if (!strcmp(F->getNameStart(), "absf")) return true;
2513 if (!strcmp(F->getNameStart(), "absl")) return true;
2514 break;
2515 }
2516 }
2517 }
2518 }
2519
2520 return false;
2521}
2522
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002523/// WillNotOverflowSignedAdd - Return true if we can prove that:
2524/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2525/// This basically requires proving that the add in the original type would not
2526/// overflow to change the sign bit or have a carry out.
2527bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2528 // There are different heuristics we can use for this. Here are some simple
2529 // ones.
2530
2531 // Add has the property that adding any two 2's complement numbers can only
2532 // have one carry bit which can change a sign. As such, if LHS and RHS each
2533 // have at least two sign bits, we know that the addition of the two values will
2534 // sign extend fine.
2535 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2536 return true;
2537
2538
2539 // If one of the operands only has one non-zero bit, and if the other operand
2540 // has a known-zero bit in a more significant place than it (not including the
2541 // sign bit) the ripple may go up to and fill the zero, but won't change the
2542 // sign. For example, (X & ~4) + 1.
2543
2544 // TODO: Implement.
2545
2546 return false;
2547}
2548
Chris Lattner2454a2e2008-01-29 06:52:45 +00002549
Chris Lattner7e708292002-06-25 16:13:24 +00002550Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002551 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002552 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002553
Nick Lewyckyfd12a0b2008-05-31 17:10:28 +00002554 if (I.getType() == Type::Int1Ty)
2555 return BinaryOperator::CreateXor(LHS, RHS);
2556
Chris Lattner66331a42004-04-10 22:01:55 +00002557 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002558 // X + undef -> undef
2559 if (isa<UndefValue>(RHS))
2560 return ReplaceInstUsesWith(I, RHS);
2561
Chris Lattner66331a42004-04-10 22:01:55 +00002562 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002563 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002564 if (RHSC->isNullValue())
2565 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002566 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002567 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2568 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002569 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002570 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002571
Chris Lattner66331a42004-04-10 22:01:55 +00002572 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002573 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002574 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002575 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002576 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002577 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002578
2579 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2580 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002581 if (!isa<VectorType>(I.getType())) {
2582 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2583 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2584 KnownZero, KnownOne))
2585 return &I;
2586 }
Chris Lattner66331a42004-04-10 22:01:55 +00002587 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002588
2589 if (isa<PHINode>(LHS))
2590 if (Instruction *NV = FoldOpIntoPhi(I))
2591 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002592
Chris Lattner4f637d42006-01-06 17:59:59 +00002593 ConstantInt *XorRHS = 0;
2594 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002595 if (isa<ConstantInt>(RHSC) &&
2596 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002597 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002598 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002599
Zhou Sheng4351c642007-04-02 08:20:41 +00002600 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002601 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2602 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002603 do {
2604 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002605 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2606 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002607 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2608 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002609 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002610 if (!MaskedValueIsZero(XorLHS,
2611 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002612 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002613 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002614 }
2615 }
2616 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002617 C0080Val = APIntOps::lshr(C0080Val, Size);
2618 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2619 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002620
Reid Spencer35c38852007-03-28 01:36:16 +00002621 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002622 // with funny bit widths then this switch statement should be removed. It
2623 // is just here to get the size of the "middle" type back up to something
2624 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002625 const Type *MiddleType = 0;
2626 switch (Size) {
2627 default: break;
2628 case 32: MiddleType = Type::Int32Ty; break;
2629 case 16: MiddleType = Type::Int16Ty; break;
2630 case 8: MiddleType = Type::Int8Ty; break;
2631 }
2632 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002633 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002634 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002635 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002636 }
2637 }
Chris Lattner66331a42004-04-10 22:01:55 +00002638 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002639
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002640 // X + X --> X << 1
Nick Lewycky02d639f2008-05-23 04:34:58 +00002641 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002642 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002643
2644 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2645 if (RHSI->getOpcode() == Instruction::Sub)
2646 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2647 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2648 }
2649 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2650 if (LHSI->getOpcode() == Instruction::Sub)
2651 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2652 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2653 }
Robert Bocchino71698282004-07-27 21:02:21 +00002654 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002655
Chris Lattner5c4afb92002-05-08 22:46:53 +00002656 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002657 // -A + -B --> -(A + B)
2658 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002659 if (LHS->getType()->isIntOrIntVector()) {
2660 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002661 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002662 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002663 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002664 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002665 }
2666
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002667 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002668 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002669
2670 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002671 if (!isa<Constant>(RHS))
2672 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002673 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002674
Misha Brukmanfd939082005-04-21 23:48:37 +00002675
Chris Lattner50af16a2004-11-13 19:50:12 +00002676 ConstantInt *C2;
2677 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2678 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002679 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002680
2681 // X*C1 + X*C2 --> X * (C1+C2)
2682 ConstantInt *C1;
2683 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002684 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002685 }
2686
2687 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002688 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002689 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002690
Chris Lattnere617c9e2007-01-05 02:17:46 +00002691 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002692 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2693 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002694
Chris Lattnerad3448c2003-02-18 19:57:07 +00002695
Chris Lattner564a7272003-08-13 19:01:45 +00002696 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002697 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002698 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2699 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002700
2701 // A+B --> A|B iff A and B have no bits set in common.
2702 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2703 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2704 APInt LHSKnownOne(IT->getBitWidth(), 0);
2705 APInt LHSKnownZero(IT->getBitWidth(), 0);
2706 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2707 if (LHSKnownZero != 0) {
2708 APInt RHSKnownOne(IT->getBitWidth(), 0);
2709 APInt RHSKnownZero(IT->getBitWidth(), 0);
2710 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2711
2712 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002713 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002714 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002715 }
2716 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002717
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002718 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002719 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002720 Value *W, *X, *Y, *Z;
2721 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2722 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2723 if (W != Y) {
2724 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002725 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002726 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002727 std::swap(W, X);
2728 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002729 std::swap(Y, Z);
2730 std::swap(W, X);
2731 }
2732 }
2733
2734 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002735 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002736 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002737 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002738 }
2739 }
2740 }
2741
Chris Lattner6b032052003-10-02 15:11:26 +00002742 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002743 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002744 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002745 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002746
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002747 // (X & FF00) + xx00 -> (X+xx00) & FF00
2748 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002749 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002750 if (Anded == CRHS) {
2751 // See if all bits from the first bit set in the Add RHS up are included
2752 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002753 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002754
2755 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002756 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002757
2758 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002759 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002760
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002761 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2762 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002763 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002764 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002765 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002766 }
2767 }
2768 }
2769
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002770 // Try to fold constant add into select arguments.
2771 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002772 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002773 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002774 }
2775
Reid Spencer1628cec2006-10-26 06:15:43 +00002776 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002777 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002778 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002779 CastInst *CI = dyn_cast<CastInst>(LHS);
2780 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002781 if (!CI) {
2782 CI = dyn_cast<CastInst>(RHS);
2783 Other = LHS;
2784 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002785 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002786 (CI->getType()->getPrimitiveSizeInBits() ==
2787 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002788 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002789 unsigned AS =
2790 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002791 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2792 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002793 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002794 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002795 }
2796 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002797
Chris Lattner42790482007-12-20 01:56:58 +00002798 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002799 {
2800 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2801 Value *Other = RHS;
2802 if (!SI) {
2803 SI = dyn_cast<SelectInst>(RHS);
2804 Other = LHS;
2805 }
Chris Lattner42790482007-12-20 01:56:58 +00002806 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002807 Value *TV = SI->getTrueValue();
2808 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002809 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002810
2811 // Can we fold the add into the argument of the select?
2812 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002813 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2814 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002815 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002816 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2817 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002818 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002819 }
2820 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002821
2822 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2823 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2824 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2825 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002826
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002827 // Check for (add (sext x), y), see if we can merge this into an
2828 // integer add followed by a sext.
2829 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2830 // (add (sext x), cst) --> (sext (add x, cst'))
2831 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2832 Constant *CI =
2833 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2834 if (LHSConv->hasOneUse() &&
2835 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2836 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2837 // Insert the new, smaller add.
2838 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2839 CI, "addconv");
2840 InsertNewInstBefore(NewAdd, I);
2841 return new SExtInst(NewAdd, I.getType());
2842 }
2843 }
2844
2845 // (add (sext x), (sext y)) --> (sext (add int x, y))
2846 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2847 // Only do this if x/y have the same type, if at last one of them has a
2848 // single use (so we don't increase the number of sexts), and if the
2849 // integer add will not overflow.
2850 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2851 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2852 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2853 RHSConv->getOperand(0))) {
2854 // Insert the new integer add.
2855 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2856 RHSConv->getOperand(0),
2857 "addconv");
2858 InsertNewInstBefore(NewAdd, I);
2859 return new SExtInst(NewAdd, I.getType());
2860 }
2861 }
2862 }
2863
2864 // Check for (add double (sitofp x), y), see if we can merge this into an
2865 // integer add followed by a promotion.
2866 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2867 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2868 // ... if the constant fits in the integer value. This is useful for things
2869 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2870 // requires a constant pool load, and generally allows the add to be better
2871 // instcombined.
2872 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2873 Constant *CI =
2874 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2875 if (LHSConv->hasOneUse() &&
2876 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2877 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2878 // Insert the new integer add.
2879 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2880 CI, "addconv");
2881 InsertNewInstBefore(NewAdd, I);
2882 return new SIToFPInst(NewAdd, I.getType());
2883 }
2884 }
2885
2886 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2887 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2888 // Only do this if x/y have the same type, if at last one of them has a
2889 // single use (so we don't increase the number of int->fp conversions),
2890 // and if the integer add will not overflow.
2891 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2892 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2893 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2894 RHSConv->getOperand(0))) {
2895 // Insert the new integer add.
2896 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2897 RHSConv->getOperand(0),
2898 "addconv");
2899 InsertNewInstBefore(NewAdd, I);
2900 return new SIToFPInst(NewAdd, I.getType());
2901 }
2902 }
2903 }
2904
Chris Lattner7e708292002-06-25 16:13:24 +00002905 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002906}
2907
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002908// isSignBit - Return true if the value represented by the constant only has the
2909// highest order bit set.
2910static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002911 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002912 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002913}
2914
Chris Lattner7e708292002-06-25 16:13:24 +00002915Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002916 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002917
Chris Lattner233f7dc2002-08-12 21:17:25 +00002918 if (Op0 == Op1) // sub X, X -> 0
2919 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002920
Chris Lattner233f7dc2002-08-12 21:17:25 +00002921 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002922 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002923 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002924
Chris Lattnere87597f2004-10-16 18:11:37 +00002925 if (isa<UndefValue>(Op0))
2926 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2927 if (isa<UndefValue>(Op1))
2928 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2929
Chris Lattnerd65460f2003-11-05 01:06:05 +00002930 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2931 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002932 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002933 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002934
Chris Lattnerd65460f2003-11-05 01:06:05 +00002935 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002936 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002937 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002938 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002939
Chris Lattner76b7a062007-01-15 07:02:54 +00002940 // -(X >>u 31) -> (X >>s 31)
2941 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002942 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002943 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002944 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002945 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002946 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002947 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002948 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002949 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002950 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002951 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002952 }
2953 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002954 }
2955 else if (SI->getOpcode() == Instruction::AShr) {
2956 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2957 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002958 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002959 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002960 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002961 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002962 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002963 }
2964 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002965 }
2966 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002967 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002968
2969 // Try to fold constant sub into select arguments.
2970 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002971 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002972 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002973
2974 if (isa<PHINode>(Op0))
2975 if (Instruction *NV = FoldOpIntoPhi(I))
2976 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002977 }
2978
Chris Lattner43d84d62005-04-07 16:15:25 +00002979 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2980 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002981 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002982 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002983 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002984 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002985 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002986 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2987 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2988 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002989 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002990 Op1I->getOperand(0));
2991 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002992 }
2993
Chris Lattnerfd059242003-10-15 16:48:29 +00002994 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002995 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2996 // is not used by anyone else...
2997 //
Chris Lattner0517e722004-02-02 20:09:56 +00002998 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002999 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00003000 // Swap the two operands of the subexpr...
3001 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
3002 Op1I->setOperand(0, IIOp1);
3003 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00003004
Chris Lattnera2881962003-02-18 19:28:33 +00003005 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003006 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003007 }
3008
3009 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
3010 //
3011 if (Op1I->getOpcode() == Instruction::And &&
3012 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
3013 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
3014
Chris Lattnerf523d062004-06-09 05:08:07 +00003015 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003016 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
3017 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00003018 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00003019
Reid Spencerac5209e2006-10-16 23:08:08 +00003020 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00003021 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00003022 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00003023 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00003024 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003025 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00003026 ConstantExpr::getNeg(DivRHS));
3027
Chris Lattnerad3448c2003-02-18 19:57:07 +00003028 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00003029 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00003030 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00003031 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003032 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00003033 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00003034
3035 // X - ((X / Y) * Y) --> X % Y
3036 if (Op1I->getOpcode() == Instruction::Mul)
3037 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
3038 if (Op0 == I->getOperand(0) &&
3039 Op1I->getOperand(1) == I->getOperand(1)) {
3040 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003041 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00003042 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003043 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00003044 }
Chris Lattner40371712002-05-09 01:29:19 +00003045 }
Chris Lattner43d84d62005-04-07 16:15:25 +00003046 }
Chris Lattnera2881962003-02-18 19:28:33 +00003047
Chris Lattner9919e3d2006-12-02 00:13:08 +00003048 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003049 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00003050 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003051 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
3052 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3053 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
3054 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00003055 } else if (Op0I->getOpcode() == Instruction::Sub) {
3056 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003057 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003058 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003059 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003060
Chris Lattner50af16a2004-11-13 19:50:12 +00003061 ConstantInt *C1;
3062 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00003063 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003064 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00003065
Chris Lattner50af16a2004-11-13 19:50:12 +00003066 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
3067 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003068 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00003069 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003070 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003071}
3072
Chris Lattnera0141b92007-07-15 20:42:37 +00003073/// isSignBitCheck - Given an exploded icmp instruction, return true if the
3074/// comparison only checks the sign bit. If it only checks the sign bit, set
3075/// TrueIfSigned if the result of the comparison is true when the input value is
3076/// signed.
3077static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3078 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003079 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003080 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3081 TrueIfSigned = true;
3082 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003083 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3084 TrueIfSigned = true;
3085 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00003086 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3087 TrueIfSigned = false;
3088 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003089 case ICmpInst::ICMP_UGT:
3090 // True if LHS u> RHS and RHS == high-bit-mask - 1
3091 TrueIfSigned = true;
3092 return RHS->getValue() ==
3093 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3094 case ICmpInst::ICMP_UGE:
3095 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3096 TrueIfSigned = true;
3097 return RHS->getValue() ==
3098 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00003099 default:
3100 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00003101 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00003102}
3103
Chris Lattner7e708292002-06-25 16:13:24 +00003104Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003105 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00003106 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003107
Chris Lattnere87597f2004-10-16 18:11:37 +00003108 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
3109 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3110
Chris Lattner233f7dc2002-08-12 21:17:25 +00003111 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00003112 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
3113 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00003114
3115 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00003116 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00003117 if (SI->getOpcode() == Instruction::Shl)
3118 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003119 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00003120 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00003121
Zhou Sheng843f07672007-04-19 05:39:12 +00003122 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00003123 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
3124 if (CI->equalsInt(1)) // X * 1 == X
3125 return ReplaceInstUsesWith(I, Op0);
3126 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003127 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00003128
Zhou Sheng97b52c22007-03-29 01:57:21 +00003129 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003130 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003131 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00003132 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003133 }
Robert Bocchino71698282004-07-27 21:02:21 +00003134 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00003135 if (Op1F->isNullValue())
3136 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00003137
Chris Lattnera2881962003-02-18 19:28:33 +00003138 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3139 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00003140 // We need a better interface for long double here.
3141 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
3142 if (Op1F->isExactlyValue(1.0))
3143 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00003144 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003145
3146 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3147 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00003148 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003149 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003150 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003151 Op1, "tmp");
3152 InsertNewInstBefore(Add, I);
3153 Value *C1C2 = ConstantExpr::getMul(Op1,
3154 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003155 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003156
3157 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003158
3159 // Try to fold constant mul into select arguments.
3160 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003161 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003162 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003163
3164 if (isa<PHINode>(Op0))
3165 if (Instruction *NV = FoldOpIntoPhi(I))
3166 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003167 }
3168
Chris Lattnera4f445b2003-03-10 23:23:04 +00003169 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
3170 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003171 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003172
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003173 // If one of the operands of the multiply is a cast from a boolean value, then
3174 // we know the bool is either zero or one, so this is a 'masking' multiply.
3175 // See if we can simplify things based on how the boolean was originally
3176 // formed.
3177 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00003178 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003179 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003180 BoolCast = CI;
3181 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00003182 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003183 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003184 BoolCast = CI;
3185 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003186 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003187 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3188 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00003189 bool TIS = false;
3190
Reid Spencere4d87aa2006-12-23 06:05:41 +00003191 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00003192 // multiply into a shift/and combination.
3193 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00003194 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
3195 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003196 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00003197 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00003198 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00003199 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00003200 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003201 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00003202 BoolCast->getOperand(0)->getName()+
3203 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003204
3205 // If the multiply type is not the same as the source type, sign extend
3206 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00003207 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00003208 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
3209 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00003210 Instruction::CastOps opcode =
3211 (SrcBits == DstBits ? Instruction::BitCast :
3212 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3213 V = InsertCastBefore(opcode, V, I.getType(), I);
3214 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003215
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003216 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003217 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003218 }
3219 }
3220 }
3221
Chris Lattner7e708292002-06-25 16:13:24 +00003222 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003223}
3224
Reid Spencer1628cec2006-10-26 06:15:43 +00003225/// This function implements the transforms on div instructions that work
3226/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3227/// used by the visitors to those instructions.
3228/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003229Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003230 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003231
Chris Lattner50b2ca42008-02-19 06:12:18 +00003232 // undef / X -> 0 for integer.
3233 // undef / X -> undef for FP (the undef could be a snan).
3234 if (isa<UndefValue>(Op0)) {
3235 if (Op0->getType()->isFPOrFPVector())
3236 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003237 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003238 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003239
3240 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003241 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003242 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003243
Chris Lattner25feae52008-01-28 00:58:18 +00003244 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3245 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00003246 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00003247 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
3248 // the same basic block, then we replace the select with Y, and the
3249 // condition of the select with false (if the cond value is in the same BB).
3250 // If the select has uses other than the div, this allows them to be
3251 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
3252 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003253 if (ST->isNullValue()) {
3254 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3255 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003256 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00003257 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3258 I.setOperand(1, SI->getOperand(2));
3259 else
3260 UpdateValueUsesWith(SI, SI->getOperand(2));
3261 return &I;
3262 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003263
Chris Lattner25feae52008-01-28 00:58:18 +00003264 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3265 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003266 if (ST->isNullValue()) {
3267 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3268 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003269 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00003270 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3271 I.setOperand(1, SI->getOperand(1));
3272 else
3273 UpdateValueUsesWith(SI, SI->getOperand(1));
3274 return &I;
3275 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003276 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003277
Reid Spencer1628cec2006-10-26 06:15:43 +00003278 return 0;
3279}
Misha Brukmanfd939082005-04-21 23:48:37 +00003280
Reid Spencer1628cec2006-10-26 06:15:43 +00003281/// This function implements the transforms common to both integer division
3282/// instructions (udiv and sdiv). It is called by the visitors to those integer
3283/// division instructions.
3284/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003285Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003286 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3287
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003288 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003289 if (Op0 == Op1) {
3290 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3291 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
3292 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3293 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3294 }
3295
3296 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
3297 return ReplaceInstUsesWith(I, CI);
3298 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003299
Reid Spencer1628cec2006-10-26 06:15:43 +00003300 if (Instruction *Common = commonDivTransforms(I))
3301 return Common;
3302
3303 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3304 // div X, 1 == X
3305 if (RHS->equalsInt(1))
3306 return ReplaceInstUsesWith(I, Op0);
3307
3308 // (X / C1) / C2 -> X / (C1*C2)
3309 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3310 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3311 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003312 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3313 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3314 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003315 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003316 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003317 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003318
Reid Spencerbca0e382007-03-23 20:05:17 +00003319 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003320 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3321 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3322 return R;
3323 if (isa<PHINode>(Op0))
3324 if (Instruction *NV = FoldOpIntoPhi(I))
3325 return NV;
3326 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003327 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003328
Chris Lattnera2881962003-02-18 19:28:33 +00003329 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003330 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003331 if (LHS->equalsInt(0))
3332 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3333
Reid Spencer1628cec2006-10-26 06:15:43 +00003334 return 0;
3335}
3336
3337Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3338 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3339
3340 // Handle the integer div common cases
3341 if (Instruction *Common = commonIDivTransforms(I))
3342 return Common;
3343
3344 // X udiv C^2 -> X >> C
3345 // Check to see if this is an unsigned division with an exact power of 2,
3346 // if so, convert to a right shift.
3347 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00003348 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003349 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003350 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003351 }
3352
3353 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003354 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003355 if (RHSI->getOpcode() == Instruction::Shl &&
3356 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003357 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003358 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003359 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003360 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003361 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003362 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003363 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003364 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003365 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003366 }
3367 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003368 }
3369
Reid Spencer1628cec2006-10-26 06:15:43 +00003370 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3371 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003372 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003373 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003374 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003375 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003376 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003377 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003378 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003379 // Construct the "on true" case of the select
3380 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003381 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003382 Op0, TC, SI->getName()+".t");
3383 TSI = InsertNewInstBefore(TSI, I);
3384
3385 // Construct the "on false" case of the select
3386 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003387 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003388 Op0, FC, SI->getName()+".f");
3389 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003390
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003391 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003392 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003393 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003394 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003395 return 0;
3396}
3397
Reid Spencer1628cec2006-10-26 06:15:43 +00003398Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3399 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3400
3401 // Handle the integer div common cases
3402 if (Instruction *Common = commonIDivTransforms(I))
3403 return Common;
3404
3405 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3406 // sdiv X, -1 == -X
3407 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003408 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003409
3410 // -X/C -> X/-C
3411 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003412 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003413 }
3414
3415 // If the sign bits of both operands are zero (i.e. we can prove they are
3416 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003417 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003418 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003419 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003420 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003421 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003422 }
3423 }
3424
3425 return 0;
3426}
3427
3428Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3429 return commonDivTransforms(I);
3430}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003431
Reid Spencer0a783f72006-11-02 01:53:59 +00003432/// This function implements the transforms on rem instructions that work
3433/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3434/// is used by the visitors to those instructions.
3435/// @brief Transforms common to all three rem instructions
3436Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003437 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003438
Chris Lattner50b2ca42008-02-19 06:12:18 +00003439 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003440 if (Constant *LHS = dyn_cast<Constant>(Op0))
3441 if (LHS->isNullValue())
3442 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3443
Chris Lattner50b2ca42008-02-19 06:12:18 +00003444 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3445 if (I.getType()->isFPOrFPVector())
3446 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003447 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003448 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003449 if (isa<UndefValue>(Op1))
3450 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003451
3452 // Handle cases involving: rem X, (select Cond, Y, Z)
3453 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3454 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3455 // the same basic block, then we replace the select with Y, and the
3456 // condition of the select with false (if the cond value is in the same
3457 // BB). If the select has uses other than the div, this allows them to be
3458 // simplified also.
3459 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3460 if (ST->isNullValue()) {
3461 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3462 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003463 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003464 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3465 I.setOperand(1, SI->getOperand(2));
3466 else
3467 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003468 return &I;
3469 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003470 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3471 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3472 if (ST->isNullValue()) {
3473 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3474 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003475 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003476 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3477 I.setOperand(1, SI->getOperand(1));
3478 else
3479 UpdateValueUsesWith(SI, SI->getOperand(1));
3480 return &I;
3481 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003482 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003483
Reid Spencer0a783f72006-11-02 01:53:59 +00003484 return 0;
3485}
3486
3487/// This function implements the transforms common to both integer remainder
3488/// instructions (urem and srem). It is called by the visitors to those integer
3489/// remainder instructions.
3490/// @brief Common integer remainder transforms
3491Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3492 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3493
3494 if (Instruction *common = commonRemTransforms(I))
3495 return common;
3496
Chris Lattner857e8cd2004-12-12 21:48:58 +00003497 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003498 // X % 0 == undef, we don't need to preserve faults!
3499 if (RHS->equalsInt(0))
3500 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3501
Chris Lattnera2881962003-02-18 19:28:33 +00003502 if (RHS->equalsInt(1)) // X % 1 == 0
3503 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3504
Chris Lattner97943922006-02-28 05:49:21 +00003505 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3506 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3507 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3508 return R;
3509 } else if (isa<PHINode>(Op0I)) {
3510 if (Instruction *NV = FoldOpIntoPhi(I))
3511 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003512 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003513
3514 // See if we can fold away this rem instruction.
3515 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3516 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3517 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3518 KnownZero, KnownOne))
3519 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003520 }
Chris Lattnera2881962003-02-18 19:28:33 +00003521 }
3522
Reid Spencer0a783f72006-11-02 01:53:59 +00003523 return 0;
3524}
3525
3526Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3527 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3528
3529 if (Instruction *common = commonIRemTransforms(I))
3530 return common;
3531
3532 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3533 // X urem C^2 -> X and C
3534 // Check to see if this is an unsigned remainder with an exact power of 2,
3535 // if so, convert to a bitwise and.
3536 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003537 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003538 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003539 }
3540
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003541 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003542 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3543 if (RHSI->getOpcode() == Instruction::Shl &&
3544 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003545 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003546 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003547 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003548 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003549 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003550 }
3551 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003552 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003553
Reid Spencer0a783f72006-11-02 01:53:59 +00003554 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3555 // where C1&C2 are powers of two.
3556 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3557 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3558 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3559 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003560 if ((STO->getValue().isPowerOf2()) &&
3561 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003562 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003563 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003564 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003565 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003566 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003567 }
3568 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003569 }
3570
Chris Lattner3f5b8772002-05-06 16:14:14 +00003571 return 0;
3572}
3573
Reid Spencer0a783f72006-11-02 01:53:59 +00003574Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3575 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3576
Dan Gohmancff55092007-11-05 23:16:33 +00003577 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003578 if (Instruction *common = commonIRemTransforms(I))
3579 return common;
3580
3581 if (Value *RHSNeg = dyn_castNegVal(Op1))
3582 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003583 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003584 // X % -Y -> X % Y
3585 AddUsesToWorkList(I);
3586 I.setOperand(1, RHSNeg);
3587 return &I;
3588 }
3589
Dan Gohmancff55092007-11-05 23:16:33 +00003590 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003591 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003592 if (I.getType()->isInteger()) {
3593 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3594 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3595 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003596 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003597 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003598 }
3599
3600 return 0;
3601}
3602
3603Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003604 return commonRemTransforms(I);
3605}
3606
Chris Lattner8b170942002-08-09 23:47:40 +00003607// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003608static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003609 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003610 if (!isSigned)
3611 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3612 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003613}
3614
3615// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003616static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003617 if (!isSigned)
3618 return C->getValue() == 1; // unsigned
3619
3620 // Calculate 1111111111000000000000
3621 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3622 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003623}
3624
Chris Lattner457dd822004-06-09 07:59:58 +00003625// isOneBitSet - Return true if there is exactly one bit set in the specified
3626// constant.
3627static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003628 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003629}
3630
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003631// isHighOnes - Return true if the constant is of the form 1+0+.
3632// This is the same as lowones(~X).
3633static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003634 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003635}
3636
Reid Spencere4d87aa2006-12-23 06:05:41 +00003637/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003638/// are carefully arranged to allow folding of expressions such as:
3639///
3640/// (A < B) | (A > B) --> (A != B)
3641///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003642/// Note that this is only valid if the first and second predicates have the
3643/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003644///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003645/// Three bits are used to represent the condition, as follows:
3646/// 0 A > B
3647/// 1 A == B
3648/// 2 A < B
3649///
3650/// <=> Value Definition
3651/// 000 0 Always false
3652/// 001 1 A > B
3653/// 010 2 A == B
3654/// 011 3 A >= B
3655/// 100 4 A < B
3656/// 101 5 A != B
3657/// 110 6 A <= B
3658/// 111 7 Always true
3659///
3660static unsigned getICmpCode(const ICmpInst *ICI) {
3661 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003662 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003663 case ICmpInst::ICMP_UGT: return 1; // 001
3664 case ICmpInst::ICMP_SGT: return 1; // 001
3665 case ICmpInst::ICMP_EQ: return 2; // 010
3666 case ICmpInst::ICMP_UGE: return 3; // 011
3667 case ICmpInst::ICMP_SGE: return 3; // 011
3668 case ICmpInst::ICMP_ULT: return 4; // 100
3669 case ICmpInst::ICMP_SLT: return 4; // 100
3670 case ICmpInst::ICMP_NE: return 5; // 101
3671 case ICmpInst::ICMP_ULE: return 6; // 110
3672 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003673 // True -> 7
3674 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003675 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003676 return 0;
3677 }
3678}
3679
Reid Spencere4d87aa2006-12-23 06:05:41 +00003680/// getICmpValue - This is the complement of getICmpCode, which turns an
3681/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003682/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003683/// of predicate to use in new icmp instructions.
3684static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3685 switch (code) {
3686 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003687 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003688 case 1:
3689 if (sign)
3690 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3691 else
3692 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3693 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3694 case 3:
3695 if (sign)
3696 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3697 else
3698 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3699 case 4:
3700 if (sign)
3701 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3702 else
3703 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3704 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3705 case 6:
3706 if (sign)
3707 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3708 else
3709 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003710 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003711 }
3712}
3713
Reid Spencere4d87aa2006-12-23 06:05:41 +00003714static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3715 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3716 (ICmpInst::isSignedPredicate(p1) &&
3717 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3718 (ICmpInst::isSignedPredicate(p2) &&
3719 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3720}
3721
3722namespace {
3723// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3724struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003725 InstCombiner &IC;
3726 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003727 ICmpInst::Predicate pred;
3728 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3729 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3730 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003731 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003732 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3733 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003734 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3735 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003736 return false;
3737 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003738 Instruction *apply(Instruction &Log) const {
3739 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3740 if (ICI->getOperand(0) != LHS) {
3741 assert(ICI->getOperand(1) == LHS);
3742 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003743 }
3744
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003745 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003746 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003747 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003748 unsigned Code;
3749 switch (Log.getOpcode()) {
3750 case Instruction::And: Code = LHSCode & RHSCode; break;
3751 case Instruction::Or: Code = LHSCode | RHSCode; break;
3752 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003753 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003754 }
3755
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003756 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3757 ICmpInst::isSignedPredicate(ICI->getPredicate());
3758
3759 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003760 if (Instruction *I = dyn_cast<Instruction>(RV))
3761 return I;
3762 // Otherwise, it's a constant boolean value...
3763 return IC.ReplaceInstUsesWith(Log, RV);
3764 }
3765};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003766} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003767
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003768// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3769// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003770// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003771Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003772 ConstantInt *OpRHS,
3773 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003774 BinaryOperator &TheAnd) {
3775 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003776 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003777 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003778 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003779
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003780 switch (Op->getOpcode()) {
3781 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003782 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003783 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003784 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003785 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003786 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003787 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003788 }
3789 break;
3790 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003791 if (Together == AndRHS) // (X | C) & C --> C
3792 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003793
Chris Lattner6e7ba452005-01-01 16:22:27 +00003794 if (Op->hasOneUse() && Together != OpRHS) {
3795 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003796 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003797 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003798 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003799 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003800 }
3801 break;
3802 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003803 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003804 // Adding a one to a single bit bit-field should be turned into an XOR
3805 // of the bit. First thing to check is to see if this AND is with a
3806 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003807 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003808
3809 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003810 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003811 // Ok, at this point, we know that we are masking the result of the
3812 // ADD down to exactly one bit. If the constant we are adding has
3813 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003814 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003815
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003816 // Check to see if any bits below the one bit set in AndRHSV are set.
3817 if ((AddRHS & (AndRHSV-1)) == 0) {
3818 // If not, the only thing that can effect the output of the AND is
3819 // the bit specified by AndRHSV. If that bit is set, the effect of
3820 // the XOR is to toggle the bit. If it is clear, then the ADD has
3821 // no effect.
3822 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3823 TheAnd.setOperand(0, X);
3824 return &TheAnd;
3825 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003826 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003827 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003828 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003829 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003830 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003831 }
3832 }
3833 }
3834 }
3835 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003836
3837 case Instruction::Shl: {
3838 // We know that the AND will not produce any of the bits shifted in, so if
3839 // the anded constant includes them, clear them now!
3840 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003841 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003842 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003843 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3844 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003845
Zhou Sheng290bec52007-03-29 08:15:12 +00003846 if (CI->getValue() == ShlMask) {
3847 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003848 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3849 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003850 TheAnd.setOperand(1, CI);
3851 return &TheAnd;
3852 }
3853 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003854 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003855 case Instruction::LShr:
3856 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003857 // We know that the AND will not produce any of the bits shifted in, so if
3858 // the anded constant includes them, clear them now! This only applies to
3859 // unsigned shifts, because a signed shr may bring in set bits!
3860 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003861 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003862 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003863 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3864 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003865
Zhou Sheng290bec52007-03-29 08:15:12 +00003866 if (CI->getValue() == ShrMask) {
3867 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003868 return ReplaceInstUsesWith(TheAnd, Op);
3869 } else if (CI != AndRHS) {
3870 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3871 return &TheAnd;
3872 }
3873 break;
3874 }
3875 case Instruction::AShr:
3876 // Signed shr.
3877 // See if this is shifting in some sign extension, then masking it out
3878 // with an and.
3879 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003880 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003881 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003882 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3883 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003884 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003885 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003886 // Make the argument unsigned.
3887 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003888 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003889 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003890 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003891 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003892 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003893 }
3894 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003895 }
3896 return 0;
3897}
3898
Chris Lattner8b170942002-08-09 23:47:40 +00003899
Chris Lattnera96879a2004-09-29 17:40:11 +00003900/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3901/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003902/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3903/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003904/// insert new instructions.
3905Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003906 bool isSigned, bool Inside,
3907 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003908 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003909 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003910 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003911
Chris Lattnera96879a2004-09-29 17:40:11 +00003912 if (Inside) {
3913 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003914 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003915
Reid Spencere4d87aa2006-12-23 06:05:41 +00003916 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003917 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003918 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003919 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3920 return new ICmpInst(pred, V, Hi);
3921 }
3922
3923 // Emit V-Lo <u Hi-Lo
3924 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003925 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003926 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003927 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3928 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003929 }
3930
3931 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003932 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003933
Reid Spencere4e40032007-03-21 23:19:50 +00003934 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003935 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003936 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003937 ICmpInst::Predicate pred = (isSigned ?
3938 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3939 return new ICmpInst(pred, V, Hi);
3940 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003941
Reid Spencere4e40032007-03-21 23:19:50 +00003942 // Emit V-Lo >u Hi-1-Lo
3943 // Note that Hi has already had one subtracted from it, above.
3944 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003945 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003946 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003947 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3948 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003949}
3950
Chris Lattner7203e152005-09-18 07:22:02 +00003951// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3952// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3953// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3954// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003955static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003956 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003957 uint32_t BitWidth = Val->getType()->getBitWidth();
3958 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003959
3960 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003961 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003962 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003963 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003964 return true;
3965}
3966
Chris Lattner7203e152005-09-18 07:22:02 +00003967/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3968/// where isSub determines whether the operator is a sub. If we can fold one of
3969/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003970///
3971/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3972/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3973/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3974///
3975/// return (A +/- B).
3976///
3977Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003978 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003979 Instruction &I) {
3980 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3981 if (!LHSI || LHSI->getNumOperands() != 2 ||
3982 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3983
3984 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3985
3986 switch (LHSI->getOpcode()) {
3987 default: return 0;
3988 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003989 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003990 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003991 if ((Mask->getValue().countLeadingZeros() +
3992 Mask->getValue().countPopulation()) ==
3993 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003994 break;
3995
3996 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3997 // part, we don't need any explicit masks to take them out of A. If that
3998 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003999 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00004000 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00004001 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004002 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004003 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004004 break;
4005 }
4006 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004007 return 0;
4008 case Instruction::Or:
4009 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004010 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004011 if ((Mask->getValue().countLeadingZeros() +
4012 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00004013 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004014 break;
4015 return 0;
4016 }
4017
4018 Instruction *New;
4019 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004020 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004021 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004022 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004023 return InsertNewInstBefore(New, I);
4024}
4025
Chris Lattner7e708292002-06-25 16:13:24 +00004026Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004027 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004028 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004029
Chris Lattnere87597f2004-10-16 18:11:37 +00004030 if (isa<UndefValue>(Op1)) // X & undef -> 0
4031 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4032
Chris Lattner6e7ba452005-01-01 16:22:27 +00004033 // and X, X = X
4034 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004035 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004036
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004037 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004038 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00004039 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00004040 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4041 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4042 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00004043 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00004044 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00004045 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004046 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004047 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004048 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004049 } else if (isa<ConstantAggregateZero>(Op1)) {
4050 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004051 }
4052 }
Chris Lattner9ca96412006-02-08 03:25:32 +00004053
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004054 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004055 const APInt& AndRHSMask = AndRHS->getValue();
4056 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004057
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004058 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004059 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004060 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004061 Value *Op0LHS = Op0I->getOperand(0);
4062 Value *Op0RHS = Op0I->getOperand(1);
4063 switch (Op0I->getOpcode()) {
4064 case Instruction::Xor:
4065 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004066 // If the mask is only needed on one incoming arm, push it up.
4067 if (Op0I->hasOneUse()) {
4068 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4069 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004070 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004071 Op0RHS->getName()+".masked");
4072 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004073 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004074 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004075 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004076 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004077 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4078 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004079 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004080 Op0LHS->getName()+".masked");
4081 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004082 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004083 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4084 }
4085 }
4086
Chris Lattner6e7ba452005-01-01 16:22:27 +00004087 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004088 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004089 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4090 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4091 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4092 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004093 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004094 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004095 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004096 break;
4097
4098 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004099 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4100 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4101 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4102 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004103 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00004104 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004105 }
4106
Chris Lattner58403262003-07-23 19:25:52 +00004107 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004108 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004109 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004110 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004111 // If this is an integer truncation or change from signed-to-unsigned, and
4112 // if the source is an and/or with immediate, transform it. This
4113 // frequently occurs for bitfield accesses.
4114 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004115 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004116 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004117 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004118 if (CastOp->getOpcode() == Instruction::And) {
4119 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004120 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4121 // This will fold the two constants together, which may allow
4122 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004123 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004124 CastOp->getOperand(0), I.getType(),
4125 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004126 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004127 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00004128 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00004129 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004130 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004131 } else if (CastOp->getOpcode() == Instruction::Or) {
4132 // Change: and (cast (or X, C1) to T), C2
4133 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00004134 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00004135 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4136 return ReplaceInstUsesWith(I, AndRHS);
4137 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004138 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004139 }
Chris Lattner06782f82003-07-23 19:36:21 +00004140 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004141
4142 // Try to fold constant and into select arguments.
4143 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004144 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004145 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004146 if (isa<PHINode>(Op0))
4147 if (Instruction *NV = FoldOpIntoPhi(I))
4148 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004149 }
4150
Chris Lattner8d969642003-03-10 23:06:50 +00004151 Value *Op0NotVal = dyn_castNotVal(Op0);
4152 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004153
Chris Lattner5b62aa72004-06-18 06:07:51 +00004154 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4155 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4156
Misha Brukmancb6267b2004-07-30 12:50:08 +00004157 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004158 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004159 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004160 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004161 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004162 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004163 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004164
4165 {
Chris Lattner003b6202007-06-15 05:58:24 +00004166 Value *A = 0, *B = 0, *C = 0, *D = 0;
4167 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004168 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4169 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004170
4171 // (A|B) & ~(A&B) -> A^B
4172 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4173 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004174 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004175 }
4176 }
4177
4178 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004179 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4180 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004181
4182 // ~(A&B) & (A|B) -> A^B
4183 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4184 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004185 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004186 }
4187 }
Chris Lattner64daab52006-04-01 08:03:55 +00004188
4189 if (Op0->hasOneUse() &&
4190 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4191 if (A == Op1) { // (A^B)&A -> A&(A^B)
4192 I.swapOperands(); // Simplify below
4193 std::swap(Op0, Op1);
4194 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4195 cast<BinaryOperator>(Op0)->swapOperands();
4196 I.swapOperands(); // Simplify below
4197 std::swap(Op0, Op1);
4198 }
4199 }
4200 if (Op1->hasOneUse() &&
4201 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4202 if (B == Op0) { // B&(A^B) -> B&(B^A)
4203 cast<BinaryOperator>(Op1)->swapOperands();
4204 std::swap(A, B);
4205 }
4206 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004207 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004208 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004209 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004210 }
4211 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004212 }
4213
Reid Spencere4d87aa2006-12-23 06:05:41 +00004214 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4215 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4216 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004217 return R;
4218
Chris Lattner955f3312004-09-28 21:48:02 +00004219 Value *LHSVal, *RHSVal;
4220 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004221 ICmpInst::Predicate LHSCC, RHSCC;
4222 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4223 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4224 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
4225 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4226 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4227 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4228 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00004229 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4230
4231 // Don't try to fold ICMP_SLT + ICMP_ULT.
4232 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
4233 ICmpInst::isSignedPredicate(LHSCC) ==
4234 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00004235 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00004236 ICmpInst::Predicate GT;
4237 if (ICmpInst::isSignedPredicate(LHSCC) ||
4238 (ICmpInst::isEquality(LHSCC) &&
4239 ICmpInst::isSignedPredicate(RHSCC)))
4240 GT = ICmpInst::ICMP_SGT;
4241 else
4242 GT = ICmpInst::ICMP_UGT;
4243
Reid Spencere4d87aa2006-12-23 06:05:41 +00004244 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4245 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00004246 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00004247 std::swap(LHS, RHS);
4248 std::swap(LHSCst, RHSCst);
4249 std::swap(LHSCC, RHSCC);
4250 }
4251
Reid Spencere4d87aa2006-12-23 06:05:41 +00004252 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00004253 // comparing a value against two constants and and'ing the result
4254 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004255 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4256 // (from the FoldICmpLogical check above), that the two constants
4257 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00004258 assert(LHSCst != RHSCst && "Compares not folded above?");
4259
4260 switch (LHSCC) {
4261 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004262 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00004263 switch (RHSCC) {
4264 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004265 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4266 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4267 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004268 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004269 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4270 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4271 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00004272 return ReplaceInstUsesWith(I, LHS);
4273 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004274 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00004275 switch (RHSCC) {
4276 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004277 case ICmpInst::ICMP_ULT:
4278 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4279 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4280 break; // (X != 13 & X u< 15) -> no change
4281 case ICmpInst::ICMP_SLT:
4282 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4283 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4284 break; // (X != 13 & X s< 15) -> no change
4285 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4286 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4287 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00004288 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004289 case ICmpInst::ICMP_NE:
4290 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00004291 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004292 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00004293 LHSVal->getName()+".off");
4294 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00004295 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4296 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00004297 }
4298 break; // (X != 13 & X != 15) -> no change
4299 }
4300 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004301 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00004302 switch (RHSCC) {
4303 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004304 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4305 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004306 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004307 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4308 break;
4309 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4310 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00004311 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004312 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4313 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004314 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004315 break;
4316 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00004317 switch (RHSCC) {
4318 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004319 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4320 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004321 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004322 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4323 break;
4324 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4325 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00004326 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004327 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4328 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004329 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004330 break;
4331 case ICmpInst::ICMP_UGT:
4332 switch (RHSCC) {
4333 default: assert(0 && "Unknown integer condition code!");
4334 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4335 return ReplaceInstUsesWith(I, LHS);
4336 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4337 return ReplaceInstUsesWith(I, RHS);
4338 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4339 break;
4340 case ICmpInst::ICMP_NE:
4341 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4342 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4343 break; // (X u> 13 & X != 15) -> no change
4344 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4345 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4346 true, I);
4347 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4348 break;
4349 }
4350 break;
4351 case ICmpInst::ICMP_SGT:
4352 switch (RHSCC) {
4353 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004354 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004355 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4356 return ReplaceInstUsesWith(I, RHS);
4357 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4358 break;
4359 case ICmpInst::ICMP_NE:
4360 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4361 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4362 break; // (X s> 13 & X != 15) -> no change
4363 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4364 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4365 true, I);
4366 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4367 break;
4368 }
4369 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004370 }
4371 }
4372 }
4373
Chris Lattner6fc205f2006-05-05 06:39:07 +00004374 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004375 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4376 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4377 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4378 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004379 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004380 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004381 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4382 I.getType(), TD) &&
4383 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4384 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004385 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004386 Op1C->getOperand(0),
4387 I.getName());
4388 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004389 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004390 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004391 }
Chris Lattnere511b742006-11-14 07:46:50 +00004392
4393 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004394 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4395 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4396 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004397 SI0->getOperand(1) == SI1->getOperand(1) &&
4398 (SI0->hasOneUse() || SI1->hasOneUse())) {
4399 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004400 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004401 SI1->getOperand(0),
4402 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004403 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004404 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004405 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004406 }
4407
Chris Lattner99c65742007-10-24 05:38:08 +00004408 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4409 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4410 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4411 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4412 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4413 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4414 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4415 // If either of the constants are nans, then the whole thing returns
4416 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004417 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004418 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4419 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4420 RHS->getOperand(0));
4421 }
4422 }
4423 }
4424
Chris Lattner7e708292002-06-25 16:13:24 +00004425 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004426}
4427
Chris Lattnerafe91a52006-06-15 19:07:26 +00004428/// CollectBSwapParts - Look to see if the specified value defines a single byte
4429/// in the result. If it does, and if the specified byte hasn't been filled in
4430/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004431static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004432 Instruction *I = dyn_cast<Instruction>(V);
4433 if (I == 0) return true;
4434
4435 // If this is an or instruction, it is an inner node of the bswap.
4436 if (I->getOpcode() == Instruction::Or)
4437 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4438 CollectBSwapParts(I->getOperand(1), ByteValues);
4439
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004440 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004441 // If this is a shift by a constant int, and it is "24", then its operand
4442 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004443 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004444 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004445 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004446 8*(ByteValues.size()-1))
4447 return true;
4448
4449 unsigned DestNo;
4450 if (I->getOpcode() == Instruction::Shl) {
4451 // X << 24 defines the top byte with the lowest of the input bytes.
4452 DestNo = ByteValues.size()-1;
4453 } else {
4454 // X >>u 24 defines the low byte with the highest of the input bytes.
4455 DestNo = 0;
4456 }
4457
4458 // If the destination byte value is already defined, the values are or'd
4459 // together, which isn't a bswap (unless it's an or of the same bits).
4460 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4461 return true;
4462 ByteValues[DestNo] = I->getOperand(0);
4463 return false;
4464 }
4465
4466 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4467 // don't have this.
4468 Value *Shift = 0, *ShiftLHS = 0;
4469 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4470 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4471 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4472 return true;
4473 Instruction *SI = cast<Instruction>(Shift);
4474
4475 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004476 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4477 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004478 return true;
4479
4480 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4481 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004482 if (AndAmt->getValue().getActiveBits() > 64)
4483 return true;
4484 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004485 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004486 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004487 break;
4488 // Unknown mask for bswap.
4489 if (DestByte == ByteValues.size()) return true;
4490
Reid Spencerb83eb642006-10-20 07:07:24 +00004491 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004492 unsigned SrcByte;
4493 if (SI->getOpcode() == Instruction::Shl)
4494 SrcByte = DestByte - ShiftBytes;
4495 else
4496 SrcByte = DestByte + ShiftBytes;
4497
4498 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4499 if (SrcByte != ByteValues.size()-DestByte-1)
4500 return true;
4501
4502 // If the destination byte value is already defined, the values are or'd
4503 // together, which isn't a bswap (unless it's an or of the same bits).
4504 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4505 return true;
4506 ByteValues[DestByte] = SI->getOperand(0);
4507 return false;
4508}
4509
4510/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4511/// If so, insert the new bswap intrinsic and return it.
4512Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004513 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4514 if (!ITy || ITy->getBitWidth() % 16)
4515 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004516
4517 /// ByteValues - For each byte of the result, we keep track of which value
4518 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004519 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004520 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004521
4522 // Try to find all the pieces corresponding to the bswap.
4523 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4524 CollectBSwapParts(I.getOperand(1), ByteValues))
4525 return 0;
4526
4527 // Check to see if all of the bytes come from the same value.
4528 Value *V = ByteValues[0];
4529 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4530
4531 // Check to make sure that all of the bytes come from the same value.
4532 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4533 if (ByteValues[i] != V)
4534 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004535 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004536 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004537 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004538 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004539}
4540
4541
Chris Lattner7e708292002-06-25 16:13:24 +00004542Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004543 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004544 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004545
Chris Lattner42593e62007-03-24 23:56:43 +00004546 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004547 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004548
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004549 // or X, X = X
4550 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004551 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004552
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004553 // See if we can simplify any instructions used by the instruction whose sole
4554 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004555 if (!isa<VectorType>(I.getType())) {
4556 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4557 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4558 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4559 KnownZero, KnownOne))
4560 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004561 } else if (isa<ConstantAggregateZero>(Op1)) {
4562 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4563 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4564 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4565 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004566 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004567
4568
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004569
Chris Lattner3f5b8772002-05-06 16:14:14 +00004570 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004571 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004572 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004573 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4574 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004575 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004576 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004577 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004578 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004579 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004580 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004581
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004582 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4583 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004584 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004585 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004586 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004587 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004588 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004589 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004590
4591 // Try to fold constant and into select arguments.
4592 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004593 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004594 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004595 if (isa<PHINode>(Op0))
4596 if (Instruction *NV = FoldOpIntoPhi(I))
4597 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004598 }
4599
Chris Lattner4f637d42006-01-06 17:59:59 +00004600 Value *A = 0, *B = 0;
4601 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004602
4603 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4604 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4605 return ReplaceInstUsesWith(I, Op1);
4606 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4607 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4608 return ReplaceInstUsesWith(I, Op0);
4609
Chris Lattner6423d4c2006-07-10 20:25:24 +00004610 // (A | B) | C and A | (B | C) -> bswap if possible.
4611 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004612 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004613 match(Op1, m_Or(m_Value(), m_Value())) ||
4614 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4615 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004616 if (Instruction *BSwap = MatchBSwap(I))
4617 return BSwap;
4618 }
4619
Chris Lattner6e4c6492005-05-09 04:58:36 +00004620 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4621 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004622 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004623 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004624 InsertNewInstBefore(NOr, I);
4625 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004626 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004627 }
4628
4629 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4630 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004631 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004632 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004633 InsertNewInstBefore(NOr, I);
4634 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004635 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004636 }
4637
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004638 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004639 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004640 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4641 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004642 Value *V1 = 0, *V2 = 0, *V3 = 0;
4643 C1 = dyn_cast<ConstantInt>(C);
4644 C2 = dyn_cast<ConstantInt>(D);
4645 if (C1 && C2) { // (A & C1)|(B & C2)
4646 // If we have: ((V + N) & C1) | (V & C2)
4647 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4648 // replace with V+N.
4649 if (C1->getValue() == ~C2->getValue()) {
4650 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4651 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4652 // Add commutes, try both ways.
4653 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4654 return ReplaceInstUsesWith(I, A);
4655 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4656 return ReplaceInstUsesWith(I, A);
4657 }
4658 // Or commutes, try both ways.
4659 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4660 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4661 // Add commutes, try both ways.
4662 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4663 return ReplaceInstUsesWith(I, B);
4664 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4665 return ReplaceInstUsesWith(I, B);
4666 }
4667 }
Chris Lattner044e5332007-04-08 08:01:49 +00004668 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004669 }
4670
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004671 // Check to see if we have any common things being and'ed. If so, find the
4672 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004673 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4674 if (A == B) // (A & C)|(A & D) == A & (C|D)
4675 V1 = A, V2 = C, V3 = D;
4676 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4677 V1 = A, V2 = B, V3 = C;
4678 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4679 V1 = C, V2 = A, V3 = D;
4680 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4681 V1 = C, V2 = A, V3 = B;
4682
4683 if (V1) {
4684 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004685 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4686 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004687 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004688 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004689 }
Chris Lattnere511b742006-11-14 07:46:50 +00004690
4691 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004692 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4693 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4694 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004695 SI0->getOperand(1) == SI1->getOperand(1) &&
4696 (SI0->hasOneUse() || SI1->hasOneUse())) {
4697 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004698 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004699 SI1->getOperand(0),
4700 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004701 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004702 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004703 }
4704 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004705
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004706 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4707 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004708 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004709 } else {
4710 A = 0;
4711 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004712 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004713 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4714 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004715 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004716
Misha Brukmancb6267b2004-07-30 12:50:08 +00004717 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004718 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004719 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004720 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004721 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004722 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004723 }
Chris Lattnera2881962003-02-18 19:28:33 +00004724
Reid Spencere4d87aa2006-12-23 06:05:41 +00004725 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4726 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4727 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004728 return R;
4729
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004730 Value *LHSVal, *RHSVal;
4731 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004732 ICmpInst::Predicate LHSCC, RHSCC;
4733 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4734 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4735 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4736 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4737 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4738 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4739 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004740 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4741 // We can't fold (ugt x, C) | (sgt x, C2).
4742 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004743 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004744 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004745 bool NeedsSwap;
4746 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004747 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004748 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004749 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004750
4751 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004752 std::swap(LHS, RHS);
4753 std::swap(LHSCst, RHSCst);
4754 std::swap(LHSCC, RHSCC);
4755 }
4756
Reid Spencere4d87aa2006-12-23 06:05:41 +00004757 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004758 // comparing a value against two constants and or'ing the result
4759 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004760 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4761 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004762 // equal.
4763 assert(LHSCst != RHSCst && "Compares not folded above?");
4764
4765 switch (LHSCC) {
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 switch (RHSCC) {
4769 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004770 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004771 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4772 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004773 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004774 LHSVal->getName()+".off");
4775 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004776 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004777 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004778 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004779 break; // (X == 13 | X == 15) -> no change
4780 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4781 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004782 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004783 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4784 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4785 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004786 return ReplaceInstUsesWith(I, RHS);
4787 }
4788 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004789 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004790 switch (RHSCC) {
4791 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004792 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4793 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4794 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004795 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004796 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4797 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4798 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004799 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004800 }
4801 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004802 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004803 switch (RHSCC) {
4804 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004805 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004806 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004807 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004808 // If RHSCst is [us]MAXINT, it is always false. Not handling
4809 // this can cause overflow.
4810 if (RHSCst->isMaxValue(false))
4811 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004812 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4813 false, I);
4814 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4815 break;
4816 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4817 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004818 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004819 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4820 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004821 }
4822 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004823 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004824 switch (RHSCC) {
4825 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004826 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4827 break;
4828 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004829 // If RHSCst is [us]MAXINT, it is always false. Not handling
4830 // this can cause overflow.
4831 if (RHSCst->isMaxValue(true))
4832 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004833 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4834 false, I);
4835 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4836 break;
4837 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4838 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4839 return ReplaceInstUsesWith(I, RHS);
4840 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4841 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004842 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004843 break;
4844 case ICmpInst::ICMP_UGT:
4845 switch (RHSCC) {
4846 default: assert(0 && "Unknown integer condition code!");
4847 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4848 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4849 return ReplaceInstUsesWith(I, LHS);
4850 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4851 break;
4852 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4853 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004854 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004855 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4856 break;
4857 }
4858 break;
4859 case ICmpInst::ICMP_SGT:
4860 switch (RHSCC) {
4861 default: assert(0 && "Unknown integer condition code!");
4862 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4863 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4864 return ReplaceInstUsesWith(I, LHS);
4865 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4866 break;
4867 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4868 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004869 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004870 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4871 break;
4872 }
4873 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004874 }
4875 }
4876 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004877
4878 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004879 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004880 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004881 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004882 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4883 !isa<ICmpInst>(Op1C->getOperand(0))) {
4884 const Type *SrcTy = Op0C->getOperand(0)->getType();
4885 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4886 // Only do this if the casts both really cause code to be
4887 // generated.
4888 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4889 I.getType(), TD) &&
4890 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4891 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004892 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004893 Op1C->getOperand(0),
4894 I.getName());
4895 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004896 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004897 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004898 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004899 }
Chris Lattner99c65742007-10-24 05:38:08 +00004900 }
4901
4902
4903 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4904 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4905 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4906 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004907 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4908 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004909 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4910 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4911 // If either of the constants are nans, then the whole thing returns
4912 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004913 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004914 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4915
4916 // Otherwise, no need to compare the two constants, compare the
4917 // rest.
4918 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4919 RHS->getOperand(0));
4920 }
4921 }
4922 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004923
Chris Lattner7e708292002-06-25 16:13:24 +00004924 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004925}
4926
Dan Gohman844731a2008-05-13 00:00:25 +00004927namespace {
4928
Chris Lattnerc317d392004-02-16 01:20:27 +00004929// XorSelf - Implements: X ^ X --> 0
4930struct XorSelf {
4931 Value *RHS;
4932 XorSelf(Value *rhs) : RHS(rhs) {}
4933 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4934 Instruction *apply(BinaryOperator &Xor) const {
4935 return &Xor;
4936 }
4937};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004938
Dan Gohman844731a2008-05-13 00:00:25 +00004939}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004940
Chris Lattner7e708292002-06-25 16:13:24 +00004941Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004942 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004943 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004944
Evan Chengd34af782008-03-25 20:07:13 +00004945 if (isa<UndefValue>(Op1)) {
4946 if (isa<UndefValue>(Op0))
4947 // Handle undef ^ undef -> 0 special case. This is a common
4948 // idiom (misuse).
4949 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004950 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004951 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004952
Chris Lattnerc317d392004-02-16 01:20:27 +00004953 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4954 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004955 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004956 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004957 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004958
4959 // See if we can simplify any instructions used by the instruction whose sole
4960 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004961 if (!isa<VectorType>(I.getType())) {
4962 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4963 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4964 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4965 KnownZero, KnownOne))
4966 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004967 } else if (isa<ConstantAggregateZero>(Op1)) {
4968 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004969 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004970
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004971 // Is this a ~ operation?
4972 if (Value *NotOp = dyn_castNotVal(&I)) {
4973 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4974 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4975 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4976 if (Op0I->getOpcode() == Instruction::And ||
4977 Op0I->getOpcode() == Instruction::Or) {
4978 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4979 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4980 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004981 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004982 Op0I->getOperand(1)->getName()+".not");
4983 InsertNewInstBefore(NotY, I);
4984 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004985 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004986 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004987 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004988 }
4989 }
4990 }
4991 }
4992
4993
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004994 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004995 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4996 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4997 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004998 return new ICmpInst(ICI->getInversePredicate(),
4999 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005000
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005001 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5002 return new FCmpInst(FCI->getInversePredicate(),
5003 FCI->getOperand(0), FCI->getOperand(1));
5004 }
5005
Reid Spencere4d87aa2006-12-23 06:05:41 +00005006 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005007 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005008 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5009 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00005010 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5011 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005012 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005013 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005014 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005015
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005016 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005017 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005018 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005019 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00005020 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005021 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00005022 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005023 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00005024 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005025 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005026 // (X + C) ^ signbit -> (X + C + signbit)
5027 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005028 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005029
Chris Lattner7c4049c2004-01-12 19:35:11 +00005030 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005031 } else if (Op0I->getOpcode() == Instruction::Or) {
5032 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005033 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00005034 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5035 // Anything in both C1 and C2 is known to be zero, remove it from
5036 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005037 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005038 NewRHS = ConstantExpr::getAnd(NewRHS,
5039 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005040 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005041 I.setOperand(0, Op0I->getOperand(0));
5042 I.setOperand(1, NewRHS);
5043 return &I;
5044 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005045 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005046 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005047 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005048
5049 // Try to fold constant and into select arguments.
5050 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005051 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005052 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005053 if (isa<PHINode>(Op0))
5054 if (Instruction *NV = FoldOpIntoPhi(I))
5055 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005056 }
5057
Chris Lattner8d969642003-03-10 23:06:50 +00005058 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005059 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005060 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005061
Chris Lattner8d969642003-03-10 23:06:50 +00005062 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005063 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005064 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005065
Chris Lattner318bf792007-03-18 22:51:34 +00005066
5067 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5068 if (Op1I) {
5069 Value *A, *B;
5070 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5071 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005072 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005073 I.swapOperands();
5074 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005075 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005076 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005077 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005078 }
Chris Lattner318bf792007-03-18 22:51:34 +00005079 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
5080 if (Op0 == A) // A^(A^B) == B
5081 return ReplaceInstUsesWith(I, B);
5082 else if (Op0 == B) // A^(B^A) == B
5083 return ReplaceInstUsesWith(I, A);
5084 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005085 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005086 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005087 std::swap(A, B);
5088 }
Chris Lattner318bf792007-03-18 22:51:34 +00005089 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005090 I.swapOperands(); // Simplified below.
5091 std::swap(Op0, Op1);
5092 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005093 }
Chris Lattner318bf792007-03-18 22:51:34 +00005094 }
5095
5096 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5097 if (Op0I) {
5098 Value *A, *B;
5099 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5100 if (A == Op1) // (B|A)^B == (A|B)^B
5101 std::swap(A, B);
5102 if (B == Op1) { // (A|B)^B == A & ~B
5103 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005104 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5105 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005106 }
Chris Lattner318bf792007-03-18 22:51:34 +00005107 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
5108 if (Op1 == A) // (A^B)^A == B
5109 return ReplaceInstUsesWith(I, B);
5110 else if (Op1 == B) // (B^A)^A == B
5111 return ReplaceInstUsesWith(I, A);
5112 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5113 if (A == Op1) // (A&B)^A -> (B&A)^A
5114 std::swap(A, B);
5115 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005116 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005117 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005118 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5119 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005120 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005121 }
Chris Lattner318bf792007-03-18 22:51:34 +00005122 }
5123
5124 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5125 if (Op0I && Op1I && Op0I->isShift() &&
5126 Op0I->getOpcode() == Op1I->getOpcode() &&
5127 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5128 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5129 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005130 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005131 Op1I->getOperand(0),
5132 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005133 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005134 Op1I->getOperand(1));
5135 }
5136
5137 if (Op0I && Op1I) {
5138 Value *A, *B, *C, *D;
5139 // (A & B)^(A | B) -> A ^ B
5140 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5141 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5142 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005143 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005144 }
5145 // (A | B)^(A & B) -> A ^ B
5146 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5147 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5148 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005149 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005150 }
5151
5152 // (A & B)^(C & D)
5153 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5154 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5155 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5156 // (X & Y)^(X & Y) -> (Y^Z) & X
5157 Value *X = 0, *Y = 0, *Z = 0;
5158 if (A == C)
5159 X = A, Y = B, Z = D;
5160 else if (A == D)
5161 X = A, Y = B, Z = C;
5162 else if (B == C)
5163 X = B, Y = A, Z = D;
5164 else if (B == D)
5165 X = B, Y = A, Z = C;
5166
5167 if (X) {
5168 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005169 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5170 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005171 }
5172 }
5173 }
5174
Reid Spencere4d87aa2006-12-23 06:05:41 +00005175 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5176 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5177 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005178 return R;
5179
Chris Lattner6fc205f2006-05-05 06:39:07 +00005180 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005181 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005182 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005183 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5184 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005185 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005186 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005187 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5188 I.getType(), TD) &&
5189 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5190 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005191 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005192 Op1C->getOperand(0),
5193 I.getName());
5194 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005195 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005196 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005197 }
Chris Lattner99c65742007-10-24 05:38:08 +00005198 }
Chris Lattner7e708292002-06-25 16:13:24 +00005199 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005200}
5201
Chris Lattnera96879a2004-09-29 17:40:11 +00005202/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5203/// overflowed for this type.
5204static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005205 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005206 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005207
Reid Spencere4e40032007-03-21 23:19:50 +00005208 if (IsSigned)
5209 if (In2->getValue().isNegative())
5210 return Result->getValue().sgt(In1->getValue());
5211 else
5212 return Result->getValue().slt(In1->getValue());
5213 else
5214 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005215}
5216
Chris Lattner574da9b2005-01-13 20:14:25 +00005217/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5218/// code necessary to compute the offset from the base pointer (without adding
5219/// in the base pointer). Return the result as a signed integer of intptr size.
5220static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5221 TargetData &TD = IC.getTargetData();
5222 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005223 const Type *IntPtrTy = TD.getIntPtrType();
5224 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005225
5226 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005227 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005228 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005229
Chris Lattner574da9b2005-01-13 20:14:25 +00005230 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5231 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00005232 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005233 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5234 if (OpC->isZero()) continue;
5235
5236 // Handle a struct index, which adds its field offset to the pointer.
5237 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5238 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5239
5240 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5241 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005242 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005243 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005244 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005245 ConstantInt::get(IntPtrTy, Size),
5246 GEP->getName()+".offs"), I);
5247 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005248 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005249
5250 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5251 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5252 Scale = ConstantExpr::getMul(OC, Scale);
5253 if (Constant *RC = dyn_cast<Constant>(Result))
5254 Result = ConstantExpr::getAdd(RC, Scale);
5255 else {
5256 // Emit an add instruction.
5257 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005258 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005259 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005260 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005261 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005262 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005263 // Convert to correct type.
5264 if (Op->getType() != IntPtrTy) {
5265 if (Constant *OpC = dyn_cast<Constant>(Op))
5266 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5267 else
5268 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5269 Op->getName()+".c"), I);
5270 }
5271 if (Size != 1) {
5272 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5273 if (Constant *OpC = dyn_cast<Constant>(Op))
5274 Op = ConstantExpr::getMul(OpC, Scale);
5275 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005276 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005277 GEP->getName()+".idx"), I);
5278 }
5279
5280 // Emit an add instruction.
5281 if (isa<Constant>(Op) && isa<Constant>(Result))
5282 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5283 cast<Constant>(Result));
5284 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005285 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005286 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005287 }
5288 return Result;
5289}
5290
Chris Lattner10c0d912008-04-22 02:53:33 +00005291
5292/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5293/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5294/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5295/// complex, and scales are involved. The above expression would also be legal
5296/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5297/// later form is less amenable to optimization though, and we are allowed to
5298/// generate the first by knowing that pointer arithmetic doesn't overflow.
5299///
5300/// If we can't emit an optimized form for this expression, this returns null.
5301///
5302static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5303 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005304 TargetData &TD = IC.getTargetData();
5305 gep_type_iterator GTI = gep_type_begin(GEP);
5306
5307 // Check to see if this gep only has a single variable index. If so, and if
5308 // any constant indices are a multiple of its scale, then we can compute this
5309 // in terms of the scale of the variable index. For example, if the GEP
5310 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5311 // because the expression will cross zero at the same point.
5312 unsigned i, e = GEP->getNumOperands();
5313 int64_t Offset = 0;
5314 for (i = 1; i != e; ++i, ++GTI) {
5315 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5316 // Compute the aggregate offset of constant indices.
5317 if (CI->isZero()) continue;
5318
5319 // Handle a struct index, which adds its field offset to the pointer.
5320 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5321 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5322 } else {
5323 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5324 Offset += Size*CI->getSExtValue();
5325 }
5326 } else {
5327 // Found our variable index.
5328 break;
5329 }
5330 }
5331
5332 // If there are no variable indices, we must have a constant offset, just
5333 // evaluate it the general way.
5334 if (i == e) return 0;
5335
5336 Value *VariableIdx = GEP->getOperand(i);
5337 // Determine the scale factor of the variable element. For example, this is
5338 // 4 if the variable index is into an array of i32.
5339 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5340
5341 // Verify that there are no other variable indices. If so, emit the hard way.
5342 for (++i, ++GTI; i != e; ++i, ++GTI) {
5343 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5344 if (!CI) return 0;
5345
5346 // Compute the aggregate offset of constant indices.
5347 if (CI->isZero()) continue;
5348
5349 // Handle a struct index, which adds its field offset to the pointer.
5350 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5351 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5352 } else {
5353 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5354 Offset += Size*CI->getSExtValue();
5355 }
5356 }
5357
5358 // Okay, we know we have a single variable index, which must be a
5359 // pointer/array/vector index. If there is no offset, life is simple, return
5360 // the index.
5361 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5362 if (Offset == 0) {
5363 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5364 // we don't need to bother extending: the extension won't affect where the
5365 // computation crosses zero.
5366 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5367 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5368 VariableIdx->getNameStart(), &I);
5369 return VariableIdx;
5370 }
5371
5372 // Otherwise, there is an index. The computation we will do will be modulo
5373 // the pointer size, so get it.
5374 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5375
5376 Offset &= PtrSizeMask;
5377 VariableScale &= PtrSizeMask;
5378
5379 // To do this transformation, any constant index must be a multiple of the
5380 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5381 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5382 // multiple of the variable scale.
5383 int64_t NewOffs = Offset / (int64_t)VariableScale;
5384 if (Offset != NewOffs*(int64_t)VariableScale)
5385 return 0;
5386
5387 // Okay, we can do this evaluation. Start by converting the index to intptr.
5388 const Type *IntPtrTy = TD.getIntPtrType();
5389 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005390 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005391 true /*SExt*/,
5392 VariableIdx->getNameStart(), &I);
5393 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005394 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005395}
5396
5397
Reid Spencere4d87aa2006-12-23 06:05:41 +00005398/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005399/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005400Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5401 ICmpInst::Predicate Cond,
5402 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005403 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005404
Chris Lattner10c0d912008-04-22 02:53:33 +00005405 // Look through bitcasts.
5406 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5407 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005408
Chris Lattner574da9b2005-01-13 20:14:25 +00005409 Value *PtrBase = GEPLHS->getOperand(0);
5410 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005411 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005412 // This transformation (ignoring the base and scales) is valid because we
5413 // know pointers can't overflow. See if we can output an optimized form.
5414 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5415
5416 // If not, synthesize the offset the hard way.
5417 if (Offset == 0)
5418 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005419 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5420 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005421 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005422 // If the base pointers are different, but the indices are the same, just
5423 // compare the base pointer.
5424 if (PtrBase != GEPRHS->getOperand(0)) {
5425 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005426 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005427 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005428 if (IndicesTheSame)
5429 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5430 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5431 IndicesTheSame = false;
5432 break;
5433 }
5434
5435 // If all indices are the same, just compare the base pointers.
5436 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005437 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5438 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005439
5440 // Otherwise, the base pointers are different and the indices are
5441 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005442 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005443 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005444
Chris Lattnere9d782b2005-01-13 22:25:21 +00005445 // If one of the GEPs has all zero indices, recurse.
5446 bool AllZeros = true;
5447 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5448 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5449 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5450 AllZeros = false;
5451 break;
5452 }
5453 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005454 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5455 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005456
5457 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005458 AllZeros = true;
5459 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5460 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5461 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5462 AllZeros = false;
5463 break;
5464 }
5465 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005466 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005467
Chris Lattner4401c9c2005-01-14 00:20:05 +00005468 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5469 // If the GEPs only differ by one index, compare it.
5470 unsigned NumDifferences = 0; // Keep track of # differences.
5471 unsigned DiffOperand = 0; // The operand that differs.
5472 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5473 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005474 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5475 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005476 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005477 NumDifferences = 2;
5478 break;
5479 } else {
5480 if (NumDifferences++) break;
5481 DiffOperand = i;
5482 }
5483 }
5484
5485 if (NumDifferences == 0) // SAME GEP?
5486 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005487 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005488 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005489
Chris Lattner4401c9c2005-01-14 00:20:05 +00005490 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005491 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5492 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005493 // Make sure we do a signed comparison here.
5494 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005495 }
5496 }
5497
Reid Spencere4d87aa2006-12-23 06:05:41 +00005498 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005499 // the result to fold to a constant!
5500 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5501 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5502 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5503 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5504 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005505 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005506 }
5507 }
5508 return 0;
5509}
5510
Chris Lattnera5406232008-05-19 20:18:56 +00005511/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5512///
5513Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5514 Instruction *LHSI,
5515 Constant *RHSC) {
5516 if (!isa<ConstantFP>(RHSC)) return 0;
5517 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5518
5519 // Get the width of the mantissa. We don't want to hack on conversions that
5520 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005521 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005522 if (MantissaWidth == -1) return 0; // Unknown.
5523
5524 // Check to see that the input is converted from an integer type that is small
5525 // enough that preserves all bits. TODO: check here for "known" sign bits.
5526 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5527 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5528
5529 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5530 if (isa<UIToFPInst>(LHSI))
5531 ++InputSize;
5532
5533 // If the conversion would lose info, don't hack on this.
5534 if ((int)InputSize > MantissaWidth)
5535 return 0;
5536
5537 // Otherwise, we can potentially simplify the comparison. We know that it
5538 // will always come through as an integer value and we know the constant is
5539 // not a NAN (it would have been previously simplified).
5540 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5541
5542 ICmpInst::Predicate Pred;
5543 switch (I.getPredicate()) {
5544 default: assert(0 && "Unexpected predicate!");
5545 case FCmpInst::FCMP_UEQ:
5546 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5547 case FCmpInst::FCMP_UGT:
5548 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5549 case FCmpInst::FCMP_UGE:
5550 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5551 case FCmpInst::FCMP_ULT:
5552 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5553 case FCmpInst::FCMP_ULE:
5554 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5555 case FCmpInst::FCMP_UNE:
5556 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5557 case FCmpInst::FCMP_ORD:
5558 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5559 case FCmpInst::FCMP_UNO:
5560 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5561 }
5562
5563 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5564
5565 // Now we know that the APFloat is a normal number, zero or inf.
5566
Chris Lattner85162782008-05-20 03:50:52 +00005567 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005568 // comparing an i8 to 300.0.
5569 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5570
5571 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5572 // and large values.
5573 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5574 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5575 APFloat::rmNearestTiesToEven);
5576 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00005577 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5578 Pred == ICmpInst::ICMP_SLE)
Chris Lattnera5406232008-05-19 20:18:56 +00005579 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5580 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5581 }
5582
5583 // See if the RHS value is < SignedMin.
5584 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5585 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5586 APFloat::rmNearestTiesToEven);
5587 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00005588 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5589 Pred == ICmpInst::ICMP_SGE)
Chris Lattnera5406232008-05-19 20:18:56 +00005590 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5591 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5592 }
5593
5594 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5595 // it may still be fractional. See if it is fractional by casting the FP
5596 // value to the integer value and back, checking for equality. Don't do this
5597 // for zero, because -0.0 is not fractional.
5598 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5599 if (!RHS.isZero() &&
5600 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5601 // If we had a comparison against a fractional value, we have to adjust
5602 // the compare predicate and sometimes the value. RHSC is rounded towards
5603 // zero at this point.
5604 switch (Pred) {
5605 default: assert(0 && "Unexpected integer comparison!");
5606 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5607 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5608 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5609 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5610 case ICmpInst::ICMP_SLE:
5611 // (float)int <= 4.4 --> int <= 4
5612 // (float)int <= -4.4 --> int < -4
5613 if (RHS.isNegative())
5614 Pred = ICmpInst::ICMP_SLT;
5615 break;
5616 case ICmpInst::ICMP_SLT:
5617 // (float)int < -4.4 --> int < -4
5618 // (float)int < 4.4 --> int <= 4
5619 if (!RHS.isNegative())
5620 Pred = ICmpInst::ICMP_SLE;
5621 break;
5622 case ICmpInst::ICMP_SGT:
5623 // (float)int > 4.4 --> int > 4
5624 // (float)int > -4.4 --> int >= -4
5625 if (RHS.isNegative())
5626 Pred = ICmpInst::ICMP_SGE;
5627 break;
5628 case ICmpInst::ICMP_SGE:
5629 // (float)int >= -4.4 --> int >= -4
5630 // (float)int >= 4.4 --> int > 4
5631 if (!RHS.isNegative())
5632 Pred = ICmpInst::ICMP_SGT;
5633 break;
5634 }
5635 }
5636
5637 // Lower this FP comparison into an appropriate integer version of the
5638 // comparison.
5639 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5640}
5641
Reid Spencere4d87aa2006-12-23 06:05:41 +00005642Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5643 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005644 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005645
Chris Lattner58e97462007-01-14 19:42:17 +00005646 // Fold trivial predicates.
5647 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5648 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5649 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5650 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5651
5652 // Simplify 'fcmp pred X, X'
5653 if (Op0 == Op1) {
5654 switch (I.getPredicate()) {
5655 default: assert(0 && "Unknown predicate!");
5656 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5657 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5658 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5659 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5660 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5661 case FCmpInst::FCMP_OLT: // True if ordered and less than
5662 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5663 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5664
5665 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5666 case FCmpInst::FCMP_ULT: // True if unordered or less than
5667 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5668 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5669 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5670 I.setPredicate(FCmpInst::FCMP_UNO);
5671 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5672 return &I;
5673
5674 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5675 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5676 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5677 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5678 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5679 I.setPredicate(FCmpInst::FCMP_ORD);
5680 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5681 return &I;
5682 }
5683 }
5684
Reid Spencere4d87aa2006-12-23 06:05:41 +00005685 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005686 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005687
Reid Spencere4d87aa2006-12-23 06:05:41 +00005688 // Handle fcmp with constant RHS
5689 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005690 // If the constant is a nan, see if we can fold the comparison based on it.
5691 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5692 if (CFP->getValueAPF().isNaN()) {
5693 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5694 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005695 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5696 "Comparison must be either ordered or unordered!");
5697 // True if unordered.
5698 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005699 }
5700 }
5701
Reid Spencere4d87aa2006-12-23 06:05:41 +00005702 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5703 switch (LHSI->getOpcode()) {
5704 case Instruction::PHI:
5705 if (Instruction *NV = FoldOpIntoPhi(I))
5706 return NV;
5707 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005708 case Instruction::SIToFP:
5709 case Instruction::UIToFP:
5710 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5711 return NV;
5712 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005713 case Instruction::Select:
5714 // If either operand of the select is a constant, we can fold the
5715 // comparison into the select arms, which will cause one to be
5716 // constant folded and the select turned into a bitwise or.
5717 Value *Op1 = 0, *Op2 = 0;
5718 if (LHSI->hasOneUse()) {
5719 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5720 // Fold the known value into the constant operand.
5721 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5722 // Insert a new FCmp of the other select operand.
5723 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5724 LHSI->getOperand(2), RHSC,
5725 I.getName()), I);
5726 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5727 // Fold the known value into the constant operand.
5728 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5729 // Insert a new FCmp of the other select operand.
5730 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5731 LHSI->getOperand(1), RHSC,
5732 I.getName()), I);
5733 }
5734 }
5735
5736 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005737 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005738 break;
5739 }
5740 }
5741
5742 return Changed ? &I : 0;
5743}
5744
5745Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5746 bool Changed = SimplifyCompare(I);
5747 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5748 const Type *Ty = Op0->getType();
5749
5750 // icmp X, X
5751 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005752 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005753 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005754
5755 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005756 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005757
Reid Spencere4d87aa2006-12-23 06:05:41 +00005758 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005759 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005760 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5761 isa<ConstantPointerNull>(Op0)) &&
5762 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005763 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005764 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005765 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005766
Reid Spencere4d87aa2006-12-23 06:05:41 +00005767 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005768 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005769 switch (I.getPredicate()) {
5770 default: assert(0 && "Invalid icmp instruction!");
5771 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005772 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005773 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005774 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005775 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005776 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005777 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005778
Reid Spencere4d87aa2006-12-23 06:05:41 +00005779 case ICmpInst::ICMP_UGT:
5780 case ICmpInst::ICMP_SGT:
5781 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005782 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005783 case ICmpInst::ICMP_ULT:
5784 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005785 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005786 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005787 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005788 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005789 case ICmpInst::ICMP_UGE:
5790 case ICmpInst::ICMP_SGE:
5791 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005792 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005793 case ICmpInst::ICMP_ULE:
5794 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005795 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005796 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005797 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005798 }
5799 }
Chris Lattner8b170942002-08-09 23:47:40 +00005800 }
5801
Chris Lattner2be51ae2004-06-09 04:24:29 +00005802 // See if we are doing a comparison between a constant and an instruction that
5803 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005804 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005805 Value *A, *B;
5806
Chris Lattnerb6566012008-01-05 01:18:20 +00005807 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5808 if (I.isEquality() && CI->isNullValue() &&
5809 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5810 // (icmp cond A B) if cond is equality
5811 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005812 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005813
Reid Spencere4d87aa2006-12-23 06:05:41 +00005814 switch (I.getPredicate()) {
5815 default: break;
5816 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5817 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005818 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005819 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5820 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5821 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5822 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005823 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5824 if (CI->isMinValue(true))
5825 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5826 ConstantInt::getAllOnesValue(Op0->getType()));
5827
Reid Spencere4d87aa2006-12-23 06:05:41 +00005828 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005829
Reid Spencere4d87aa2006-12-23 06:05:41 +00005830 case ICmpInst::ICMP_SLT:
5831 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005832 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005833 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5834 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5835 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5836 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5837 break;
5838
5839 case ICmpInst::ICMP_UGT:
5840 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005841 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005842 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5843 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5844 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5845 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005846
5847 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5848 if (CI->isMaxValue(true))
5849 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5850 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005851 break;
5852
5853 case ICmpInst::ICMP_SGT:
5854 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005855 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005856 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5857 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5858 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5859 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5860 break;
5861
5862 case ICmpInst::ICMP_ULE:
5863 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005864 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005865 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5866 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5867 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5868 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5869 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005870
Reid Spencere4d87aa2006-12-23 06:05:41 +00005871 case ICmpInst::ICMP_SLE:
5872 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005873 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005874 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5875 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5876 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5877 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5878 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005879
Reid Spencere4d87aa2006-12-23 06:05:41 +00005880 case ICmpInst::ICMP_UGE:
5881 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005882 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005883 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5884 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5885 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5886 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5887 break;
5888
5889 case ICmpInst::ICMP_SGE:
5890 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005891 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005892 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5893 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5894 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5895 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5896 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005897 }
5898
Reid Spencere4d87aa2006-12-23 06:05:41 +00005899 // If we still have a icmp le or icmp ge instruction, turn it into the
5900 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005901 // already been handled above, this requires little checking.
5902 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005903 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005904 default: break;
5905 case ICmpInst::ICMP_ULE:
5906 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5907 case ICmpInst::ICMP_SLE:
5908 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5909 case ICmpInst::ICMP_UGE:
5910 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5911 case ICmpInst::ICMP_SGE:
5912 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005913 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005914
5915 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005916 // in the input. If this comparison is a normal comparison, it demands all
5917 // bits, if it is a sign bit comparison, it only demands the sign bit.
5918
5919 bool UnusedBit;
5920 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5921
Reid Spencer0460fb32007-03-22 20:36:03 +00005922 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5923 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005924 if (SimplifyDemandedBits(Op0,
5925 isSignBit ? APInt::getSignBit(BitWidth)
5926 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005927 KnownZero, KnownOne, 0))
5928 return &I;
5929
5930 // Given the known and unknown bits, compute a range that the LHS could be
5931 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005932 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005933 // Compute the Min, Max and RHS values based on the known bits. For the
5934 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005935 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5936 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005937 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005938 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5939 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005940 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005941 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5942 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005943 }
5944 switch (I.getPredicate()) { // LE/GE have been folded already.
5945 default: assert(0 && "Unknown icmp opcode!");
5946 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005947 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005948 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005949 break;
5950 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005951 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005952 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005953 break;
5954 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005955 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005956 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005957 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005958 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005959 break;
5960 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005961 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005962 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005963 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005964 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005965 break;
5966 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005967 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005968 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005969 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005970 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005971 break;
5972 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005973 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005974 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005975 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005976 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005977 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005978 }
5979 }
5980
Reid Spencere4d87aa2006-12-23 06:05:41 +00005981 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005982 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005983 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005984 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005985 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5986 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005987 }
5988
Chris Lattner01deb9d2007-04-03 17:43:25 +00005989 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005990 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5991 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5992 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005993 case Instruction::GetElementPtr:
5994 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005995 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005996 bool isAllZeros = true;
5997 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5998 if (!isa<Constant>(LHSI->getOperand(i)) ||
5999 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6000 isAllZeros = false;
6001 break;
6002 }
6003 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006004 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00006005 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6006 }
6007 break;
6008
Chris Lattner6970b662005-04-23 15:31:55 +00006009 case Instruction::PHI:
6010 if (Instruction *NV = FoldOpIntoPhi(I))
6011 return NV;
6012 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006013 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006014 // If either operand of the select is a constant, we can fold the
6015 // comparison into the select arms, which will cause one to be
6016 // constant folded and the select turned into a bitwise or.
6017 Value *Op1 = 0, *Op2 = 0;
6018 if (LHSI->hasOneUse()) {
6019 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6020 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006021 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6022 // Insert a new ICmp of the other select operand.
6023 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6024 LHSI->getOperand(2), RHSC,
6025 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006026 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6027 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006028 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6029 // Insert a new ICmp of the other select operand.
6030 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6031 LHSI->getOperand(1), RHSC,
6032 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006033 }
6034 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006035
Chris Lattner6970b662005-04-23 15:31:55 +00006036 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006037 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006038 break;
6039 }
Chris Lattner4802d902007-04-06 18:57:34 +00006040 case Instruction::Malloc:
6041 // If we have (malloc != null), and if the malloc has a single use, we
6042 // can assume it is successful and remove the malloc.
6043 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6044 AddToWorkList(LHSI);
6045 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006046 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006047 }
6048 break;
6049 }
Chris Lattner6970b662005-04-23 15:31:55 +00006050 }
6051
Reid Spencere4d87aa2006-12-23 06:05:41 +00006052 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006053 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006054 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006055 return NI;
6056 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006057 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6058 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006059 return NI;
6060
Reid Spencere4d87aa2006-12-23 06:05:41 +00006061 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006062 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6063 // now.
6064 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6065 if (isa<PointerType>(Op0->getType()) &&
6066 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006067 // We keep moving the cast from the left operand over to the right
6068 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006069 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006070
Chris Lattner57d86372007-01-06 01:45:59 +00006071 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6072 // so eliminate it as well.
6073 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6074 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006075
Chris Lattnerde90b762003-11-03 04:25:02 +00006076 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006077 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006078 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006079 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006080 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006081 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006082 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006083 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006084 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006085 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006086 }
Chris Lattner57d86372007-01-06 01:45:59 +00006087 }
6088
6089 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006090 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006091 // This comes up when you have code like
6092 // int X = A < B;
6093 // if (X) ...
6094 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006095 // with a constant or another cast from the same type.
6096 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006097 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006098 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006099 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006100
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006101 // ~x < ~y --> y < x
6102 { Value *A, *B;
6103 if (match(Op0, m_Not(m_Value(A))) &&
6104 match(Op1, m_Not(m_Value(B))))
6105 return new ICmpInst(I.getPredicate(), B, A);
6106 }
6107
Chris Lattner65b72ba2006-09-18 04:22:48 +00006108 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006109 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006110
6111 // -x == -y --> x == y
6112 if (match(Op0, m_Neg(m_Value(A))) &&
6113 match(Op1, m_Neg(m_Value(B))))
6114 return new ICmpInst(I.getPredicate(), A, B);
6115
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006116 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6117 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6118 Value *OtherVal = A == Op1 ? B : A;
6119 return new ICmpInst(I.getPredicate(), OtherVal,
6120 Constant::getNullValue(A->getType()));
6121 }
6122
6123 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6124 // A^c1 == C^c2 --> A == C^(c1^c2)
6125 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6126 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6127 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006128 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006129 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006130 return new ICmpInst(I.getPredicate(), A,
6131 InsertNewInstBefore(Xor, I));
6132 }
6133
6134 // A^B == A^D -> B == D
6135 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6136 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6137 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6138 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6139 }
6140 }
6141
6142 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6143 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006144 // A == (A^B) -> B == 0
6145 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006146 return new ICmpInst(I.getPredicate(), OtherVal,
6147 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006148 }
6149 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006150 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006151 return new ICmpInst(I.getPredicate(), B,
6152 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006153 }
6154 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006155 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006156 return new ICmpInst(I.getPredicate(), B,
6157 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00006158 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00006159
Chris Lattner9c2328e2006-11-14 06:06:06 +00006160 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6161 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6162 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6163 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6164 Value *X = 0, *Y = 0, *Z = 0;
6165
6166 if (A == C) {
6167 X = B; Y = D; Z = A;
6168 } else if (A == D) {
6169 X = B; Y = C; Z = A;
6170 } else if (B == C) {
6171 X = A; Y = D; Z = B;
6172 } else if (B == D) {
6173 X = A; Y = C; Z = B;
6174 }
6175
6176 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006177 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6178 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006179 I.setOperand(0, Op1);
6180 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6181 return &I;
6182 }
6183 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006184 }
Chris Lattner7e708292002-06-25 16:13:24 +00006185 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006186}
6187
Chris Lattner562ef782007-06-20 23:46:26 +00006188
6189/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6190/// and CmpRHS are both known to be integer constants.
6191Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6192 ConstantInt *DivRHS) {
6193 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6194 const APInt &CmpRHSV = CmpRHS->getValue();
6195
6196 // FIXME: If the operand types don't match the type of the divide
6197 // then don't attempt this transform. The code below doesn't have the
6198 // logic to deal with a signed divide and an unsigned compare (and
6199 // vice versa). This is because (x /s C1) <s C2 produces different
6200 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6201 // (x /u C1) <u C2. Simply casting the operands and result won't
6202 // work. :( The if statement below tests that condition and bails
6203 // if it finds it.
6204 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6205 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6206 return 0;
6207 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006208 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00006209
6210 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6211 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6212 // C2 (CI). By solving for X we can turn this into a range check
6213 // instead of computing a divide.
6214 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6215
6216 // Determine if the product overflows by seeing if the product is
6217 // not equal to the divide. Make sure we do the same kind of divide
6218 // as in the LHS instruction that we're folding.
6219 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6220 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6221
6222 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006223 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006224
Chris Lattner1dbfd482007-06-21 18:11:19 +00006225 // Figure out the interval that is being checked. For example, a comparison
6226 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6227 // Compute this interval based on the constants involved and the signedness of
6228 // the compare/divide. This computes a half-open interval, keeping track of
6229 // whether either value in the interval overflows. After analysis each
6230 // overflow variable is set to 0 if it's corresponding bound variable is valid
6231 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6232 int LoOverflow = 0, HiOverflow = 0;
6233 ConstantInt *LoBound = 0, *HiBound = 0;
6234
6235
Chris Lattner562ef782007-06-20 23:46:26 +00006236 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006237 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006238 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006239 HiOverflow = LoOverflow = ProdOV;
6240 if (!HiOverflow)
6241 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006242 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006243 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006244 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006245 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6246 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006247 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006248 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6249 HiOverflow = LoOverflow = ProdOV;
6250 if (!HiOverflow)
6251 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006252 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006253 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006254 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
6255 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00006256 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006257 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006258 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006259 }
Dan Gohman76491272008-02-13 22:09:18 +00006260 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006261 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006262 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006263 LoBound = AddOne(DivRHS);
6264 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006265 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6266 HiOverflow = 1; // [INTMIN+1, overflow)
6267 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6268 }
Dan Gohman76491272008-02-13 22:09:18 +00006269 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006270 // e.g. X/-5 op 3 --> [-19, -14)
6271 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006272 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006273 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00006274 HiBound = AddOne(Prod);
6275 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006276 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006277 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006278 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006279 HiBound = Subtract(Prod, DivRHS);
6280 }
6281
Chris Lattner1dbfd482007-06-21 18:11:19 +00006282 // Dividing by a negative swaps the condition. LT <-> GT
6283 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006284 }
6285
6286 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006287 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006288 default: assert(0 && "Unhandled icmp opcode!");
6289 case ICmpInst::ICMP_EQ:
6290 if (LoOverflow && HiOverflow)
6291 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6292 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006293 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006294 ICmpInst::ICMP_UGE, X, LoBound);
6295 else if (LoOverflow)
6296 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6297 ICmpInst::ICMP_ULT, X, HiBound);
6298 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006299 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006300 case ICmpInst::ICMP_NE:
6301 if (LoOverflow && HiOverflow)
6302 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6303 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006304 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006305 ICmpInst::ICMP_ULT, X, LoBound);
6306 else if (LoOverflow)
6307 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6308 ICmpInst::ICMP_UGE, X, HiBound);
6309 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006310 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006311 case ICmpInst::ICMP_ULT:
6312 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006313 if (LoOverflow == +1) // Low bound is greater than input range.
6314 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6315 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006316 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006317 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006318 case ICmpInst::ICMP_UGT:
6319 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006320 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006321 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006322 else if (HiOverflow == -1) // High bound less than input range.
6323 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6324 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006325 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6326 else
6327 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6328 }
6329}
6330
6331
Chris Lattner01deb9d2007-04-03 17:43:25 +00006332/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6333///
6334Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6335 Instruction *LHSI,
6336 ConstantInt *RHS) {
6337 const APInt &RHSV = RHS->getValue();
6338
6339 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00006340 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006341 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6342 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6343 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006344 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6345 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006346 Value *CompareVal = LHSI->getOperand(0);
6347
6348 // If the sign bit of the XorCST is not set, there is no change to
6349 // the operation, just stop using the Xor.
6350 if (!XorCST->getValue().isNegative()) {
6351 ICI.setOperand(0, CompareVal);
6352 AddToWorkList(LHSI);
6353 return &ICI;
6354 }
6355
6356 // Was the old condition true if the operand is positive?
6357 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6358
6359 // If so, the new one isn't.
6360 isTrueIfPositive ^= true;
6361
6362 if (isTrueIfPositive)
6363 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6364 else
6365 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6366 }
6367 }
6368 break;
6369 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6370 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6371 LHSI->getOperand(0)->hasOneUse()) {
6372 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6373
6374 // If the LHS is an AND of a truncating cast, we can widen the
6375 // and/compare to be the input width without changing the value
6376 // produced, eliminating a cast.
6377 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6378 // We can do this transformation if either the AND constant does not
6379 // have its sign bit set or if it is an equality comparison.
6380 // Extending a relational comparison when we're checking the sign
6381 // bit would not work.
6382 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006383 (ICI.isEquality() ||
6384 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006385 uint32_t BitWidth =
6386 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6387 APInt NewCST = AndCST->getValue();
6388 NewCST.zext(BitWidth);
6389 APInt NewCI = RHSV;
6390 NewCI.zext(BitWidth);
6391 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006392 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006393 ConstantInt::get(NewCST),LHSI->getName());
6394 InsertNewInstBefore(NewAnd, ICI);
6395 return new ICmpInst(ICI.getPredicate(), NewAnd,
6396 ConstantInt::get(NewCI));
6397 }
6398 }
6399
6400 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6401 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6402 // happens a LOT in code produced by the C front-end, for bitfield
6403 // access.
6404 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6405 if (Shift && !Shift->isShift())
6406 Shift = 0;
6407
6408 ConstantInt *ShAmt;
6409 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6410 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6411 const Type *AndTy = AndCST->getType(); // Type of the and.
6412
6413 // We can fold this as long as we can't shift unknown bits
6414 // into the mask. This can only happen with signed shift
6415 // rights, as they sign-extend.
6416 if (ShAmt) {
6417 bool CanFold = Shift->isLogicalShift();
6418 if (!CanFold) {
6419 // To test for the bad case of the signed shr, see if any
6420 // of the bits shifted in could be tested after the mask.
6421 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6422 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6423
6424 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6425 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6426 AndCST->getValue()) == 0)
6427 CanFold = true;
6428 }
6429
6430 if (CanFold) {
6431 Constant *NewCst;
6432 if (Shift->getOpcode() == Instruction::Shl)
6433 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6434 else
6435 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6436
6437 // Check to see if we are shifting out any of the bits being
6438 // compared.
6439 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6440 // If we shifted bits out, the fold is not going to work out.
6441 // As a special case, check to see if this means that the
6442 // result is always true or false now.
6443 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6444 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6445 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6446 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6447 } else {
6448 ICI.setOperand(1, NewCst);
6449 Constant *NewAndCST;
6450 if (Shift->getOpcode() == Instruction::Shl)
6451 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6452 else
6453 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6454 LHSI->setOperand(1, NewAndCST);
6455 LHSI->setOperand(0, Shift->getOperand(0));
6456 AddToWorkList(Shift); // Shift is dead.
6457 AddUsesToWorkList(ICI);
6458 return &ICI;
6459 }
6460 }
6461 }
6462
6463 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6464 // preferable because it allows the C<<Y expression to be hoisted out
6465 // of a loop if Y is invariant and X is not.
6466 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6467 ICI.isEquality() && !Shift->isArithmeticShift() &&
6468 isa<Instruction>(Shift->getOperand(0))) {
6469 // Compute C << Y.
6470 Value *NS;
6471 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006472 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006473 Shift->getOperand(1), "tmp");
6474 } else {
6475 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006476 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006477 Shift->getOperand(1), "tmp");
6478 }
6479 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6480
6481 // Compute X & (C << Y).
6482 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006483 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006484 InsertNewInstBefore(NewAnd, ICI);
6485
6486 ICI.setOperand(0, NewAnd);
6487 return &ICI;
6488 }
6489 }
6490 break;
6491
Chris Lattnera0141b92007-07-15 20:42:37 +00006492 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6493 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6494 if (!ShAmt) break;
6495
6496 uint32_t TypeBits = RHSV.getBitWidth();
6497
6498 // Check that the shift amount is in range. If not, don't perform
6499 // undefined shifts. When the shift is visited it will be
6500 // simplified.
6501 if (ShAmt->uge(TypeBits))
6502 break;
6503
6504 if (ICI.isEquality()) {
6505 // If we are comparing against bits always shifted out, the
6506 // comparison cannot succeed.
6507 Constant *Comp =
6508 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6509 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6510 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6511 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6512 return ReplaceInstUsesWith(ICI, Cst);
6513 }
6514
6515 if (LHSI->hasOneUse()) {
6516 // Otherwise strength reduce the shift into an and.
6517 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6518 Constant *Mask =
6519 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006520
Chris Lattnera0141b92007-07-15 20:42:37 +00006521 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006522 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006523 Mask, LHSI->getName()+".mask");
6524 Value *And = InsertNewInstBefore(AndI, ICI);
6525 return new ICmpInst(ICI.getPredicate(), And,
6526 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006527 }
6528 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006529
6530 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6531 bool TrueIfSigned = false;
6532 if (LHSI->hasOneUse() &&
6533 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6534 // (X << 31) <s 0 --> (X&1) != 0
6535 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6536 (TypeBits-ShAmt->getZExtValue()-1));
6537 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006538 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006539 Mask, LHSI->getName()+".mask");
6540 Value *And = InsertNewInstBefore(AndI, ICI);
6541
6542 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6543 And, Constant::getNullValue(And->getType()));
6544 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006545 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006546 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006547
6548 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006549 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006550 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006551 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006552 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006553
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006554 // Check that the shift amount is in range. If not, don't perform
6555 // undefined shifts. When the shift is visited it will be
6556 // simplified.
6557 uint32_t TypeBits = RHSV.getBitWidth();
6558 if (ShAmt->uge(TypeBits))
6559 break;
6560
6561 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006562
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006563 // If we are comparing against bits always shifted out, the
6564 // comparison cannot succeed.
6565 APInt Comp = RHSV << ShAmtVal;
6566 if (LHSI->getOpcode() == Instruction::LShr)
6567 Comp = Comp.lshr(ShAmtVal);
6568 else
6569 Comp = Comp.ashr(ShAmtVal);
6570
6571 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6572 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6573 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6574 return ReplaceInstUsesWith(ICI, Cst);
6575 }
6576
6577 // Otherwise, check to see if the bits shifted out are known to be zero.
6578 // If so, we can compare against the unshifted value:
6579 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006580 if (LHSI->hasOneUse() &&
6581 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006582 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6583 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6584 ConstantExpr::getShl(RHS, ShAmt));
6585 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006586
Evan Chengf30752c2008-04-23 00:38:06 +00006587 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006588 // Otherwise strength reduce the shift into an and.
6589 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6590 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006591
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006592 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006593 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006594 Mask, LHSI->getName()+".mask");
6595 Value *And = InsertNewInstBefore(AndI, ICI);
6596 return new ICmpInst(ICI.getPredicate(), And,
6597 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006598 }
6599 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006600 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006601
6602 case Instruction::SDiv:
6603 case Instruction::UDiv:
6604 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6605 // Fold this div into the comparison, producing a range check.
6606 // Determine, based on the divide type, what the range is being
6607 // checked. If there is an overflow on the low or high side, remember
6608 // it, otherwise compute the range [low, hi) bounding the new value.
6609 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006610 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6611 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6612 DivRHS))
6613 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006614 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006615
6616 case Instruction::Add:
6617 // Fold: icmp pred (add, X, C1), C2
6618
6619 if (!ICI.isEquality()) {
6620 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6621 if (!LHSC) break;
6622 const APInt &LHSV = LHSC->getValue();
6623
6624 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6625 .subtract(LHSV);
6626
6627 if (ICI.isSignedPredicate()) {
6628 if (CR.getLower().isSignBit()) {
6629 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6630 ConstantInt::get(CR.getUpper()));
6631 } else if (CR.getUpper().isSignBit()) {
6632 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6633 ConstantInt::get(CR.getLower()));
6634 }
6635 } else {
6636 if (CR.getLower().isMinValue()) {
6637 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6638 ConstantInt::get(CR.getUpper()));
6639 } else if (CR.getUpper().isMinValue()) {
6640 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6641 ConstantInt::get(CR.getLower()));
6642 }
6643 }
6644 }
6645 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006646 }
6647
6648 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6649 if (ICI.isEquality()) {
6650 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6651
6652 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6653 // the second operand is a constant, simplify a bit.
6654 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6655 switch (BO->getOpcode()) {
6656 case Instruction::SRem:
6657 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6658 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6659 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6660 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6661 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006662 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006663 BO->getName());
6664 InsertNewInstBefore(NewRem, ICI);
6665 return new ICmpInst(ICI.getPredicate(), NewRem,
6666 Constant::getNullValue(BO->getType()));
6667 }
6668 }
6669 break;
6670 case Instruction::Add:
6671 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6672 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6673 if (BO->hasOneUse())
6674 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6675 Subtract(RHS, BOp1C));
6676 } else if (RHSV == 0) {
6677 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6678 // efficiently invertible, or if the add has just this one use.
6679 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6680
6681 if (Value *NegVal = dyn_castNegVal(BOp1))
6682 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6683 else if (Value *NegVal = dyn_castNegVal(BOp0))
6684 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6685 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006686 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006687 InsertNewInstBefore(Neg, ICI);
6688 Neg->takeName(BO);
6689 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6690 }
6691 }
6692 break;
6693 case Instruction::Xor:
6694 // For the xor case, we can xor two constants together, eliminating
6695 // the explicit xor.
6696 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6697 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6698 ConstantExpr::getXor(RHS, BOC));
6699
6700 // FALLTHROUGH
6701 case Instruction::Sub:
6702 // Replace (([sub|xor] A, B) != 0) with (A != B)
6703 if (RHSV == 0)
6704 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6705 BO->getOperand(1));
6706 break;
6707
6708 case Instruction::Or:
6709 // If bits are being or'd in that are not present in the constant we
6710 // are comparing against, then the comparison could never succeed!
6711 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6712 Constant *NotCI = ConstantExpr::getNot(RHS);
6713 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6714 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6715 isICMP_NE));
6716 }
6717 break;
6718
6719 case Instruction::And:
6720 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6721 // If bits are being compared against that are and'd out, then the
6722 // comparison can never succeed!
6723 if ((RHSV & ~BOC->getValue()) != 0)
6724 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6725 isICMP_NE));
6726
6727 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6728 if (RHS == BOC && RHSV.isPowerOf2())
6729 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6730 ICmpInst::ICMP_NE, LHSI,
6731 Constant::getNullValue(RHS->getType()));
6732
6733 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6734 if (isSignBit(BOC)) {
6735 Value *X = BO->getOperand(0);
6736 Constant *Zero = Constant::getNullValue(X->getType());
6737 ICmpInst::Predicate pred = isICMP_NE ?
6738 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6739 return new ICmpInst(pred, X, Zero);
6740 }
6741
6742 // ((X & ~7) == 0) --> X < 8
6743 if (RHSV == 0 && isHighOnes(BOC)) {
6744 Value *X = BO->getOperand(0);
6745 Constant *NegX = ConstantExpr::getNeg(BOC);
6746 ICmpInst::Predicate pred = isICMP_NE ?
6747 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6748 return new ICmpInst(pred, X, NegX);
6749 }
6750 }
6751 default: break;
6752 }
6753 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6754 // Handle icmp {eq|ne} <intrinsic>, intcst.
6755 if (II->getIntrinsicID() == Intrinsic::bswap) {
6756 AddToWorkList(II);
6757 ICI.setOperand(0, II->getOperand(1));
6758 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6759 return &ICI;
6760 }
6761 }
6762 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006763 // If the LHS is a cast from an integral value of the same size,
6764 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006765 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6766 Value *CastOp = Cast->getOperand(0);
6767 const Type *SrcTy = CastOp->getType();
6768 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6769 if (SrcTy->isInteger() &&
6770 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6771 // If this is an unsigned comparison, try to make the comparison use
6772 // smaller constant values.
6773 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6774 // X u< 128 => X s> -1
6775 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6776 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6777 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6778 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6779 // X u> 127 => X s< 0
6780 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6781 Constant::getNullValue(SrcTy));
6782 }
6783 }
6784 }
6785 }
6786 return 0;
6787}
6788
6789/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6790/// We only handle extending casts so far.
6791///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006792Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6793 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006794 Value *LHSCIOp = LHSCI->getOperand(0);
6795 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006796 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006797 Value *RHSCIOp;
6798
Chris Lattner8c756c12007-05-05 22:41:33 +00006799 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6800 // integer type is the same size as the pointer type.
6801 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6802 getTargetData().getPointerSizeInBits() ==
6803 cast<IntegerType>(DestTy)->getBitWidth()) {
6804 Value *RHSOp = 0;
6805 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006806 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006807 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6808 RHSOp = RHSC->getOperand(0);
6809 // If the pointer types don't match, insert a bitcast.
6810 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006811 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006812 }
6813
6814 if (RHSOp)
6815 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6816 }
6817
6818 // The code below only handles extension cast instructions, so far.
6819 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006820 if (LHSCI->getOpcode() != Instruction::ZExt &&
6821 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006822 return 0;
6823
Reid Spencere4d87aa2006-12-23 06:05:41 +00006824 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6825 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006826
Reid Spencere4d87aa2006-12-23 06:05:41 +00006827 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006828 // Not an extension from the same type?
6829 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006830 if (RHSCIOp->getType() != LHSCIOp->getType())
6831 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006832
Nick Lewycky4189a532008-01-28 03:48:02 +00006833 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006834 // and the other is a zext), then we can't handle this.
6835 if (CI->getOpcode() != LHSCI->getOpcode())
6836 return 0;
6837
Nick Lewycky4189a532008-01-28 03:48:02 +00006838 // Deal with equality cases early.
6839 if (ICI.isEquality())
6840 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6841
6842 // A signed comparison of sign extended values simplifies into a
6843 // signed comparison.
6844 if (isSignedCmp && isSignedExt)
6845 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6846
6847 // The other three cases all fold into an unsigned comparison.
6848 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006849 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006850
Reid Spencere4d87aa2006-12-23 06:05:41 +00006851 // If we aren't dealing with a constant on the RHS, exit early
6852 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6853 if (!CI)
6854 return 0;
6855
6856 // Compute the constant that would happen if we truncated to SrcTy then
6857 // reextended to DestTy.
6858 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6859 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6860
6861 // If the re-extended constant didn't change...
6862 if (Res2 == CI) {
6863 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6864 // For example, we might have:
6865 // %A = sext short %X to uint
6866 // %B = icmp ugt uint %A, 1330
6867 // It is incorrect to transform this into
6868 // %B = icmp ugt short %X, 1330
6869 // because %A may have negative value.
6870 //
6871 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6872 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006873 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006874 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6875 else
6876 return 0;
6877 }
6878
6879 // The re-extended constant changed so the constant cannot be represented
6880 // in the shorter type. Consequently, we cannot emit a simple comparison.
6881
6882 // First, handle some easy cases. We know the result cannot be equal at this
6883 // point so handle the ICI.isEquality() cases
6884 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006885 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006886 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006887 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006888
6889 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6890 // should have been folded away previously and not enter in here.
6891 Value *Result;
6892 if (isSignedCmp) {
6893 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006894 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006895 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006896 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006897 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006898 } else {
6899 // We're performing an unsigned comparison.
6900 if (isSignedExt) {
6901 // We're performing an unsigned comp with a sign extended value.
6902 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006903 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006904 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6905 NegOne, ICI.getName()), ICI);
6906 } else {
6907 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006908 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006909 }
6910 }
6911
6912 // Finally, return the value computed.
6913 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6914 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6915 return ReplaceInstUsesWith(ICI, Result);
6916 } else {
6917 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6918 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6919 "ICmp should be folded!");
6920 if (Constant *CI = dyn_cast<Constant>(Result))
6921 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6922 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006923 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006924 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006925}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006926
Reid Spencer832254e2007-02-02 02:16:23 +00006927Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6928 return commonShiftTransforms(I);
6929}
6930
6931Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6932 return commonShiftTransforms(I);
6933}
6934
6935Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006936 if (Instruction *R = commonShiftTransforms(I))
6937 return R;
6938
6939 Value *Op0 = I.getOperand(0);
6940
6941 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6942 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6943 if (CSI->isAllOnesValue())
6944 return ReplaceInstUsesWith(I, CSI);
6945
6946 // See if we can turn a signed shr into an unsigned shr.
6947 if (MaskedValueIsZero(Op0,
6948 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006949 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006950
6951 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006952}
6953
6954Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6955 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006956 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006957
6958 // shl X, 0 == X and shr X, 0 == X
6959 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006960 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006961 Op0 == Constant::getNullValue(Op0->getType()))
6962 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006963
Reid Spencere4d87aa2006-12-23 06:05:41 +00006964 if (isa<UndefValue>(Op0)) {
6965 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006966 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006967 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006968 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6969 }
6970 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006971 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6972 return ReplaceInstUsesWith(I, Op0);
6973 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006974 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006975 }
6976
Chris Lattner2eefe512004-04-09 19:05:30 +00006977 // Try to fold constant and into select arguments.
6978 if (isa<Constant>(Op0))
6979 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006980 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006981 return R;
6982
Reid Spencerb83eb642006-10-20 07:07:24 +00006983 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006984 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6985 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006986 return 0;
6987}
6988
Reid Spencerb83eb642006-10-20 07:07:24 +00006989Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006990 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006991 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006992
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006993 // See if we can simplify any instructions used by the instruction whose sole
6994 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006995 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6996 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6997 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006998 KnownZero, KnownOne))
6999 return &I;
7000
Chris Lattner4d5542c2006-01-06 07:12:35 +00007001 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7002 // of a signed value.
7003 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007004 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007005 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00007006 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7007 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007008 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007009 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007010 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007011 }
7012
7013 // ((X*C1) << C2) == (X * (C1 << C2))
7014 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7015 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7016 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007017 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007018 ConstantExpr::getShl(BOOp, Op1));
7019
7020 // Try to fold constant and into select arguments.
7021 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7022 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7023 return R;
7024 if (isa<PHINode>(Op0))
7025 if (Instruction *NV = FoldOpIntoPhi(I))
7026 return NV;
7027
Chris Lattner8999dd32007-12-22 09:07:47 +00007028 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7029 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7030 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7031 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7032 // place. Don't try to do this transformation in this case. Also, we
7033 // require that the input operand is a shift-by-constant so that we have
7034 // confidence that the shifts will get folded together. We could do this
7035 // xform in more cases, but it is unlikely to be profitable.
7036 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7037 isa<ConstantInt>(TrOp->getOperand(1))) {
7038 // Okay, we'll do this xform. Make the shift of shift.
7039 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007040 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007041 I.getName());
7042 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7043
7044 // For logical shifts, the truncation has the effect of making the high
7045 // part of the register be zeros. Emulate this by inserting an AND to
7046 // clear the top bits as needed. This 'and' will usually be zapped by
7047 // other xforms later if dead.
7048 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7049 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7050 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7051
7052 // The mask we constructed says what the trunc would do if occurring
7053 // between the shifts. We want to know the effect *after* the second
7054 // shift. We know that it is a logical shift by a constant, so adjust the
7055 // mask as appropriate.
7056 if (I.getOpcode() == Instruction::Shl)
7057 MaskV <<= Op1->getZExtValue();
7058 else {
7059 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7060 MaskV = MaskV.lshr(Op1->getZExtValue());
7061 }
7062
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007063 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007064 TI->getName());
7065 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7066
7067 // Return the value truncated to the interesting size.
7068 return new TruncInst(And, I.getType());
7069 }
7070 }
7071
Chris Lattner4d5542c2006-01-06 07:12:35 +00007072 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007073 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7074 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7075 Value *V1, *V2;
7076 ConstantInt *CC;
7077 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007078 default: break;
7079 case Instruction::Add:
7080 case Instruction::And:
7081 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007082 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007083 // These operators commute.
7084 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007085 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7086 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007087 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007088 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007089 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007090 Op0BO->getName());
7091 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007092 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007093 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007094 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007095 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007096 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007097 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007098 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007099 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007100
Chris Lattner150f12a2005-09-18 06:30:59 +00007101 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007102 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007103 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007104 match(Op0BOOp1,
7105 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00007106 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
7107 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007108 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007109 Op0BO->getOperand(0), Op1,
7110 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007111 InsertNewInstBefore(YS, I); // (Y << C)
7112 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007113 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007114 V1->getName()+".mask");
7115 InsertNewInstBefore(XM, I); // X & (CC << C)
7116
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007117 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007118 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007119 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007120
Reid Spencera07cb7d2007-02-02 14:41:37 +00007121 // FALL THROUGH.
7122 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007123 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007124 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7125 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007126 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007127 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007128 Op0BO->getOperand(1), Op1,
7129 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007130 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007131 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007132 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007133 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007134 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007135 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007136 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007137 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007138 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007139
Chris Lattner13d4ab42006-05-31 21:14:00 +00007140 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007141 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7142 match(Op0BO->getOperand(0),
7143 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007144 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007145 cast<BinaryOperator>(Op0BO->getOperand(0))
7146 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007147 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007148 Op0BO->getOperand(1), Op1,
7149 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007150 InsertNewInstBefore(YS, I); // (Y << C)
7151 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007152 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007153 V1->getName()+".mask");
7154 InsertNewInstBefore(XM, I); // X & (CC << C)
7155
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007156 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007157 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007158
Chris Lattner11021cb2005-09-18 05:12:10 +00007159 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007160 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007161 }
7162
7163
7164 // If the operand is an bitwise operator with a constant RHS, and the
7165 // shift is the only use, we can pull it out of the shift.
7166 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7167 bool isValid = true; // Valid only for And, Or, Xor
7168 bool highBitSet = false; // Transform if high bit of constant set?
7169
7170 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007171 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007172 case Instruction::Add:
7173 isValid = isLeftShift;
7174 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007175 case Instruction::Or:
7176 case Instruction::Xor:
7177 highBitSet = false;
7178 break;
7179 case Instruction::And:
7180 highBitSet = true;
7181 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007182 }
7183
7184 // If this is a signed shift right, and the high bit is modified
7185 // by the logical operation, do not perform the transformation.
7186 // The highBitSet boolean indicates the value of the high bit of
7187 // the constant which would cause it to be modified for this
7188 // operation.
7189 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007190 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007191 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007192
7193 if (isValid) {
7194 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7195
7196 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007197 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007198 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007199 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007200
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007201 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007202 NewRHS);
7203 }
7204 }
7205 }
7206 }
7207
Chris Lattnerad0124c2006-01-06 07:52:12 +00007208 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007209 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7210 if (ShiftOp && !ShiftOp->isShift())
7211 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007212
Reid Spencerb83eb642006-10-20 07:07:24 +00007213 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007214 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007215 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7216 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007217 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7218 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7219 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007220
Zhou Sheng4351c642007-04-02 08:20:41 +00007221 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00007222 if (AmtSum > TypeBits)
7223 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007224
7225 const IntegerType *Ty = cast<IntegerType>(I.getType());
7226
7227 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007228 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007229 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007230 ConstantInt::get(Ty, AmtSum));
7231 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7232 I.getOpcode() == Instruction::AShr) {
7233 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007234 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007235 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7236 I.getOpcode() == Instruction::LShr) {
7237 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7238 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007239 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007240 InsertNewInstBefore(Shift, I);
7241
Zhou Shenge9e03f62007-03-28 15:02:20 +00007242 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007243 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007244 }
7245
Chris Lattnerb87056f2007-02-05 00:57:54 +00007246 // Okay, if we get here, one shift must be left, and the other shift must be
7247 // right. See if the amounts are equal.
7248 if (ShiftAmt1 == ShiftAmt2) {
7249 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7250 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007251 APInt Mask(APInt::getHighBitsSet(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 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7255 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007256 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007257 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007258 }
7259 // We can simplify ((X << C) >>s C) into a trunc + sext.
7260 // NOTE: we could do this for any C, but that would make 'unusual' integer
7261 // types. For now, just stick to ones well-supported by the code
7262 // generators.
7263 const Type *SExtType = 0;
7264 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007265 case 1 :
7266 case 8 :
7267 case 16 :
7268 case 32 :
7269 case 64 :
7270 case 128:
7271 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7272 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007273 default: break;
7274 }
7275 if (SExtType) {
7276 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7277 InsertNewInstBefore(NewTrunc, I);
7278 return new SExtInst(NewTrunc, Ty);
7279 }
7280 // Otherwise, we can't handle it yet.
7281 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007282 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007283
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007284 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007285 if (I.getOpcode() == Instruction::Shl) {
7286 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7287 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007288 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007289 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007290 InsertNewInstBefore(Shift, I);
7291
Reid Spencer55702aa2007-03-25 21:11:44 +00007292 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007293 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007294 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007295
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007296 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007297 if (I.getOpcode() == Instruction::LShr) {
7298 assert(ShiftOp->getOpcode() == Instruction::Shl);
7299 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007300 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007301 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007302
Reid Spencerd5e30f02007-03-26 17:18:58 +00007303 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007304 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007305 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007306
7307 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7308 } else {
7309 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007310 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007311
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007312 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007313 if (I.getOpcode() == Instruction::Shl) {
7314 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7315 ShiftOp->getOpcode() == Instruction::AShr);
7316 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007317 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007318 ConstantInt::get(Ty, ShiftDiff));
7319 InsertNewInstBefore(Shift, I);
7320
Reid Spencer55702aa2007-03-25 21:11:44 +00007321 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007322 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007323 }
7324
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007325 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007326 if (I.getOpcode() == Instruction::LShr) {
7327 assert(ShiftOp->getOpcode() == Instruction::Shl);
7328 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007329 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007330 InsertNewInstBefore(Shift, I);
7331
Reid Spencer68d27cf2007-03-26 23:45:51 +00007332 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007333 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007334 }
7335
7336 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007337 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007338 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007339 return 0;
7340}
7341
Chris Lattnera1be5662002-05-02 17:06:02 +00007342
Chris Lattnercfd65102005-10-29 04:36:15 +00007343/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7344/// expression. If so, decompose it, returning some value X, such that Val is
7345/// X*Scale+Offset.
7346///
7347static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007348 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007349 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007350 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007351 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007352 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007353 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007354 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7355 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7356 if (I->getOpcode() == Instruction::Shl) {
7357 // This is a value scaled by '1 << the shift amt'.
7358 Scale = 1U << RHS->getZExtValue();
7359 Offset = 0;
7360 return I->getOperand(0);
7361 } else if (I->getOpcode() == Instruction::Mul) {
7362 // This value is scaled by 'RHS'.
7363 Scale = RHS->getZExtValue();
7364 Offset = 0;
7365 return I->getOperand(0);
7366 } else if (I->getOpcode() == Instruction::Add) {
7367 // We have X+C. Check to see if we really have (X*C2)+C1,
7368 // where C1 is divisible by C2.
7369 unsigned SubScale;
7370 Value *SubVal =
7371 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7372 Offset += RHS->getZExtValue();
7373 Scale = SubScale;
7374 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007375 }
7376 }
7377 }
7378
7379 // Otherwise, we can't look past this.
7380 Scale = 1;
7381 Offset = 0;
7382 return Val;
7383}
7384
7385
Chris Lattnerb3f83972005-10-24 06:03:58 +00007386/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7387/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007388Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007389 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007390 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007391
Chris Lattnerb53c2382005-10-24 06:22:12 +00007392 // Remove any uses of AI that are dead.
7393 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007394
Chris Lattnerb53c2382005-10-24 06:22:12 +00007395 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7396 Instruction *User = cast<Instruction>(*UI++);
7397 if (isInstructionTriviallyDead(User)) {
7398 while (UI != E && *UI == User)
7399 ++UI; // If this instruction uses AI more than once, don't break UI.
7400
Chris Lattnerb53c2382005-10-24 06:22:12 +00007401 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007402 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007403 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007404 }
7405 }
7406
Chris Lattnerb3f83972005-10-24 06:03:58 +00007407 // Get the type really allocated and the type casted to.
7408 const Type *AllocElTy = AI.getAllocatedType();
7409 const Type *CastElTy = PTy->getElementType();
7410 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007411
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007412 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7413 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007414 if (CastElTyAlign < AllocElTyAlign) return 0;
7415
Chris Lattner39387a52005-10-24 06:35:18 +00007416 // If the allocation has multiple uses, only promote it if we are strictly
7417 // increasing the alignment of the resultant allocation. If we keep it the
7418 // same, we open the door to infinite loops of various kinds.
7419 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7420
Duncan Sands514ab342007-11-01 20:53:16 +00007421 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7422 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007423 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007424
Chris Lattner455fcc82005-10-29 03:19:53 +00007425 // See if we can satisfy the modulus by pulling a scale out of the array
7426 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007427 unsigned ArraySizeScale;
7428 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007429 Value *NumElements = // See if the array size is a decomposable linear expr.
7430 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7431
Chris Lattner455fcc82005-10-29 03:19:53 +00007432 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7433 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007434 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7435 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007436
Chris Lattner455fcc82005-10-29 03:19:53 +00007437 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7438 Value *Amt = 0;
7439 if (Scale == 1) {
7440 Amt = NumElements;
7441 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007442 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007443 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7444 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007445 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007446 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007447 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007448 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007449 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007450 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007451 }
7452
Jeff Cohen86796be2007-04-04 16:58:57 +00007453 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7454 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007455 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007456 Amt = InsertNewInstBefore(Tmp, AI);
7457 }
7458
Chris Lattnerb3f83972005-10-24 06:03:58 +00007459 AllocationInst *New;
7460 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007461 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007462 else
Chris Lattner6934a042007-02-11 01:23:03 +00007463 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007464 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007465 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007466
7467 // If the allocation has multiple uses, insert a cast and change all things
7468 // that used it to use the new cast. This will also hack on CI, but it will
7469 // die soon.
7470 if (!AI.hasOneUse()) {
7471 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007472 // New is the allocation instruction, pointer typed. AI is the original
7473 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7474 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007475 InsertNewInstBefore(NewCast, AI);
7476 AI.replaceAllUsesWith(NewCast);
7477 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007478 return ReplaceInstUsesWith(CI, New);
7479}
7480
Chris Lattner70074e02006-05-13 02:06:03 +00007481/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007482/// and return it as type Ty without inserting any new casts and without
7483/// changing the computed value. This is used by code that tries to decide
7484/// whether promoting or shrinking integer operations to wider or smaller types
7485/// will allow us to eliminate a truncate or extend.
7486///
7487/// This is a truncation operation if Ty is smaller than V->getType(), or an
7488/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00007489bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7490 unsigned CastOpc,
7491 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007492 // We can always evaluate constants in another type.
7493 if (isa<ConstantInt>(V))
7494 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007495
7496 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007497 if (!I) return false;
7498
7499 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007500
Chris Lattner951626b2007-08-02 06:11:14 +00007501 // If this is an extension or truncate, we can often eliminate it.
7502 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7503 // If this is a cast from the destination type, we can trivially eliminate
7504 // it, and this will remove a cast overall.
7505 if (I->getOperand(0)->getType() == Ty) {
7506 // If the first operand is itself a cast, and is eliminable, do not count
7507 // this as an eliminable cast. We would prefer to eliminate those two
7508 // casts first.
7509 if (!isa<CastInst>(I->getOperand(0)))
7510 ++NumCastsRemoved;
7511 return true;
7512 }
7513 }
7514
7515 // We can't extend or shrink something that has multiple uses: doing so would
7516 // require duplicating the instruction in general, which isn't profitable.
7517 if (!I->hasOneUse()) return false;
7518
Chris Lattner70074e02006-05-13 02:06:03 +00007519 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007520 case Instruction::Add:
7521 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00007522 case Instruction::And:
7523 case Instruction::Or:
7524 case Instruction::Xor:
7525 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007526 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7527 NumCastsRemoved) &&
7528 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7529 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007530
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007531 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007532 // A multiply can be truncated by truncating its operands.
7533 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7534 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7535 NumCastsRemoved) &&
7536 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7537 NumCastsRemoved);
7538
Chris Lattner46b96052006-11-29 07:18:39 +00007539 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007540 // If we are truncating the result of this SHL, and if it's a shift of a
7541 // constant amount, we can always perform a SHL in a smaller type.
7542 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007543 uint32_t BitWidth = Ty->getBitWidth();
7544 if (BitWidth < OrigTy->getBitWidth() &&
7545 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007546 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7547 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007548 }
7549 break;
7550 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007551 // If this is a truncate of a logical shr, we can truncate it to a smaller
7552 // lshr iff we know that the bits we would otherwise be shifting in are
7553 // already zeros.
7554 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007555 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7556 uint32_t BitWidth = Ty->getBitWidth();
7557 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007558 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007559 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7560 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007561 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7562 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007563 }
7564 }
Chris Lattner46b96052006-11-29 07:18:39 +00007565 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007566 case Instruction::ZExt:
7567 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007568 case Instruction::Trunc:
7569 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007570 // can safely replace it. Note that replacing it does not reduce the number
7571 // of casts in the input.
7572 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007573 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00007574
Reid Spencer3da59db2006-11-27 01:05:10 +00007575 break;
7576 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007577 // TODO: Can handle more cases here.
7578 break;
7579 }
7580
7581 return false;
7582}
7583
7584/// EvaluateInDifferentType - Given an expression that
7585/// CanEvaluateInDifferentType returns true for, actually insert the code to
7586/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007587Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007588 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007589 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007590 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007591
7592 // Otherwise, it must be an instruction.
7593 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007594 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007595 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007596 case Instruction::Add:
7597 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007598 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007599 case Instruction::And:
7600 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007601 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007602 case Instruction::AShr:
7603 case Instruction::LShr:
7604 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007605 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007606 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007607 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00007608 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00007609 break;
7610 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007611 case Instruction::Trunc:
7612 case Instruction::ZExt:
7613 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007614 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007615 // just return the source. There's no need to insert it because it is not
7616 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007617 if (I->getOperand(0)->getType() == Ty)
7618 return I->getOperand(0);
7619
Chris Lattner951626b2007-08-02 06:11:14 +00007620 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007621 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00007622 Ty, I->getName());
7623 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007624 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007625 // TODO: Can handle more cases here.
7626 assert(0 && "Unreachable!");
7627 break;
7628 }
7629
7630 return InsertNewInstBefore(Res, *I);
7631}
7632
Reid Spencer3da59db2006-11-27 01:05:10 +00007633/// @brief Implement the transforms common to all CastInst visitors.
7634Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007635 Value *Src = CI.getOperand(0);
7636
Dan Gohman23d9d272007-05-11 21:10:54 +00007637 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007638 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007639 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007640 if (Instruction::CastOps opc =
7641 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7642 // The first cast (CSrc) is eliminable so we need to fix up or replace
7643 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007644 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007645 }
7646 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007647
Reid Spencer3da59db2006-11-27 01:05:10 +00007648 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007649 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7650 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7651 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007652
7653 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007654 if (isa<PHINode>(Src))
7655 if (Instruction *NV = FoldOpIntoPhi(CI))
7656 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007657
Reid Spencer3da59db2006-11-27 01:05:10 +00007658 return 0;
7659}
7660
Chris Lattnerd3e28342007-04-27 17:44:50 +00007661/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7662Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7663 Value *Src = CI.getOperand(0);
7664
Chris Lattnerd3e28342007-04-27 17:44:50 +00007665 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007666 // If casting the result of a getelementptr instruction with no offset, turn
7667 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007668 if (GEP->hasAllZeroIndices()) {
7669 // Changing the cast operand is usually not a good idea but it is safe
7670 // here because the pointer operand is being replaced with another
7671 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007672 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007673 CI.setOperand(0, GEP->getOperand(0));
7674 return &CI;
7675 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007676
7677 // If the GEP has a single use, and the base pointer is a bitcast, and the
7678 // GEP computes a constant offset, see if we can convert these three
7679 // instructions into fewer. This typically happens with unions and other
7680 // non-type-safe code.
7681 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7682 if (GEP->hasAllConstantIndices()) {
7683 // We are guaranteed to get a constant from EmitGEPOffset.
7684 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7685 int64_t Offset = OffsetV->getSExtValue();
7686
7687 // Get the base pointer input of the bitcast, and the type it points to.
7688 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7689 const Type *GEPIdxTy =
7690 cast<PointerType>(OrigBase->getType())->getElementType();
7691 if (GEPIdxTy->isSized()) {
7692 SmallVector<Value*, 8> NewIndices;
7693
Chris Lattnerc42e2262007-05-05 01:59:31 +00007694 // Start with the index over the outer type. Note that the type size
7695 // might be zero (even if the offset isn't zero) if the indexed type
7696 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007697 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007698 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007699 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007700 FirstIdx = Offset/TySize;
7701 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007702
Chris Lattnerc42e2262007-05-05 01:59:31 +00007703 // Handle silly modulus not returning values values [0..TySize).
7704 if (Offset < 0) {
7705 --FirstIdx;
7706 Offset += TySize;
7707 assert(Offset >= 0);
7708 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007709 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007710 }
7711
7712 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007713
7714 // Index into the types. If we fail, set OrigBase to null.
7715 while (Offset) {
7716 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7717 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007718 if (Offset < (int64_t)SL->getSizeInBytes()) {
7719 unsigned Elt = SL->getElementContainingOffset(Offset);
7720 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007721
Chris Lattner6b6aef82007-05-15 00:16:00 +00007722 Offset -= SL->getElementOffset(Elt);
7723 GEPIdxTy = STy->getElementType(Elt);
7724 } else {
7725 // Otherwise, we can't index into this, bail out.
7726 Offset = 0;
7727 OrigBase = 0;
7728 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007729 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7730 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007731 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007732 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7733 Offset %= EltSize;
7734 } else {
7735 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7736 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007737 GEPIdxTy = STy->getElementType();
7738 } else {
7739 // Otherwise, we can't index into this, bail out.
7740 Offset = 0;
7741 OrigBase = 0;
7742 }
7743 }
7744 if (OrigBase) {
7745 // If we were able to index down into an element, create the GEP
7746 // and bitcast the result. This eliminates one bitcast, potentially
7747 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007748 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7749 NewIndices.begin(),
7750 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007751 InsertNewInstBefore(NGEP, CI);
7752 NGEP->takeName(GEP);
7753
Chris Lattner9bc14642007-04-28 00:57:34 +00007754 if (isa<BitCastInst>(CI))
7755 return new BitCastInst(NGEP, CI.getType());
7756 assert(isa<PtrToIntInst>(CI));
7757 return new PtrToIntInst(NGEP, CI.getType());
7758 }
7759 }
7760 }
7761 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007762 }
7763
7764 return commonCastTransforms(CI);
7765}
7766
7767
7768
Chris Lattnerc739cd62007-03-03 05:27:34 +00007769/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7770/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007771/// cases.
7772/// @brief Implement the transforms common to CastInst with integer operands
7773Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7774 if (Instruction *Result = commonCastTransforms(CI))
7775 return Result;
7776
7777 Value *Src = CI.getOperand(0);
7778 const Type *SrcTy = Src->getType();
7779 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007780 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7781 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007782
Reid Spencer3da59db2006-11-27 01:05:10 +00007783 // See if we can simplify any instructions used by the LHS whose sole
7784 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007785 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7786 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007787 KnownZero, KnownOne))
7788 return &CI;
7789
7790 // If the source isn't an instruction or has more than one use then we
7791 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007792 Instruction *SrcI = dyn_cast<Instruction>(Src);
7793 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007794 return 0;
7795
Chris Lattnerc739cd62007-03-03 05:27:34 +00007796 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007797 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007798 if (!isa<BitCastInst>(CI) &&
7799 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007800 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007801 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007802 // eliminates the cast, so it is always a win. If this is a zero-extension,
7803 // we need to do an AND to maintain the clear top-part of the computation,
7804 // so we require that the input have eliminated at least one cast. If this
7805 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007806 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007807 bool DoXForm;
7808 switch (CI.getOpcode()) {
7809 default:
7810 // All the others use floating point so we shouldn't actually
7811 // get here because of the check above.
7812 assert(0 && "Unknown cast type");
7813 case Instruction::Trunc:
7814 DoXForm = true;
7815 break;
7816 case Instruction::ZExt:
7817 DoXForm = NumCastsRemoved >= 1;
7818 break;
7819 case Instruction::SExt:
7820 DoXForm = NumCastsRemoved >= 2;
7821 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007822 }
7823
7824 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007825 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7826 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007827 assert(Res->getType() == DestTy);
7828 switch (CI.getOpcode()) {
7829 default: assert(0 && "Unknown cast type!");
7830 case Instruction::Trunc:
7831 case Instruction::BitCast:
7832 // Just replace this cast with the result.
7833 return ReplaceInstUsesWith(CI, Res);
7834 case Instruction::ZExt: {
7835 // We need to emit an AND to clear the high bits.
7836 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007837 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7838 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007839 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007840 }
7841 case Instruction::SExt:
7842 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007843 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007844 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7845 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007846 }
7847 }
7848 }
7849
7850 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7851 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7852
7853 switch (SrcI->getOpcode()) {
7854 case Instruction::Add:
7855 case Instruction::Mul:
7856 case Instruction::And:
7857 case Instruction::Or:
7858 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007859 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007860 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7861 // Don't insert two casts if they cannot be eliminated. We allow
7862 // two casts to be inserted if the sizes are the same. This could
7863 // only be converting signedness, which is a noop.
7864 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007865 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7866 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007867 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007868 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7869 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007870 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007871 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007872 }
7873 }
7874
7875 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7876 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7877 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007878 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007879 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007880 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007881 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007882 }
7883 break;
7884 case Instruction::SDiv:
7885 case Instruction::UDiv:
7886 case Instruction::SRem:
7887 case Instruction::URem:
7888 // If we are just changing the sign, rewrite.
7889 if (DestBitSize == SrcBitSize) {
7890 // Don't insert two casts if they cannot be eliminated. We allow
7891 // two casts to be inserted if the sizes are the same. This could
7892 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007893 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7894 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007895 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7896 Op0, DestTy, SrcI);
7897 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7898 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007899 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007900 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7901 }
7902 }
7903 break;
7904
7905 case Instruction::Shl:
7906 // Allow changing the sign of the source operand. Do not allow
7907 // changing the size of the shift, UNLESS the shift amount is a
7908 // constant. We must not change variable sized shifts to a smaller
7909 // size, because it is undefined to shift more bits out than exist
7910 // in the value.
7911 if (DestBitSize == SrcBitSize ||
7912 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007913 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7914 Instruction::BitCast : Instruction::Trunc);
7915 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007916 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007917 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007918 }
7919 break;
7920 case Instruction::AShr:
7921 // If this is a signed shr, and if all bits shifted in are about to be
7922 // truncated off, turn it into an unsigned shr to allow greater
7923 // simplifications.
7924 if (DestBitSize < SrcBitSize &&
7925 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007926 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007927 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7928 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007929 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007930 }
7931 }
7932 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007933 }
7934 return 0;
7935}
7936
Chris Lattner8a9f5712007-04-11 06:57:46 +00007937Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007938 if (Instruction *Result = commonIntCastTransforms(CI))
7939 return Result;
7940
7941 Value *Src = CI.getOperand(0);
7942 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007943 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7944 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007945
7946 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7947 switch (SrcI->getOpcode()) {
7948 default: break;
7949 case Instruction::LShr:
7950 // We can shrink lshr to something smaller if we know the bits shifted in
7951 // are already zeros.
7952 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007953 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007954
7955 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007956 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007957 Value* SrcIOp0 = SrcI->getOperand(0);
7958 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007959 if (ShAmt >= DestBitWidth) // All zeros.
7960 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7961
7962 // Okay, we can shrink this. Truncate the input, then return a new
7963 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007964 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7965 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7966 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007967 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007968 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007969 } else { // This is a variable shr.
7970
7971 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7972 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7973 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007974 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007975 Value *One = ConstantInt::get(SrcI->getType(), 1);
7976
Reid Spencer832254e2007-02-02 02:16:23 +00007977 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007978 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007979 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007980 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007981 SrcI->getOperand(0),
7982 "tmp"), CI);
7983 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007984 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007985 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007986 }
7987 break;
7988 }
7989 }
7990
7991 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007992}
7993
Evan Chengb98a10e2008-03-24 00:21:34 +00007994/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7995/// in order to eliminate the icmp.
7996Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7997 bool DoXform) {
7998 // If we are just checking for a icmp eq of a single bit and zext'ing it
7999 // to an integer, then shift the bit to the appropriate place and then
8000 // cast to integer to avoid the comparison.
8001 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8002 const APInt &Op1CV = Op1C->getValue();
8003
8004 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8005 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8006 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8007 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8008 if (!DoXform) return ICI;
8009
8010 Value *In = ICI->getOperand(0);
8011 Value *Sh = ConstantInt::get(In->getType(),
8012 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008013 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008014 In->getName()+".lobit"),
8015 CI);
8016 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008017 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008018 false/*ZExt*/, "tmp", &CI);
8019
8020 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8021 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008022 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008023 In->getName()+".not"),
8024 CI);
8025 }
8026
8027 return ReplaceInstUsesWith(CI, In);
8028 }
8029
8030
8031
8032 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8033 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8034 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8035 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8036 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8037 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8038 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8039 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8040 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8041 // This only works for EQ and NE
8042 ICI->isEquality()) {
8043 // If Op1C some other power of two, convert:
8044 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8045 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8046 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8047 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8048
8049 APInt KnownZeroMask(~KnownZero);
8050 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8051 if (!DoXform) return ICI;
8052
8053 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8054 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8055 // (X&4) == 2 --> false
8056 // (X&4) != 2 --> true
8057 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8058 Res = ConstantExpr::getZExt(Res, CI.getType());
8059 return ReplaceInstUsesWith(CI, Res);
8060 }
8061
8062 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8063 Value *In = ICI->getOperand(0);
8064 if (ShiftAmt) {
8065 // Perform a logical shr by shiftamt.
8066 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008067 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008068 ConstantInt::get(In->getType(), ShiftAmt),
8069 In->getName()+".lobit"), CI);
8070 }
8071
8072 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8073 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008074 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008075 InsertNewInstBefore(cast<Instruction>(In), CI);
8076 }
8077
8078 if (CI.getType() == In->getType())
8079 return ReplaceInstUsesWith(CI, In);
8080 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008081 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008082 }
8083 }
8084 }
8085
8086 return 0;
8087}
8088
Chris Lattner8a9f5712007-04-11 06:57:46 +00008089Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008090 // If one of the common conversion will work ..
8091 if (Instruction *Result = commonIntCastTransforms(CI))
8092 return Result;
8093
8094 Value *Src = CI.getOperand(0);
8095
8096 // If this is a cast of a cast
8097 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008098 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8099 // types and if the sizes are just right we can convert this into a logical
8100 // 'and' which will be much cheaper than the pair of casts.
8101 if (isa<TruncInst>(CSrc)) {
8102 // Get the sizes of the types involved
8103 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008104 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8105 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8106 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008107 // If we're actually extending zero bits and the trunc is a no-op
8108 if (MidSize < DstSize && SrcSize == DstSize) {
8109 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00008110 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00008111 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00008112 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008113 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00008114 // Unfortunately, if the type changed, we need to cast it back.
8115 if (And->getType() != CI.getType()) {
8116 And->setName(CSrc->getName()+".mask");
8117 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008118 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00008119 }
8120 return And;
8121 }
8122 }
8123 }
8124
Evan Chengb98a10e2008-03-24 00:21:34 +00008125 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8126 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008127
Evan Chengb98a10e2008-03-24 00:21:34 +00008128 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8129 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8130 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8131 // of the (zext icmp) will be transformed.
8132 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8133 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8134 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8135 (transformZExtICmp(LHS, CI, false) ||
8136 transformZExtICmp(RHS, CI, false))) {
8137 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8138 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008139 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008140 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008141 }
8142
Reid Spencer3da59db2006-11-27 01:05:10 +00008143 return 0;
8144}
8145
Chris Lattner8a9f5712007-04-11 06:57:46 +00008146Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008147 if (Instruction *I = commonIntCastTransforms(CI))
8148 return I;
8149
Chris Lattner8a9f5712007-04-11 06:57:46 +00008150 Value *Src = CI.getOperand(0);
8151
8152 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
8153 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
8154 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
8155 // If we are just checking for a icmp eq of a single bit and zext'ing it
8156 // to an integer, then shift the bit to the appropriate place and then
8157 // cast to integer to avoid the comparison.
8158 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8159 const APInt &Op1CV = Op1C->getValue();
8160
8161 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8162 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8163 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8164 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
8165 Value *In = ICI->getOperand(0);
8166 Value *Sh = ConstantInt::get(In->getType(),
8167 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008168 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00008169 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008170 CI);
8171 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008172 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008173 true/*SExt*/, "tmp", &CI);
8174
8175 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008176 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00008177 In->getName()+".not"), CI);
8178
8179 return ReplaceInstUsesWith(CI, In);
8180 }
8181 }
8182 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00008183
8184 // See if the value being truncated is already sign extended. If so, just
8185 // eliminate the trunc/sext pair.
8186 if (getOpcode(Src) == Instruction::Trunc) {
8187 Value *Op = cast<User>(Src)->getOperand(0);
8188 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8189 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8190 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8191 unsigned NumSignBits = ComputeNumSignBits(Op);
8192
8193 if (OpBits == DestBits) {
8194 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8195 // bits, it is already ready.
8196 if (NumSignBits > DestBits-MidBits)
8197 return ReplaceInstUsesWith(CI, Op);
8198 } else if (OpBits < DestBits) {
8199 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8200 // bits, just sext from i32.
8201 if (NumSignBits > OpBits-MidBits)
8202 return new SExtInst(Op, CI.getType(), "tmp");
8203 } else {
8204 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8205 // bits, just truncate to i32.
8206 if (NumSignBits > OpBits-MidBits)
8207 return new TruncInst(Op, CI.getType(), "tmp");
8208 }
8209 }
Chris Lattner8a9f5712007-04-11 06:57:46 +00008210
Chris Lattnerba417832007-04-11 06:12:58 +00008211 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008212}
8213
Chris Lattnerb7530652008-01-27 05:29:54 +00008214/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8215/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008216static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008217 APFloat F = CFP->getValueAPF();
8218 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00008219 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008220 return 0;
8221}
8222
8223/// LookThroughFPExtensions - If this is an fp extension instruction, look
8224/// through it until we get the source value.
8225static Value *LookThroughFPExtensions(Value *V) {
8226 if (Instruction *I = dyn_cast<Instruction>(V))
8227 if (I->getOpcode() == Instruction::FPExt)
8228 return LookThroughFPExtensions(I->getOperand(0));
8229
8230 // If this value is a constant, return the constant in the smallest FP type
8231 // that can accurately represent it. This allows us to turn
8232 // (float)((double)X+2.0) into x+2.0f.
8233 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8234 if (CFP->getType() == Type::PPC_FP128Ty)
8235 return V; // No constant folding of this.
8236 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008237 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008238 return V;
8239 if (CFP->getType() == Type::DoubleTy)
8240 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008241 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008242 return V;
8243 // Don't try to shrink to various long double types.
8244 }
8245
8246 return V;
8247}
8248
8249Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8250 if (Instruction *I = commonCastTransforms(CI))
8251 return I;
8252
8253 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8254 // smaller than the destination type, we can eliminate the truncate by doing
8255 // the add as the smaller type. This applies to add/sub/mul/div as well as
8256 // many builtins (sqrt, etc).
8257 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8258 if (OpI && OpI->hasOneUse()) {
8259 switch (OpI->getOpcode()) {
8260 default: break;
8261 case Instruction::Add:
8262 case Instruction::Sub:
8263 case Instruction::Mul:
8264 case Instruction::FDiv:
8265 case Instruction::FRem:
8266 const Type *SrcTy = OpI->getType();
8267 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8268 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8269 if (LHSTrunc->getType() != SrcTy &&
8270 RHSTrunc->getType() != SrcTy) {
8271 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8272 // If the source types were both smaller than the destination type of
8273 // the cast, do this xform.
8274 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8275 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8276 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8277 CI.getType(), CI);
8278 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8279 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008280 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008281 }
8282 }
8283 break;
8284 }
8285 }
8286 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008287}
8288
8289Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8290 return commonCastTransforms(CI);
8291}
8292
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008293Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8294 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
8295 // mantissa to accurately represent all values of X. For example, do not
8296 // do this with i64->float->i64.
8297 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8298 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8299 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00008300 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008301 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8302
8303 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008304}
8305
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008306Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8307 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
8308 // mantissa to accurately represent all values of X. For example, do not
8309 // do this with i64->float->i64.
8310 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8311 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8312 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00008313 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008314 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8315
8316 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008317}
8318
8319Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8320 return commonCastTransforms(CI);
8321}
8322
8323Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8324 return commonCastTransforms(CI);
8325}
8326
8327Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008328 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008329}
8330
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008331Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8332 if (Instruction *I = commonCastTransforms(CI))
8333 return I;
8334
8335 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8336 if (!DestPointee->isSized()) return 0;
8337
8338 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8339 ConstantInt *Cst;
8340 Value *X;
8341 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8342 m_ConstantInt(Cst)))) {
8343 // If the source and destination operands have the same type, see if this
8344 // is a single-index GEP.
8345 if (X->getType() == CI.getType()) {
8346 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00008347 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008348
8349 // Convert the constant to intptr type.
8350 APInt Offset = Cst->getValue();
8351 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8352
8353 // If Offset is evenly divisible by Size, we can do this xform.
8354 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8355 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008356 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008357 }
8358 }
8359 // TODO: Could handle other cases, e.g. where add is indexing into field of
8360 // struct etc.
8361 } else if (CI.getOperand(0)->hasOneUse() &&
8362 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8363 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8364 // "inttoptr+GEP" instead of "add+intptr".
8365
8366 // Get the size of the pointee type.
8367 uint64_t Size = TD->getABITypeSize(DestPointee);
8368
8369 // Convert the constant to intptr type.
8370 APInt Offset = Cst->getValue();
8371 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8372
8373 // If Offset is evenly divisible by Size, we can do this xform.
8374 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8375 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8376
8377 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8378 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008379 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008380 }
8381 }
8382 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008383}
8384
Chris Lattnerd3e28342007-04-27 17:44:50 +00008385Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008386 // If the operands are integer typed then apply the integer transforms,
8387 // otherwise just apply the common ones.
8388 Value *Src = CI.getOperand(0);
8389 const Type *SrcTy = Src->getType();
8390 const Type *DestTy = CI.getType();
8391
Chris Lattner42a75512007-01-15 02:27:26 +00008392 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008393 if (Instruction *Result = commonIntCastTransforms(CI))
8394 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008395 } else if (isa<PointerType>(SrcTy)) {
8396 if (Instruction *I = commonPointerCastTransforms(CI))
8397 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008398 } else {
8399 if (Instruction *Result = commonCastTransforms(CI))
8400 return Result;
8401 }
8402
8403
8404 // Get rid of casts from one type to the same type. These are useless and can
8405 // be replaced by the operand.
8406 if (DestTy == Src->getType())
8407 return ReplaceInstUsesWith(CI, Src);
8408
Reid Spencer3da59db2006-11-27 01:05:10 +00008409 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008410 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8411 const Type *DstElTy = DstPTy->getElementType();
8412 const Type *SrcElTy = SrcPTy->getElementType();
8413
Nate Begeman83ad90a2008-03-31 00:22:16 +00008414 // If the address spaces don't match, don't eliminate the bitcast, which is
8415 // required for changing types.
8416 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8417 return 0;
8418
Chris Lattnerd3e28342007-04-27 17:44:50 +00008419 // If we are casting a malloc or alloca to a pointer to a type of the same
8420 // size, rewrite the allocation instruction to allocate the "right" type.
8421 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8422 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8423 return V;
8424
Chris Lattnerd717c182007-05-05 22:32:24 +00008425 // If the source and destination are pointers, and this cast is equivalent
8426 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008427 // This can enhance SROA and other transforms that want type-safe pointers.
8428 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8429 unsigned NumZeros = 0;
8430 while (SrcElTy != DstElTy &&
8431 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8432 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8433 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8434 ++NumZeros;
8435 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008436
Chris Lattnerd3e28342007-04-27 17:44:50 +00008437 // If we found a path from the src to dest, create the getelementptr now.
8438 if (SrcElTy == DstElTy) {
8439 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008440 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8441 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008442 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008443 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008444
Reid Spencer3da59db2006-11-27 01:05:10 +00008445 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8446 if (SVI->hasOneUse()) {
8447 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8448 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008449 if (isa<VectorType>(DestTy) &&
8450 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00008451 SVI->getType()->getNumElements()) {
8452 CastInst *Tmp;
8453 // If either of the operands is a cast from CI.getType(), then
8454 // evaluating the shuffle in the casted destination's type will allow
8455 // us to eliminate at least one cast.
8456 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8457 Tmp->getOperand(0)->getType() == DestTy) ||
8458 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8459 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008460 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8461 SVI->getOperand(0), DestTy, &CI);
8462 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8463 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008464 // Return a new shuffle vector. Use the same element ID's, as we
8465 // know the vector types match #elts.
8466 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008467 }
8468 }
8469 }
8470 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008471 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008472}
8473
Chris Lattnere576b912004-04-09 23:46:01 +00008474/// GetSelectFoldableOperands - We want to turn code that looks like this:
8475/// %C = or %A, %B
8476/// %D = select %cond, %C, %A
8477/// into:
8478/// %C = select %cond, %B, 0
8479/// %D = or %A, %C
8480///
8481/// Assuming that the specified instruction is an operand to the select, return
8482/// a bitmask indicating which operands of this instruction are foldable if they
8483/// equal the other incoming value of the select.
8484///
8485static unsigned GetSelectFoldableOperands(Instruction *I) {
8486 switch (I->getOpcode()) {
8487 case Instruction::Add:
8488 case Instruction::Mul:
8489 case Instruction::And:
8490 case Instruction::Or:
8491 case Instruction::Xor:
8492 return 3; // Can fold through either operand.
8493 case Instruction::Sub: // Can only fold on the amount subtracted.
8494 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008495 case Instruction::LShr:
8496 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008497 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008498 default:
8499 return 0; // Cannot fold
8500 }
8501}
8502
8503/// GetSelectFoldableConstant - For the same transformation as the previous
8504/// function, return the identity constant that goes into the select.
8505static Constant *GetSelectFoldableConstant(Instruction *I) {
8506 switch (I->getOpcode()) {
8507 default: assert(0 && "This cannot happen!"); abort();
8508 case Instruction::Add:
8509 case Instruction::Sub:
8510 case Instruction::Or:
8511 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008512 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008513 case Instruction::LShr:
8514 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008515 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008516 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008517 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008518 case Instruction::Mul:
8519 return ConstantInt::get(I->getType(), 1);
8520 }
8521}
8522
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008523/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8524/// have the same opcode and only one use each. Try to simplify this.
8525Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8526 Instruction *FI) {
8527 if (TI->getNumOperands() == 1) {
8528 // If this is a non-volatile load or a cast from the same type,
8529 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008530 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008531 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8532 return 0;
8533 } else {
8534 return 0; // unknown unary op.
8535 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008536
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008537 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008538 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8539 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008540 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008541 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008542 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008543 }
8544
Reid Spencer832254e2007-02-02 02:16:23 +00008545 // Only handle binary operators here.
8546 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008547 return 0;
8548
8549 // Figure out if the operations have any operands in common.
8550 Value *MatchOp, *OtherOpT, *OtherOpF;
8551 bool MatchIsOpZero;
8552 if (TI->getOperand(0) == FI->getOperand(0)) {
8553 MatchOp = TI->getOperand(0);
8554 OtherOpT = TI->getOperand(1);
8555 OtherOpF = FI->getOperand(1);
8556 MatchIsOpZero = true;
8557 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8558 MatchOp = TI->getOperand(1);
8559 OtherOpT = TI->getOperand(0);
8560 OtherOpF = FI->getOperand(0);
8561 MatchIsOpZero = false;
8562 } else if (!TI->isCommutative()) {
8563 return 0;
8564 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8565 MatchOp = TI->getOperand(0);
8566 OtherOpT = TI->getOperand(1);
8567 OtherOpF = FI->getOperand(0);
8568 MatchIsOpZero = true;
8569 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8570 MatchOp = TI->getOperand(1);
8571 OtherOpT = TI->getOperand(0);
8572 OtherOpF = FI->getOperand(1);
8573 MatchIsOpZero = true;
8574 } else {
8575 return 0;
8576 }
8577
8578 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008579 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8580 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008581 InsertNewInstBefore(NewSI, SI);
8582
8583 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8584 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008585 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008586 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008587 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008588 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008589 assert(0 && "Shouldn't get here");
8590 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008591}
8592
Chris Lattner3d69f462004-03-12 05:52:32 +00008593Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008594 Value *CondVal = SI.getCondition();
8595 Value *TrueVal = SI.getTrueValue();
8596 Value *FalseVal = SI.getFalseValue();
8597
8598 // select true, X, Y -> X
8599 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008600 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008601 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008602
8603 // select C, X, X -> X
8604 if (TrueVal == FalseVal)
8605 return ReplaceInstUsesWith(SI, TrueVal);
8606
Chris Lattnere87597f2004-10-16 18:11:37 +00008607 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8608 return ReplaceInstUsesWith(SI, FalseVal);
8609 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8610 return ReplaceInstUsesWith(SI, TrueVal);
8611 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8612 if (isa<Constant>(TrueVal))
8613 return ReplaceInstUsesWith(SI, TrueVal);
8614 else
8615 return ReplaceInstUsesWith(SI, FalseVal);
8616 }
8617
Reid Spencer4fe16d62007-01-11 18:21:29 +00008618 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008619 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008620 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008621 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008622 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008623 } else {
8624 // Change: A = select B, false, C --> A = and !B, C
8625 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008626 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008627 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008628 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008629 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008630 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008631 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008632 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008633 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008634 } else {
8635 // Change: A = select B, C, true --> A = or !B, C
8636 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008637 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008638 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008639 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008640 }
8641 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008642
8643 // select a, b, a -> a&b
8644 // select a, a, b -> a|b
8645 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008646 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008647 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008648 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008649 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008650
Chris Lattner2eefe512004-04-09 19:05:30 +00008651 // Selecting between two integer constants?
8652 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8653 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008654 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008655 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008656 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008657 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008658 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008659 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008660 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008661 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008662 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008663 }
Chris Lattnerba417832007-04-11 06:12:58 +00008664
8665 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008666
Reid Spencere4d87aa2006-12-23 06:05:41 +00008667 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008668
Reid Spencere4d87aa2006-12-23 06:05:41 +00008669 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008670 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008671 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008672 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008673 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008674 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008675 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008676 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008677 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008678 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008679 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008680 InsertNewInstBefore(SRA, SI);
8681
Reid Spencer3da59db2006-11-27 01:05:10 +00008682 // Finally, convert to the type of the select RHS. We figure out
8683 // if this requires a SExt, Trunc or BitCast based on the sizes.
8684 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008685 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8686 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008687 if (SRASize < SISize)
8688 opc = Instruction::SExt;
8689 else if (SRASize > SISize)
8690 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008691 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008692 }
8693 }
8694
8695
8696 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008697 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008698 // non-constant value, eliminate this whole mess. This corresponds to
8699 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008700 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008701 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008702 cast<Constant>(IC->getOperand(1))->isNullValue())
8703 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8704 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008705 isa<ConstantInt>(ICA->getOperand(1)) &&
8706 (ICA->getOperand(1) == TrueValC ||
8707 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008708 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8709 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008710 // know whether we have a icmp_ne or icmp_eq and whether the
8711 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008712 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008713 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008714 Value *V = ICA;
8715 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008716 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008717 Instruction::Xor, V, ICA->getOperand(1)), SI);
8718 return ReplaceInstUsesWith(SI, V);
8719 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008720 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008721 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008722
8723 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008724 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8725 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008726 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008727 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8728 // This is not safe in general for floating point:
8729 // consider X== -0, Y== +0.
8730 // It becomes safe if either operand is a nonzero constant.
8731 ConstantFP *CFPt, *CFPf;
8732 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8733 !CFPt->getValueAPF().isZero()) ||
8734 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8735 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008736 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008737 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008738 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008739 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008740 return ReplaceInstUsesWith(SI, TrueVal);
8741 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8742
Reid Spencere4d87aa2006-12-23 06:05:41 +00008743 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008744 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008745 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8746 // This is not safe in general for floating point:
8747 // consider X== -0, Y== +0.
8748 // It becomes safe if either operand is a nonzero constant.
8749 ConstantFP *CFPt, *CFPf;
8750 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8751 !CFPt->getValueAPF().isZero()) ||
8752 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8753 !CFPf->getValueAPF().isZero()))
8754 return ReplaceInstUsesWith(SI, FalseVal);
8755 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008756 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008757 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8758 return ReplaceInstUsesWith(SI, TrueVal);
8759 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8760 }
8761 }
8762
8763 // See if we are selecting two values based on a comparison of the two values.
8764 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8765 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8766 // Transform (X == Y) ? X : Y -> Y
8767 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8768 return ReplaceInstUsesWith(SI, FalseVal);
8769 // Transform (X != Y) ? X : Y -> X
8770 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8771 return ReplaceInstUsesWith(SI, TrueVal);
8772 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8773
8774 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8775 // Transform (X == Y) ? Y : X -> X
8776 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8777 return ReplaceInstUsesWith(SI, FalseVal);
8778 // Transform (X != Y) ? Y : X -> Y
8779 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008780 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008781 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8782 }
8783 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008784
Chris Lattner87875da2005-01-13 22:52:24 +00008785 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8786 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8787 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008788 Instruction *AddOp = 0, *SubOp = 0;
8789
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008790 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8791 if (TI->getOpcode() == FI->getOpcode())
8792 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8793 return IV;
8794
8795 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8796 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008797 if (TI->getOpcode() == Instruction::Sub &&
8798 FI->getOpcode() == Instruction::Add) {
8799 AddOp = FI; SubOp = TI;
8800 } else if (FI->getOpcode() == Instruction::Sub &&
8801 TI->getOpcode() == Instruction::Add) {
8802 AddOp = TI; SubOp = FI;
8803 }
8804
8805 if (AddOp) {
8806 Value *OtherAddOp = 0;
8807 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8808 OtherAddOp = AddOp->getOperand(1);
8809 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8810 OtherAddOp = AddOp->getOperand(0);
8811 }
8812
8813 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008814 // So at this point we know we have (Y -> OtherAddOp):
8815 // select C, (add X, Y), (sub X, Z)
8816 Value *NegVal; // Compute -Z
8817 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8818 NegVal = ConstantExpr::getNeg(C);
8819 } else {
8820 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008821 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008822 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008823
8824 Value *NewTrueOp = OtherAddOp;
8825 Value *NewFalseOp = NegVal;
8826 if (AddOp != TI)
8827 std::swap(NewTrueOp, NewFalseOp);
8828 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008829 SelectInst::Create(CondVal, NewTrueOp,
8830 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008831
8832 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008833 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008834 }
8835 }
8836 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008837
Chris Lattnere576b912004-04-09 23:46:01 +00008838 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008839 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008840 // See the comment above GetSelectFoldableOperands for a description of the
8841 // transformation we are doing here.
8842 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8843 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8844 !isa<Constant>(FalseVal))
8845 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8846 unsigned OpToFold = 0;
8847 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8848 OpToFold = 1;
8849 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8850 OpToFold = 2;
8851 }
8852
8853 if (OpToFold) {
8854 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008855 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008856 SelectInst::Create(SI.getCondition(),
8857 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008858 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008859 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008860 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008861 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008862 else {
8863 assert(0 && "Unknown instruction!!");
8864 }
8865 }
8866 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008867
Chris Lattnere576b912004-04-09 23:46:01 +00008868 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8869 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8870 !isa<Constant>(TrueVal))
8871 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8872 unsigned OpToFold = 0;
8873 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8874 OpToFold = 1;
8875 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8876 OpToFold = 2;
8877 }
8878
8879 if (OpToFold) {
8880 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008881 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008882 SelectInst::Create(SI.getCondition(), C,
8883 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008884 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008885 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008886 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008887 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008888 else
Chris Lattnere576b912004-04-09 23:46:01 +00008889 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008890 }
8891 }
8892 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008893
8894 if (BinaryOperator::isNot(CondVal)) {
8895 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8896 SI.setOperand(1, FalseVal);
8897 SI.setOperand(2, TrueVal);
8898 return &SI;
8899 }
8900
Chris Lattner3d69f462004-03-12 05:52:32 +00008901 return 0;
8902}
8903
Dan Gohmaneee962e2008-04-10 18:43:06 +00008904/// EnforceKnownAlignment - If the specified pointer points to an object that
8905/// we control, modify the object's alignment to PrefAlign. This isn't
8906/// often possible though. If alignment is important, a more reliable approach
8907/// is to simply align all global variables and allocation instructions to
8908/// their preferred alignment from the beginning.
8909///
8910static unsigned EnforceKnownAlignment(Value *V,
8911 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008912
Dan Gohmaneee962e2008-04-10 18:43:06 +00008913 User *U = dyn_cast<User>(V);
8914 if (!U) return Align;
8915
8916 switch (getOpcode(U)) {
8917 default: break;
8918 case Instruction::BitCast:
8919 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8920 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008921 // If all indexes are zero, it is just the alignment of the base pointer.
8922 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008923 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8924 if (!isa<Constant>(U->getOperand(i)) ||
8925 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008926 AllZeroOperands = false;
8927 break;
8928 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008929
8930 if (AllZeroOperands) {
8931 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008932 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008933 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008934 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008935 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008936 }
8937
8938 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8939 // If there is a large requested alignment and we can, bump up the alignment
8940 // of the global.
8941 if (!GV->isDeclaration()) {
8942 GV->setAlignment(PrefAlign);
8943 Align = PrefAlign;
8944 }
8945 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8946 // If there is a requested alignment and if this is an alloca, round up. We
8947 // don't do this for malloc, because some systems can't respect the request.
8948 if (isa<AllocaInst>(AI)) {
8949 AI->setAlignment(PrefAlign);
8950 Align = PrefAlign;
8951 }
8952 }
8953
8954 return Align;
8955}
8956
8957/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8958/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8959/// and it is more than the alignment of the ultimate object, see if we can
8960/// increase the alignment of the ultimate object, making this check succeed.
8961unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8962 unsigned PrefAlign) {
8963 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8964 sizeof(PrefAlign) * CHAR_BIT;
8965 APInt Mask = APInt::getAllOnesValue(BitWidth);
8966 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8967 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8968 unsigned TrailZ = KnownZero.countTrailingOnes();
8969 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8970
8971 if (PrefAlign > Align)
8972 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8973
8974 // We don't need to make any adjustment.
8975 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008976}
8977
Chris Lattnerf497b022008-01-13 23:50:23 +00008978Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008979 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8980 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008981 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8982 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8983
8984 if (CopyAlign < MinAlign) {
8985 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8986 return MI;
8987 }
8988
8989 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8990 // load/store.
8991 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8992 if (MemOpLength == 0) return 0;
8993
Chris Lattner37ac6082008-01-14 00:28:35 +00008994 // Source and destination pointer types are always "i8*" for intrinsic. See
8995 // if the size is something we can handle with a single primitive load/store.
8996 // A single load+store correctly handles overlapping memory in the memmove
8997 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008998 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008999 if (Size == 0) return MI; // Delete this mem transfer.
9000
9001 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009002 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009003
Chris Lattner37ac6082008-01-14 00:28:35 +00009004 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009005 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009006
9007 // Memcpy forces the use of i8* for the source and destination. That means
9008 // that if you're using memcpy to move one double around, you'll get a cast
9009 // from double* to i8*. We'd much rather use a double load+store rather than
9010 // an i64 load+store, here because this improves the odds that the source or
9011 // dest address will be promotable. See if we can find a better type than the
9012 // integer datatype.
9013 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9014 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9015 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9016 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9017 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009018 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009019 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9020 if (STy->getNumElements() == 1)
9021 SrcETy = STy->getElementType(0);
9022 else
9023 break;
9024 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9025 if (ATy->getNumElements() == 1)
9026 SrcETy = ATy->getElementType();
9027 else
9028 break;
9029 } else
9030 break;
9031 }
9032
Dan Gohman8f8e2692008-05-23 01:52:21 +00009033 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009034 NewPtrTy = PointerType::getUnqual(SrcETy);
9035 }
9036 }
9037
9038
Chris Lattnerf497b022008-01-13 23:50:23 +00009039 // If the memcpy/memmove provides better alignment info than we can
9040 // infer, use it.
9041 SrcAlign = std::max(SrcAlign, CopyAlign);
9042 DstAlign = std::max(DstAlign, CopyAlign);
9043
9044 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9045 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009046 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9047 InsertNewInstBefore(L, *MI);
9048 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9049
9050 // Set the size of the copy to 0, it will be deleted on the next iteration.
9051 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9052 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009053}
Chris Lattner3d69f462004-03-12 05:52:32 +00009054
Chris Lattner69ea9d22008-04-30 06:39:11 +00009055Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9056 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9057 if (MI->getAlignment()->getZExtValue() < Alignment) {
9058 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9059 return MI;
9060 }
9061
9062 // Extract the length and alignment and fill if they are constant.
9063 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9064 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9065 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9066 return 0;
9067 uint64_t Len = LenC->getZExtValue();
9068 Alignment = MI->getAlignment()->getZExtValue();
9069
9070 // If the length is zero, this is a no-op
9071 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9072
9073 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9074 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9075 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9076
9077 Value *Dest = MI->getDest();
9078 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9079
9080 // Alignment 0 is identity for alignment 1 for memset, but not store.
9081 if (Alignment == 0) Alignment = 1;
9082
9083 // Extract the fill value and store.
9084 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9085 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9086 Alignment), *MI);
9087
9088 // Set the size of the copy to 0, it will be deleted on the next iteration.
9089 MI->setLength(Constant::getNullValue(LenC->getType()));
9090 return MI;
9091 }
9092
9093 return 0;
9094}
9095
9096
Chris Lattner8b0ea312006-01-13 20:11:04 +00009097/// visitCallInst - CallInst simplification. This mostly only handles folding
9098/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9099/// the heavy lifting.
9100///
Chris Lattner9fe38862003-06-19 17:00:31 +00009101Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00009102 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9103 if (!II) return visitCallSite(&CI);
9104
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009105 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9106 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009107 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009108 bool Changed = false;
9109
9110 // memmove/cpy/set of zero bytes is a noop.
9111 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9112 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9113
Chris Lattner35b9e482004-10-12 04:52:52 +00009114 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009115 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009116 // Replace the instruction with just byte operations. We would
9117 // transform other cases to loads/stores, but we don't know if
9118 // alignment is sufficient.
9119 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009120 }
9121
Chris Lattner35b9e482004-10-12 04:52:52 +00009122 // If we have a memmove and the source operation is a constant global,
9123 // then the source and dest pointers can't alias, so we can change this
9124 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009125 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009126 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9127 if (GVSrc->isConstant()) {
9128 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00009129 Intrinsic::ID MemCpyID;
9130 if (CI.getOperand(3)->getType() == Type::Int32Ty)
9131 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00009132 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00009133 MemCpyID = Intrinsic::memcpy_i64;
9134 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00009135 Changed = true;
9136 }
Chris Lattnera935db82008-05-28 05:30:41 +00009137
9138 // memmove(x,x,size) -> noop.
9139 if (MMI->getSource() == MMI->getDest())
9140 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009141 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009142
Chris Lattner95a959d2006-03-06 20:18:44 +00009143 // If we can determine a pointer alignment that is bigger than currently
9144 // set, update the alignment.
9145 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009146 if (Instruction *I = SimplifyMemTransfer(MI))
9147 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009148 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9149 if (Instruction *I = SimplifyMemSet(MSI))
9150 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009151 }
9152
Chris Lattner8b0ea312006-01-13 20:11:04 +00009153 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00009154 } else {
9155 switch (II->getIntrinsicID()) {
9156 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00009157 case Intrinsic::ppc_altivec_lvx:
9158 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009159 case Intrinsic::x86_sse_loadu_ps:
9160 case Intrinsic::x86_sse2_loadu_pd:
9161 case Intrinsic::x86_sse2_loadu_dq:
9162 // Turn PPC lvx -> load if the pointer is known aligned.
9163 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009164 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00009165 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9166 PointerType::getUnqual(II->getType()),
9167 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009168 return new LoadInst(Ptr);
9169 }
9170 break;
9171 case Intrinsic::ppc_altivec_stvx:
9172 case Intrinsic::ppc_altivec_stvxl:
9173 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009174 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009175 const Type *OpPtrTy =
9176 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009177 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009178 return new StoreInst(II->getOperand(1), Ptr);
9179 }
9180 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009181 case Intrinsic::x86_sse_storeu_ps:
9182 case Intrinsic::x86_sse2_storeu_pd:
9183 case Intrinsic::x86_sse2_storeu_dq:
9184 case Intrinsic::x86_sse2_storel_dq:
9185 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009186 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009187 const Type *OpPtrTy =
9188 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009189 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009190 return new StoreInst(II->getOperand(2), Ptr);
9191 }
9192 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00009193
9194 case Intrinsic::x86_sse_cvttss2si: {
9195 // These intrinsics only demands the 0th element of its input vector. If
9196 // we can simplify the input based on that, do so now.
9197 uint64_t UndefElts;
9198 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9199 UndefElts)) {
9200 II->setOperand(1, V);
9201 return II;
9202 }
9203 break;
9204 }
9205
Chris Lattnere2ed0572006-04-06 19:19:17 +00009206 case Intrinsic::ppc_altivec_vperm:
9207 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009208 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00009209 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9210
9211 // Check that all of the elements are integer constants or undefs.
9212 bool AllEltsOk = true;
9213 for (unsigned i = 0; i != 16; ++i) {
9214 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9215 !isa<UndefValue>(Mask->getOperand(i))) {
9216 AllEltsOk = false;
9217 break;
9218 }
9219 }
9220
9221 if (AllEltsOk) {
9222 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00009223 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9224 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009225 Value *Result = UndefValue::get(Op0->getType());
9226
9227 // Only extract each element once.
9228 Value *ExtractedElts[32];
9229 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9230
9231 for (unsigned i = 0; i != 16; ++i) {
9232 if (isa<UndefValue>(Mask->getOperand(i)))
9233 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00009234 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00009235 Idx &= 31; // Match the hardware behavior.
9236
9237 if (ExtractedElts[Idx] == 0) {
9238 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00009239 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009240 InsertNewInstBefore(Elt, CI);
9241 ExtractedElts[Idx] = Elt;
9242 }
9243
9244 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009245 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9246 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009247 InsertNewInstBefore(cast<Instruction>(Result), CI);
9248 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009249 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009250 }
9251 }
9252 break;
9253
Chris Lattnera728ddc2006-01-13 21:28:09 +00009254 case Intrinsic::stackrestore: {
9255 // If the save is right next to the restore, remove the restore. This can
9256 // happen when variable allocas are DCE'd.
9257 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9258 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9259 BasicBlock::iterator BI = SS;
9260 if (&*++BI == II)
9261 return EraseInstFromFunction(CI);
9262 }
9263 }
9264
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009265 // Scan down this block to see if there is another stack restore in the
9266 // same block without an intervening call/alloca.
9267 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00009268 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009269 bool CannotRemove = false;
9270 for (++BI; &*BI != TI; ++BI) {
9271 if (isa<AllocaInst>(BI)) {
9272 CannotRemove = true;
9273 break;
9274 }
9275 if (isa<CallInst>(BI)) {
9276 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00009277 CannotRemove = true;
9278 break;
9279 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009280 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00009281 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009282 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009283 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009284
9285 // If the stack restore is in a return/unwind block and if there are no
9286 // allocas or calls between the restore and the return, nuke the restore.
9287 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9288 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009289 break;
9290 }
9291 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009292 }
9293
Chris Lattner8b0ea312006-01-13 20:11:04 +00009294 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009295}
9296
9297// InvokeInst simplification
9298//
9299Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009300 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009301}
9302
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009303/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9304/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009305static bool isSafeToEliminateVarargsCast(const CallSite CS,
9306 const CastInst * const CI,
9307 const TargetData * const TD,
9308 const int ix) {
9309 if (!CI->isLosslessCast())
9310 return false;
9311
9312 // The size of ByVal arguments is derived from the type, so we
9313 // can't change to a type with a different size. If the size were
9314 // passed explicitly we could avoid this check.
9315 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9316 return true;
9317
9318 const Type* SrcTy =
9319 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9320 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9321 if (!SrcTy->isSized() || !DstTy->isSized())
9322 return false;
9323 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9324 return false;
9325 return true;
9326}
9327
Chris Lattnera44d8a22003-10-07 22:32:43 +00009328// visitCallSite - Improvements for call and invoke instructions.
9329//
9330Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009331 bool Changed = false;
9332
9333 // If the callee is a constexpr cast of a function, attempt to move the cast
9334 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009335 if (transformConstExprCastCall(CS)) return 0;
9336
Chris Lattner6c266db2003-10-07 22:54:13 +00009337 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009338
Chris Lattner08b22ec2005-05-13 07:09:09 +00009339 if (Function *CalleeF = dyn_cast<Function>(Callee))
9340 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9341 Instruction *OldCall = CS.getInstruction();
9342 // If the call and callee calling conventions don't match, this call must
9343 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009344 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009345 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9346 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009347 if (!OldCall->use_empty())
9348 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9349 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9350 return EraseInstFromFunction(*OldCall);
9351 return 0;
9352 }
9353
Chris Lattner17be6352004-10-18 02:59:09 +00009354 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9355 // This instruction is not reachable, just remove it. We insert a store to
9356 // undef so that we know that this code is not reachable, despite the fact
9357 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009358 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009359 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009360 CS.getInstruction());
9361
9362 if (!CS.getInstruction()->use_empty())
9363 CS.getInstruction()->
9364 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9365
9366 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9367 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009368 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9369 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009370 }
Chris Lattner17be6352004-10-18 02:59:09 +00009371 return EraseInstFromFunction(*CS.getInstruction());
9372 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009373
Duncan Sandscdb6d922007-09-17 10:26:40 +00009374 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9375 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9376 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9377 return transformCallThroughTrampoline(CS);
9378
Chris Lattner6c266db2003-10-07 22:54:13 +00009379 const PointerType *PTy = cast<PointerType>(Callee->getType());
9380 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9381 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009382 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009383 // See if we can optimize any arguments passed through the varargs area of
9384 // the call.
9385 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009386 E = CS.arg_end(); I != E; ++I, ++ix) {
9387 CastInst *CI = dyn_cast<CastInst>(*I);
9388 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9389 *I = CI->getOperand(0);
9390 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009391 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009392 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009393 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009394
Duncan Sandsf0c33542007-12-19 21:13:37 +00009395 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009396 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009397 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009398 Changed = true;
9399 }
9400
Chris Lattner6c266db2003-10-07 22:54:13 +00009401 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009402}
9403
Chris Lattner9fe38862003-06-19 17:00:31 +00009404// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9405// attempt to move the cast to the arguments of the call/invoke.
9406//
9407bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9408 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9409 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009410 if (CE->getOpcode() != Instruction::BitCast ||
9411 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009412 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009413 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009414 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00009415 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00009416
9417 // Okay, this is a cast from a function to a different type. Unless doing so
9418 // would cause a type conversion of one of our arguments, change this call to
9419 // be a direct call with arguments casted to the appropriate types.
9420 //
9421 const FunctionType *FT = Callee->getFunctionType();
9422 const Type *OldRetTy = Caller->getType();
9423
Devang Patel75e6f022008-03-11 18:04:06 +00009424 if (isa<StructType>(FT->getReturnType()))
9425 return false; // TODO: Handle multiple return values.
9426
Chris Lattnerf78616b2004-01-14 06:06:08 +00009427 // Check to see if we are changing the return type...
9428 if (OldRetTy != FT->getReturnType()) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009429 if (Callee->isDeclaration() &&
Chris Lattner46013f42007-01-06 19:53:32 +00009430 // Conversion is ok if changing from pointer to int of same size.
9431 !(isa<PointerType>(FT->getReturnType()) &&
9432 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00009433 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009434
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009435 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009436 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00009437 FT->getReturnType() != Type::VoidTy &&
9438 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009439 return false; // Cannot transform this return value.
9440
Chris Lattner58d74912008-03-12 17:45:29 +00009441 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9442 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00009443 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9444 return false; // Attribute not compatible with transformed value.
9445 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009446
Chris Lattnerf78616b2004-01-14 06:06:08 +00009447 // If the callsite is an invoke instruction, and the return value is used by
9448 // a PHI node in a successor, we cannot change the return type of the call
9449 // because there is no place to put the cast instruction (without breaking
9450 // the critical edge). Bail out in this case.
9451 if (!Caller->use_empty())
9452 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9453 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9454 UI != E; ++UI)
9455 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9456 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009457 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009458 return false;
9459 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009460
9461 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9462 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009463
Chris Lattner9fe38862003-06-19 17:00:31 +00009464 CallSite::arg_iterator AI = CS.arg_begin();
9465 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9466 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009467 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009468
9469 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009470 return false; // Cannot transform this parameter value.
9471
Chris Lattner58d74912008-03-12 17:45:29 +00009472 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9473 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009474
Reid Spencer3da59db2006-11-27 01:05:10 +00009475 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009476 // Some conversions are safe even if we do not have a body.
9477 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00009478 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00009479 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00009480 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009481 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9482 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00009483 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00009484 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009485 }
9486
9487 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009488 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009489 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009490
Chris Lattner58d74912008-03-12 17:45:29 +00009491 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9492 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009493 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009494 // won't be dropping them. Check that these extra arguments have attributes
9495 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009496 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9497 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009498 break;
Chris Lattner58d74912008-03-12 17:45:29 +00009499 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00009500 if (PAttrs & ParamAttr::VarArgsIncompatible)
9501 return false;
9502 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009503
Chris Lattner9fe38862003-06-19 17:00:31 +00009504 // Okay, we decided that this is a safe thing to do: go ahead and start
9505 // inserting cast instructions as necessary...
9506 std::vector<Value*> Args;
9507 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00009508 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009509 attrVec.reserve(NumCommonArgs);
9510
9511 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009512 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009513
9514 // If the return value is not being used, the type may not be compatible
9515 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00009516 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009517
9518 // Add the new return attributes.
9519 if (RAttrs)
9520 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009521
9522 AI = CS.arg_begin();
9523 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9524 const Type *ParamTy = FT->getParamType(i);
9525 if ((*AI)->getType() == ParamTy) {
9526 Args.push_back(*AI);
9527 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009528 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009529 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009530 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009531 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009532 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009533
9534 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009535 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009536 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009537 }
9538
9539 // If the function takes more arguments than the call was taking, add them
9540 // now...
9541 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9542 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9543
9544 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009545 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009546 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009547 cerr << "WARNING: While resolving call to function '"
9548 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009549 } else {
9550 // Add all of the arguments in their promoted form to the arg list...
9551 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9552 const Type *PTy = getPromotedType((*AI)->getType());
9553 if (PTy != (*AI)->getType()) {
9554 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009555 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9556 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009557 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009558 InsertNewInstBefore(Cast, *Caller);
9559 Args.push_back(Cast);
9560 } else {
9561 Args.push_back(*AI);
9562 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009563
Duncan Sandse1e520f2008-01-13 08:02:44 +00009564 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009565 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009566 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9567 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009568 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009569 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009570
9571 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009572 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009573
Chris Lattner58d74912008-03-12 17:45:29 +00009574 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009575
Chris Lattner9fe38862003-06-19 17:00:31 +00009576 Instruction *NC;
9577 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009578 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009579 Args.begin(), Args.end(),
9580 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009581 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009582 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009583 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009584 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9585 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009586 CallInst *CI = cast<CallInst>(Caller);
9587 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009588 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009589 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009590 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009591 }
9592
Chris Lattner6934a042007-02-11 01:23:03 +00009593 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009594 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009595 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009596 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009597 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009598 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009599 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009600
9601 // If this is an invoke instruction, we should insert it after the first
9602 // non-phi, instruction in the normal successor block.
9603 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009604 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009605 InsertNewInstBefore(NC, *I);
9606 } else {
9607 // Otherwise, it's a call, just insert cast right after the call instr
9608 InsertNewInstBefore(NC, *Caller);
9609 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009610 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009611 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009612 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009613 }
9614 }
9615
9616 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9617 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009618 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009619 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009620 return true;
9621}
9622
Duncan Sandscdb6d922007-09-17 10:26:40 +00009623// transformCallThroughTrampoline - Turn a call to a function created by the
9624// init_trampoline intrinsic into a direct call to the underlying function.
9625//
9626Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9627 Value *Callee = CS.getCalledValue();
9628 const PointerType *PTy = cast<PointerType>(Callee->getType());
9629 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009630 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009631
9632 // If the call already has the 'nest' attribute somewhere then give up -
9633 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009634 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009635 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009636
9637 IntrinsicInst *Tramp =
9638 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9639
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009640 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009641 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9642 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9643
Chris Lattner58d74912008-03-12 17:45:29 +00009644 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9645 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009646 unsigned NestIdx = 1;
9647 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009648 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009649
9650 // Look for a parameter marked with the 'nest' attribute.
9651 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9652 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009653 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009654 // Record the parameter type and any other attributes.
9655 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009656 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009657 break;
9658 }
9659
9660 if (NestTy) {
9661 Instruction *Caller = CS.getInstruction();
9662 std::vector<Value*> NewArgs;
9663 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9664
Chris Lattner58d74912008-03-12 17:45:29 +00009665 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9666 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009667
Duncan Sandscdb6d922007-09-17 10:26:40 +00009668 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009669 // mean appending it. Likewise for attributes.
9670
9671 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009672 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9673 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009674
Duncan Sandscdb6d922007-09-17 10:26:40 +00009675 {
9676 unsigned Idx = 1;
9677 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9678 do {
9679 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009680 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009681 Value *NestVal = Tramp->getOperand(3);
9682 if (NestVal->getType() != NestTy)
9683 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9684 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009685 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009686 }
9687
9688 if (I == E)
9689 break;
9690
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009691 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009692 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009693 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009694 NewAttrs.push_back
9695 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009696
9697 ++Idx, ++I;
9698 } while (1);
9699 }
9700
9701 // The trampoline may have been bitcast to a bogus type (FTy).
9702 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009703 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009704
Duncan Sandscdb6d922007-09-17 10:26:40 +00009705 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009706 NewTypes.reserve(FTy->getNumParams()+1);
9707
Duncan Sandscdb6d922007-09-17 10:26:40 +00009708 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009709 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009710 {
9711 unsigned Idx = 1;
9712 FunctionType::param_iterator I = FTy->param_begin(),
9713 E = FTy->param_end();
9714
9715 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009716 if (Idx == NestIdx)
9717 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009718 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009719
9720 if (I == E)
9721 break;
9722
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009723 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009724 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009725
9726 ++Idx, ++I;
9727 } while (1);
9728 }
9729
9730 // Replace the trampoline call with a direct call. Let the generic
9731 // code sort out any function type mismatches.
9732 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009733 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009734 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9735 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009736 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009737
9738 Instruction *NewCaller;
9739 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009740 NewCaller = InvokeInst::Create(NewCallee,
9741 II->getNormalDest(), II->getUnwindDest(),
9742 NewArgs.begin(), NewArgs.end(),
9743 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009744 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009745 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009746 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009747 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9748 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009749 if (cast<CallInst>(Caller)->isTailCall())
9750 cast<CallInst>(NewCaller)->setTailCall();
9751 cast<CallInst>(NewCaller)->
9752 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009753 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009754 }
9755 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9756 Caller->replaceAllUsesWith(NewCaller);
9757 Caller->eraseFromParent();
9758 RemoveFromWorkList(Caller);
9759 return 0;
9760 }
9761 }
9762
9763 // Replace the trampoline call with a direct call. Since there is no 'nest'
9764 // parameter, there is no need to adjust the argument list. Let the generic
9765 // code sort out any function type mismatches.
9766 Constant *NewCallee =
9767 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9768 CS.setCalledFunction(NewCallee);
9769 return CS.getInstruction();
9770}
9771
Chris Lattner7da52b22006-11-01 04:51:18 +00009772/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9773/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9774/// and a single binop.
9775Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9776 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009777 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9778 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009779 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009780 Value *LHSVal = FirstInst->getOperand(0);
9781 Value *RHSVal = FirstInst->getOperand(1);
9782
9783 const Type *LHSType = LHSVal->getType();
9784 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009785
9786 // Scan to see if all operands are the same opcode, all have one use, and all
9787 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009788 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009789 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009790 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009791 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009792 // types or GEP's with different index types.
9793 I->getOperand(0)->getType() != LHSType ||
9794 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009795 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009796
9797 // If they are CmpInst instructions, check their predicates
9798 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9799 if (cast<CmpInst>(I)->getPredicate() !=
9800 cast<CmpInst>(FirstInst)->getPredicate())
9801 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009802
9803 // Keep track of which operand needs a phi node.
9804 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9805 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009806 }
9807
Chris Lattner53738a42006-11-08 19:42:28 +00009808 // Otherwise, this is safe to transform, determine if it is profitable.
9809
9810 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9811 // Indexes are often folded into load/store instructions, so we don't want to
9812 // hide them behind a phi.
9813 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9814 return 0;
9815
Chris Lattner7da52b22006-11-01 04:51:18 +00009816 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009817 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009818 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009819 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009820 NewLHS = PHINode::Create(LHSType,
9821 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009822 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9823 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009824 InsertNewInstBefore(NewLHS, PN);
9825 LHSVal = NewLHS;
9826 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009827
9828 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009829 NewRHS = PHINode::Create(RHSType,
9830 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009831 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9832 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009833 InsertNewInstBefore(NewRHS, PN);
9834 RHSVal = NewRHS;
9835 }
9836
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009837 // Add all operands to the new PHIs.
9838 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9839 if (NewLHS) {
9840 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9841 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9842 }
9843 if (NewRHS) {
9844 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9845 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9846 }
9847 }
9848
Chris Lattner7da52b22006-11-01 04:51:18 +00009849 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009850 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009851 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009852 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009853 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009854 else {
9855 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009856 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009857 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009858}
9859
Chris Lattner76c73142006-11-01 07:13:54 +00009860/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9861/// of the block that defines it. This means that it must be obvious the value
9862/// of the load is not changed from the point of the load to the end of the
9863/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009864///
9865/// Finally, it is safe, but not profitable, to sink a load targetting a
9866/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9867/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009868static bool isSafeToSinkLoad(LoadInst *L) {
9869 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9870
9871 for (++BBI; BBI != E; ++BBI)
9872 if (BBI->mayWriteToMemory())
9873 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009874
9875 // Check for non-address taken alloca. If not address-taken already, it isn't
9876 // profitable to do this xform.
9877 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9878 bool isAddressTaken = false;
9879 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9880 UI != E; ++UI) {
9881 if (isa<LoadInst>(UI)) continue;
9882 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9883 // If storing TO the alloca, then the address isn't taken.
9884 if (SI->getOperand(1) == AI) continue;
9885 }
9886 isAddressTaken = true;
9887 break;
9888 }
9889
9890 if (!isAddressTaken)
9891 return false;
9892 }
9893
Chris Lattner76c73142006-11-01 07:13:54 +00009894 return true;
9895}
9896
Chris Lattner9fe38862003-06-19 17:00:31 +00009897
Chris Lattnerbac32862004-11-14 19:13:23 +00009898// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9899// operator and they all are only used by the PHI, PHI together their
9900// inputs, and do the operation once, to the result of the PHI.
9901Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9902 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9903
9904 // Scan the instruction, looking for input operations that can be folded away.
9905 // If all input operands to the phi are the same instruction (e.g. a cast from
9906 // the same type or "+42") we can pull the operation through the PHI, reducing
9907 // code size and simplifying code.
9908 Constant *ConstantOp = 0;
9909 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009910 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009911 if (isa<CastInst>(FirstInst)) {
9912 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009913 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009914 // Can fold binop, compare or shift here if the RHS is a constant,
9915 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009916 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009917 if (ConstantOp == 0)
9918 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009919 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9920 isVolatile = LI->isVolatile();
9921 // We can't sink the load if the loaded value could be modified between the
9922 // load and the PHI.
9923 if (LI->getParent() != PN.getIncomingBlock(0) ||
9924 !isSafeToSinkLoad(LI))
9925 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009926 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009927 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009928 return FoldPHIArgBinOpIntoPHI(PN);
9929 // Can't handle general GEPs yet.
9930 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009931 } else {
9932 return 0; // Cannot fold this operation.
9933 }
9934
9935 // Check to see if all arguments are the same operation.
9936 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9937 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9938 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009939 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009940 return 0;
9941 if (CastSrcTy) {
9942 if (I->getOperand(0)->getType() != CastSrcTy)
9943 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009944 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009945 // We can't sink the load if the loaded value could be modified between
9946 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009947 if (LI->isVolatile() != isVolatile ||
9948 LI->getParent() != PN.getIncomingBlock(i) ||
9949 !isSafeToSinkLoad(LI))
9950 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009951
9952 // If the PHI is volatile and its block has multiple successors, sinking
9953 // it would remove a load of the volatile value from the path through the
9954 // other successor.
9955 if (isVolatile &&
9956 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9957 return 0;
9958
9959
Chris Lattnerbac32862004-11-14 19:13:23 +00009960 } else if (I->getOperand(1) != ConstantOp) {
9961 return 0;
9962 }
9963 }
9964
9965 // Okay, they are all the same operation. Create a new PHI node of the
9966 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009967 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9968 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009969 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009970
9971 Value *InVal = FirstInst->getOperand(0);
9972 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009973
9974 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009975 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9976 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9977 if (NewInVal != InVal)
9978 InVal = 0;
9979 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9980 }
9981
9982 Value *PhiVal;
9983 if (InVal) {
9984 // The new PHI unions all of the same values together. This is really
9985 // common, so we handle it intelligently here for compile-time speed.
9986 PhiVal = InVal;
9987 delete NewPN;
9988 } else {
9989 InsertNewInstBefore(NewPN, PN);
9990 PhiVal = NewPN;
9991 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009992
Chris Lattnerbac32862004-11-14 19:13:23 +00009993 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009994 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009995 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009996 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009997 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009998 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009999 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010000 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010001 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10002
10003 // If this was a volatile load that we are merging, make sure to loop through
10004 // and mark all the input loads as non-volatile. If we don't do this, we will
10005 // insert a new volatile load and the old ones will not be deletable.
10006 if (isVolatile)
10007 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10008 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10009
10010 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010011}
Chris Lattnera1be5662002-05-02 17:06:02 +000010012
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010013/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10014/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010015static bool DeadPHICycle(PHINode *PN,
10016 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010017 if (PN->use_empty()) return true;
10018 if (!PN->hasOneUse()) return false;
10019
10020 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010021 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010022 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010023
10024 // Don't scan crazily complex things.
10025 if (PotentiallyDeadPHIs.size() == 16)
10026 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010027
10028 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10029 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010030
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010031 return false;
10032}
10033
Chris Lattnercf5008a2007-11-06 21:52:06 +000010034/// PHIsEqualValue - Return true if this phi node is always equal to
10035/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10036/// z = some value; x = phi (y, z); y = phi (x, z)
10037static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10038 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10039 // See if we already saw this PHI node.
10040 if (!ValueEqualPHIs.insert(PN))
10041 return true;
10042
10043 // Don't scan crazily complex things.
10044 if (ValueEqualPHIs.size() == 16)
10045 return false;
10046
10047 // Scan the operands to see if they are either phi nodes or are equal to
10048 // the value.
10049 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10050 Value *Op = PN->getIncomingValue(i);
10051 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10052 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10053 return false;
10054 } else if (Op != NonPhiInVal)
10055 return false;
10056 }
10057
10058 return true;
10059}
10060
10061
Chris Lattner473945d2002-05-06 18:06:38 +000010062// PHINode simplification
10063//
Chris Lattner7e708292002-06-25 16:13:24 +000010064Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010065 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010066 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010067
Owen Anderson7e057142006-07-10 22:03:18 +000010068 if (Value *V = PN.hasConstantValue())
10069 return ReplaceInstUsesWith(PN, V);
10070
Owen Anderson7e057142006-07-10 22:03:18 +000010071 // If all PHI operands are the same operation, pull them through the PHI,
10072 // reducing code size.
10073 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10074 PN.getIncomingValue(0)->hasOneUse())
10075 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10076 return Result;
10077
10078 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10079 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10080 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010081 if (PN.hasOneUse()) {
10082 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10083 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010084 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010085 PotentiallyDeadPHIs.insert(&PN);
10086 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10087 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10088 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010089
10090 // If this phi has a single use, and if that use just computes a value for
10091 // the next iteration of a loop, delete the phi. This occurs with unused
10092 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10093 // common case here is good because the only other things that catch this
10094 // are induction variable analysis (sometimes) and ADCE, which is only run
10095 // late.
10096 if (PHIUser->hasOneUse() &&
10097 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10098 PHIUser->use_back() == &PN) {
10099 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10100 }
10101 }
Owen Anderson7e057142006-07-10 22:03:18 +000010102
Chris Lattnercf5008a2007-11-06 21:52:06 +000010103 // We sometimes end up with phi cycles that non-obviously end up being the
10104 // same value, for example:
10105 // z = some value; x = phi (y, z); y = phi (x, z)
10106 // where the phi nodes don't necessarily need to be in the same block. Do a
10107 // quick check to see if the PHI node only contains a single non-phi value, if
10108 // so, scan to see if the phi cycle is actually equal to that value.
10109 {
10110 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10111 // Scan for the first non-phi operand.
10112 while (InValNo != NumOperandVals &&
10113 isa<PHINode>(PN.getIncomingValue(InValNo)))
10114 ++InValNo;
10115
10116 if (InValNo != NumOperandVals) {
10117 Value *NonPhiInVal = PN.getOperand(InValNo);
10118
10119 // Scan the rest of the operands to see if there are any conflicts, if so
10120 // there is no need to recursively scan other phis.
10121 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10122 Value *OpVal = PN.getIncomingValue(InValNo);
10123 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10124 break;
10125 }
10126
10127 // If we scanned over all operands, then we have one unique value plus
10128 // phi values. Scan PHI nodes to see if they all merge in each other or
10129 // the value.
10130 if (InValNo == NumOperandVals) {
10131 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10132 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10133 return ReplaceInstUsesWith(PN, NonPhiInVal);
10134 }
10135 }
10136 }
Chris Lattner60921c92003-12-19 05:58:40 +000010137 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010138}
10139
Reid Spencer17212df2006-12-12 09:18:51 +000010140static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10141 Instruction *InsertPoint,
10142 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010143 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10144 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010145 // We must cast correctly to the pointer type. Ensure that we
10146 // sign extend the integer value if it is smaller as this is
10147 // used for address computation.
10148 Instruction::CastOps opcode =
10149 (VTySize < PtrSize ? Instruction::SExt :
10150 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10151 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010152}
10153
Chris Lattnera1be5662002-05-02 17:06:02 +000010154
Chris Lattner7e708292002-06-25 16:13:24 +000010155Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010156 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010157 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010158 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010159 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010160 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010161
Chris Lattnere87597f2004-10-16 18:11:37 +000010162 if (isa<UndefValue>(GEP.getOperand(0)))
10163 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10164
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010165 bool HasZeroPointerIndex = false;
10166 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10167 HasZeroPointerIndex = C->isNullValue();
10168
10169 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010170 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010171
Chris Lattner28977af2004-04-05 01:30:19 +000010172 // Eliminate unneeded casts for indices.
10173 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010174
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010175 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010176 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010177 if (isa<SequentialType>(*GTI)) {
10178 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010179 if (CI->getOpcode() == Instruction::ZExt ||
10180 CI->getOpcode() == Instruction::SExt) {
10181 const Type *SrcTy = CI->getOperand(0)->getType();
10182 // We can eliminate a cast from i32 to i64 iff the target
10183 // is a 32-bit pointer target.
10184 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10185 MadeChange = true;
10186 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +000010187 }
10188 }
10189 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010190 // If we are using a wider index than needed for this platform, shrink it
10191 // to what we need. If the incoming value needs a cast instruction,
10192 // insert it. This explicit cast can make subsequent optimizations more
10193 // obvious.
10194 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010195 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010196 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010197 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +000010198 MadeChange = true;
10199 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010200 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10201 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010202 GEP.setOperand(i, Op);
10203 MadeChange = true;
10204 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010205 }
Chris Lattner28977af2004-04-05 01:30:19 +000010206 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010207 }
Chris Lattner28977af2004-04-05 01:30:19 +000010208 if (MadeChange) return &GEP;
10209
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010210 // If this GEP instruction doesn't move the pointer, and if the input operand
10211 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10212 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +000010213 if (GEP.hasAllZeroIndices()) {
10214 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10215 // If the bitcast is of an allocation, and the allocation will be
10216 // converted to match the type of the cast, don't touch this.
10217 if (isa<AllocationInst>(BCI->getOperand(0))) {
10218 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +000010219 if (Instruction *I = visitBitCast(*BCI)) {
10220 if (I != BCI) {
10221 I->takeName(BCI);
10222 BCI->getParent()->getInstList().insert(BCI, I);
10223 ReplaceInstUsesWith(*BCI, I);
10224 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010225 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +000010226 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010227 }
10228 return new BitCastInst(BCI->getOperand(0), GEP.getType());
10229 }
10230 }
10231
Chris Lattner90ac28c2002-08-02 19:29:35 +000010232 // Combine Indices - If the source pointer to this getelementptr instruction
10233 // is a getelementptr instruction, combine the indices of the two
10234 // getelementptr instructions into a single instruction.
10235 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010236 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010237 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010238 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010239
10240 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010241 // Note that if our source is a gep chain itself that we wait for that
10242 // chain to be resolved before we perform this transformation. This
10243 // avoids us creating a TON of code in some cases.
10244 //
10245 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10246 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10247 return 0; // Wait until our source is folded to completion.
10248
Chris Lattner72588fc2007-02-15 22:48:32 +000010249 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010250
10251 // Find out whether the last index in the source GEP is a sequential idx.
10252 bool EndsWithSequential = false;
10253 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10254 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010255 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010256
Chris Lattner90ac28c2002-08-02 19:29:35 +000010257 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010258 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010259 // Replace: gep (gep %P, long B), long A, ...
10260 // With: T = long A+B; gep %P, T, ...
10261 //
Chris Lattner620ce142004-05-07 22:09:22 +000010262 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010263 if (SO1 == Constant::getNullValue(SO1->getType())) {
10264 Sum = GO1;
10265 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10266 Sum = SO1;
10267 } else {
10268 // If they aren't the same type, convert both to an integer of the
10269 // target's pointer size.
10270 if (SO1->getType() != GO1->getType()) {
10271 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010272 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010273 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010274 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010275 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010276 unsigned PS = TD->getPointerSizeInBits();
10277 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010278 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010279 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010280
Duncan Sands514ab342007-11-01 20:53:16 +000010281 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010282 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010283 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010284 } else {
10285 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010286 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10287 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010288 }
10289 }
10290 }
Chris Lattner620ce142004-05-07 22:09:22 +000010291 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10292 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10293 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010294 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010295 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010296 }
Chris Lattner28977af2004-04-05 01:30:19 +000010297 }
Chris Lattner620ce142004-05-07 22:09:22 +000010298
10299 // Recycle the GEP we already have if possible.
10300 if (SrcGEPOperands.size() == 2) {
10301 GEP.setOperand(0, SrcGEPOperands[0]);
10302 GEP.setOperand(1, Sum);
10303 return &GEP;
10304 } else {
10305 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10306 SrcGEPOperands.end()-1);
10307 Indices.push_back(Sum);
10308 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10309 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010310 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010311 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010312 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010313 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010314 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10315 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010316 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10317 }
10318
10319 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010320 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10321 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010322
Chris Lattner620ce142004-05-07 22:09:22 +000010323 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010324 // GEP of global variable. If all of the indices for this GEP are
10325 // constants, we can promote this to a constexpr instead of an instruction.
10326
10327 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010328 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010329 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10330 for (; I != E && isa<Constant>(*I); ++I)
10331 Indices.push_back(cast<Constant>(*I));
10332
10333 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010334 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10335 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010336
10337 // Replace all uses of the GEP with the new constexpr...
10338 return ReplaceInstUsesWith(GEP, CE);
10339 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010340 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010341 if (!isa<PointerType>(X->getType())) {
10342 // Not interesting. Source pointer must be a cast from pointer.
10343 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010344 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10345 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010346 //
10347 // This occurs when the program declares an array extern like "int X[];"
10348 //
10349 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10350 const PointerType *XTy = cast<PointerType>(X->getType());
10351 if (const ArrayType *XATy =
10352 dyn_cast<ArrayType>(XTy->getElementType()))
10353 if (const ArrayType *CATy =
10354 dyn_cast<ArrayType>(CPTy->getElementType()))
10355 if (CATy->getElementType() == XATy->getElementType()) {
10356 // At this point, we know that the cast source type is a pointer
10357 // to an array of the same type as the destination pointer
10358 // array. Because the array type is never stepped over (there
10359 // is a leading zero) we can fold the cast into this GEP.
10360 GEP.setOperand(0, X);
10361 return &GEP;
10362 }
10363 } else if (GEP.getNumOperands() == 2) {
10364 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010365 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10366 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010367 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10368 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10369 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +000010370 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10371 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010372 Value *Idx[2];
10373 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10374 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010375 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010376 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010377 // V and GEP are both pointer types --> BitCast
10378 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010379 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010380
10381 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010382 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010383 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010384 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010385
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010386 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010387 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +000010388 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010389
10390 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10391 // allow either a mul, shift, or constant here.
10392 Value *NewIdx = 0;
10393 ConstantInt *Scale = 0;
10394 if (ArrayEltSize == 1) {
10395 NewIdx = GEP.getOperand(1);
10396 Scale = ConstantInt::get(NewIdx->getType(), 1);
10397 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010398 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010399 Scale = CI;
10400 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10401 if (Inst->getOpcode() == Instruction::Shl &&
10402 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010403 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10404 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10405 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010406 NewIdx = Inst->getOperand(0);
10407 } else if (Inst->getOpcode() == Instruction::Mul &&
10408 isa<ConstantInt>(Inst->getOperand(1))) {
10409 Scale = cast<ConstantInt>(Inst->getOperand(1));
10410 NewIdx = Inst->getOperand(0);
10411 }
10412 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010413
Chris Lattner7835cdd2005-09-13 18:36:04 +000010414 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010415 // out, perform the transformation. Note, we don't know whether Scale is
10416 // signed or not. We'll use unsigned version of division/modulo
10417 // operation after making sure Scale doesn't have the sign bit set.
10418 if (Scale && Scale->getSExtValue() >= 0LL &&
10419 Scale->getZExtValue() % ArrayEltSize == 0) {
10420 Scale = ConstantInt::get(Scale->getType(),
10421 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010422 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010423 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010424 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010425 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010426 NewIdx = InsertNewInstBefore(Sc, GEP);
10427 }
10428
10429 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010430 Value *Idx[2];
10431 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10432 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010433 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010434 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010435 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10436 // The NewGEP must be pointer typed, so must the old one -> BitCast
10437 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010438 }
10439 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010440 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010441 }
10442
Chris Lattner8a2a3112001-12-14 16:52:21 +000010443 return 0;
10444}
10445
Chris Lattner0864acf2002-11-04 16:18:53 +000010446Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10447 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010448 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010449 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10450 const Type *NewTy =
10451 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010452 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010453
10454 // Create and insert the replacement instruction...
10455 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010456 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010457 else {
10458 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010459 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010460 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010461
10462 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010463
Chris Lattner0864acf2002-11-04 16:18:53 +000010464 // Scan to the end of the allocation instructions, to skip over a block of
10465 // allocas if possible...
10466 //
10467 BasicBlock::iterator It = New;
10468 while (isa<AllocationInst>(*It)) ++It;
10469
10470 // Now that I is pointing to the first non-allocation-inst in the block,
10471 // insert our getelementptr instruction...
10472 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010473 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010474 Value *Idx[2];
10475 Idx[0] = NullIdx;
10476 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010477 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10478 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010479
10480 // Now make everything use the getelementptr instead of the original
10481 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010482 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010483 } else if (isa<UndefValue>(AI.getArraySize())) {
10484 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010485 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010486 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010487
10488 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10489 // Note that we only do this for alloca's, because malloc should allocate and
10490 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +000010491 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +000010492 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +000010493 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10494
Chris Lattner0864acf2002-11-04 16:18:53 +000010495 return 0;
10496}
10497
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010498Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10499 Value *Op = FI.getOperand(0);
10500
Chris Lattner17be6352004-10-18 02:59:09 +000010501 // free undef -> unreachable.
10502 if (isa<UndefValue>(Op)) {
10503 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010504 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010505 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010506 return EraseInstFromFunction(FI);
10507 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010508
Chris Lattner6160e852004-02-28 04:57:37 +000010509 // If we have 'free null' delete the instruction. This can happen in stl code
10510 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010511 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010512 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010513
10514 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10515 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10516 FI.setOperand(0, CI->getOperand(0));
10517 return &FI;
10518 }
10519
10520 // Change free (gep X, 0,0,0,0) into free(X)
10521 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10522 if (GEPI->hasAllZeroIndices()) {
10523 AddToWorkList(GEPI);
10524 FI.setOperand(0, GEPI->getOperand(0));
10525 return &FI;
10526 }
10527 }
10528
10529 // Change free(malloc) into nothing, if the malloc has a single use.
10530 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10531 if (MI->hasOneUse()) {
10532 EraseInstFromFunction(FI);
10533 return EraseInstFromFunction(*MI);
10534 }
Chris Lattner6160e852004-02-28 04:57:37 +000010535
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010536 return 0;
10537}
10538
10539
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010540/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010541static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010542 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010543 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010544 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010545
Devang Patel99db6ad2007-10-18 19:52:32 +000010546 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10547 // Instead of loading constant c string, use corresponding integer value
10548 // directly if string length is small enough.
10549 const std::string &Str = CE->getOperand(0)->getStringValue();
10550 if (!Str.empty()) {
10551 unsigned len = Str.length();
10552 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10553 unsigned numBits = Ty->getPrimitiveSizeInBits();
10554 // Replace LI with immediate integer store.
10555 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010556 APInt StrVal(numBits, 0);
10557 APInt SingleChar(numBits, 0);
10558 if (TD->isLittleEndian()) {
10559 for (signed i = len-1; i >= 0; i--) {
10560 SingleChar = (uint64_t) Str[i];
10561 StrVal = (StrVal << 8) | SingleChar;
10562 }
10563 } else {
10564 for (unsigned i = 0; i < len; i++) {
10565 SingleChar = (uint64_t) Str[i];
10566 StrVal = (StrVal << 8) | SingleChar;
10567 }
10568 // Append NULL at the end.
10569 SingleChar = 0;
10570 StrVal = (StrVal << 8) | SingleChar;
10571 }
10572 Value *NL = ConstantInt::get(StrVal);
10573 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010574 }
10575 }
10576 }
10577
Chris Lattnerb89e0712004-07-13 01:49:43 +000010578 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010579 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010580 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010581
Reid Spencer42230162007-01-22 05:51:25 +000010582 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010583 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010584 // If the source is an array, the code below will not succeed. Check to
10585 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10586 // constants.
10587 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10588 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10589 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010590 Value *Idxs[2];
10591 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10592 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010593 SrcTy = cast<PointerType>(CastOp->getType());
10594 SrcPTy = SrcTy->getElementType();
10595 }
10596
Reid Spencer42230162007-01-22 05:51:25 +000010597 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010598 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010599 // Do not allow turning this into a load of an integer, which is then
10600 // casted to a pointer, this pessimizes pointer analysis a lot.
10601 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010602 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10603 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010604
Chris Lattnerf9527852005-01-31 04:50:46 +000010605 // Okay, we are casting from one integer or pointer type to another of
10606 // the same size. Instead of casting the pointer before the load, cast
10607 // the result of the loaded value.
10608 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10609 CI->getName(),
10610 LI.isVolatile()),LI);
10611 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010612 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010613 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010614 }
10615 }
10616 return 0;
10617}
10618
Chris Lattnerc10aced2004-09-19 18:43:46 +000010619/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010620/// from this value cannot trap. If it is not obviously safe to load from the
10621/// specified pointer, we do a quick local scan of the basic block containing
10622/// ScanFrom, to determine if the address is already accessed.
10623static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010624 // If it is an alloca it is always safe to load from.
10625 if (isa<AllocaInst>(V)) return true;
10626
Duncan Sands46318cd2007-09-19 10:25:38 +000010627 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010628 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010629 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010630 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010631
10632 // Otherwise, be a little bit agressive by scanning the local block where we
10633 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010634 // from/to. If so, the previous load or store would have already trapped,
10635 // so there is no harm doing an extra load (also, CSE will later eliminate
10636 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010637 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10638
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010639 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010640 --BBI;
10641
10642 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10643 if (LI->getOperand(0) == V) return true;
10644 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10645 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010646
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010647 }
Chris Lattner8a375202004-09-19 19:18:10 +000010648 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010649}
10650
Chris Lattner8d2e8882007-08-11 18:48:48 +000010651/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10652/// until we find the underlying object a pointer is referring to or something
10653/// we don't understand. Note that the returned pointer may be offset from the
10654/// input, because we ignore GEP indices.
10655static Value *GetUnderlyingObject(Value *Ptr) {
10656 while (1) {
10657 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10658 if (CE->getOpcode() == Instruction::BitCast ||
10659 CE->getOpcode() == Instruction::GetElementPtr)
10660 Ptr = CE->getOperand(0);
10661 else
10662 return Ptr;
10663 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10664 Ptr = BCI->getOperand(0);
10665 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10666 Ptr = GEP->getOperand(0);
10667 } else {
10668 return Ptr;
10669 }
10670 }
10671}
10672
Chris Lattner833b8a42003-06-26 05:06:25 +000010673Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10674 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010675
Dan Gohman9941f742007-07-20 16:34:21 +000010676 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010677 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10678 if (KnownAlign >
10679 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10680 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010681 LI.setAlignment(KnownAlign);
10682
Chris Lattner37366c12005-05-01 04:24:53 +000010683 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010684 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010685 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010686 return Res;
10687
10688 // None of the following transforms are legal for volatile loads.
10689 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010690
Chris Lattner62f254d2005-09-12 22:00:15 +000010691 if (&LI.getParent()->front() != &LI) {
10692 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010693 // If the instruction immediately before this is a store to the same
10694 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010695 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10696 if (SI->getOperand(1) == LI.getOperand(0))
10697 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010698 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10699 if (LIB->getOperand(0) == LI.getOperand(0))
10700 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010701 }
Chris Lattner37366c12005-05-01 04:24:53 +000010702
Christopher Lambb15147e2007-12-29 07:56:53 +000010703 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10704 const Value *GEPI0 = GEPI->getOperand(0);
10705 // TODO: Consider a target hook for valid address spaces for this xform.
10706 if (isa<ConstantPointerNull>(GEPI0) &&
10707 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010708 // Insert a new store to null instruction before the load to indicate
10709 // that this code is not reachable. We do this instead of inserting
10710 // an unreachable instruction directly because we cannot modify the
10711 // CFG.
10712 new StoreInst(UndefValue::get(LI.getType()),
10713 Constant::getNullValue(Op->getType()), &LI);
10714 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10715 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010716 }
Chris Lattner37366c12005-05-01 04:24:53 +000010717
Chris Lattnere87597f2004-10-16 18:11:37 +000010718 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010719 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010720 // TODO: Consider a target hook for valid address spaces for this xform.
10721 if (isa<UndefValue>(C) || (C->isNullValue() &&
10722 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010723 // Insert a new store to null instruction before the load to indicate that
10724 // this code is not reachable. We do this instead of inserting an
10725 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010726 new StoreInst(UndefValue::get(LI.getType()),
10727 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010728 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010729 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010730
Chris Lattnere87597f2004-10-16 18:11:37 +000010731 // Instcombine load (constant global) into the value loaded.
10732 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010733 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010734 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010735
Chris Lattnere87597f2004-10-16 18:11:37 +000010736 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010737 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010738 if (CE->getOpcode() == Instruction::GetElementPtr) {
10739 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010740 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010741 if (Constant *V =
10742 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010743 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010744 if (CE->getOperand(0)->isNullValue()) {
10745 // Insert a new store to null instruction before the load to indicate
10746 // that this code is not reachable. We do this instead of inserting
10747 // an unreachable instruction directly because we cannot modify the
10748 // CFG.
10749 new StoreInst(UndefValue::get(LI.getType()),
10750 Constant::getNullValue(Op->getType()), &LI);
10751 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10752 }
10753
Reid Spencer3da59db2006-11-27 01:05:10 +000010754 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010755 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010756 return Res;
10757 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010758 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010759 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010760
10761 // If this load comes from anywhere in a constant global, and if the global
10762 // is all undef or zero, we know what it loads.
10763 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10764 if (GV->isConstant() && GV->hasInitializer()) {
10765 if (GV->getInitializer()->isNullValue())
10766 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10767 else if (isa<UndefValue>(GV->getInitializer()))
10768 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10769 }
10770 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010771
Chris Lattner37366c12005-05-01 04:24:53 +000010772 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010773 // Change select and PHI nodes to select values instead of addresses: this
10774 // helps alias analysis out a lot, allows many others simplifications, and
10775 // exposes redundancy in the code.
10776 //
10777 // Note that we cannot do the transformation unless we know that the
10778 // introduced loads cannot trap! Something like this is valid as long as
10779 // the condition is always false: load (select bool %C, int* null, int* %G),
10780 // but it would not be valid if we transformed it to load from null
10781 // unconditionally.
10782 //
10783 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10784 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010785 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10786 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010787 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010788 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010789 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010790 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010791 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010792 }
10793
Chris Lattner684fe212004-09-23 15:46:00 +000010794 // load (select (cond, null, P)) -> load P
10795 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10796 if (C->isNullValue()) {
10797 LI.setOperand(0, SI->getOperand(2));
10798 return &LI;
10799 }
10800
10801 // load (select (cond, P, null)) -> load P
10802 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10803 if (C->isNullValue()) {
10804 LI.setOperand(0, SI->getOperand(1));
10805 return &LI;
10806 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010807 }
10808 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010809 return 0;
10810}
10811
Reid Spencer55af2b52007-01-19 21:20:31 +000010812/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010813/// when possible.
10814static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10815 User *CI = cast<User>(SI.getOperand(1));
10816 Value *CastOp = CI->getOperand(0);
10817
10818 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10819 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10820 const Type *SrcPTy = SrcTy->getElementType();
10821
Reid Spencer42230162007-01-22 05:51:25 +000010822 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010823 // If the source is an array, the code below will not succeed. Check to
10824 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10825 // constants.
10826 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10827 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10828 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010829 Value* Idxs[2];
10830 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10831 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010832 SrcTy = cast<PointerType>(CastOp->getType());
10833 SrcPTy = SrcTy->getElementType();
10834 }
10835
Reid Spencer67f827c2007-01-20 23:35:48 +000010836 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10837 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10838 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010839
10840 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010841 // the same size. Instead of casting the pointer before
10842 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010843 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010844 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010845 Instruction::CastOps opcode = Instruction::BitCast;
10846 const Type* CastSrcTy = SIOp0->getType();
10847 const Type* CastDstTy = SrcPTy;
10848 if (isa<PointerType>(CastDstTy)) {
10849 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010850 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010851 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010852 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010853 opcode = Instruction::PtrToInt;
10854 }
10855 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010856 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010857 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010858 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010859 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010860 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010861 return new StoreInst(NewCast, CastOp);
10862 }
10863 }
10864 }
10865 return 0;
10866}
10867
Chris Lattner2f503e62005-01-31 05:36:43 +000010868Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10869 Value *Val = SI.getOperand(0);
10870 Value *Ptr = SI.getOperand(1);
10871
10872 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010873 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010874 ++NumCombined;
10875 return 0;
10876 }
Chris Lattner836692d2007-01-15 06:51:56 +000010877
10878 // If the RHS is an alloca with a single use, zapify the store, making the
10879 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010880 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010881 if (isa<AllocaInst>(Ptr)) {
10882 EraseInstFromFunction(SI);
10883 ++NumCombined;
10884 return 0;
10885 }
10886
10887 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10888 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10889 GEP->getOperand(0)->hasOneUse()) {
10890 EraseInstFromFunction(SI);
10891 ++NumCombined;
10892 return 0;
10893 }
10894 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010895
Dan Gohman9941f742007-07-20 16:34:21 +000010896 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010897 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10898 if (KnownAlign >
10899 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10900 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010901 SI.setAlignment(KnownAlign);
10902
Chris Lattner9ca96412006-02-08 03:25:32 +000010903 // Do really simple DSE, to catch cases where there are several consequtive
10904 // stores to the same location, separated by a few arithmetic operations. This
10905 // situation often occurs with bitfield accesses.
10906 BasicBlock::iterator BBI = &SI;
10907 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10908 --ScanInsts) {
10909 --BBI;
10910
10911 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10912 // Prev store isn't volatile, and stores to the same location?
10913 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10914 ++NumDeadStore;
10915 ++BBI;
10916 EraseInstFromFunction(*PrevSI);
10917 continue;
10918 }
10919 break;
10920 }
10921
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010922 // If this is a load, we have to stop. However, if the loaded value is from
10923 // the pointer we're loading and is producing the pointer we're storing,
10924 // then *this* store is dead (X = load P; store X -> P).
10925 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010926 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010927 EraseInstFromFunction(SI);
10928 ++NumCombined;
10929 return 0;
10930 }
10931 // Otherwise, this is a load from some other location. Stores before it
10932 // may not be dead.
10933 break;
10934 }
10935
Chris Lattner9ca96412006-02-08 03:25:32 +000010936 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010937 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010938 break;
10939 }
10940
10941
10942 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010943
10944 // store X, null -> turns into 'unreachable' in SimplifyCFG
10945 if (isa<ConstantPointerNull>(Ptr)) {
10946 if (!isa<UndefValue>(Val)) {
10947 SI.setOperand(0, UndefValue::get(Val->getType()));
10948 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010949 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010950 ++NumCombined;
10951 }
10952 return 0; // Do not modify these!
10953 }
10954
10955 // store undef, Ptr -> noop
10956 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010957 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010958 ++NumCombined;
10959 return 0;
10960 }
10961
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010962 // If the pointer destination is a cast, see if we can fold the cast into the
10963 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010964 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010965 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10966 return Res;
10967 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010968 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010969 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10970 return Res;
10971
Chris Lattner408902b2005-09-12 23:23:25 +000010972
10973 // If this store is the last instruction in the basic block, and if the block
10974 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010975 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010976 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010977 if (BI->isUnconditional())
10978 if (SimplifyStoreAtEndOfBlock(SI))
10979 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010980
Chris Lattner2f503e62005-01-31 05:36:43 +000010981 return 0;
10982}
10983
Chris Lattner3284d1f2007-04-15 00:07:55 +000010984/// SimplifyStoreAtEndOfBlock - Turn things like:
10985/// if () { *P = v1; } else { *P = v2 }
10986/// into a phi node with a store in the successor.
10987///
Chris Lattner31755a02007-04-15 01:02:18 +000010988/// Simplify things like:
10989/// *P = v1; if () { *P = v2; }
10990/// into a phi node with a store in the successor.
10991///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010992bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10993 BasicBlock *StoreBB = SI.getParent();
10994
10995 // Check to see if the successor block has exactly two incoming edges. If
10996 // so, see if the other predecessor contains a store to the same location.
10997 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010998 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010999
11000 // Determine whether Dest has exactly two predecessors and, if so, compute
11001 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011002 pred_iterator PI = pred_begin(DestBB);
11003 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011004 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011005 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011006 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011007 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011008 return false;
11009
11010 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011011 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011012 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011013 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011014 }
Chris Lattner31755a02007-04-15 01:02:18 +000011015 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011016 return false;
11017
11018
Chris Lattner31755a02007-04-15 01:02:18 +000011019 // Verify that the other block ends in a branch and is not otherwise empty.
11020 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011021 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011022 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011023 return false;
11024
Chris Lattner31755a02007-04-15 01:02:18 +000011025 // If the other block ends in an unconditional branch, check for the 'if then
11026 // else' case. there is an instruction before the branch.
11027 StoreInst *OtherStore = 0;
11028 if (OtherBr->isUnconditional()) {
11029 // If this isn't a store, or isn't a store to the same location, bail out.
11030 --BBI;
11031 OtherStore = dyn_cast<StoreInst>(BBI);
11032 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11033 return false;
11034 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011035 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011036 // destinations is StoreBB, then we have the if/then case.
11037 if (OtherBr->getSuccessor(0) != StoreBB &&
11038 OtherBr->getSuccessor(1) != StoreBB)
11039 return false;
11040
11041 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011042 // if/then triangle. See if there is a store to the same ptr as SI that
11043 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011044 for (;; --BBI) {
11045 // Check to see if we find the matching store.
11046 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11047 if (OtherStore->getOperand(1) != SI.getOperand(1))
11048 return false;
11049 break;
11050 }
Chris Lattnerd717c182007-05-05 22:32:24 +000011051 // If we find something that may be using the stored value, or if we run
11052 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000011053 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
11054 BBI == OtherBB->begin())
11055 return false;
11056 }
11057
11058 // In order to eliminate the store in OtherBr, we have to
11059 // make sure nothing reads the stored value in StoreBB.
11060 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11061 // FIXME: This should really be AA driven.
11062 if (isa<LoadInst>(I) || I->mayWriteToMemory())
11063 return false;
11064 }
11065 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011066
Chris Lattner31755a02007-04-15 01:02:18 +000011067 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011068 Value *MergedVal = OtherStore->getOperand(0);
11069 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011070 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011071 PN->reserveOperandSpace(2);
11072 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011073 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11074 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011075 }
11076
11077 // Advance to a place where it is safe to insert the new store and
11078 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011079 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011080 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11081 OtherStore->isVolatile()), *BBI);
11082
11083 // Nuke the old stores.
11084 EraseInstFromFunction(SI);
11085 EraseInstFromFunction(*OtherStore);
11086 ++NumCombined;
11087 return true;
11088}
11089
Chris Lattner2f503e62005-01-31 05:36:43 +000011090
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011091Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11092 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011093 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011094 BasicBlock *TrueDest;
11095 BasicBlock *FalseDest;
11096 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11097 !isa<Constant>(X)) {
11098 // Swap Destinations and condition...
11099 BI.setCondition(X);
11100 BI.setSuccessor(0, FalseDest);
11101 BI.setSuccessor(1, TrueDest);
11102 return &BI;
11103 }
11104
Reid Spencere4d87aa2006-12-23 06:05:41 +000011105 // Cannonicalize fcmp_one -> fcmp_oeq
11106 FCmpInst::Predicate FPred; Value *Y;
11107 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11108 TrueDest, FalseDest)))
11109 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11110 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11111 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011112 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011113 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11114 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011115 // Swap Destinations and condition...
11116 BI.setCondition(NewSCC);
11117 BI.setSuccessor(0, FalseDest);
11118 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011119 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011120 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011121 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011122 return &BI;
11123 }
11124
11125 // Cannonicalize icmp_ne -> icmp_eq
11126 ICmpInst::Predicate IPred;
11127 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11128 TrueDest, FalseDest)))
11129 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11130 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11131 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11132 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011133 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011134 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11135 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000011136 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011137 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011138 BI.setSuccessor(0, FalseDest);
11139 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011140 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011141 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011142 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011143 return &BI;
11144 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011145
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011146 return 0;
11147}
Chris Lattner0864acf2002-11-04 16:18:53 +000011148
Chris Lattner46238a62004-07-03 00:26:11 +000011149Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11150 Value *Cond = SI.getCondition();
11151 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11152 if (I->getOpcode() == Instruction::Add)
11153 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11154 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11155 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000011156 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011157 AddRHS));
11158 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000011159 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011160 return &SI;
11161 }
11162 }
11163 return 0;
11164}
11165
Chris Lattner220b0cf2006-03-05 00:22:33 +000011166/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11167/// is to leave as a vector operation.
11168static bool CheapToScalarize(Value *V, bool isConstant) {
11169 if (isa<ConstantAggregateZero>(V))
11170 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011171 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011172 if (isConstant) return true;
11173 // If all elts are the same, we can extract.
11174 Constant *Op0 = C->getOperand(0);
11175 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11176 if (C->getOperand(i) != Op0)
11177 return false;
11178 return true;
11179 }
11180 Instruction *I = dyn_cast<Instruction>(V);
11181 if (!I) return false;
11182
11183 // Insert element gets simplified to the inserted element or is deleted if
11184 // this is constant idx extract element and its a constant idx insertelt.
11185 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11186 isa<ConstantInt>(I->getOperand(2)))
11187 return true;
11188 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11189 return true;
11190 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11191 if (BO->hasOneUse() &&
11192 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11193 CheapToScalarize(BO->getOperand(1), isConstant)))
11194 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011195 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11196 if (CI->hasOneUse() &&
11197 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11198 CheapToScalarize(CI->getOperand(1), isConstant)))
11199 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011200
11201 return false;
11202}
11203
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011204/// Read and decode a shufflevector mask.
11205///
11206/// It turns undef elements into values that are larger than the number of
11207/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011208static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11209 unsigned NElts = SVI->getType()->getNumElements();
11210 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11211 return std::vector<unsigned>(NElts, 0);
11212 if (isa<UndefValue>(SVI->getOperand(2)))
11213 return std::vector<unsigned>(NElts, 2*NElts);
11214
11215 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011216 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000011217 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
11218 if (isa<UndefValue>(CP->getOperand(i)))
11219 Result.push_back(NElts*2); // undef -> 8
11220 else
Reid Spencerb83eb642006-10-20 07:07:24 +000011221 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011222 return Result;
11223}
11224
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011225/// FindScalarElement - Given a vector and an element number, see if the scalar
11226/// value is already around as a register, for example if it were inserted then
11227/// extracted from the vector.
11228static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011229 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11230 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011231 unsigned Width = PTy->getNumElements();
11232 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011233 return UndefValue::get(PTy->getElementType());
11234
11235 if (isa<UndefValue>(V))
11236 return UndefValue::get(PTy->getElementType());
11237 else if (isa<ConstantAggregateZero>(V))
11238 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011239 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011240 return CP->getOperand(EltNo);
11241 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11242 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000011243 if (!isa<ConstantInt>(III->getOperand(2)))
11244 return 0;
11245 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011246
11247 // If this is an insert to the element we are looking for, return the
11248 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000011249 if (EltNo == IIElt)
11250 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011251
11252 // Otherwise, the insertelement doesn't modify the value, recurse on its
11253 // vector input.
11254 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000011255 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000011256 unsigned InEl = getShuffleMask(SVI)[EltNo];
11257 if (InEl < Width)
11258 return FindScalarElement(SVI->getOperand(0), InEl);
11259 else if (InEl < Width*2)
11260 return FindScalarElement(SVI->getOperand(1), InEl - Width);
11261 else
11262 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011263 }
11264
11265 // Otherwise, we don't know.
11266 return 0;
11267}
11268
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011269Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011270
Dan Gohman07a96762007-07-16 14:29:03 +000011271 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000011272 if (isa<UndefValue>(EI.getOperand(0)))
11273 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11274
Dan Gohman07a96762007-07-16 14:29:03 +000011275 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000011276 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11277 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11278
Reid Spencer9d6565a2007-02-15 02:26:10 +000011279 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000011280 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011281 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000011282 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011283 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000011284 if (C->getOperand(i) != op0) {
11285 op0 = 0;
11286 break;
11287 }
11288 if (op0)
11289 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011290 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000011291
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011292 // If extracting a specified index from the vector, see if we can recursively
11293 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000011294 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000011295 unsigned IndexVal = IdxC->getZExtValue();
11296 unsigned VectorWidth =
11297 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11298
11299 // If this is extracting an invalid index, turn this into undef, to avoid
11300 // crashing the code below.
11301 if (IndexVal >= VectorWidth)
11302 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11303
Chris Lattner867b99f2006-10-05 06:55:50 +000011304 // This instruction only demands the single element from the input vector.
11305 // If the input vector has a single use, simplify it based on this use
11306 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011307 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011308 uint64_t UndefElts;
11309 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000011310 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000011311 UndefElts)) {
11312 EI.setOperand(0, V);
11313 return &EI;
11314 }
11315 }
11316
Reid Spencerb83eb642006-10-20 07:07:24 +000011317 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011318 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011319
11320 // If the this extractelement is directly using a bitcast from a vector of
11321 // the same number of elements, see if we can find the source element from
11322 // it. In this case, we will end up needing to bitcast the scalars.
11323 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11324 if (const VectorType *VT =
11325 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11326 if (VT->getNumElements() == VectorWidth)
11327 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11328 return new BitCastInst(Elt, EI.getType());
11329 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011330 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011331
Chris Lattner73fa49d2006-05-25 22:53:38 +000011332 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011333 if (I->hasOneUse()) {
11334 // Push extractelement into predecessor operation if legal and
11335 // profitable to do so
11336 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011337 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11338 if (CheapToScalarize(BO, isConstantElt)) {
11339 ExtractElementInst *newEI0 =
11340 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11341 EI.getName()+".lhs");
11342 ExtractElementInst *newEI1 =
11343 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11344 EI.getName()+".rhs");
11345 InsertNewInstBefore(newEI0, EI);
11346 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011347 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011348 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011349 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011350 unsigned AS =
11351 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011352 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11353 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011354 GetElementPtrInst *GEP =
11355 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011356 InsertNewInstBefore(GEP, EI);
11357 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011358 }
11359 }
11360 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11361 // Extracting the inserted element?
11362 if (IE->getOperand(2) == EI.getOperand(1))
11363 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11364 // If the inserted and extracted elements are constants, they must not
11365 // be the same value, extract from the pre-inserted value instead.
11366 if (isa<Constant>(IE->getOperand(2)) &&
11367 isa<Constant>(EI.getOperand(1))) {
11368 AddUsesToWorkList(EI);
11369 EI.setOperand(0, IE->getOperand(0));
11370 return &EI;
11371 }
11372 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11373 // If this is extracting an element from a shufflevector, figure out where
11374 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011375 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11376 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011377 Value *Src;
11378 if (SrcIdx < SVI->getType()->getNumElements())
11379 Src = SVI->getOperand(0);
11380 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11381 SrcIdx -= SVI->getType()->getNumElements();
11382 Src = SVI->getOperand(1);
11383 } else {
11384 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011385 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011386 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011387 }
11388 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011389 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011390 return 0;
11391}
11392
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011393/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11394/// elements from either LHS or RHS, return the shuffle mask and true.
11395/// Otherwise, return false.
11396static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11397 std::vector<Constant*> &Mask) {
11398 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11399 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011400 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011401
11402 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011403 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011404 return true;
11405 } else if (V == LHS) {
11406 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011407 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011408 return true;
11409 } else if (V == RHS) {
11410 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011411 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011412 return true;
11413 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11414 // If this is an insert of an extract from some other vector, include it.
11415 Value *VecOp = IEI->getOperand(0);
11416 Value *ScalarOp = IEI->getOperand(1);
11417 Value *IdxOp = IEI->getOperand(2);
11418
Chris Lattnerd929f062006-04-27 21:14:21 +000011419 if (!isa<ConstantInt>(IdxOp))
11420 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011421 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011422
11423 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11424 // Okay, we can handle this if the vector we are insertinting into is
11425 // transitively ok.
11426 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11427 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011428 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011429 return true;
11430 }
11431 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11432 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011433 EI->getOperand(0)->getType() == V->getType()) {
11434 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011435 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011436
11437 // This must be extracting from either LHS or RHS.
11438 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11439 // Okay, we can handle this if the vector we are insertinting into is
11440 // transitively ok.
11441 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11442 // If so, update the mask to reflect the inserted value.
11443 if (EI->getOperand(0) == LHS) {
11444 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011445 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011446 } else {
11447 assert(EI->getOperand(0) == RHS);
11448 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011449 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011450
11451 }
11452 return true;
11453 }
11454 }
11455 }
11456 }
11457 }
11458 // TODO: Handle shufflevector here!
11459
11460 return false;
11461}
11462
11463/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11464/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11465/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011466static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011467 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011468 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011469 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011470 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011471 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011472
11473 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011474 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011475 return V;
11476 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011477 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011478 return V;
11479 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11480 // If this is an insert of an extract from some other vector, include it.
11481 Value *VecOp = IEI->getOperand(0);
11482 Value *ScalarOp = IEI->getOperand(1);
11483 Value *IdxOp = IEI->getOperand(2);
11484
11485 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11486 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11487 EI->getOperand(0)->getType() == V->getType()) {
11488 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011489 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11490 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011491
11492 // Either the extracted from or inserted into vector must be RHSVec,
11493 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011494 if (EI->getOperand(0) == RHS || RHS == 0) {
11495 RHS = EI->getOperand(0);
11496 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011497 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011498 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011499 return V;
11500 }
11501
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011502 if (VecOp == RHS) {
11503 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011504 // Everything but the extracted element is replaced with the RHS.
11505 for (unsigned i = 0; i != NumElts; ++i) {
11506 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011507 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011508 }
11509 return V;
11510 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011511
11512 // If this insertelement is a chain that comes from exactly these two
11513 // vectors, return the vector and the effective shuffle.
11514 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11515 return EI->getOperand(0);
11516
Chris Lattnerefb47352006-04-15 01:39:45 +000011517 }
11518 }
11519 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011520 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011521
11522 // Otherwise, can't do anything fancy. Return an identity vector.
11523 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011524 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011525 return V;
11526}
11527
11528Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11529 Value *VecOp = IE.getOperand(0);
11530 Value *ScalarOp = IE.getOperand(1);
11531 Value *IdxOp = IE.getOperand(2);
11532
Chris Lattner599ded12007-04-09 01:11:16 +000011533 // Inserting an undef or into an undefined place, remove this.
11534 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11535 ReplaceInstUsesWith(IE, VecOp);
11536
Chris Lattnerefb47352006-04-15 01:39:45 +000011537 // If the inserted element was extracted from some other vector, and if the
11538 // indexes are constant, try to turn this into a shufflevector operation.
11539 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11540 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11541 EI->getOperand(0)->getType() == IE.getType()) {
11542 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011543 unsigned ExtractedIdx =
11544 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011545 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011546
11547 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11548 return ReplaceInstUsesWith(IE, VecOp);
11549
11550 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11551 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11552
11553 // If we are extracting a value from a vector, then inserting it right
11554 // back into the same place, just use the input vector.
11555 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11556 return ReplaceInstUsesWith(IE, VecOp);
11557
11558 // We could theoretically do this for ANY input. However, doing so could
11559 // turn chains of insertelement instructions into a chain of shufflevector
11560 // instructions, and right now we do not merge shufflevectors. As such,
11561 // only do this in a situation where it is clear that there is benefit.
11562 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11563 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11564 // the values of VecOp, except then one read from EIOp0.
11565 // Build a new shuffle mask.
11566 std::vector<Constant*> Mask;
11567 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011568 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011569 else {
11570 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011571 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011572 NumVectorElts));
11573 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011574 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011575 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011576 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011577 }
11578
11579 // If this insertelement isn't used by some other insertelement, turn it
11580 // (and any insertelements it points to), into one big shuffle.
11581 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11582 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011583 Value *RHS = 0;
11584 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11585 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11586 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011587 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011588 }
11589 }
11590 }
11591
11592 return 0;
11593}
11594
11595
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011596Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11597 Value *LHS = SVI.getOperand(0);
11598 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011599 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011600
11601 bool MadeChange = false;
11602
Chris Lattner867b99f2006-10-05 06:55:50 +000011603 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011604 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011605 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11606
Chris Lattnere4929dd2007-01-05 07:36:08 +000011607 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011608 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011609 if (isa<UndefValue>(SVI.getOperand(1))) {
11610 // Scan to see if there are any references to the RHS. If so, replace them
11611 // with undef element refs and set MadeChange to true.
11612 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11613 if (Mask[i] >= e && Mask[i] != 2*e) {
11614 Mask[i] = 2*e;
11615 MadeChange = true;
11616 }
11617 }
11618
11619 if (MadeChange) {
11620 // Remap any references to RHS to use LHS.
11621 std::vector<Constant*> Elts;
11622 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11623 if (Mask[i] == 2*e)
11624 Elts.push_back(UndefValue::get(Type::Int32Ty));
11625 else
11626 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11627 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011628 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011629 }
11630 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011631
Chris Lattner863bcff2006-05-25 23:48:38 +000011632 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11633 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11634 if (LHS == RHS || isa<UndefValue>(LHS)) {
11635 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011636 // shuffle(undef,undef,mask) -> undef.
11637 return ReplaceInstUsesWith(SVI, LHS);
11638 }
11639
Chris Lattner863bcff2006-05-25 23:48:38 +000011640 // Remap any references to RHS to use LHS.
11641 std::vector<Constant*> Elts;
11642 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011643 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011644 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011645 else {
11646 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11647 (Mask[i] < e && isa<UndefValue>(LHS)))
11648 Mask[i] = 2*e; // Turn into undef.
11649 else
11650 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011651 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011652 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011653 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011654 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011655 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011656 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011657 LHS = SVI.getOperand(0);
11658 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011659 MadeChange = true;
11660 }
11661
Chris Lattner7b2e27922006-05-26 00:29:06 +000011662 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011663 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011664
Chris Lattner863bcff2006-05-25 23:48:38 +000011665 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11666 if (Mask[i] >= e*2) continue; // Ignore undef values.
11667 // Is this an identity shuffle of the LHS value?
11668 isLHSID &= (Mask[i] == i);
11669
11670 // Is this an identity shuffle of the RHS value?
11671 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011672 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011673
Chris Lattner863bcff2006-05-25 23:48:38 +000011674 // Eliminate identity shuffles.
11675 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11676 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011677
Chris Lattner7b2e27922006-05-26 00:29:06 +000011678 // If the LHS is a shufflevector itself, see if we can combine it with this
11679 // one without producing an unusual shuffle. Here we are really conservative:
11680 // we are absolutely afraid of producing a shuffle mask not in the input
11681 // program, because the code gen may not be smart enough to turn a merged
11682 // shuffle into two specific shuffles: it may produce worse code. As such,
11683 // we only merge two shuffles if the result is one of the two input shuffle
11684 // masks. In this case, merging the shuffles just removes one instruction,
11685 // which we know is safe. This is good for things like turning:
11686 // (splat(splat)) -> splat.
11687 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11688 if (isa<UndefValue>(RHS)) {
11689 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11690
11691 std::vector<unsigned> NewMask;
11692 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11693 if (Mask[i] >= 2*e)
11694 NewMask.push_back(2*e);
11695 else
11696 NewMask.push_back(LHSMask[Mask[i]]);
11697
11698 // If the result mask is equal to the src shuffle or this shuffle mask, do
11699 // the replacement.
11700 if (NewMask == LHSMask || NewMask == Mask) {
11701 std::vector<Constant*> Elts;
11702 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11703 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011704 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011705 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011706 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011707 }
11708 }
11709 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11710 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011711 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011712 }
11713 }
11714 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011715
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011716 return MadeChange ? &SVI : 0;
11717}
11718
11719
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011720
Chris Lattnerea1c4542004-12-08 23:43:58 +000011721
11722/// TryToSinkInstruction - Try to move the specified instruction from its
11723/// current block into the beginning of DestBlock, which can only happen if it's
11724/// safe to move the instruction past all of the instructions between it and the
11725/// end of its block.
11726static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11727 assert(I->hasOneUse() && "Invariants didn't hold!");
11728
Chris Lattner108e9022005-10-27 17:13:11 +000011729 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011730 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11731 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011732
Chris Lattnerea1c4542004-12-08 23:43:58 +000011733 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011734 if (isa<AllocaInst>(I) && I->getParent() ==
11735 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011736 return false;
11737
Chris Lattner96a52a62004-12-09 07:14:34 +000011738 // We can only sink load instructions if there is nothing between the load and
11739 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011740 if (I->mayReadFromMemory()) {
11741 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011742 Scan != E; ++Scan)
11743 if (Scan->mayWriteToMemory())
11744 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011745 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011746
Dan Gohman02dea8b2008-05-23 21:05:58 +000011747 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000011748
Chris Lattner4bc5f802005-08-08 19:11:57 +000011749 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011750 ++NumSunkInst;
11751 return true;
11752}
11753
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011754
11755/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11756/// all reachable code to the worklist.
11757///
11758/// This has a couple of tricks to make the code faster and more powerful. In
11759/// particular, we constant fold and DCE instructions as we go, to avoid adding
11760/// them to the worklist (this significantly speeds up instcombine on code where
11761/// many instructions are dead or constant). Additionally, if we find a branch
11762/// whose condition is a known constant, we only visit the reachable successors.
11763///
11764static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011765 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011766 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011767 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011768 std::vector<BasicBlock*> Worklist;
11769 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011770
Chris Lattner2c7718a2007-03-23 19:17:18 +000011771 while (!Worklist.empty()) {
11772 BB = Worklist.back();
11773 Worklist.pop_back();
11774
11775 // We have now visited this block! If we've already been here, ignore it.
11776 if (!Visited.insert(BB)) continue;
11777
11778 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11779 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011780
Chris Lattner2c7718a2007-03-23 19:17:18 +000011781 // DCE instruction if trivially dead.
11782 if (isInstructionTriviallyDead(Inst)) {
11783 ++NumDeadInst;
11784 DOUT << "IC: DCE: " << *Inst;
11785 Inst->eraseFromParent();
11786 continue;
11787 }
11788
11789 // ConstantProp instruction if trivially constant.
11790 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11791 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11792 Inst->replaceAllUsesWith(C);
11793 ++NumConstProp;
11794 Inst->eraseFromParent();
11795 continue;
11796 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011797
Chris Lattner2c7718a2007-03-23 19:17:18 +000011798 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011799 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011800
11801 // Recursively visit successors. If this is a branch or switch on a
11802 // constant, only visit the reachable successor.
11803 TerminatorInst *TI = BB->getTerminator();
11804 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11805 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11806 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011807 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011808 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011809 continue;
11810 }
11811 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11812 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11813 // See if this is an explicit destination.
11814 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11815 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011816 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011817 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011818 continue;
11819 }
11820
11821 // Otherwise it is the default destination.
11822 Worklist.push_back(SI->getSuccessor(0));
11823 continue;
11824 }
11825 }
11826
11827 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11828 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011829 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011830}
11831
Chris Lattnerec9c3582007-03-03 02:04:50 +000011832bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011833 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011834 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011835
11836 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11837 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011838
Chris Lattnerb3d59702005-07-07 20:40:38 +000011839 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011840 // Do a depth-first traversal of the function, populate the worklist with
11841 // the reachable instructions. Ignore blocks that are not reachable. Keep
11842 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011843 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011844 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011845
Chris Lattnerb3d59702005-07-07 20:40:38 +000011846 // Do a quick scan over the function. If we find any blocks that are
11847 // unreachable, remove any instructions inside of them. This prevents
11848 // the instcombine code from having to deal with some bad special cases.
11849 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11850 if (!Visited.count(BB)) {
11851 Instruction *Term = BB->getTerminator();
11852 while (Term != BB->begin()) { // Remove instrs bottom-up
11853 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011854
Bill Wendlingb7427032006-11-26 09:46:52 +000011855 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011856 ++NumDeadInst;
11857
11858 if (!I->use_empty())
11859 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11860 I->eraseFromParent();
11861 }
11862 }
11863 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011864
Chris Lattnerdbab3862007-03-02 21:28:56 +000011865 while (!Worklist.empty()) {
11866 Instruction *I = RemoveOneFromWorkList();
11867 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011868
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011869 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011870 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011871 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011872 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011873 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011874 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011875
Bill Wendlingb7427032006-11-26 09:46:52 +000011876 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011877
11878 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011879 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011880 continue;
11881 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011882
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011883 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011884 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011885 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011886
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011887 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011888 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011889 ReplaceInstUsesWith(*I, C);
11890
Chris Lattner62b14df2002-09-02 04:59:56 +000011891 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011892 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011893 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011894 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011895 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011896
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000011897 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11898 // See if we can constant fold its operands.
11899 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11900 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11901 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11902 i->set(NewC);
11903 }
11904 }
11905 }
11906
Chris Lattnerea1c4542004-12-08 23:43:58 +000011907 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011908 // FIXME: Remove GetResultInst test when first class support for aggregates
11909 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011910 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011911 BasicBlock *BB = I->getParent();
11912 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11913 if (UserParent != BB) {
11914 bool UserIsSuccessor = false;
11915 // See if the user is one of our successors.
11916 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11917 if (*SI == UserParent) {
11918 UserIsSuccessor = true;
11919 break;
11920 }
11921
11922 // If the user is one of our immediate successors, and if that successor
11923 // only has us as a predecessors (we'd have to split the critical edge
11924 // otherwise), we can keep going.
11925 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11926 next(pred_begin(UserParent)) == pred_end(UserParent))
11927 // Okay, the CFG is simple enough, try to sink this instruction.
11928 Changed |= TryToSinkInstruction(I, UserParent);
11929 }
11930 }
11931
Chris Lattner8a2a3112001-12-14 16:52:21 +000011932 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011933#ifndef NDEBUG
11934 std::string OrigI;
11935#endif
11936 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011937 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011938 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011939 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011940 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011941 DOUT << "IC: Old = " << *I
11942 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011943
Chris Lattnerf523d062004-06-09 05:08:07 +000011944 // Everything uses the new instruction now.
11945 I->replaceAllUsesWith(Result);
11946
11947 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011948 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011949 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011950
Chris Lattner6934a042007-02-11 01:23:03 +000011951 // Move the name to the new instruction first.
11952 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011953
11954 // Insert the new instruction into the basic block...
11955 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011956 BasicBlock::iterator InsertPos = I;
11957
11958 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11959 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11960 ++InsertPos;
11961
11962 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011963
Chris Lattner00d51312004-05-01 23:27:23 +000011964 // Make sure that we reprocess all operands now that we reduced their
11965 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011966 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011967
Chris Lattnerf523d062004-06-09 05:08:07 +000011968 // Instructions can end up on the worklist more than once. Make sure
11969 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011970 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011971
11972 // Erase the old instruction.
11973 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011974 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011975#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011976 DOUT << "IC: Mod = " << OrigI
11977 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011978#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011979
Chris Lattner90ac28c2002-08-02 19:29:35 +000011980 // If the instruction was modified, it's possible that it is now dead.
11981 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011982 if (isInstructionTriviallyDead(I)) {
11983 // Make sure we process all operands now that we are reducing their
11984 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011985 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011986
Chris Lattner00d51312004-05-01 23:27:23 +000011987 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011988 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011989 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011990 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011991 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011992 AddToWorkList(I);
11993 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011994 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011995 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011996 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011997 }
11998 }
11999
Chris Lattnerec9c3582007-03-03 02:04:50 +000012000 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000012001
12002 // Do an explicit clear, this shrinks the map if needed.
12003 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012004 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012005}
12006
Chris Lattnerec9c3582007-03-03 02:04:50 +000012007
12008bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012009 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12010
Chris Lattnerec9c3582007-03-03 02:04:50 +000012011 bool EverMadeChange = false;
12012
12013 // Iterate while there is work to do.
12014 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012015 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012016 EverMadeChange = true;
12017 return EverMadeChange;
12018}
12019
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012020FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012021 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012022}
Brian Gaeked0fde302003-11-11 22:41:34 +000012023