blob: 46dba398cfeabb15f2b1c0d8ba6dfef2167323d2 [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 Lattner9fe38862003-06-19 17:00:31 +0000244
Chris Lattner28977af2004-04-05 01:30:19 +0000245 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000246 // InsertNewInstBefore - insert an instruction New before instruction Old
247 // in the program. Add the new instruction to the worklist.
248 //
Chris Lattner955f3312004-09-28 21:48:02 +0000249 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000250 assert(New && New->getParent() == 0 &&
251 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000252 BasicBlock *BB = Old.getParent();
253 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000254 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000255 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000256 }
257
Chris Lattner0c967662004-09-24 15:21:34 +0000258 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
259 /// This also adds the cast to the worklist. Finally, this returns the
260 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000261 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
262 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000263 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000264
Chris Lattnere2ed0572006-04-06 19:19:17 +0000265 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000266 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000267
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000268 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000269 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000270 return C;
271 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000272
273 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
274 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
275 }
276
Chris Lattner0c967662004-09-24 15:21:34 +0000277
Chris Lattner8b170942002-08-09 23:47:40 +0000278 // ReplaceInstUsesWith - This method is to be used when an instruction is
279 // found to be dead, replacable with another preexisting expression. Here
280 // we add all uses of I to the worklist, replace all uses of I with the new
281 // value, then return I, so that the inst combiner will know that I was
282 // modified.
283 //
284 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000285 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000286 if (&I != V) {
287 I.replaceAllUsesWith(V);
288 return &I;
289 } else {
290 // If we are replacing the instruction with itself, this must be in a
291 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000292 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000293 return &I;
294 }
Chris Lattner8b170942002-08-09 23:47:40 +0000295 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000296
Chris Lattner6dce1a72006-02-07 06:56:34 +0000297 // UpdateValueUsesWith - This method is to be used when an value is
298 // found to be replacable with another preexisting expression or was
299 // updated. Here we add all uses of I to the worklist, replace all uses of
300 // I with the new value (unless the instruction was just updated), then
301 // return true, so that the inst combiner will know that I was modified.
302 //
303 bool UpdateValueUsesWith(Value *Old, Value *New) {
304 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
305 if (Old != New)
306 Old->replaceAllUsesWith(New);
307 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000308 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000309 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000310 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000311 return true;
312 }
313
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000314 // EraseInstFromFunction - When dealing with an instruction that has side
315 // effects or produces a void value, we can't rely on DCE to delete the
316 // instruction. Instead, visit methods should return the value returned by
317 // this function.
318 Instruction *EraseInstFromFunction(Instruction &I) {
319 assert(I.use_empty() && "Cannot erase instruction that is used!");
320 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000321 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000322 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000323 return 0; // Don't do anything with FI
324 }
325
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000326 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000327 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
328 /// InsertBefore instruction. This is specialized a bit to avoid inserting
329 /// casts that are known to not do anything...
330 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000331 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
332 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000333 Instruction *InsertBefore);
334
Reid Spencere4d87aa2006-12-23 06:05:41 +0000335 /// SimplifyCommutative - This performs a few simplifications for
336 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000337 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000338
Reid Spencere4d87aa2006-12-23 06:05:41 +0000339 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
340 /// most-complex to least-complex order.
341 bool SimplifyCompare(CmpInst &I);
342
Reid Spencer2ec619a2007-03-23 21:24:59 +0000343 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
344 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000345 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
346 APInt& KnownZero, APInt& KnownOne,
347 unsigned Depth = 0);
348
Chris Lattner867b99f2006-10-05 06:55:50 +0000349 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
350 uint64_t &UndefElts, unsigned Depth = 0);
351
Chris Lattner4e998b22004-09-29 05:07:12 +0000352 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
353 // PHI node as operand #0, see if we can fold the instruction into the PHI
354 // (which is only possible if all operands to the PHI are constants).
355 Instruction *FoldOpIntoPhi(Instruction &I);
356
Chris Lattnerbac32862004-11-14 19:13:23 +0000357 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
358 // operator and they all are only used by the PHI, PHI together their
359 // inputs, and do the operation once, to the result of the PHI.
360 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000361 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
362
363
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000364 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
365 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000366
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000367 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000368 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000369 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000370 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000371 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000372 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000373 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000374 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000375 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000376
Chris Lattnerafe91a52006-06-15 19:07:26 +0000377
Reid Spencerc55b2432006-12-13 18:21:21 +0000378 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000379
380 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
381 APInt& KnownOne, unsigned Depth = 0);
382 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
383 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
384 unsigned CastOpc,
385 int &NumCastsRemoved);
386 unsigned GetOrEnforceKnownAlignment(Value *V,
387 unsigned PrefAlign = 0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000388 };
389}
390
Dan Gohman844731a2008-05-13 00:00:25 +0000391char InstCombiner::ID = 0;
392static RegisterPass<InstCombiner>
393X("instcombine", "Combine redundant instructions");
394
Chris Lattner4f98c562003-03-10 21:43:22 +0000395// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000396// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000397static unsigned getComplexity(Value *V) {
398 if (isa<Instruction>(V)) {
399 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000400 return 3;
401 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000402 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000403 if (isa<Argument>(V)) return 3;
404 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000405}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000406
Chris Lattnerc8802d22003-03-11 00:12:48 +0000407// isOnlyUse - Return true if this instruction will be deleted if we stop using
408// it.
409static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000410 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000411}
412
Chris Lattner4cb170c2004-02-23 06:38:22 +0000413// getPromotedType - Return the specified type promoted as it would be to pass
414// though a va_arg area...
415static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000416 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
417 if (ITy->getBitWidth() < 32)
418 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000419 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000420 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000421}
422
Chris Lattnera5406232008-05-19 20:18:56 +0000423/// GetFPMantissaWidth - Return the width of the mantissa (aka significand) of
424/// the specified floating point type in bits. This returns -1 if unknown.
425static int GetFPMantissaWidth(const Type *FPType) {
426 if (FPType == Type::FloatTy)
427 return 24;
428 if (FPType == Type::DoubleTy)
429 return 53;
430 if (FPType == Type::X86_FP80Ty)
431 return 64;
432 return -1; // Unknown/crazy type.
433}
434
Reid Spencer3da59db2006-11-27 01:05:10 +0000435/// getBitCastOperand - If the specified operand is a CastInst or a constant
436/// expression bitcast, return the operand value, otherwise return null.
437static Value *getBitCastOperand(Value *V) {
438 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000439 return I->getOperand(0);
440 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000441 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000442 return CE->getOperand(0);
443 return 0;
444}
445
Reid Spencer3da59db2006-11-27 01:05:10 +0000446/// This function is a wrapper around CastInst::isEliminableCastPair. It
447/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000448static Instruction::CastOps
449isEliminableCastPair(
450 const CastInst *CI, ///< The first cast instruction
451 unsigned opcode, ///< The opcode of the second cast instruction
452 const Type *DstTy, ///< The target type for the second cast instruction
453 TargetData *TD ///< The target data for pointer size
454) {
455
456 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
457 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000458
Reid Spencer3da59db2006-11-27 01:05:10 +0000459 // Get the opcodes of the two Cast instructions
460 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
461 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000462
Reid Spencer3da59db2006-11-27 01:05:10 +0000463 return Instruction::CastOps(
464 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
465 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000466}
467
468/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
469/// in any code being generated. It does not require codegen if V is simple
470/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000471static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
472 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000473 if (V->getType() == Ty || isa<Constant>(V)) return false;
474
Chris Lattner01575b72006-05-25 23:24:33 +0000475 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000476 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000477 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000478 return false;
479 return true;
480}
481
482/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
483/// InsertBefore instruction. This is specialized a bit to avoid inserting
484/// casts that are known to not do anything...
485///
Reid Spencer17212df2006-12-12 09:18:51 +0000486Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
487 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000488 Instruction *InsertBefore) {
489 if (V->getType() == DestTy) return V;
490 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000491 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000492
Reid Spencer17212df2006-12-12 09:18:51 +0000493 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000494}
495
Chris Lattner4f98c562003-03-10 21:43:22 +0000496// SimplifyCommutative - This performs a few simplifications for commutative
497// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000498//
Chris Lattner4f98c562003-03-10 21:43:22 +0000499// 1. Order operands such that they are listed from right (least complex) to
500// left (most complex). This puts constants before unary operators before
501// binary operators.
502//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000503// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
504// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000505//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000506bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000507 bool Changed = false;
508 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
509 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000510
Chris Lattner4f98c562003-03-10 21:43:22 +0000511 if (!I.isAssociative()) return Changed;
512 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000513 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
514 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
515 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000516 Constant *Folded = ConstantExpr::get(I.getOpcode(),
517 cast<Constant>(I.getOperand(1)),
518 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000519 I.setOperand(0, Op->getOperand(0));
520 I.setOperand(1, Folded);
521 return true;
522 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
523 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
524 isOnlyUse(Op) && isOnlyUse(Op1)) {
525 Constant *C1 = cast<Constant>(Op->getOperand(1));
526 Constant *C2 = cast<Constant>(Op1->getOperand(1));
527
528 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000529 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000530 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000531 Op1->getOperand(0),
532 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000533 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000534 I.setOperand(0, New);
535 I.setOperand(1, Folded);
536 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000537 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000538 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000539 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000540}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000541
Reid Spencere4d87aa2006-12-23 06:05:41 +0000542/// SimplifyCompare - For a CmpInst this function just orders the operands
543/// so that theyare listed from right (least complex) to left (most complex).
544/// This puts constants before unary operators before binary operators.
545bool InstCombiner::SimplifyCompare(CmpInst &I) {
546 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
547 return false;
548 I.swapOperands();
549 // Compare instructions are not associative so there's nothing else we can do.
550 return true;
551}
552
Chris Lattner8d969642003-03-10 23:06:50 +0000553// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
554// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000555//
Chris Lattner8d969642003-03-10 23:06:50 +0000556static inline Value *dyn_castNegVal(Value *V) {
557 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000558 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000559
Chris Lattner0ce85802004-12-14 20:08:06 +0000560 // Constants can be considered to be negated values if they can be folded.
561 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
562 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000563 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000564}
565
Chris Lattner8d969642003-03-10 23:06:50 +0000566static inline Value *dyn_castNotVal(Value *V) {
567 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000568 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000569
570 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000571 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000572 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000573 return 0;
574}
575
Chris Lattnerc8802d22003-03-11 00:12:48 +0000576// dyn_castFoldableMul - If this value is a multiply that can be folded into
577// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000578// non-constant operand of the multiply, and set CST to point to the multiplier.
579// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000580//
Chris Lattner50af16a2004-11-13 19:50:12 +0000581static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000582 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000583 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000584 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000585 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000586 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000587 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000588 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000589 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000590 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000591 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000592 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000593 return I->getOperand(0);
594 }
595 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000596 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000597}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000598
Chris Lattner574da9b2005-01-13 20:14:25 +0000599/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
600/// expression, return it.
601static User *dyn_castGetElementPtr(Value *V) {
602 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
603 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
604 if (CE->getOpcode() == Instruction::GetElementPtr)
605 return cast<User>(V);
606 return false;
607}
608
Dan Gohmaneee962e2008-04-10 18:43:06 +0000609/// getOpcode - If this is an Instruction or a ConstantExpr, return the
610/// opcode value. Otherwise return UserOp1.
611static unsigned getOpcode(User *U) {
612 if (Instruction *I = dyn_cast<Instruction>(U))
613 return I->getOpcode();
614 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U))
615 return CE->getOpcode();
616 // Use UserOp1 to mean there's no opcode.
617 return Instruction::UserOp1;
618}
619
Reid Spencer7177c3a2007-03-25 05:33:51 +0000620/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000621static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000622 APInt Val(C->getValue());
623 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000624}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000625/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000626static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000627 APInt Val(C->getValue());
628 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000629}
630/// Add - Add two ConstantInts together
631static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
632 return ConstantInt::get(C1->getValue() + C2->getValue());
633}
634/// And - Bitwise AND two ConstantInts together
635static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
636 return ConstantInt::get(C1->getValue() & C2->getValue());
637}
638/// Subtract - Subtract one ConstantInt from another
639static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
640 return ConstantInt::get(C1->getValue() - C2->getValue());
641}
642/// Multiply - Multiply two ConstantInts together
643static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
644 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000645}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000646/// MultiplyOverflows - True if the multiply can not be expressed in an int
647/// this size.
648static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
649 uint32_t W = C1->getBitWidth();
650 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
651 if (sign) {
652 LHSExt.sext(W * 2);
653 RHSExt.sext(W * 2);
654 } else {
655 LHSExt.zext(W * 2);
656 RHSExt.zext(W * 2);
657 }
658
659 APInt MulExt = LHSExt * RHSExt;
660
661 if (sign) {
662 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
663 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
664 return MulExt.slt(Min) || MulExt.sgt(Max);
665 } else
666 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
667}
Chris Lattner955f3312004-09-28 21:48:02 +0000668
Chris Lattner68d5ff22006-02-09 07:38:58 +0000669/// ComputeMaskedBits - Determine which of the bits specified in Mask are
670/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000671/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
672/// processing.
673/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
674/// we cannot optimize based on the assumption that it is zero without changing
675/// it to be an explicit zero. If we don't change it to zero, other code could
676/// optimized based on the contradictory assumption that it is non-zero.
677/// Because instcombine aggressively folds operations with undef args anyway,
678/// this won't lose us code quality.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000679void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
680 APInt& KnownZero, APInt& KnownOne,
681 unsigned Depth) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000682 assert(V && "No Value?");
683 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000684 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000685 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
686 "Not integer or pointer type!");
687 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
688 (!isa<IntegerType>(V->getType()) ||
689 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000690 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000691 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000692 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000693 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
694 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000695 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000696 KnownZero = ~KnownOne & Mask;
697 return;
698 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000699 // Null is all-zeros.
700 if (isa<ConstantPointerNull>(V)) {
701 KnownOne.clear();
702 KnownZero = Mask;
703 return;
704 }
705 // The address of an aligned GlobalValue has trailing zeros.
706 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
707 unsigned Align = GV->getAlignment();
708 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
709 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
710 if (Align > 0)
711 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
712 CountTrailingZeros_32(Align));
713 else
714 KnownZero.clear();
715 KnownOne.clear();
716 return;
717 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000718
Dan Gohman23e8b712008-04-28 17:02:21 +0000719 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
720
Reid Spencer3e7594f2007-03-08 01:46:38 +0000721 if (Depth == 6 || Mask == 0)
722 return; // Limit search depth.
723
Dan Gohmaneee962e2008-04-10 18:43:06 +0000724 User *I = dyn_cast<User>(V);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000725 if (!I) return;
726
727 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000728 switch (getOpcode(I)) {
729 default: break;
Reid Spencer2b812072007-03-25 02:03:12 +0000730 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000731 // If either the LHS or the RHS are Zero, the result is zero.
732 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000733 APInt Mask2(Mask & ~KnownZero);
734 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000735 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
736 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
737
738 // Output known-1 bits are only known if set in both the LHS & RHS.
739 KnownOne &= KnownOne2;
740 // Output known-0 are known to be clear if zero in either the LHS | RHS.
741 KnownZero |= KnownZero2;
742 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000743 }
744 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000745 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000746 APInt Mask2(Mask & ~KnownOne);
747 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000748 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
749 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
750
751 // Output known-0 bits are only known if clear in both the LHS & RHS.
752 KnownZero &= KnownZero2;
753 // Output known-1 are known to be set if set in either the LHS | RHS.
754 KnownOne |= KnownOne2;
755 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000756 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000757 case Instruction::Xor: {
758 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
759 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
760 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
761 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
762
763 // Output known-0 bits are known if clear or set in both the LHS & RHS.
764 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
765 // Output known-1 are known to be set if set in only one of the LHS, RHS.
766 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
767 KnownZero = KnownZeroOut;
768 return;
769 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000770 case Instruction::Mul: {
771 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
772 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
773 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
774 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
775 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
776
777 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohman23e8b712008-04-28 17:02:21 +0000778 // Also compute a conserative estimate for high known-0 bits.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000779 // More trickiness is possible, but this is sufficient for the
780 // interesting case of alignment computation.
781 KnownOne.clear();
782 unsigned TrailZ = KnownZero.countTrailingOnes() +
783 KnownZero2.countTrailingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +0000784 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
Dan Gohman42ac9292008-05-07 00:35:55 +0000785 KnownZero2.countLeadingOnes(),
786 BitWidth) - BitWidth;
Dan Gohman23e8b712008-04-28 17:02:21 +0000787
Dan Gohmaneee962e2008-04-10 18:43:06 +0000788 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000789 LeadZ = std::min(LeadZ, BitWidth);
790 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
791 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000792 KnownZero &= Mask;
793 return;
794 }
Dan Gohman23e8b712008-04-28 17:02:21 +0000795 case Instruction::UDiv: {
796 // For the purposes of computing leading zeros we can conservatively
797 // treat a udiv as a logical right shift by the power of 2 known to
Dan Gohman1d9cd502008-05-02 21:30:02 +0000798 // be less than the denominator.
Dan Gohman23e8b712008-04-28 17:02:21 +0000799 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
800 ComputeMaskedBits(I->getOperand(0),
801 AllOnes, KnownZero2, KnownOne2, Depth+1);
802 unsigned LeadZ = KnownZero2.countLeadingOnes();
803
804 KnownOne2.clear();
805 KnownZero2.clear();
806 ComputeMaskedBits(I->getOperand(1),
807 AllOnes, KnownZero2, KnownOne2, Depth+1);
Dan Gohman1d9cd502008-05-02 21:30:02 +0000808 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
809 if (RHSUnknownLeadingOnes != BitWidth)
810 LeadZ = std::min(BitWidth,
811 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000812
813 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
814 return;
815 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000816 case Instruction::Select:
817 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
818 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
819 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
820 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
821
822 // Only known if known in both the LHS and RHS.
823 KnownOne &= KnownOne2;
824 KnownZero &= KnownZero2;
825 return;
826 case Instruction::FPTrunc:
827 case Instruction::FPExt:
828 case Instruction::FPToUI:
829 case Instruction::FPToSI:
830 case Instruction::SIToFP:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000831 case Instruction::UIToFP:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000832 return; // Can't work with floating point.
833 case Instruction::PtrToInt:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000834 case Instruction::IntToPtr:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000835 // We can't handle these if we don't know the pointer size.
836 if (!TD) return;
837 // Fall through and handle them the same as zext/trunc.
838 case Instruction::ZExt:
Zhou Sheng771dbf72007-03-13 02:23:10 +0000839 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000840 // All these have integer operands
Dan Gohmaneee962e2008-04-10 18:43:06 +0000841 const Type *SrcTy = I->getOperand(0)->getType();
842 uint32_t SrcBitWidth = TD ?
843 TD->getTypeSizeInBits(SrcTy) :
844 SrcTy->getPrimitiveSizeInBits();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000845 APInt MaskIn(Mask);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000846 MaskIn.zextOrTrunc(SrcBitWidth);
847 KnownZero.zextOrTrunc(SrcBitWidth);
848 KnownOne.zextOrTrunc(SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000849 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000850 KnownZero.zextOrTrunc(BitWidth);
851 KnownOne.zextOrTrunc(BitWidth);
852 // Any top bits are known to be zero.
853 if (BitWidth > SrcBitWidth)
854 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000855 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000856 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000857 case Instruction::BitCast: {
858 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000859 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000860 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
861 return;
862 }
863 break;
864 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000865 case Instruction::SExt: {
866 // Compute the bits in the result that are not present in the input.
867 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000868 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000869
Zhou Shengaa305ab2007-03-28 02:19:03 +0000870 APInt MaskIn(Mask);
871 MaskIn.trunc(SrcBitWidth);
872 KnownZero.trunc(SrcBitWidth);
873 KnownOne.trunc(SrcBitWidth);
874 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000875 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000876 KnownZero.zext(BitWidth);
877 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000878
879 // If the sign bit of the input is known set or clear, then we know the
880 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000881 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000882 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000883 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000884 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000885 return;
886 }
887 case Instruction::Shl:
888 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
889 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000890 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000891 APInt Mask2(Mask.lshr(ShiftAmt));
892 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000893 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000894 KnownZero <<= ShiftAmt;
895 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000896 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000897 return;
898 }
899 break;
900 case Instruction::LShr:
901 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
902 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
903 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000904 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000905
906 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000907 APInt Mask2(Mask.shl(ShiftAmt));
908 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000909 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
910 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
911 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000912 // high bits known zero.
913 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000914 return;
915 }
916 break;
917 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000918 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000919 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
920 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000921 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000922
923 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000924 APInt Mask2(Mask.shl(ShiftAmt));
925 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000926 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
927 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
928 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
929
Zhou Shengaa305ab2007-03-28 02:19:03 +0000930 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
931 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000932 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000933 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000934 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000935 return;
936 }
937 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000938 case Instruction::Sub: {
939 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
940 // We know that the top bits of C-X are clear if X contains less bits
941 // than C (i.e. no wrap-around can happen). For example, 20-X is
942 // positive if we can prove that X is >= 0 and < 16.
943 if (!CLHS->getValue().isNegative()) {
944 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
945 // NLZ can't be BitWidth with no sign bit
946 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000947 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
948 Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000949
Dan Gohman23e8b712008-04-28 17:02:21 +0000950 // If all of the MaskV bits are known to be zero, then we know the
951 // output top bits are zero, because we now know that the output is
952 // from [0-C].
953 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohmaneee962e2008-04-10 18:43:06 +0000954 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
955 // Top bits known zero.
956 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000957 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000958 }
959 }
960 }
961 // fall through
Duncan Sands1d57a752008-03-21 08:32:17 +0000962 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000963 // Output known-0 bits are known if clear or set in both the low clear bits
964 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
965 // low 3 bits clear.
Dan Gohman23e8b712008-04-28 17:02:21 +0000966 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
967 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
968 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
969 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
970
971 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
972 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
973 KnownZeroOut = std::min(KnownZeroOut,
974 KnownZero2.countTrailingOnes());
975
976 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000977 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000978 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000979 case Instruction::SRem:
980 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
981 APInt RA = Rem->getValue();
982 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +0000983 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000984 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
985 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
986
987 // The sign of a remainder is equal to the sign of the first
988 // operand (zero being positive).
989 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
990 KnownZero2 |= ~LowBits;
991 else if (KnownOne2[BitWidth-1])
992 KnownOne2 |= ~LowBits;
993
994 KnownZero |= KnownZero2 & Mask;
995 KnownOne |= KnownOne2 & Mask;
996
997 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
998 }
999 }
1000 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001001 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001002 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1003 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001004 if (RA.isPowerOf2()) {
1005 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001006 APInt Mask2 = LowBits & Mask;
1007 KnownZero |= ~LowBits & Mask;
1008 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1009 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001010 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001011 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001012 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001013
1014 // Since the result is less than or equal to either operand, any leading
1015 // zero bits in either operand must also exist in the result.
1016 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1017 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1018 Depth+1);
1019 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1020 Depth+1);
1021
1022 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1023 KnownZero2.countLeadingOnes());
1024 KnownOne.clear();
1025 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001026 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001027 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00001028
1029 case Instruction::Alloca:
1030 case Instruction::Malloc: {
1031 AllocationInst *AI = cast<AllocationInst>(V);
1032 unsigned Align = AI->getAlignment();
1033 if (Align == 0 && TD) {
1034 if (isa<AllocaInst>(AI))
1035 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1036 else if (isa<MallocInst>(AI)) {
1037 // Malloc returns maximally aligned memory.
1038 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1039 Align =
1040 std::max(Align,
1041 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1042 Align =
1043 std::max(Align,
1044 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1045 }
1046 }
1047
1048 if (Align > 0)
1049 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1050 CountTrailingZeros_32(Align));
1051 break;
1052 }
1053 case Instruction::GetElementPtr: {
1054 // Analyze all of the subscripts of this getelementptr instruction
1055 // to determine if we can prove known low zero bits.
1056 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1057 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1058 ComputeMaskedBits(I->getOperand(0), LocalMask,
1059 LocalKnownZero, LocalKnownOne, Depth+1);
1060 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1061
1062 gep_type_iterator GTI = gep_type_begin(I);
1063 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1064 Value *Index = I->getOperand(i);
1065 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1066 // Handle struct member offset arithmetic.
1067 if (!TD) return;
1068 const StructLayout *SL = TD->getStructLayout(STy);
1069 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1070 uint64_t Offset = SL->getElementOffset(Idx);
1071 TrailZ = std::min(TrailZ,
1072 CountTrailingZeros_64(Offset));
1073 } else {
1074 // Handle array index arithmetic.
1075 const Type *IndexedTy = GTI.getIndexedType();
1076 if (!IndexedTy->isSized()) return;
1077 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1078 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1079 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1080 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1081 ComputeMaskedBits(Index, LocalMask,
1082 LocalKnownZero, LocalKnownOne, Depth+1);
1083 TrailZ = std::min(TrailZ,
1084 CountTrailingZeros_64(TypeSize) +
1085 LocalKnownZero.countTrailingOnes());
1086 }
1087 }
1088
1089 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1090 break;
1091 }
1092 case Instruction::PHI: {
1093 PHINode *P = cast<PHINode>(I);
1094 // Handle the case of a simple two-predecessor recurrence PHI.
1095 // There's a lot more that could theoretically be done here, but
1096 // this is sufficient to catch some interesting cases.
1097 if (P->getNumIncomingValues() == 2) {
1098 for (unsigned i = 0; i != 2; ++i) {
1099 Value *L = P->getIncomingValue(i);
1100 Value *R = P->getIncomingValue(!i);
1101 User *LU = dyn_cast<User>(L);
1102 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1103 // Check for operations that have the property that if
1104 // both their operands have low zero bits, the result
1105 // will have low zero bits.
1106 if (Opcode == Instruction::Add ||
1107 Opcode == Instruction::Sub ||
1108 Opcode == Instruction::And ||
1109 Opcode == Instruction::Or ||
1110 Opcode == Instruction::Mul) {
1111 Value *LL = LU->getOperand(0);
1112 Value *LR = LU->getOperand(1);
1113 // Find a recurrence.
1114 if (LL == I)
1115 L = LR;
1116 else if (LR == I)
1117 L = LL;
1118 else
1119 break;
1120 // Ok, we have a PHI of the form L op= R. Check for low
1121 // zero bits.
1122 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1123 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1124 Mask2 = APInt::getLowBitsSet(BitWidth,
1125 KnownZero2.countTrailingOnes());
1126 KnownOne2.clear();
1127 KnownZero2.clear();
1128 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1129 KnownZero = Mask &
1130 APInt::getLowBitsSet(BitWidth,
1131 KnownZero2.countTrailingOnes());
1132 break;
1133 }
1134 }
1135 }
1136 break;
1137 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001138 case Instruction::Call:
1139 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1140 switch (II->getIntrinsicID()) {
1141 default: break;
1142 case Intrinsic::ctpop:
1143 case Intrinsic::ctlz:
1144 case Intrinsic::cttz: {
1145 unsigned LowBits = Log2_32(BitWidth)+1;
1146 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1147 break;
1148 }
1149 }
1150 }
1151 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +00001152 }
1153}
1154
Reid Spencere7816b52007-03-08 01:52:58 +00001155/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1156/// this predicate to simplify operations downstream. Mask is known to be zero
1157/// for bits that V cannot have.
Dan Gohmaneee962e2008-04-10 18:43:06 +00001158bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1159 unsigned Depth) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001160 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001161 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1162 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1163 return (KnownZero & Mask) == Mask;
1164}
1165
Chris Lattner255d8912006-02-11 09:31:47 +00001166/// ShrinkDemandedConstant - Check to see if the specified operand of the
1167/// specified instruction is a constant integer. If so, check to see if there
1168/// are any bits set in the constant that are not demanded. If so, shrink the
1169/// constant and return true.
1170static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001171 APInt Demanded) {
1172 assert(I && "No instruction?");
1173 assert(OpNo < I->getNumOperands() && "Operand index too large");
1174
1175 // If the operand is not a constant integer, nothing to do.
1176 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1177 if (!OpC) return false;
1178
1179 // If there are no bits set that aren't demanded, nothing to do.
1180 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1181 if ((~Demanded & OpC->getValue()) == 0)
1182 return false;
1183
1184 // This instruction is producing bits that are not demanded. Shrink the RHS.
1185 Demanded &= OpC->getValue();
1186 I->setOperand(OpNo, ConstantInt::get(Demanded));
1187 return true;
1188}
1189
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001190// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1191// set of known zero and one bits, compute the maximum and minimum values that
1192// could have the specified known zero and known one bits, returning them in
1193// min/max.
1194static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +00001195 const APInt& KnownZero,
1196 const APInt& KnownOne,
1197 APInt& Min, APInt& Max) {
1198 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1199 assert(KnownZero.getBitWidth() == BitWidth &&
1200 KnownOne.getBitWidth() == BitWidth &&
1201 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1202 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001203 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001204
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001205 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1206 // bit if it is unknown.
1207 Min = KnownOne;
1208 Max = KnownOne|UnknownBits;
1209
Zhou Sheng4acf1552007-03-28 05:15:57 +00001210 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001211 Min.set(BitWidth-1);
1212 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001213 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001214}
1215
1216// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1217// a set of known zero and one bits, compute the maximum and minimum values that
1218// could have the specified known zero and known one bits, returning them in
1219// min/max.
1220static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001221 const APInt &KnownZero,
1222 const APInt &KnownOne,
1223 APInt &Min, APInt &Max) {
1224 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +00001225 assert(KnownZero.getBitWidth() == BitWidth &&
1226 KnownOne.getBitWidth() == BitWidth &&
1227 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1228 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001229 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001230
1231 // The minimum value is when the unknown bits are all zeros.
1232 Min = KnownOne;
1233 // The maximum value is when the unknown bits are all ones.
1234 Max = KnownOne|UnknownBits;
1235}
Chris Lattner255d8912006-02-11 09:31:47 +00001236
Reid Spencer8cb68342007-03-12 17:25:59 +00001237/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1238/// value based on the demanded bits. When this function is called, it is known
1239/// that only the bits set in DemandedMask of the result of V are ever used
1240/// downstream. Consequently, depending on the mask and V, it may be possible
1241/// to replace V with a constant or one of its operands. In such cases, this
1242/// function does the replacement and returns true. In all other cases, it
1243/// returns false after analyzing the expression and setting KnownOne and known
1244/// to be one in the expression. KnownZero contains all the bits that are known
1245/// to be zero in the expression. These are provided to potentially allow the
1246/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1247/// the expression. KnownOne and KnownZero always follow the invariant that
1248/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1249/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1250/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1251/// and KnownOne must all be the same.
1252bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1253 APInt& KnownZero, APInt& KnownOne,
1254 unsigned Depth) {
1255 assert(V != 0 && "Null pointer of Value???");
1256 assert(Depth <= 6 && "Limit Search Depth");
1257 uint32_t BitWidth = DemandedMask.getBitWidth();
1258 const IntegerType *VTy = cast<IntegerType>(V->getType());
1259 assert(VTy->getBitWidth() == BitWidth &&
1260 KnownZero.getBitWidth() == BitWidth &&
1261 KnownOne.getBitWidth() == BitWidth &&
1262 "Value *V, DemandedMask, KnownZero and KnownOne \
1263 must have same BitWidth");
1264 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1265 // We know all of the bits for a constant!
1266 KnownOne = CI->getValue() & DemandedMask;
1267 KnownZero = ~KnownOne & DemandedMask;
1268 return false;
1269 }
1270
Zhou Sheng96704452007-03-14 03:21:24 +00001271 KnownZero.clear();
1272 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 if (!V->hasOneUse()) { // Other users may use these bits.
1274 if (Depth != 0) { // Not at the root.
1275 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1276 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1277 return false;
1278 }
1279 // If this is the root being simplified, allow it to have multiple uses,
1280 // just set the DemandedMask to all bits.
1281 DemandedMask = APInt::getAllOnesValue(BitWidth);
1282 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1283 if (V != UndefValue::get(VTy))
1284 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1285 return false;
1286 } else if (Depth == 6) { // Limit search depth.
1287 return false;
1288 }
1289
1290 Instruction *I = dyn_cast<Instruction>(V);
1291 if (!I) return false; // Only analyze instructions.
1292
Reid Spencer8cb68342007-03-12 17:25:59 +00001293 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1294 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1295 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001296 default:
1297 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1298 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001299 case Instruction::And:
1300 // If either the LHS or the RHS are Zero, the result is zero.
1301 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1302 RHSKnownZero, RHSKnownOne, Depth+1))
1303 return true;
1304 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1305 "Bits known to be one AND zero?");
1306
1307 // If something is known zero on the RHS, the bits aren't demanded on the
1308 // LHS.
1309 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1310 LHSKnownZero, LHSKnownOne, Depth+1))
1311 return true;
1312 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1313 "Bits known to be one AND zero?");
1314
1315 // If all of the demanded bits are known 1 on one side, return the other.
1316 // These bits cannot contribute to the result of the 'and'.
1317 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1318 (DemandedMask & ~LHSKnownZero))
1319 return UpdateValueUsesWith(I, I->getOperand(0));
1320 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1321 (DemandedMask & ~RHSKnownZero))
1322 return UpdateValueUsesWith(I, I->getOperand(1));
1323
1324 // If all of the demanded bits in the inputs are known zeros, return zero.
1325 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1326 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1327
1328 // If the RHS is a constant, see if we can simplify it.
1329 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1330 return UpdateValueUsesWith(I, I);
1331
1332 // Output known-1 bits are only known if set in both the LHS & RHS.
1333 RHSKnownOne &= LHSKnownOne;
1334 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1335 RHSKnownZero |= LHSKnownZero;
1336 break;
1337 case Instruction::Or:
1338 // If either the LHS or the RHS are One, the result is One.
1339 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1340 RHSKnownZero, RHSKnownOne, Depth+1))
1341 return true;
1342 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1343 "Bits known to be one AND zero?");
1344 // If something is known one on the RHS, the bits aren't demanded on the
1345 // LHS.
1346 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1347 LHSKnownZero, LHSKnownOne, Depth+1))
1348 return true;
1349 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1350 "Bits known to be one AND zero?");
1351
1352 // If all of the demanded bits are known zero on one side, return the other.
1353 // These bits cannot contribute to the result of the 'or'.
1354 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1355 (DemandedMask & ~LHSKnownOne))
1356 return UpdateValueUsesWith(I, I->getOperand(0));
1357 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1358 (DemandedMask & ~RHSKnownOne))
1359 return UpdateValueUsesWith(I, I->getOperand(1));
1360
1361 // If all of the potentially set bits on one side are known to be set on
1362 // the other side, just use the 'other' side.
1363 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1364 (DemandedMask & (~RHSKnownZero)))
1365 return UpdateValueUsesWith(I, I->getOperand(0));
1366 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1367 (DemandedMask & (~LHSKnownZero)))
1368 return UpdateValueUsesWith(I, I->getOperand(1));
1369
1370 // If the RHS is a constant, see if we can simplify it.
1371 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1372 return UpdateValueUsesWith(I, I);
1373
1374 // Output known-0 bits are only known if clear in both the LHS & RHS.
1375 RHSKnownZero &= LHSKnownZero;
1376 // Output known-1 are known to be set if set in either the LHS | RHS.
1377 RHSKnownOne |= LHSKnownOne;
1378 break;
1379 case Instruction::Xor: {
1380 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1381 RHSKnownZero, RHSKnownOne, Depth+1))
1382 return true;
1383 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1384 "Bits known to be one AND zero?");
1385 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1386 LHSKnownZero, LHSKnownOne, Depth+1))
1387 return true;
1388 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1389 "Bits known to be one AND zero?");
1390
1391 // If all of the demanded bits are known zero on one side, return the other.
1392 // These bits cannot contribute to the result of the 'xor'.
1393 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1394 return UpdateValueUsesWith(I, I->getOperand(0));
1395 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1396 return UpdateValueUsesWith(I, I->getOperand(1));
1397
1398 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1399 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1400 (RHSKnownOne & LHSKnownOne);
1401 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1402 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1403 (RHSKnownOne & LHSKnownZero);
1404
1405 // If all of the demanded bits are known to be zero on one side or the
1406 // other, turn this into an *inclusive* or.
1407 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1408 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1409 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001410 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001411 I->getName());
1412 InsertNewInstBefore(Or, *I);
1413 return UpdateValueUsesWith(I, Or);
1414 }
1415
1416 // If all of the demanded bits on one side are known, and all of the set
1417 // bits on that side are also known to be set on the other side, turn this
1418 // into an AND, as we know the bits will be cleared.
1419 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1420 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1421 // all known
1422 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1423 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1424 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001425 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +00001426 InsertNewInstBefore(And, *I);
1427 return UpdateValueUsesWith(I, And);
1428 }
1429 }
1430
1431 // If the RHS is a constant, see if we can simplify it.
1432 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1433 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1434 return UpdateValueUsesWith(I, I);
1435
1436 RHSKnownZero = KnownZeroOut;
1437 RHSKnownOne = KnownOneOut;
1438 break;
1439 }
1440 case Instruction::Select:
1441 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1442 RHSKnownZero, RHSKnownOne, Depth+1))
1443 return true;
1444 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1445 LHSKnownZero, LHSKnownOne, Depth+1))
1446 return true;
1447 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1448 "Bits known to be one AND zero?");
1449 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1450 "Bits known to be one AND zero?");
1451
1452 // If the operands are constants, see if we can simplify them.
1453 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1454 return UpdateValueUsesWith(I, I);
1455 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1456 return UpdateValueUsesWith(I, I);
1457
1458 // Only known if known in both the LHS and RHS.
1459 RHSKnownOne &= LHSKnownOne;
1460 RHSKnownZero &= LHSKnownZero;
1461 break;
1462 case Instruction::Trunc: {
1463 uint32_t truncBf =
1464 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001465 DemandedMask.zext(truncBf);
1466 RHSKnownZero.zext(truncBf);
1467 RHSKnownOne.zext(truncBf);
1468 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1469 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001470 return true;
1471 DemandedMask.trunc(BitWidth);
1472 RHSKnownZero.trunc(BitWidth);
1473 RHSKnownOne.trunc(BitWidth);
1474 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1475 "Bits known to be one AND zero?");
1476 break;
1477 }
1478 case Instruction::BitCast:
1479 if (!I->getOperand(0)->getType()->isInteger())
1480 return false;
1481
1482 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1483 RHSKnownZero, RHSKnownOne, Depth+1))
1484 return true;
1485 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1486 "Bits known to be one AND zero?");
1487 break;
1488 case Instruction::ZExt: {
1489 // Compute the bits in the result that are not present in the input.
1490 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001491 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001492
Zhou Shengd48653a2007-03-29 04:45:55 +00001493 DemandedMask.trunc(SrcBitWidth);
1494 RHSKnownZero.trunc(SrcBitWidth);
1495 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001496 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1497 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001498 return true;
1499 DemandedMask.zext(BitWidth);
1500 RHSKnownZero.zext(BitWidth);
1501 RHSKnownOne.zext(BitWidth);
1502 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1503 "Bits known to be one AND zero?");
1504 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001505 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001506 break;
1507 }
1508 case Instruction::SExt: {
1509 // Compute the bits in the result that are not present in the input.
1510 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001511 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001512
Reid Spencer8cb68342007-03-12 17:25:59 +00001513 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001514 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001515
Zhou Sheng01542f32007-03-29 02:26:30 +00001516 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001517 // If any of the sign extended bits are demanded, we know that the sign
1518 // bit is demanded.
1519 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001520 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001521
Zhou Shengd48653a2007-03-29 04:45:55 +00001522 InputDemandedBits.trunc(SrcBitWidth);
1523 RHSKnownZero.trunc(SrcBitWidth);
1524 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001525 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1526 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001527 return true;
1528 InputDemandedBits.zext(BitWidth);
1529 RHSKnownZero.zext(BitWidth);
1530 RHSKnownOne.zext(BitWidth);
1531 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1532 "Bits known to be one AND zero?");
1533
1534 // If the sign bit of the input is known set or clear, then we know the
1535 // top bits of the result.
1536
1537 // If the input sign bit is known zero, or if the NewBits are not demanded
1538 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001539 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001540 {
1541 // Convert to ZExt cast
1542 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1543 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001544 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001545 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001546 }
1547 break;
1548 }
1549 case Instruction::Add: {
1550 // Figure out what the input bits are. If the top bits of the and result
1551 // are not demanded, then the add doesn't demand them from its input
1552 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001553 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001554
1555 // If there is a constant on the RHS, there are a variety of xformations
1556 // we can do.
1557 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1558 // If null, this should be simplified elsewhere. Some of the xforms here
1559 // won't work if the RHS is zero.
1560 if (RHS->isZero())
1561 break;
1562
1563 // If the top bit of the output is demanded, demand everything from the
1564 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001565 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001566
1567 // Find information about known zero/one bits in the input.
1568 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1569 LHSKnownZero, LHSKnownOne, Depth+1))
1570 return true;
1571
1572 // If the RHS of the add has bits set that can't affect the input, reduce
1573 // the constant.
1574 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1575 return UpdateValueUsesWith(I, I);
1576
1577 // Avoid excess work.
1578 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1579 break;
1580
1581 // Turn it into OR if input bits are zero.
1582 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1583 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001584 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001585 I->getName());
1586 InsertNewInstBefore(Or, *I);
1587 return UpdateValueUsesWith(I, Or);
1588 }
1589
1590 // We can say something about the output known-zero and known-one bits,
1591 // depending on potential carries from the input constant and the
1592 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1593 // bits set and the RHS constant is 0x01001, then we know we have a known
1594 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1595
1596 // To compute this, we first compute the potential carry bits. These are
1597 // the bits which may be modified. I'm not aware of a better way to do
1598 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001599 const APInt& RHSVal = RHS->getValue();
1600 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001601
1602 // Now that we know which bits have carries, compute the known-1/0 sets.
1603
1604 // Bits are known one if they are known zero in one operand and one in the
1605 // other, and there is no input carry.
1606 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1607 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1608
1609 // Bits are known zero if they are known zero in both operands and there
1610 // is no input carry.
1611 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1612 } else {
1613 // If the high-bits of this ADD are not demanded, then it does not demand
1614 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001615 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001616 // Right fill the mask of bits for this ADD to demand the most
1617 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001618 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001619 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1620 LHSKnownZero, LHSKnownOne, Depth+1))
1621 return true;
1622 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1623 LHSKnownZero, LHSKnownOne, Depth+1))
1624 return true;
1625 }
1626 }
1627 break;
1628 }
1629 case Instruction::Sub:
1630 // If the high-bits of this SUB are not demanded, then it does not demand
1631 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001632 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001633 // Right fill the mask of bits for this SUB to demand the most
1634 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001635 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001636 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001637 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1638 LHSKnownZero, LHSKnownOne, Depth+1))
1639 return true;
1640 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1641 LHSKnownZero, LHSKnownOne, Depth+1))
1642 return true;
1643 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001644 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1645 // the known zeros and ones.
1646 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001647 break;
1648 case Instruction::Shl:
1649 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001650 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001651 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1652 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001653 RHSKnownZero, RHSKnownOne, Depth+1))
1654 return true;
1655 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1656 "Bits known to be one AND zero?");
1657 RHSKnownZero <<= ShiftAmt;
1658 RHSKnownOne <<= ShiftAmt;
1659 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001660 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001661 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001662 }
1663 break;
1664 case Instruction::LShr:
1665 // For a logical shift right
1666 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001667 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001668
Reid Spencer8cb68342007-03-12 17:25:59 +00001669 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001670 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1671 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001672 RHSKnownZero, RHSKnownOne, Depth+1))
1673 return true;
1674 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1675 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001676 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1677 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001678 if (ShiftAmt) {
1679 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001680 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001681 RHSKnownZero |= HighBits; // high bits known zero.
1682 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001683 }
1684 break;
1685 case Instruction::AShr:
1686 // If this is an arithmetic shift right and only the low-bit is set, we can
1687 // always convert this into a logical shr, even if the shift amount is
1688 // variable. The low bit of the shift cannot be an input sign bit unless
1689 // the shift amount is >= the size of the datatype, which is undefined.
1690 if (DemandedMask == 1) {
1691 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001692 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001693 I->getOperand(0), I->getOperand(1), I->getName());
1694 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1695 return UpdateValueUsesWith(I, NewVal);
1696 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001697
1698 // If the sign bit is the only bit demanded by this ashr, then there is no
1699 // need to do it, the shift doesn't change the high bit.
1700 if (DemandedMask.isSignBit())
1701 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001702
1703 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001704 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001705
Reid Spencer8cb68342007-03-12 17:25:59 +00001706 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001707 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001708 // If any of the "high bits" are demanded, we should set the sign bit as
1709 // demanded.
1710 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1711 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001712 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001713 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001714 RHSKnownZero, RHSKnownOne, Depth+1))
1715 return true;
1716 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1717 "Bits known to be one AND zero?");
1718 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001719 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001720 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1721 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1722
1723 // Handle the sign bits.
1724 APInt SignBit(APInt::getSignBit(BitWidth));
1725 // Adjust to where it is now in the mask.
1726 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1727
1728 // If the input sign bit is known to be zero, or if none of the top bits
1729 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001730 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001731 (HighBits & ~DemandedMask) == HighBits) {
1732 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001733 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001734 I->getOperand(0), SA, I->getName());
1735 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1736 return UpdateValueUsesWith(I, NewVal);
1737 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1738 RHSKnownOne |= HighBits;
1739 }
1740 }
1741 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001742 case Instruction::SRem:
1743 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1744 APInt RA = Rem->getValue();
1745 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001746 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001747 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1748 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1749 LHSKnownZero, LHSKnownOne, Depth+1))
1750 return true;
1751
1752 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1753 LHSKnownZero |= ~LowBits;
1754 else if (LHSKnownOne[BitWidth-1])
1755 LHSKnownOne |= ~LowBits;
1756
1757 KnownZero |= LHSKnownZero & DemandedMask;
1758 KnownOne |= LHSKnownOne & DemandedMask;
1759
1760 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1761 }
1762 }
1763 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001764 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001765 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1766 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001767 if (RA.isPowerOf2()) {
1768 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001769 APInt Mask2 = LowBits & DemandedMask;
1770 KnownZero |= ~LowBits & DemandedMask;
1771 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1772 KnownZero, KnownOne, Depth+1))
1773 return true;
1774
1775 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001776 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001777 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001778 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001779
1780 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1781 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001782 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1783 KnownZero2, KnownOne2, Depth+1))
1784 return true;
1785
Dan Gohman23e8b712008-04-28 17:02:21 +00001786 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001787 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001788 KnownZero2, KnownOne2, Depth+1))
1789 return true;
1790
1791 Leaders = std::max(Leaders,
1792 KnownZero2.countLeadingOnes());
1793 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001794 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001795 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001796 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001797
1798 // If the client is only demanding bits that we know, return the known
1799 // constant.
1800 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1801 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1802 return false;
1803}
1804
Chris Lattner867b99f2006-10-05 06:55:50 +00001805
1806/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1807/// 64 or fewer elements. DemandedElts contains the set of elements that are
1808/// actually used by the caller. This method analyzes which elements of the
1809/// operand are undef and returns that information in UndefElts.
1810///
1811/// If the information about demanded elements can be used to simplify the
1812/// operation, the operation is simplified, then the resultant value is
1813/// returned. This returns null if no change was made.
1814Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1815 uint64_t &UndefElts,
1816 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001817 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001818 assert(VWidth <= 64 && "Vector too wide to analyze!");
1819 uint64_t EltMask = ~0ULL >> (64-VWidth);
1820 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1821 "Invalid DemandedElts!");
1822
1823 if (isa<UndefValue>(V)) {
1824 // If the entire vector is undefined, just return this info.
1825 UndefElts = EltMask;
1826 return 0;
1827 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1828 UndefElts = EltMask;
1829 return UndefValue::get(V->getType());
1830 }
1831
1832 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001833 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1834 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001835 Constant *Undef = UndefValue::get(EltTy);
1836
1837 std::vector<Constant*> Elts;
1838 for (unsigned i = 0; i != VWidth; ++i)
1839 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1840 Elts.push_back(Undef);
1841 UndefElts |= (1ULL << i);
1842 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1843 Elts.push_back(Undef);
1844 UndefElts |= (1ULL << i);
1845 } else { // Otherwise, defined.
1846 Elts.push_back(CP->getOperand(i));
1847 }
1848
1849 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001850 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001851 return NewCP != CP ? NewCP : 0;
1852 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001853 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001854 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001855 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001856 Constant *Zero = Constant::getNullValue(EltTy);
1857 Constant *Undef = UndefValue::get(EltTy);
1858 std::vector<Constant*> Elts;
1859 for (unsigned i = 0; i != VWidth; ++i)
1860 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1861 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001862 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001863 }
1864
1865 if (!V->hasOneUse()) { // Other users may use these bits.
1866 if (Depth != 0) { // Not at the root.
1867 // TODO: Just compute the UndefElts information recursively.
1868 return false;
1869 }
1870 return false;
1871 } else if (Depth == 10) { // Limit search depth.
1872 return false;
1873 }
1874
1875 Instruction *I = dyn_cast<Instruction>(V);
1876 if (!I) return false; // Only analyze instructions.
1877
1878 bool MadeChange = false;
1879 uint64_t UndefElts2;
1880 Value *TmpV;
1881 switch (I->getOpcode()) {
1882 default: break;
1883
1884 case Instruction::InsertElement: {
1885 // If this is a variable index, we don't know which element it overwrites.
1886 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001887 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001888 if (Idx == 0) {
1889 // Note that we can't propagate undef elt info, because we don't know
1890 // which elt is getting updated.
1891 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1892 UndefElts2, Depth+1);
1893 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1894 break;
1895 }
1896
1897 // If this is inserting an element that isn't demanded, remove this
1898 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001899 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001900 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1901 return AddSoonDeadInstToWorklist(*I, 0);
1902
1903 // Otherwise, the element inserted overwrites whatever was there, so the
1904 // input demanded set is simpler than the output set.
1905 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1906 DemandedElts & ~(1ULL << IdxNo),
1907 UndefElts, Depth+1);
1908 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1909
1910 // The inserted element is defined.
1911 UndefElts |= 1ULL << IdxNo;
1912 break;
1913 }
Chris Lattner69878332007-04-14 22:29:23 +00001914 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001915 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001916 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1917 if (!VTy) break;
1918 unsigned InVWidth = VTy->getNumElements();
1919 uint64_t InputDemandedElts = 0;
1920 unsigned Ratio;
1921
1922 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001923 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001924 // elements as are demanded of us.
1925 Ratio = 1;
1926 InputDemandedElts = DemandedElts;
1927 } else if (VWidth > InVWidth) {
1928 // Untested so far.
1929 break;
1930
1931 // If there are more elements in the result than there are in the source,
1932 // then an input element is live if any of the corresponding output
1933 // elements are live.
1934 Ratio = VWidth/InVWidth;
1935 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1936 if (DemandedElts & (1ULL << OutIdx))
1937 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1938 }
1939 } else {
1940 // Untested so far.
1941 break;
1942
1943 // If there are more elements in the source than there are in the result,
1944 // then an input element is live if the corresponding output element is
1945 // live.
1946 Ratio = InVWidth/VWidth;
1947 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1948 if (DemandedElts & (1ULL << InIdx/Ratio))
1949 InputDemandedElts |= 1ULL << InIdx;
1950 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001951
Chris Lattner69878332007-04-14 22:29:23 +00001952 // div/rem demand all inputs, because they don't want divide by zero.
1953 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1954 UndefElts2, Depth+1);
1955 if (TmpV) {
1956 I->setOperand(0, TmpV);
1957 MadeChange = true;
1958 }
1959
1960 UndefElts = UndefElts2;
1961 if (VWidth > InVWidth) {
1962 assert(0 && "Unimp");
1963 // If there are more elements in the result than there are in the source,
1964 // then an output element is undef if the corresponding input element is
1965 // undef.
1966 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1967 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1968 UndefElts |= 1ULL << OutIdx;
1969 } else if (VWidth < InVWidth) {
1970 assert(0 && "Unimp");
1971 // If there are more elements in the source than there are in the result,
1972 // then a result element is undef if all of the corresponding input
1973 // elements are undef.
1974 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1975 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1976 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1977 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1978 }
1979 break;
1980 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001981 case Instruction::And:
1982 case Instruction::Or:
1983 case Instruction::Xor:
1984 case Instruction::Add:
1985 case Instruction::Sub:
1986 case Instruction::Mul:
1987 // div/rem demand all inputs, because they don't want divide by zero.
1988 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1989 UndefElts, Depth+1);
1990 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1991 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1992 UndefElts2, Depth+1);
1993 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1994
1995 // Output elements are undefined if both are undefined. Consider things
1996 // like undef&0. The result is known zero, not undef.
1997 UndefElts &= UndefElts2;
1998 break;
1999
2000 case Instruction::Call: {
2001 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2002 if (!II) break;
2003 switch (II->getIntrinsicID()) {
2004 default: break;
2005
2006 // Binary vector operations that work column-wise. A dest element is a
2007 // function of the corresponding input elements from the two inputs.
2008 case Intrinsic::x86_sse_sub_ss:
2009 case Intrinsic::x86_sse_mul_ss:
2010 case Intrinsic::x86_sse_min_ss:
2011 case Intrinsic::x86_sse_max_ss:
2012 case Intrinsic::x86_sse2_sub_sd:
2013 case Intrinsic::x86_sse2_mul_sd:
2014 case Intrinsic::x86_sse2_min_sd:
2015 case Intrinsic::x86_sse2_max_sd:
2016 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2017 UndefElts, Depth+1);
2018 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2019 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2020 UndefElts2, Depth+1);
2021 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2022
2023 // If only the low elt is demanded and this is a scalarizable intrinsic,
2024 // scalarize it now.
2025 if (DemandedElts == 1) {
2026 switch (II->getIntrinsicID()) {
2027 default: break;
2028 case Intrinsic::x86_sse_sub_ss:
2029 case Intrinsic::x86_sse_mul_ss:
2030 case Intrinsic::x86_sse2_sub_sd:
2031 case Intrinsic::x86_sse2_mul_sd:
2032 // TODO: Lower MIN/MAX/ABS/etc
2033 Value *LHS = II->getOperand(1);
2034 Value *RHS = II->getOperand(2);
2035 // Extract the element as scalars.
2036 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2037 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2038
2039 switch (II->getIntrinsicID()) {
2040 default: assert(0 && "Case stmts out of sync!");
2041 case Intrinsic::x86_sse_sub_ss:
2042 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002043 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002044 II->getName()), *II);
2045 break;
2046 case Intrinsic::x86_sse_mul_ss:
2047 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002048 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002049 II->getName()), *II);
2050 break;
2051 }
2052
2053 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00002054 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2055 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00002056 InsertNewInstBefore(New, *II);
2057 AddSoonDeadInstToWorklist(*II, 0);
2058 return New;
2059 }
2060 }
2061
2062 // Output elements are undefined if both are undefined. Consider things
2063 // like undef&0. The result is known zero, not undef.
2064 UndefElts &= UndefElts2;
2065 break;
2066 }
2067 break;
2068 }
2069 }
2070 return MadeChange ? I : 0;
2071}
2072
Chris Lattner564a7272003-08-13 19:01:45 +00002073/// AssociativeOpt - Perform an optimization on an associative operator. This
2074/// function is designed to check a chain of associative operators for a
2075/// potential to apply a certain optimization. Since the optimization may be
2076/// applicable if the expression was reassociated, this checks the chain, then
2077/// reassociates the expression as necessary to expose the optimization
2078/// opportunity. This makes use of a special Functor, which must define
2079/// 'shouldApply' and 'apply' methods.
2080///
2081template<typename Functor>
2082Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2083 unsigned Opcode = Root.getOpcode();
2084 Value *LHS = Root.getOperand(0);
2085
2086 // Quick check, see if the immediate LHS matches...
2087 if (F.shouldApply(LHS))
2088 return F.apply(Root);
2089
2090 // Otherwise, if the LHS is not of the same opcode as the root, return.
2091 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002092 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002093 // Should we apply this transform to the RHS?
2094 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2095
2096 // If not to the RHS, check to see if we should apply to the LHS...
2097 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2098 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2099 ShouldApply = true;
2100 }
2101
2102 // If the functor wants to apply the optimization to the RHS of LHSI,
2103 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2104 if (ShouldApply) {
2105 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002106
Chris Lattner564a7272003-08-13 19:01:45 +00002107 // Now all of the instructions are in the current basic block, go ahead
2108 // and perform the reassociation.
2109 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2110
2111 // First move the selected RHS to the LHS of the root...
2112 Root.setOperand(0, LHSI->getOperand(1));
2113
2114 // Make what used to be the LHS of the root be the user of the root...
2115 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002116 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002117 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2118 return 0;
2119 }
Chris Lattner65725312004-04-16 18:08:07 +00002120 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002121 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002122 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2123 BasicBlock::iterator ARI = &Root; ++ARI;
2124 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2125 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002126
2127 // Now propagate the ExtraOperand down the chain of instructions until we
2128 // get to LHSI.
2129 while (TmpLHSI != LHSI) {
2130 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002131 // Move the instruction to immediately before the chain we are
2132 // constructing to avoid breaking dominance properties.
2133 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2134 BB->getInstList().insert(ARI, NextLHSI);
2135 ARI = NextLHSI;
2136
Chris Lattner564a7272003-08-13 19:01:45 +00002137 Value *NextOp = NextLHSI->getOperand(1);
2138 NextLHSI->setOperand(1, ExtraOperand);
2139 TmpLHSI = NextLHSI;
2140 ExtraOperand = NextOp;
2141 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002142
Chris Lattner564a7272003-08-13 19:01:45 +00002143 // Now that the instructions are reassociated, have the functor perform
2144 // the transformation...
2145 return F.apply(Root);
2146 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002147
Chris Lattner564a7272003-08-13 19:01:45 +00002148 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2149 }
2150 return 0;
2151}
2152
Dan Gohman844731a2008-05-13 00:00:25 +00002153namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002154
2155// AddRHS - Implements: X + X --> X << 1
2156struct AddRHS {
2157 Value *RHS;
2158 AddRHS(Value *rhs) : RHS(rhs) {}
2159 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2160 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002161 return BinaryOperator::CreateShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00002162 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002163 }
2164};
2165
2166// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2167// iff C1&C2 == 0
2168struct AddMaskingAnd {
2169 Constant *C2;
2170 AddMaskingAnd(Constant *c) : C2(c) {}
2171 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002172 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002173 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002174 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002175 }
2176 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002177 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002178 }
2179};
2180
Dan Gohman844731a2008-05-13 00:00:25 +00002181}
2182
Chris Lattner6e7ba452005-01-01 16:22:27 +00002183static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002184 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002185 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002186 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002187 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002188
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002189 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00002190 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002191 }
2192
Chris Lattner2eefe512004-04-09 19:05:30 +00002193 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002194 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2195 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002196
Chris Lattner2eefe512004-04-09 19:05:30 +00002197 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2198 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002199 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2200 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002201 }
2202
2203 Value *Op0 = SO, *Op1 = ConstOperand;
2204 if (!ConstIsRHS)
2205 std::swap(Op0, Op1);
2206 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002207 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002208 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002209 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002210 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002211 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002212 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002213 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002214 abort();
2215 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002216 return IC->InsertNewInstBefore(New, I);
2217}
2218
2219// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2220// constant as the other operand, try to fold the binary operator into the
2221// select arguments. This also works for Cast instructions, which obviously do
2222// not have a second operand.
2223static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2224 InstCombiner *IC) {
2225 // Don't modify shared select instructions
2226 if (!SI->hasOneUse()) return 0;
2227 Value *TV = SI->getOperand(1);
2228 Value *FV = SI->getOperand(2);
2229
2230 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002231 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002232 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002233
Chris Lattner6e7ba452005-01-01 16:22:27 +00002234 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2235 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2236
Gabor Greif051a9502008-04-06 20:25:17 +00002237 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2238 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002239 }
2240 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002241}
2242
Chris Lattner4e998b22004-09-29 05:07:12 +00002243
2244/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2245/// node as operand #0, see if we can fold the instruction into the PHI (which
2246/// is only possible if all operands to the PHI are constants).
2247Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2248 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002249 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002250 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002251
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002252 // Check to see if all of the operands of the PHI are constants. If there is
2253 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002254 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002255 BasicBlock *NonConstBB = 0;
2256 for (unsigned i = 0; i != NumPHIValues; ++i)
2257 if (!isa<Constant>(PN->getIncomingValue(i))) {
2258 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002259 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002260 NonConstBB = PN->getIncomingBlock(i);
2261
2262 // If the incoming non-constant value is in I's block, we have an infinite
2263 // loop.
2264 if (NonConstBB == I.getParent())
2265 return 0;
2266 }
2267
2268 // If there is exactly one non-constant value, we can insert a copy of the
2269 // operation in that block. However, if this is a critical edge, we would be
2270 // inserting the computation one some other paths (e.g. inside a loop). Only
2271 // do this if the pred block is unconditionally branching into the phi block.
2272 if (NonConstBB) {
2273 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2274 if (!BI || !BI->isUnconditional()) return 0;
2275 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002276
2277 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002278 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002279 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002280 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002281 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002282
2283 // Next, add all of the operands to the PHI.
2284 if (I.getNumOperands() == 2) {
2285 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002286 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002287 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002288 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002289 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2290 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2291 else
2292 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002293 } else {
2294 assert(PN->getIncomingBlock(i) == NonConstBB);
2295 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002296 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002297 PN->getIncomingValue(i), C, "phitmp",
2298 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002299 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002300 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002301 CI->getPredicate(),
2302 PN->getIncomingValue(i), C, "phitmp",
2303 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002304 else
2305 assert(0 && "Unknown binop!");
2306
Chris Lattnerdbab3862007-03-02 21:28:56 +00002307 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002308 }
2309 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002310 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002311 } else {
2312 CastInst *CI = cast<CastInst>(&I);
2313 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002314 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002315 Value *InV;
2316 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002317 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002318 } else {
2319 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002320 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002321 I.getType(), "phitmp",
2322 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002323 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002324 }
2325 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002326 }
2327 }
2328 return ReplaceInstUsesWith(I, NewPN);
2329}
2330
Chris Lattner2454a2e2008-01-29 06:52:45 +00002331
2332/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2333/// value is never equal to -0.0.
2334///
2335/// Note that this function will need to be revisited when we support nondefault
2336/// rounding modes!
2337///
2338static bool CannotBeNegativeZero(const Value *V) {
2339 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2340 return !CFP->getValueAPF().isNegZero();
2341
2342 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2343 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2344 if (I->getOpcode() == Instruction::Add &&
2345 isa<ConstantFP>(I->getOperand(1)) &&
2346 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2347 return true;
2348
2349 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2350 if (II->getIntrinsicID() == Intrinsic::sqrt)
2351 return CannotBeNegativeZero(II->getOperand(1));
2352
2353 if (const CallInst *CI = dyn_cast<CallInst>(I))
2354 if (const Function *F = CI->getCalledFunction()) {
2355 if (F->isDeclaration()) {
2356 switch (F->getNameLen()) {
2357 case 3: // abs(x) != -0.0
2358 if (!strcmp(F->getNameStart(), "abs")) return true;
2359 break;
2360 case 4: // abs[lf](x) != -0.0
2361 if (!strcmp(F->getNameStart(), "absf")) return true;
2362 if (!strcmp(F->getNameStart(), "absl")) return true;
2363 break;
2364 }
2365 }
2366 }
2367 }
2368
2369 return false;
2370}
2371
2372
Chris Lattner7e708292002-06-25 16:13:24 +00002373Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002374 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002375 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002376
Chris Lattner66331a42004-04-10 22:01:55 +00002377 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002378 // X + undef -> undef
2379 if (isa<UndefValue>(RHS))
2380 return ReplaceInstUsesWith(I, RHS);
2381
Chris Lattner66331a42004-04-10 22:01:55 +00002382 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002383 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002384 if (RHSC->isNullValue())
2385 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002386 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002387 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2388 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002389 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002390 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002391
Chris Lattner66331a42004-04-10 22:01:55 +00002392 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002393 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002394 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002395 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002396 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002397 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002398
2399 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2400 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002401 if (!isa<VectorType>(I.getType())) {
2402 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2403 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2404 KnownZero, KnownOne))
2405 return &I;
2406 }
Chris Lattner66331a42004-04-10 22:01:55 +00002407 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002408
2409 if (isa<PHINode>(LHS))
2410 if (Instruction *NV = FoldOpIntoPhi(I))
2411 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002412
Chris Lattner4f637d42006-01-06 17:59:59 +00002413 ConstantInt *XorRHS = 0;
2414 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002415 if (isa<ConstantInt>(RHSC) &&
2416 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002417 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002418 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002419
Zhou Sheng4351c642007-04-02 08:20:41 +00002420 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002421 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2422 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002423 do {
2424 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002425 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2426 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002427 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2428 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002429 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002430 if (!MaskedValueIsZero(XorLHS,
2431 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002432 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002433 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002434 }
2435 }
2436 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002437 C0080Val = APIntOps::lshr(C0080Val, Size);
2438 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2439 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002440
Reid Spencer35c38852007-03-28 01:36:16 +00002441 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002442 // with funny bit widths then this switch statement should be removed. It
2443 // is just here to get the size of the "middle" type back up to something
2444 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002445 const Type *MiddleType = 0;
2446 switch (Size) {
2447 default: break;
2448 case 32: MiddleType = Type::Int32Ty; break;
2449 case 16: MiddleType = Type::Int16Ty; break;
2450 case 8: MiddleType = Type::Int8Ty; break;
2451 }
2452 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002453 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002454 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002455 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002456 }
2457 }
Chris Lattner66331a42004-04-10 22:01:55 +00002458 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002459
Chris Lattner564a7272003-08-13 19:01:45 +00002460 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002461 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002462 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002463
2464 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2465 if (RHSI->getOpcode() == Instruction::Sub)
2466 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2467 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2468 }
2469 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2470 if (LHSI->getOpcode() == Instruction::Sub)
2471 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2472 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2473 }
Robert Bocchino71698282004-07-27 21:02:21 +00002474 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002475
Chris Lattner5c4afb92002-05-08 22:46:53 +00002476 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002477 // -A + -B --> -(A + B)
2478 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002479 if (LHS->getType()->isIntOrIntVector()) {
2480 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002481 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002482 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002483 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002484 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002485 }
2486
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002487 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002488 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002489
2490 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002491 if (!isa<Constant>(RHS))
2492 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002493 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002494
Misha Brukmanfd939082005-04-21 23:48:37 +00002495
Chris Lattner50af16a2004-11-13 19:50:12 +00002496 ConstantInt *C2;
2497 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2498 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002499 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002500
2501 // X*C1 + X*C2 --> X * (C1+C2)
2502 ConstantInt *C1;
2503 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002504 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002505 }
2506
2507 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002508 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002509 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002510
Chris Lattnere617c9e2007-01-05 02:17:46 +00002511 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002512 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2513 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002514
Chris Lattnerad3448c2003-02-18 19:57:07 +00002515
Chris Lattner564a7272003-08-13 19:01:45 +00002516 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002517 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002518 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2519 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002520
2521 // A+B --> A|B iff A and B have no bits set in common.
2522 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2523 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2524 APInt LHSKnownOne(IT->getBitWidth(), 0);
2525 APInt LHSKnownZero(IT->getBitWidth(), 0);
2526 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2527 if (LHSKnownZero != 0) {
2528 APInt RHSKnownOne(IT->getBitWidth(), 0);
2529 APInt RHSKnownZero(IT->getBitWidth(), 0);
2530 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2531
2532 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002533 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002534 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002535 }
2536 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002537
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002538 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002539 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002540 Value *W, *X, *Y, *Z;
2541 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2542 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2543 if (W != Y) {
2544 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002545 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002546 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002547 std::swap(W, X);
2548 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002549 std::swap(Y, Z);
2550 std::swap(W, X);
2551 }
2552 }
2553
2554 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002555 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002556 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002557 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002558 }
2559 }
2560 }
2561
Chris Lattner6b032052003-10-02 15:11:26 +00002562 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002563 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002564 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002565 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002566
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002567 // (X & FF00) + xx00 -> (X+xx00) & FF00
2568 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002569 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002570 if (Anded == CRHS) {
2571 // See if all bits from the first bit set in the Add RHS up are included
2572 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002573 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002574
2575 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002576 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002577
2578 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002579 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002580
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002581 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2582 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002583 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002584 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002585 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002586 }
2587 }
2588 }
2589
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002590 // Try to fold constant add into select arguments.
2591 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002592 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002593 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002594 }
2595
Reid Spencer1628cec2006-10-26 06:15:43 +00002596 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002597 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002598 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002599 CastInst *CI = dyn_cast<CastInst>(LHS);
2600 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002601 if (!CI) {
2602 CI = dyn_cast<CastInst>(RHS);
2603 Other = LHS;
2604 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002605 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002606 (CI->getType()->getPrimitiveSizeInBits() ==
2607 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002608 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002609 unsigned AS =
2610 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002611 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2612 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002613 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002614 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002615 }
2616 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002617
Chris Lattner42790482007-12-20 01:56:58 +00002618 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002619 {
2620 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2621 Value *Other = RHS;
2622 if (!SI) {
2623 SI = dyn_cast<SelectInst>(RHS);
2624 Other = LHS;
2625 }
Chris Lattner42790482007-12-20 01:56:58 +00002626 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002627 Value *TV = SI->getTrueValue();
2628 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002629 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002630
2631 // Can we fold the add into the argument of the select?
2632 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002633 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2634 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002635 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002636 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2637 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002638 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002639 }
2640 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002641
2642 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2643 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2644 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2645 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002646
Chris Lattner7e708292002-06-25 16:13:24 +00002647 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002648}
2649
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002650// isSignBit - Return true if the value represented by the constant only has the
2651// highest order bit set.
2652static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002653 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002654 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002655}
2656
Chris Lattner7e708292002-06-25 16:13:24 +00002657Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002658 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002659
Chris Lattner233f7dc2002-08-12 21:17:25 +00002660 if (Op0 == Op1) // sub X, X -> 0
2661 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002662
Chris Lattner233f7dc2002-08-12 21:17:25 +00002663 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002664 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002665 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002666
Chris Lattnere87597f2004-10-16 18:11:37 +00002667 if (isa<UndefValue>(Op0))
2668 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2669 if (isa<UndefValue>(Op1))
2670 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2671
Chris Lattnerd65460f2003-11-05 01:06:05 +00002672 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2673 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002674 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002675 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002676
Chris Lattnerd65460f2003-11-05 01:06:05 +00002677 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002678 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002679 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002680 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002681
Chris Lattner76b7a062007-01-15 07:02:54 +00002682 // -(X >>u 31) -> (X >>s 31)
2683 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002684 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002685 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002686 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002687 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002688 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002689 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002690 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002691 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002692 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002693 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002694 }
2695 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002696 }
2697 else if (SI->getOpcode() == Instruction::AShr) {
2698 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2699 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002700 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002701 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002702 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002703 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002704 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002705 }
2706 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002707 }
2708 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002709 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002710
2711 // Try to fold constant sub into select arguments.
2712 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002713 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002714 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002715
2716 if (isa<PHINode>(Op0))
2717 if (Instruction *NV = FoldOpIntoPhi(I))
2718 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002719 }
2720
Chris Lattner43d84d62005-04-07 16:15:25 +00002721 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2722 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002723 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002724 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002725 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002726 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002727 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002728 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2729 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2730 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002731 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002732 Op1I->getOperand(0));
2733 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002734 }
2735
Chris Lattnerfd059242003-10-15 16:48:29 +00002736 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002737 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2738 // is not used by anyone else...
2739 //
Chris Lattner0517e722004-02-02 20:09:56 +00002740 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002741 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002742 // Swap the two operands of the subexpr...
2743 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2744 Op1I->setOperand(0, IIOp1);
2745 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002746
Chris Lattnera2881962003-02-18 19:28:33 +00002747 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002748 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002749 }
2750
2751 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2752 //
2753 if (Op1I->getOpcode() == Instruction::And &&
2754 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2755 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2756
Chris Lattnerf523d062004-06-09 05:08:07 +00002757 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002758 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2759 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002760 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002761
Reid Spencerac5209e2006-10-16 23:08:08 +00002762 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002763 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002764 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002765 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002766 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002767 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002768 ConstantExpr::getNeg(DivRHS));
2769
Chris Lattnerad3448c2003-02-18 19:57:07 +00002770 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002771 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002772 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002773 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002774 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002775 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002776
2777 // X - ((X / Y) * Y) --> X % Y
2778 if (Op1I->getOpcode() == Instruction::Mul)
2779 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2780 if (Op0 == I->getOperand(0) &&
2781 Op1I->getOperand(1) == I->getOperand(1)) {
2782 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002783 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002784 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002785 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002786 }
Chris Lattner40371712002-05-09 01:29:19 +00002787 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002788 }
Chris Lattnera2881962003-02-18 19:28:33 +00002789
Chris Lattner9919e3d2006-12-02 00:13:08 +00002790 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002791 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002792 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002793 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2794 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2795 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2796 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002797 } else if (Op0I->getOpcode() == Instruction::Sub) {
2798 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002799 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002800 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002801 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002802
Chris Lattner50af16a2004-11-13 19:50:12 +00002803 ConstantInt *C1;
2804 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002805 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002806 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002807
Chris Lattner50af16a2004-11-13 19:50:12 +00002808 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2809 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002810 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002811 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002812 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002813}
2814
Chris Lattnera0141b92007-07-15 20:42:37 +00002815/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2816/// comparison only checks the sign bit. If it only checks the sign bit, set
2817/// TrueIfSigned if the result of the comparison is true when the input value is
2818/// signed.
2819static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2820 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002821 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002822 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2823 TrueIfSigned = true;
2824 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002825 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2826 TrueIfSigned = true;
2827 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002828 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2829 TrueIfSigned = false;
2830 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002831 case ICmpInst::ICMP_UGT:
2832 // True if LHS u> RHS and RHS == high-bit-mask - 1
2833 TrueIfSigned = true;
2834 return RHS->getValue() ==
2835 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2836 case ICmpInst::ICMP_UGE:
2837 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2838 TrueIfSigned = true;
2839 return RHS->getValue() ==
2840 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002841 default:
2842 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002843 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002844}
2845
Chris Lattner7e708292002-06-25 16:13:24 +00002846Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002847 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002848 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002849
Chris Lattnere87597f2004-10-16 18:11:37 +00002850 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2851 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2852
Chris Lattner233f7dc2002-08-12 21:17:25 +00002853 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002854 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2855 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002856
2857 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002858 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002859 if (SI->getOpcode() == Instruction::Shl)
2860 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002861 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002862 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002863
Zhou Sheng843f07672007-04-19 05:39:12 +00002864 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002865 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2866 if (CI->equalsInt(1)) // X * 1 == X
2867 return ReplaceInstUsesWith(I, Op0);
2868 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002869 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002870
Zhou Sheng97b52c22007-03-29 01:57:21 +00002871 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002872 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002873 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002874 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002875 }
Robert Bocchino71698282004-07-27 21:02:21 +00002876 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002877 if (Op1F->isNullValue())
2878 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002879
Chris Lattnera2881962003-02-18 19:28:33 +00002880 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2881 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002882 // We need a better interface for long double here.
2883 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2884 if (Op1F->isExactlyValue(1.0))
2885 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002886 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002887
2888 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2889 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002890 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002891 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002892 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002893 Op1, "tmp");
2894 InsertNewInstBefore(Add, I);
2895 Value *C1C2 = ConstantExpr::getMul(Op1,
2896 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002897 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002898
2899 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002900
2901 // Try to fold constant mul into select arguments.
2902 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002903 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002904 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002905
2906 if (isa<PHINode>(Op0))
2907 if (Instruction *NV = FoldOpIntoPhi(I))
2908 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002909 }
2910
Chris Lattnera4f445b2003-03-10 23:23:04 +00002911 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2912 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002913 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002914
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002915 // If one of the operands of the multiply is a cast from a boolean value, then
2916 // we know the bool is either zero or one, so this is a 'masking' multiply.
2917 // See if we can simplify things based on how the boolean was originally
2918 // formed.
2919 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002920 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002921 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002922 BoolCast = CI;
2923 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002924 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002925 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002926 BoolCast = CI;
2927 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002928 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002929 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2930 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002931 bool TIS = false;
2932
Reid Spencere4d87aa2006-12-23 06:05:41 +00002933 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002934 // multiply into a shift/and combination.
2935 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002936 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2937 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002938 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002939 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002940 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002941 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002942 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002943 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002944 BoolCast->getOperand(0)->getName()+
2945 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002946
2947 // If the multiply type is not the same as the source type, sign extend
2948 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002949 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002950 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2951 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002952 Instruction::CastOps opcode =
2953 (SrcBits == DstBits ? Instruction::BitCast :
2954 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2955 V = InsertCastBefore(opcode, V, I.getType(), I);
2956 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002957
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002958 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002959 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002960 }
2961 }
2962 }
2963
Chris Lattner7e708292002-06-25 16:13:24 +00002964 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002965}
2966
Reid Spencer1628cec2006-10-26 06:15:43 +00002967/// This function implements the transforms on div instructions that work
2968/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2969/// used by the visitors to those instructions.
2970/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002971Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002972 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002973
Chris Lattner50b2ca42008-02-19 06:12:18 +00002974 // undef / X -> 0 for integer.
2975 // undef / X -> undef for FP (the undef could be a snan).
2976 if (isa<UndefValue>(Op0)) {
2977 if (Op0->getType()->isFPOrFPVector())
2978 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002979 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002980 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002981
2982 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002983 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002984 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002985
Chris Lattner25feae52008-01-28 00:58:18 +00002986 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2987 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002988 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002989 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2990 // the same basic block, then we replace the select with Y, and the
2991 // condition of the select with false (if the cond value is in the same BB).
2992 // If the select has uses other than the div, this allows them to be
2993 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2994 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002995 if (ST->isNullValue()) {
2996 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2997 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002998 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002999 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3000 I.setOperand(1, SI->getOperand(2));
3001 else
3002 UpdateValueUsesWith(SI, SI->getOperand(2));
3003 return &I;
3004 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003005
Chris Lattner25feae52008-01-28 00:58:18 +00003006 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3007 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003008 if (ST->isNullValue()) {
3009 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3010 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003011 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00003012 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3013 I.setOperand(1, SI->getOperand(1));
3014 else
3015 UpdateValueUsesWith(SI, SI->getOperand(1));
3016 return &I;
3017 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003018 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003019
Reid Spencer1628cec2006-10-26 06:15:43 +00003020 return 0;
3021}
Misha Brukmanfd939082005-04-21 23:48:37 +00003022
Reid Spencer1628cec2006-10-26 06:15:43 +00003023/// This function implements the transforms common to both integer division
3024/// instructions (udiv and sdiv). It is called by the visitors to those integer
3025/// division instructions.
3026/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003027Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003028 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3029
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003030 // (sdiv X, X) --> 1 (udiv X, X) --> 1
3031 if (Op0 == Op1)
3032 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
3033
Reid Spencer1628cec2006-10-26 06:15:43 +00003034 if (Instruction *Common = commonDivTransforms(I))
3035 return Common;
3036
3037 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3038 // div X, 1 == X
3039 if (RHS->equalsInt(1))
3040 return ReplaceInstUsesWith(I, Op0);
3041
3042 // (X / C1) / C2 -> X / (C1*C2)
3043 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3044 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3045 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003046 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3047 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3048 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003049 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003050 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003051 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003052
Reid Spencerbca0e382007-03-23 20:05:17 +00003053 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003054 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3055 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3056 return R;
3057 if (isa<PHINode>(Op0))
3058 if (Instruction *NV = FoldOpIntoPhi(I))
3059 return NV;
3060 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003061 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003062
Chris Lattnera2881962003-02-18 19:28:33 +00003063 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003064 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003065 if (LHS->equalsInt(0))
3066 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3067
Reid Spencer1628cec2006-10-26 06:15:43 +00003068 return 0;
3069}
3070
3071Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3072 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3073
3074 // Handle the integer div common cases
3075 if (Instruction *Common = commonIDivTransforms(I))
3076 return Common;
3077
3078 // X udiv C^2 -> X >> C
3079 // Check to see if this is an unsigned division with an exact power of 2,
3080 // if so, convert to a right shift.
3081 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00003082 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003083 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003084 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003085 }
3086
3087 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003088 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003089 if (RHSI->getOpcode() == Instruction::Shl &&
3090 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003091 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003092 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003093 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003094 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003095 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003096 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003097 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003098 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003099 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003100 }
3101 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003102 }
3103
Reid Spencer1628cec2006-10-26 06:15:43 +00003104 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3105 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003106 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003107 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003108 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003109 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003110 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003111 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003112 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003113 // Construct the "on true" case of the select
3114 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003115 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003116 Op0, TC, SI->getName()+".t");
3117 TSI = InsertNewInstBefore(TSI, I);
3118
3119 // Construct the "on false" case of the select
3120 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003121 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003122 Op0, FC, SI->getName()+".f");
3123 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003124
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003125 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003126 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003127 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003128 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003129 return 0;
3130}
3131
Reid Spencer1628cec2006-10-26 06:15:43 +00003132Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3133 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3134
3135 // Handle the integer div common cases
3136 if (Instruction *Common = commonIDivTransforms(I))
3137 return Common;
3138
3139 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3140 // sdiv X, -1 == -X
3141 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003142 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003143
3144 // -X/C -> X/-C
3145 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003146 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003147 }
3148
3149 // If the sign bits of both operands are zero (i.e. we can prove they are
3150 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003151 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003152 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003153 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003154 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003155 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003156 }
3157 }
3158
3159 return 0;
3160}
3161
3162Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3163 return commonDivTransforms(I);
3164}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003165
Reid Spencer0a783f72006-11-02 01:53:59 +00003166/// This function implements the transforms on rem instructions that work
3167/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3168/// is used by the visitors to those instructions.
3169/// @brief Transforms common to all three rem instructions
3170Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003171 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003172
Chris Lattner50b2ca42008-02-19 06:12:18 +00003173 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003174 if (Constant *LHS = dyn_cast<Constant>(Op0))
3175 if (LHS->isNullValue())
3176 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3177
Chris Lattner50b2ca42008-02-19 06:12:18 +00003178 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3179 if (I.getType()->isFPOrFPVector())
3180 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003181 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003182 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003183 if (isa<UndefValue>(Op1))
3184 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003185
3186 // Handle cases involving: rem X, (select Cond, Y, Z)
3187 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3188 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3189 // the same basic block, then we replace the select with Y, and the
3190 // condition of the select with false (if the cond value is in the same
3191 // BB). If the select has uses other than the div, this allows them to be
3192 // simplified also.
3193 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3194 if (ST->isNullValue()) {
3195 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3196 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003197 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003198 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3199 I.setOperand(1, SI->getOperand(2));
3200 else
3201 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003202 return &I;
3203 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003204 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3205 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3206 if (ST->isNullValue()) {
3207 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3208 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003209 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003210 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3211 I.setOperand(1, SI->getOperand(1));
3212 else
3213 UpdateValueUsesWith(SI, SI->getOperand(1));
3214 return &I;
3215 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003216 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003217
Reid Spencer0a783f72006-11-02 01:53:59 +00003218 return 0;
3219}
3220
3221/// This function implements the transforms common to both integer remainder
3222/// instructions (urem and srem). It is called by the visitors to those integer
3223/// remainder instructions.
3224/// @brief Common integer remainder transforms
3225Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3226 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3227
3228 if (Instruction *common = commonRemTransforms(I))
3229 return common;
3230
Chris Lattner857e8cd2004-12-12 21:48:58 +00003231 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003232 // X % 0 == undef, we don't need to preserve faults!
3233 if (RHS->equalsInt(0))
3234 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3235
Chris Lattnera2881962003-02-18 19:28:33 +00003236 if (RHS->equalsInt(1)) // X % 1 == 0
3237 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3238
Chris Lattner97943922006-02-28 05:49:21 +00003239 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3240 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3241 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3242 return R;
3243 } else if (isa<PHINode>(Op0I)) {
3244 if (Instruction *NV = FoldOpIntoPhi(I))
3245 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003246 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003247
3248 // See if we can fold away this rem instruction.
3249 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3250 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3251 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3252 KnownZero, KnownOne))
3253 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003254 }
Chris Lattnera2881962003-02-18 19:28:33 +00003255 }
3256
Reid Spencer0a783f72006-11-02 01:53:59 +00003257 return 0;
3258}
3259
3260Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3261 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3262
3263 if (Instruction *common = commonIRemTransforms(I))
3264 return common;
3265
3266 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3267 // X urem C^2 -> X and C
3268 // Check to see if this is an unsigned remainder with an exact power of 2,
3269 // if so, convert to a bitwise and.
3270 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003271 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003272 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003273 }
3274
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003275 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003276 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3277 if (RHSI->getOpcode() == Instruction::Shl &&
3278 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003279 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003280 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003281 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003282 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003283 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003284 }
3285 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003286 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003287
Reid Spencer0a783f72006-11-02 01:53:59 +00003288 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3289 // where C1&C2 are powers of two.
3290 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3291 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3292 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3293 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003294 if ((STO->getValue().isPowerOf2()) &&
3295 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003296 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003297 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003298 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003299 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003300 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003301 }
3302 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003303 }
3304
Chris Lattner3f5b8772002-05-06 16:14:14 +00003305 return 0;
3306}
3307
Reid Spencer0a783f72006-11-02 01:53:59 +00003308Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3309 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3310
Dan Gohmancff55092007-11-05 23:16:33 +00003311 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003312 if (Instruction *common = commonIRemTransforms(I))
3313 return common;
3314
3315 if (Value *RHSNeg = dyn_castNegVal(Op1))
3316 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003317 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003318 // X % -Y -> X % Y
3319 AddUsesToWorkList(I);
3320 I.setOperand(1, RHSNeg);
3321 return &I;
3322 }
3323
Dan Gohmancff55092007-11-05 23:16:33 +00003324 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003325 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003326 if (I.getType()->isInteger()) {
3327 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3328 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3329 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003330 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003331 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003332 }
3333
3334 return 0;
3335}
3336
3337Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003338 return commonRemTransforms(I);
3339}
3340
Chris Lattner8b170942002-08-09 23:47:40 +00003341// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003342static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003343 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003344 if (!isSigned)
3345 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3346 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003347}
3348
3349// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003350static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003351 if (!isSigned)
3352 return C->getValue() == 1; // unsigned
3353
3354 // Calculate 1111111111000000000000
3355 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3356 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003357}
3358
Chris Lattner457dd822004-06-09 07:59:58 +00003359// isOneBitSet - Return true if there is exactly one bit set in the specified
3360// constant.
3361static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003362 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003363}
3364
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003365// isHighOnes - Return true if the constant is of the form 1+0+.
3366// This is the same as lowones(~X).
3367static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003368 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003369}
3370
Reid Spencere4d87aa2006-12-23 06:05:41 +00003371/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003372/// are carefully arranged to allow folding of expressions such as:
3373///
3374/// (A < B) | (A > B) --> (A != B)
3375///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003376/// Note that this is only valid if the first and second predicates have the
3377/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003378///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003379/// Three bits are used to represent the condition, as follows:
3380/// 0 A > B
3381/// 1 A == B
3382/// 2 A < B
3383///
3384/// <=> Value Definition
3385/// 000 0 Always false
3386/// 001 1 A > B
3387/// 010 2 A == B
3388/// 011 3 A >= B
3389/// 100 4 A < B
3390/// 101 5 A != B
3391/// 110 6 A <= B
3392/// 111 7 Always true
3393///
3394static unsigned getICmpCode(const ICmpInst *ICI) {
3395 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003396 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003397 case ICmpInst::ICMP_UGT: return 1; // 001
3398 case ICmpInst::ICMP_SGT: return 1; // 001
3399 case ICmpInst::ICMP_EQ: return 2; // 010
3400 case ICmpInst::ICMP_UGE: return 3; // 011
3401 case ICmpInst::ICMP_SGE: return 3; // 011
3402 case ICmpInst::ICMP_ULT: return 4; // 100
3403 case ICmpInst::ICMP_SLT: return 4; // 100
3404 case ICmpInst::ICMP_NE: return 5; // 101
3405 case ICmpInst::ICMP_ULE: return 6; // 110
3406 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003407 // True -> 7
3408 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003409 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003410 return 0;
3411 }
3412}
3413
Reid Spencere4d87aa2006-12-23 06:05:41 +00003414/// getICmpValue - This is the complement of getICmpCode, which turns an
3415/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003416/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003417/// of predicate to use in new icmp instructions.
3418static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3419 switch (code) {
3420 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003421 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003422 case 1:
3423 if (sign)
3424 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3425 else
3426 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3427 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3428 case 3:
3429 if (sign)
3430 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3431 else
3432 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3433 case 4:
3434 if (sign)
3435 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3436 else
3437 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3438 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3439 case 6:
3440 if (sign)
3441 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3442 else
3443 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003444 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003445 }
3446}
3447
Reid Spencere4d87aa2006-12-23 06:05:41 +00003448static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3449 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3450 (ICmpInst::isSignedPredicate(p1) &&
3451 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3452 (ICmpInst::isSignedPredicate(p2) &&
3453 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3454}
3455
3456namespace {
3457// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3458struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003459 InstCombiner &IC;
3460 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003461 ICmpInst::Predicate pred;
3462 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3463 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3464 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003465 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003466 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3467 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003468 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3469 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003470 return false;
3471 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003472 Instruction *apply(Instruction &Log) const {
3473 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3474 if (ICI->getOperand(0) != LHS) {
3475 assert(ICI->getOperand(1) == LHS);
3476 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003477 }
3478
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003479 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003480 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003481 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003482 unsigned Code;
3483 switch (Log.getOpcode()) {
3484 case Instruction::And: Code = LHSCode & RHSCode; break;
3485 case Instruction::Or: Code = LHSCode | RHSCode; break;
3486 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003487 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003488 }
3489
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003490 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3491 ICmpInst::isSignedPredicate(ICI->getPredicate());
3492
3493 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003494 if (Instruction *I = dyn_cast<Instruction>(RV))
3495 return I;
3496 // Otherwise, it's a constant boolean value...
3497 return IC.ReplaceInstUsesWith(Log, RV);
3498 }
3499};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003500} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003501
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003502// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3503// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003504// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003505Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003506 ConstantInt *OpRHS,
3507 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003508 BinaryOperator &TheAnd) {
3509 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003510 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003511 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003512 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003513
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003514 switch (Op->getOpcode()) {
3515 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003516 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003517 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003518 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003519 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003520 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003521 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003522 }
3523 break;
3524 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003525 if (Together == AndRHS) // (X | C) & C --> C
3526 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003527
Chris Lattner6e7ba452005-01-01 16:22:27 +00003528 if (Op->hasOneUse() && Together != OpRHS) {
3529 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003530 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003531 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003532 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003533 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003534 }
3535 break;
3536 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003537 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003538 // Adding a one to a single bit bit-field should be turned into an XOR
3539 // of the bit. First thing to check is to see if this AND is with a
3540 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003541 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003542
3543 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003544 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003545 // Ok, at this point, we know that we are masking the result of the
3546 // ADD down to exactly one bit. If the constant we are adding has
3547 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003548 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003549
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003550 // Check to see if any bits below the one bit set in AndRHSV are set.
3551 if ((AddRHS & (AndRHSV-1)) == 0) {
3552 // If not, the only thing that can effect the output of the AND is
3553 // the bit specified by AndRHSV. If that bit is set, the effect of
3554 // the XOR is to toggle the bit. If it is clear, then the ADD has
3555 // no effect.
3556 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3557 TheAnd.setOperand(0, X);
3558 return &TheAnd;
3559 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003560 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003561 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003562 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003563 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003564 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003565 }
3566 }
3567 }
3568 }
3569 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003570
3571 case Instruction::Shl: {
3572 // We know that the AND will not produce any of the bits shifted in, so if
3573 // the anded constant includes them, clear them now!
3574 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003575 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003576 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003577 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3578 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003579
Zhou Sheng290bec52007-03-29 08:15:12 +00003580 if (CI->getValue() == ShlMask) {
3581 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003582 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3583 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003584 TheAnd.setOperand(1, CI);
3585 return &TheAnd;
3586 }
3587 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003588 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003589 case Instruction::LShr:
3590 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003591 // We know that the AND will not produce any of the bits shifted in, so if
3592 // the anded constant includes them, clear them now! This only applies to
3593 // unsigned shifts, because a signed shr may bring in set bits!
3594 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003595 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003596 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003597 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3598 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003599
Zhou Sheng290bec52007-03-29 08:15:12 +00003600 if (CI->getValue() == ShrMask) {
3601 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003602 return ReplaceInstUsesWith(TheAnd, Op);
3603 } else if (CI != AndRHS) {
3604 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3605 return &TheAnd;
3606 }
3607 break;
3608 }
3609 case Instruction::AShr:
3610 // Signed shr.
3611 // See if this is shifting in some sign extension, then masking it out
3612 // with an and.
3613 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003614 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003615 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003616 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3617 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003618 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003619 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003620 // Make the argument unsigned.
3621 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003622 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003623 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003624 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003625 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003626 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003627 }
3628 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003629 }
3630 return 0;
3631}
3632
Chris Lattner8b170942002-08-09 23:47:40 +00003633
Chris Lattnera96879a2004-09-29 17:40:11 +00003634/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3635/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003636/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3637/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003638/// insert new instructions.
3639Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003640 bool isSigned, bool Inside,
3641 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003642 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003643 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003644 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003645
Chris Lattnera96879a2004-09-29 17:40:11 +00003646 if (Inside) {
3647 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003648 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003649
Reid Spencere4d87aa2006-12-23 06:05:41 +00003650 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003651 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003652 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003653 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3654 return new ICmpInst(pred, V, Hi);
3655 }
3656
3657 // Emit V-Lo <u Hi-Lo
3658 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003659 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003660 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003661 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3662 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003663 }
3664
3665 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003666 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003667
Reid Spencere4e40032007-03-21 23:19:50 +00003668 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003669 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003670 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003671 ICmpInst::Predicate pred = (isSigned ?
3672 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3673 return new ICmpInst(pred, V, Hi);
3674 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003675
Reid Spencere4e40032007-03-21 23:19:50 +00003676 // Emit V-Lo >u Hi-1-Lo
3677 // Note that Hi has already had one subtracted from it, above.
3678 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003679 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003680 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003681 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3682 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003683}
3684
Chris Lattner7203e152005-09-18 07:22:02 +00003685// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3686// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3687// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3688// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003689static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003690 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003691 uint32_t BitWidth = Val->getType()->getBitWidth();
3692 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003693
3694 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003695 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003696 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003697 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003698 return true;
3699}
3700
Chris Lattner7203e152005-09-18 07:22:02 +00003701/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3702/// where isSub determines whether the operator is a sub. If we can fold one of
3703/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003704///
3705/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3706/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3707/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3708///
3709/// return (A +/- B).
3710///
3711Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003712 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003713 Instruction &I) {
3714 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3715 if (!LHSI || LHSI->getNumOperands() != 2 ||
3716 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3717
3718 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3719
3720 switch (LHSI->getOpcode()) {
3721 default: return 0;
3722 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003723 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003724 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003725 if ((Mask->getValue().countLeadingZeros() +
3726 Mask->getValue().countPopulation()) ==
3727 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003728 break;
3729
3730 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3731 // part, we don't need any explicit masks to take them out of A. If that
3732 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003733 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003734 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003735 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003736 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003737 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003738 break;
3739 }
3740 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003741 return 0;
3742 case Instruction::Or:
3743 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003744 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003745 if ((Mask->getValue().countLeadingZeros() +
3746 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003747 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003748 break;
3749 return 0;
3750 }
3751
3752 Instruction *New;
3753 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003754 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003755 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003756 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003757 return InsertNewInstBefore(New, I);
3758}
3759
Chris Lattner7e708292002-06-25 16:13:24 +00003760Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003761 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003762 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003763
Chris Lattnere87597f2004-10-16 18:11:37 +00003764 if (isa<UndefValue>(Op1)) // X & undef -> 0
3765 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3766
Chris Lattner6e7ba452005-01-01 16:22:27 +00003767 // and X, X = X
3768 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003769 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003770
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003771 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003772 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003773 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003774 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3775 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3776 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003777 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003778 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003779 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003780 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003781 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003782 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003783 } else if (isa<ConstantAggregateZero>(Op1)) {
3784 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003785 }
3786 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003787
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003788 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003789 const APInt& AndRHSMask = AndRHS->getValue();
3790 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003791
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003792 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003793 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003794 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003795 Value *Op0LHS = Op0I->getOperand(0);
3796 Value *Op0RHS = Op0I->getOperand(1);
3797 switch (Op0I->getOpcode()) {
3798 case Instruction::Xor:
3799 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003800 // If the mask is only needed on one incoming arm, push it up.
3801 if (Op0I->hasOneUse()) {
3802 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3803 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003804 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003805 Op0RHS->getName()+".masked");
3806 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003807 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003808 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003809 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003810 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003811 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3812 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003813 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003814 Op0LHS->getName()+".masked");
3815 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003816 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003817 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3818 }
3819 }
3820
Chris Lattner6e7ba452005-01-01 16:22:27 +00003821 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003822 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003823 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3824 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3825 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3826 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003827 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003828 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003829 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003830 break;
3831
3832 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003833 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3834 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3835 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3836 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003837 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003838 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003839 }
3840
Chris Lattner58403262003-07-23 19:25:52 +00003841 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003842 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003843 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003844 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003845 // If this is an integer truncation or change from signed-to-unsigned, and
3846 // if the source is an and/or with immediate, transform it. This
3847 // frequently occurs for bitfield accesses.
3848 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003849 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003850 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003851 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003852 if (CastOp->getOpcode() == Instruction::And) {
3853 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003854 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3855 // This will fold the two constants together, which may allow
3856 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003857 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003858 CastOp->getOperand(0), I.getType(),
3859 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003860 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003861 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003862 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003863 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003864 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003865 } else if (CastOp->getOpcode() == Instruction::Or) {
3866 // Change: and (cast (or X, C1) to T), C2
3867 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003868 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003869 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3870 return ReplaceInstUsesWith(I, AndRHS);
3871 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003872 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003873 }
Chris Lattner06782f82003-07-23 19:36:21 +00003874 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003875
3876 // Try to fold constant and into select arguments.
3877 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003878 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003879 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003880 if (isa<PHINode>(Op0))
3881 if (Instruction *NV = FoldOpIntoPhi(I))
3882 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003883 }
3884
Chris Lattner8d969642003-03-10 23:06:50 +00003885 Value *Op0NotVal = dyn_castNotVal(Op0);
3886 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003887
Chris Lattner5b62aa72004-06-18 06:07:51 +00003888 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3889 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3890
Misha Brukmancb6267b2004-07-30 12:50:08 +00003891 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003892 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003893 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003894 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003895 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003896 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003897 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003898
3899 {
Chris Lattner003b6202007-06-15 05:58:24 +00003900 Value *A = 0, *B = 0, *C = 0, *D = 0;
3901 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003902 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3903 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003904
3905 // (A|B) & ~(A&B) -> A^B
3906 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3907 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003908 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003909 }
3910 }
3911
3912 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003913 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3914 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003915
3916 // ~(A&B) & (A|B) -> A^B
3917 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3918 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003919 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003920 }
3921 }
Chris Lattner64daab52006-04-01 08:03:55 +00003922
3923 if (Op0->hasOneUse() &&
3924 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3925 if (A == Op1) { // (A^B)&A -> A&(A^B)
3926 I.swapOperands(); // Simplify below
3927 std::swap(Op0, Op1);
3928 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3929 cast<BinaryOperator>(Op0)->swapOperands();
3930 I.swapOperands(); // Simplify below
3931 std::swap(Op0, Op1);
3932 }
3933 }
3934 if (Op1->hasOneUse() &&
3935 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3936 if (B == Op0) { // B&(A^B) -> B&(B^A)
3937 cast<BinaryOperator>(Op1)->swapOperands();
3938 std::swap(A, B);
3939 }
3940 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003941 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00003942 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003943 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00003944 }
3945 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003946 }
3947
Reid Spencere4d87aa2006-12-23 06:05:41 +00003948 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3949 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3950 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003951 return R;
3952
Chris Lattner955f3312004-09-28 21:48:02 +00003953 Value *LHSVal, *RHSVal;
3954 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003955 ICmpInst::Predicate LHSCC, RHSCC;
3956 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3957 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3958 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3959 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3960 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3961 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3962 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003963 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3964
3965 // Don't try to fold ICMP_SLT + ICMP_ULT.
3966 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3967 ICmpInst::isSignedPredicate(LHSCC) ==
3968 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003969 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003970 ICmpInst::Predicate GT;
3971 if (ICmpInst::isSignedPredicate(LHSCC) ||
3972 (ICmpInst::isEquality(LHSCC) &&
3973 ICmpInst::isSignedPredicate(RHSCC)))
3974 GT = ICmpInst::ICMP_SGT;
3975 else
3976 GT = ICmpInst::ICMP_UGT;
3977
Reid Spencere4d87aa2006-12-23 06:05:41 +00003978 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3979 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003980 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003981 std::swap(LHS, RHS);
3982 std::swap(LHSCst, RHSCst);
3983 std::swap(LHSCC, RHSCC);
3984 }
3985
Reid Spencere4d87aa2006-12-23 06:05:41 +00003986 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003987 // comparing a value against two constants and and'ing the result
3988 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003989 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3990 // (from the FoldICmpLogical check above), that the two constants
3991 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003992 assert(LHSCst != RHSCst && "Compares not folded above?");
3993
3994 switch (LHSCC) {
3995 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003996 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003997 switch (RHSCC) {
3998 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003999 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4000 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4001 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004002 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004003 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4004 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4005 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00004006 return ReplaceInstUsesWith(I, LHS);
4007 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004008 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00004009 switch (RHSCC) {
4010 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004011 case ICmpInst::ICMP_ULT:
4012 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4013 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4014 break; // (X != 13 & X u< 15) -> no change
4015 case ICmpInst::ICMP_SLT:
4016 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4017 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4018 break; // (X != 13 & X s< 15) -> no change
4019 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4020 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4021 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00004022 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004023 case ICmpInst::ICMP_NE:
4024 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00004025 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004026 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00004027 LHSVal->getName()+".off");
4028 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00004029 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4030 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00004031 }
4032 break; // (X != 13 & X != 15) -> no change
4033 }
4034 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004035 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00004036 switch (RHSCC) {
4037 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004038 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4039 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004040 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004041 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4042 break;
4043 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4044 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00004045 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004046 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4047 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004048 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004049 break;
4050 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00004051 switch (RHSCC) {
4052 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004053 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4054 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004055 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004056 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4057 break;
4058 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4059 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00004060 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004061 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4062 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004063 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004064 break;
4065 case ICmpInst::ICMP_UGT:
4066 switch (RHSCC) {
4067 default: assert(0 && "Unknown integer condition code!");
4068 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4069 return ReplaceInstUsesWith(I, LHS);
4070 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4071 return ReplaceInstUsesWith(I, RHS);
4072 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4073 break;
4074 case ICmpInst::ICMP_NE:
4075 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4076 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4077 break; // (X u> 13 & X != 15) -> no change
4078 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4079 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4080 true, I);
4081 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4082 break;
4083 }
4084 break;
4085 case ICmpInst::ICMP_SGT:
4086 switch (RHSCC) {
4087 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004088 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004089 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4090 return ReplaceInstUsesWith(I, RHS);
4091 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4092 break;
4093 case ICmpInst::ICMP_NE:
4094 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4095 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4096 break; // (X s> 13 & X != 15) -> no change
4097 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4098 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4099 true, I);
4100 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4101 break;
4102 }
4103 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004104 }
4105 }
4106 }
4107
Chris Lattner6fc205f2006-05-05 06:39:07 +00004108 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004109 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4110 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4111 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4112 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004113 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004114 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004115 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4116 I.getType(), TD) &&
4117 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4118 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004119 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004120 Op1C->getOperand(0),
4121 I.getName());
4122 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004123 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004124 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004125 }
Chris Lattnere511b742006-11-14 07:46:50 +00004126
4127 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004128 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4129 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4130 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004131 SI0->getOperand(1) == SI1->getOperand(1) &&
4132 (SI0->hasOneUse() || SI1->hasOneUse())) {
4133 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004134 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004135 SI1->getOperand(0),
4136 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004137 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004138 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004139 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004140 }
4141
Chris Lattner99c65742007-10-24 05:38:08 +00004142 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4143 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4144 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4145 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4146 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4147 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4148 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4149 // If either of the constants are nans, then the whole thing returns
4150 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004151 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004152 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4153 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4154 RHS->getOperand(0));
4155 }
4156 }
4157 }
4158
Chris Lattner7e708292002-06-25 16:13:24 +00004159 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004160}
4161
Chris Lattnerafe91a52006-06-15 19:07:26 +00004162/// CollectBSwapParts - Look to see if the specified value defines a single byte
4163/// in the result. If it does, and if the specified byte hasn't been filled in
4164/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004165static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004166 Instruction *I = dyn_cast<Instruction>(V);
4167 if (I == 0) return true;
4168
4169 // If this is an or instruction, it is an inner node of the bswap.
4170 if (I->getOpcode() == Instruction::Or)
4171 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4172 CollectBSwapParts(I->getOperand(1), ByteValues);
4173
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004174 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004175 // If this is a shift by a constant int, and it is "24", then its operand
4176 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004177 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004178 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004179 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004180 8*(ByteValues.size()-1))
4181 return true;
4182
4183 unsigned DestNo;
4184 if (I->getOpcode() == Instruction::Shl) {
4185 // X << 24 defines the top byte with the lowest of the input bytes.
4186 DestNo = ByteValues.size()-1;
4187 } else {
4188 // X >>u 24 defines the low byte with the highest of the input bytes.
4189 DestNo = 0;
4190 }
4191
4192 // If the destination byte value is already defined, the values are or'd
4193 // together, which isn't a bswap (unless it's an or of the same bits).
4194 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4195 return true;
4196 ByteValues[DestNo] = I->getOperand(0);
4197 return false;
4198 }
4199
4200 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4201 // don't have this.
4202 Value *Shift = 0, *ShiftLHS = 0;
4203 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4204 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4205 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4206 return true;
4207 Instruction *SI = cast<Instruction>(Shift);
4208
4209 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004210 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4211 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004212 return true;
4213
4214 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4215 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004216 if (AndAmt->getValue().getActiveBits() > 64)
4217 return true;
4218 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004219 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004220 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004221 break;
4222 // Unknown mask for bswap.
4223 if (DestByte == ByteValues.size()) return true;
4224
Reid Spencerb83eb642006-10-20 07:07:24 +00004225 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004226 unsigned SrcByte;
4227 if (SI->getOpcode() == Instruction::Shl)
4228 SrcByte = DestByte - ShiftBytes;
4229 else
4230 SrcByte = DestByte + ShiftBytes;
4231
4232 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4233 if (SrcByte != ByteValues.size()-DestByte-1)
4234 return true;
4235
4236 // If the destination byte value is already defined, the values are or'd
4237 // together, which isn't a bswap (unless it's an or of the same bits).
4238 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4239 return true;
4240 ByteValues[DestByte] = SI->getOperand(0);
4241 return false;
4242}
4243
4244/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4245/// If so, insert the new bswap intrinsic and return it.
4246Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004247 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4248 if (!ITy || ITy->getBitWidth() % 16)
4249 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004250
4251 /// ByteValues - For each byte of the result, we keep track of which value
4252 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004253 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004254 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004255
4256 // Try to find all the pieces corresponding to the bswap.
4257 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4258 CollectBSwapParts(I.getOperand(1), ByteValues))
4259 return 0;
4260
4261 // Check to see if all of the bytes come from the same value.
4262 Value *V = ByteValues[0];
4263 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4264
4265 // Check to make sure that all of the bytes come from the same value.
4266 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4267 if (ByteValues[i] != V)
4268 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004269 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004270 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004271 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004272 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004273}
4274
4275
Chris Lattner7e708292002-06-25 16:13:24 +00004276Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004277 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004278 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004279
Chris Lattner42593e62007-03-24 23:56:43 +00004280 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004281 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004282
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004283 // or X, X = X
4284 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004285 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004286
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004287 // See if we can simplify any instructions used by the instruction whose sole
4288 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004289 if (!isa<VectorType>(I.getType())) {
4290 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4291 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4292 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4293 KnownZero, KnownOne))
4294 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004295 } else if (isa<ConstantAggregateZero>(Op1)) {
4296 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4297 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4298 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4299 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004300 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004301
4302
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004303
Chris Lattner3f5b8772002-05-06 16:14:14 +00004304 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004305 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004306 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004307 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4308 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004309 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004310 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004311 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004312 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004313 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004314 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004315
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004316 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4317 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004318 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004319 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004320 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004321 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004322 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004323 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004324
4325 // Try to fold constant and into select arguments.
4326 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004327 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004328 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004329 if (isa<PHINode>(Op0))
4330 if (Instruction *NV = FoldOpIntoPhi(I))
4331 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004332 }
4333
Chris Lattner4f637d42006-01-06 17:59:59 +00004334 Value *A = 0, *B = 0;
4335 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004336
4337 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4338 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4339 return ReplaceInstUsesWith(I, Op1);
4340 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4341 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4342 return ReplaceInstUsesWith(I, Op0);
4343
Chris Lattner6423d4c2006-07-10 20:25:24 +00004344 // (A | B) | C and A | (B | C) -> bswap if possible.
4345 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004346 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004347 match(Op1, m_Or(m_Value(), m_Value())) ||
4348 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4349 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004350 if (Instruction *BSwap = MatchBSwap(I))
4351 return BSwap;
4352 }
4353
Chris Lattner6e4c6492005-05-09 04:58:36 +00004354 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4355 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004356 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004357 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004358 InsertNewInstBefore(NOr, I);
4359 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004360 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004361 }
4362
4363 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4364 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004365 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004366 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004367 InsertNewInstBefore(NOr, I);
4368 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004369 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004370 }
4371
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004372 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004373 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004374 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4375 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004376 Value *V1 = 0, *V2 = 0, *V3 = 0;
4377 C1 = dyn_cast<ConstantInt>(C);
4378 C2 = dyn_cast<ConstantInt>(D);
4379 if (C1 && C2) { // (A & C1)|(B & C2)
4380 // If we have: ((V + N) & C1) | (V & C2)
4381 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4382 // replace with V+N.
4383 if (C1->getValue() == ~C2->getValue()) {
4384 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4385 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4386 // Add commutes, try both ways.
4387 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4388 return ReplaceInstUsesWith(I, A);
4389 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4390 return ReplaceInstUsesWith(I, A);
4391 }
4392 // Or commutes, try both ways.
4393 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4394 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4395 // Add commutes, try both ways.
4396 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4397 return ReplaceInstUsesWith(I, B);
4398 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4399 return ReplaceInstUsesWith(I, B);
4400 }
4401 }
Chris Lattner044e5332007-04-08 08:01:49 +00004402 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004403 }
4404
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004405 // Check to see if we have any common things being and'ed. If so, find the
4406 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004407 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4408 if (A == B) // (A & C)|(A & D) == A & (C|D)
4409 V1 = A, V2 = C, V3 = D;
4410 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4411 V1 = A, V2 = B, V3 = C;
4412 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4413 V1 = C, V2 = A, V3 = D;
4414 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4415 V1 = C, V2 = A, V3 = B;
4416
4417 if (V1) {
4418 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004419 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4420 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004421 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004422 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004423 }
Chris Lattnere511b742006-11-14 07:46:50 +00004424
4425 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004426 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4427 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4428 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004429 SI0->getOperand(1) == SI1->getOperand(1) &&
4430 (SI0->hasOneUse() || SI1->hasOneUse())) {
4431 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004432 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004433 SI1->getOperand(0),
4434 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004435 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004436 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004437 }
4438 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004439
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004440 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4441 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004442 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004443 } else {
4444 A = 0;
4445 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004446 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004447 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4448 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004449 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004450
Misha Brukmancb6267b2004-07-30 12:50:08 +00004451 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004452 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004453 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004454 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004455 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004456 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004457 }
Chris Lattnera2881962003-02-18 19:28:33 +00004458
Reid Spencere4d87aa2006-12-23 06:05:41 +00004459 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4460 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4461 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004462 return R;
4463
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004464 Value *LHSVal, *RHSVal;
4465 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004466 ICmpInst::Predicate LHSCC, RHSCC;
4467 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4468 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4469 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4470 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4471 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4472 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4473 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004474 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4475 // We can't fold (ugt x, C) | (sgt x, C2).
4476 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004477 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004478 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004479 bool NeedsSwap;
4480 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004481 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004482 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004483 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004484
4485 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004486 std::swap(LHS, RHS);
4487 std::swap(LHSCst, RHSCst);
4488 std::swap(LHSCC, RHSCC);
4489 }
4490
Reid Spencere4d87aa2006-12-23 06:05:41 +00004491 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004492 // comparing a value against two constants and or'ing the result
4493 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004494 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4495 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004496 // equal.
4497 assert(LHSCst != RHSCst && "Compares not folded above?");
4498
4499 switch (LHSCC) {
4500 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004501 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004502 switch (RHSCC) {
4503 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004504 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004505 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4506 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004507 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004508 LHSVal->getName()+".off");
4509 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004510 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004511 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004512 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004513 break; // (X == 13 | X == 15) -> no change
4514 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4515 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004516 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004517 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4518 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4519 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004520 return ReplaceInstUsesWith(I, RHS);
4521 }
4522 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004523 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004524 switch (RHSCC) {
4525 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004526 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4527 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4528 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004529 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004530 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4531 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4532 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004533 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004534 }
4535 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004536 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004537 switch (RHSCC) {
4538 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004539 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004540 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004541 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004542 // If RHSCst is [us]MAXINT, it is always false. Not handling
4543 // this can cause overflow.
4544 if (RHSCst->isMaxValue(false))
4545 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004546 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4547 false, I);
4548 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4549 break;
4550 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4551 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004552 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004553 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4554 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004555 }
4556 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004557 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004558 switch (RHSCC) {
4559 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004560 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4561 break;
4562 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004563 // If RHSCst is [us]MAXINT, it is always false. Not handling
4564 // this can cause overflow.
4565 if (RHSCst->isMaxValue(true))
4566 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004567 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4568 false, I);
4569 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4570 break;
4571 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4572 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4573 return ReplaceInstUsesWith(I, RHS);
4574 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4575 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004576 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004577 break;
4578 case ICmpInst::ICMP_UGT:
4579 switch (RHSCC) {
4580 default: assert(0 && "Unknown integer condition code!");
4581 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4582 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4583 return ReplaceInstUsesWith(I, LHS);
4584 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4585 break;
4586 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4587 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004588 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004589 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4590 break;
4591 }
4592 break;
4593 case ICmpInst::ICMP_SGT:
4594 switch (RHSCC) {
4595 default: assert(0 && "Unknown integer condition code!");
4596 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4597 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4598 return ReplaceInstUsesWith(I, LHS);
4599 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4600 break;
4601 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4602 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004603 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004604 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4605 break;
4606 }
4607 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004608 }
4609 }
4610 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004611
4612 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004613 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004614 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004615 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004616 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4617 !isa<ICmpInst>(Op1C->getOperand(0))) {
4618 const Type *SrcTy = Op0C->getOperand(0)->getType();
4619 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4620 // Only do this if the casts both really cause code to be
4621 // generated.
4622 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4623 I.getType(), TD) &&
4624 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4625 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004626 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004627 Op1C->getOperand(0),
4628 I.getName());
4629 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004630 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004631 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004632 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004633 }
Chris Lattner99c65742007-10-24 05:38:08 +00004634 }
4635
4636
4637 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4638 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4639 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4640 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004641 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4642 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004643 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4644 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4645 // If either of the constants are nans, then the whole thing returns
4646 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004647 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004648 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4649
4650 // Otherwise, no need to compare the two constants, compare the
4651 // rest.
4652 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4653 RHS->getOperand(0));
4654 }
4655 }
4656 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004657
Chris Lattner7e708292002-06-25 16:13:24 +00004658 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004659}
4660
Dan Gohman844731a2008-05-13 00:00:25 +00004661namespace {
4662
Chris Lattnerc317d392004-02-16 01:20:27 +00004663// XorSelf - Implements: X ^ X --> 0
4664struct XorSelf {
4665 Value *RHS;
4666 XorSelf(Value *rhs) : RHS(rhs) {}
4667 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4668 Instruction *apply(BinaryOperator &Xor) const {
4669 return &Xor;
4670 }
4671};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004672
Dan Gohman844731a2008-05-13 00:00:25 +00004673}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004674
Chris Lattner7e708292002-06-25 16:13:24 +00004675Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004676 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004677 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004678
Evan Chengd34af782008-03-25 20:07:13 +00004679 if (isa<UndefValue>(Op1)) {
4680 if (isa<UndefValue>(Op0))
4681 // Handle undef ^ undef -> 0 special case. This is a common
4682 // idiom (misuse).
4683 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004684 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004685 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004686
Chris Lattnerc317d392004-02-16 01:20:27 +00004687 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4688 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004689 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004690 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004691 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004692
4693 // See if we can simplify any instructions used by the instruction whose sole
4694 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004695 if (!isa<VectorType>(I.getType())) {
4696 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4697 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4698 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4699 KnownZero, KnownOne))
4700 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004701 } else if (isa<ConstantAggregateZero>(Op1)) {
4702 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004703 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004704
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004705 // Is this a ~ operation?
4706 if (Value *NotOp = dyn_castNotVal(&I)) {
4707 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4708 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4709 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4710 if (Op0I->getOpcode() == Instruction::And ||
4711 Op0I->getOpcode() == Instruction::Or) {
4712 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4713 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4714 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004715 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004716 Op0I->getOperand(1)->getName()+".not");
4717 InsertNewInstBefore(NotY, I);
4718 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004719 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004720 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004721 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004722 }
4723 }
4724 }
4725 }
4726
4727
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004728 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004729 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4730 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4731 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004732 return new ICmpInst(ICI->getInversePredicate(),
4733 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004734
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004735 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4736 return new FCmpInst(FCI->getInversePredicate(),
4737 FCI->getOperand(0), FCI->getOperand(1));
4738 }
4739
Reid Spencere4d87aa2006-12-23 06:05:41 +00004740 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004741 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004742 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4743 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004744 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4745 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004746 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004747 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004748 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004749
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004750 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004751 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004752 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004753 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004754 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004755 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004756 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004757 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004758 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004759 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004760 // (X + C) ^ signbit -> (X + C + signbit)
4761 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004762 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004763
Chris Lattner7c4049c2004-01-12 19:35:11 +00004764 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004765 } else if (Op0I->getOpcode() == Instruction::Or) {
4766 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004767 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004768 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4769 // Anything in both C1 and C2 is known to be zero, remove it from
4770 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004771 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004772 NewRHS = ConstantExpr::getAnd(NewRHS,
4773 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004774 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004775 I.setOperand(0, Op0I->getOperand(0));
4776 I.setOperand(1, NewRHS);
4777 return &I;
4778 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004779 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004780 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004781 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004782
4783 // Try to fold constant and into select arguments.
4784 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004785 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004786 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004787 if (isa<PHINode>(Op0))
4788 if (Instruction *NV = FoldOpIntoPhi(I))
4789 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004790 }
4791
Chris Lattner8d969642003-03-10 23:06:50 +00004792 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004793 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004794 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004795
Chris Lattner8d969642003-03-10 23:06:50 +00004796 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004797 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004798 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004799
Chris Lattner318bf792007-03-18 22:51:34 +00004800
4801 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4802 if (Op1I) {
4803 Value *A, *B;
4804 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4805 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004806 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004807 I.swapOperands();
4808 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004809 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004810 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004811 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004812 }
Chris Lattner318bf792007-03-18 22:51:34 +00004813 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4814 if (Op0 == A) // A^(A^B) == B
4815 return ReplaceInstUsesWith(I, B);
4816 else if (Op0 == B) // A^(B^A) == B
4817 return ReplaceInstUsesWith(I, A);
4818 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004819 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004820 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004821 std::swap(A, B);
4822 }
Chris Lattner318bf792007-03-18 22:51:34 +00004823 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004824 I.swapOperands(); // Simplified below.
4825 std::swap(Op0, Op1);
4826 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004827 }
Chris Lattner318bf792007-03-18 22:51:34 +00004828 }
4829
4830 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4831 if (Op0I) {
4832 Value *A, *B;
4833 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4834 if (A == Op1) // (B|A)^B == (A|B)^B
4835 std::swap(A, B);
4836 if (B == Op1) { // (A|B)^B == A & ~B
4837 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004838 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4839 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004840 }
Chris Lattner318bf792007-03-18 22:51:34 +00004841 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4842 if (Op1 == A) // (A^B)^A == B
4843 return ReplaceInstUsesWith(I, B);
4844 else if (Op1 == B) // (B^A)^A == B
4845 return ReplaceInstUsesWith(I, A);
4846 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4847 if (A == Op1) // (A&B)^A -> (B&A)^A
4848 std::swap(A, B);
4849 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004850 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004851 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004852 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4853 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004854 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004855 }
Chris Lattner318bf792007-03-18 22:51:34 +00004856 }
4857
4858 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4859 if (Op0I && Op1I && Op0I->isShift() &&
4860 Op0I->getOpcode() == Op1I->getOpcode() &&
4861 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4862 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4863 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004864 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00004865 Op1I->getOperand(0),
4866 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004867 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00004868 Op1I->getOperand(1));
4869 }
4870
4871 if (Op0I && Op1I) {
4872 Value *A, *B, *C, *D;
4873 // (A & B)^(A | B) -> A ^ B
4874 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4875 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4876 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004877 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004878 }
4879 // (A | B)^(A & B) -> A ^ B
4880 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4881 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4882 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004883 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004884 }
4885
4886 // (A & B)^(C & D)
4887 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4888 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4889 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4890 // (X & Y)^(X & Y) -> (Y^Z) & X
4891 Value *X = 0, *Y = 0, *Z = 0;
4892 if (A == C)
4893 X = A, Y = B, Z = D;
4894 else if (A == D)
4895 X = A, Y = B, Z = C;
4896 else if (B == C)
4897 X = B, Y = A, Z = D;
4898 else if (B == D)
4899 X = B, Y = A, Z = C;
4900
4901 if (X) {
4902 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004903 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4904 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00004905 }
4906 }
4907 }
4908
Reid Spencere4d87aa2006-12-23 06:05:41 +00004909 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4910 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4911 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004912 return R;
4913
Chris Lattner6fc205f2006-05-05 06:39:07 +00004914 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004915 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004916 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004917 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4918 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004919 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004920 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004921 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4922 I.getType(), TD) &&
4923 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4924 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004925 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004926 Op1C->getOperand(0),
4927 I.getName());
4928 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004929 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004930 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004931 }
Chris Lattner99c65742007-10-24 05:38:08 +00004932 }
Chris Lattner7e708292002-06-25 16:13:24 +00004933 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004934}
4935
Chris Lattnera96879a2004-09-29 17:40:11 +00004936/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4937/// overflowed for this type.
4938static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004939 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004940 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004941
Reid Spencere4e40032007-03-21 23:19:50 +00004942 if (IsSigned)
4943 if (In2->getValue().isNegative())
4944 return Result->getValue().sgt(In1->getValue());
4945 else
4946 return Result->getValue().slt(In1->getValue());
4947 else
4948 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004949}
4950
Chris Lattner574da9b2005-01-13 20:14:25 +00004951/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4952/// code necessary to compute the offset from the base pointer (without adding
4953/// in the base pointer). Return the result as a signed integer of intptr size.
4954static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4955 TargetData &TD = IC.getTargetData();
4956 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004957 const Type *IntPtrTy = TD.getIntPtrType();
4958 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004959
4960 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00004961 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00004962 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004963
Chris Lattner574da9b2005-01-13 20:14:25 +00004964 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4965 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004966 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004967 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4968 if (OpC->isZero()) continue;
4969
4970 // Handle a struct index, which adds its field offset to the pointer.
4971 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4972 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4973
4974 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4975 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004976 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004977 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004978 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004979 ConstantInt::get(IntPtrTy, Size),
4980 GEP->getName()+".offs"), I);
4981 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004982 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004983
4984 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4985 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4986 Scale = ConstantExpr::getMul(OC, Scale);
4987 if (Constant *RC = dyn_cast<Constant>(Result))
4988 Result = ConstantExpr::getAdd(RC, Scale);
4989 else {
4990 // Emit an add instruction.
4991 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004992 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004993 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004994 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004995 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004996 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004997 // Convert to correct type.
4998 if (Op->getType() != IntPtrTy) {
4999 if (Constant *OpC = dyn_cast<Constant>(Op))
5000 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5001 else
5002 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5003 Op->getName()+".c"), I);
5004 }
5005 if (Size != 1) {
5006 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5007 if (Constant *OpC = dyn_cast<Constant>(Op))
5008 Op = ConstantExpr::getMul(OpC, Scale);
5009 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005010 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005011 GEP->getName()+".idx"), I);
5012 }
5013
5014 // Emit an add instruction.
5015 if (isa<Constant>(Op) && isa<Constant>(Result))
5016 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5017 cast<Constant>(Result));
5018 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005019 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005020 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005021 }
5022 return Result;
5023}
5024
Chris Lattner10c0d912008-04-22 02:53:33 +00005025
5026/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5027/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5028/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5029/// complex, and scales are involved. The above expression would also be legal
5030/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5031/// later form is less amenable to optimization though, and we are allowed to
5032/// generate the first by knowing that pointer arithmetic doesn't overflow.
5033///
5034/// If we can't emit an optimized form for this expression, this returns null.
5035///
5036static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5037 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005038 TargetData &TD = IC.getTargetData();
5039 gep_type_iterator GTI = gep_type_begin(GEP);
5040
5041 // Check to see if this gep only has a single variable index. If so, and if
5042 // any constant indices are a multiple of its scale, then we can compute this
5043 // in terms of the scale of the variable index. For example, if the GEP
5044 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5045 // because the expression will cross zero at the same point.
5046 unsigned i, e = GEP->getNumOperands();
5047 int64_t Offset = 0;
5048 for (i = 1; i != e; ++i, ++GTI) {
5049 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5050 // Compute the aggregate offset of constant indices.
5051 if (CI->isZero()) continue;
5052
5053 // Handle a struct index, which adds its field offset to the pointer.
5054 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5055 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5056 } else {
5057 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5058 Offset += Size*CI->getSExtValue();
5059 }
5060 } else {
5061 // Found our variable index.
5062 break;
5063 }
5064 }
5065
5066 // If there are no variable indices, we must have a constant offset, just
5067 // evaluate it the general way.
5068 if (i == e) return 0;
5069
5070 Value *VariableIdx = GEP->getOperand(i);
5071 // Determine the scale factor of the variable element. For example, this is
5072 // 4 if the variable index is into an array of i32.
5073 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5074
5075 // Verify that there are no other variable indices. If so, emit the hard way.
5076 for (++i, ++GTI; i != e; ++i, ++GTI) {
5077 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5078 if (!CI) return 0;
5079
5080 // Compute the aggregate offset of constant indices.
5081 if (CI->isZero()) continue;
5082
5083 // Handle a struct index, which adds its field offset to the pointer.
5084 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5085 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5086 } else {
5087 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5088 Offset += Size*CI->getSExtValue();
5089 }
5090 }
5091
5092 // Okay, we know we have a single variable index, which must be a
5093 // pointer/array/vector index. If there is no offset, life is simple, return
5094 // the index.
5095 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5096 if (Offset == 0) {
5097 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5098 // we don't need to bother extending: the extension won't affect where the
5099 // computation crosses zero.
5100 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5101 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5102 VariableIdx->getNameStart(), &I);
5103 return VariableIdx;
5104 }
5105
5106 // Otherwise, there is an index. The computation we will do will be modulo
5107 // the pointer size, so get it.
5108 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5109
5110 Offset &= PtrSizeMask;
5111 VariableScale &= PtrSizeMask;
5112
5113 // To do this transformation, any constant index must be a multiple of the
5114 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5115 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5116 // multiple of the variable scale.
5117 int64_t NewOffs = Offset / (int64_t)VariableScale;
5118 if (Offset != NewOffs*(int64_t)VariableScale)
5119 return 0;
5120
5121 // Okay, we can do this evaluation. Start by converting the index to intptr.
5122 const Type *IntPtrTy = TD.getIntPtrType();
5123 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005124 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005125 true /*SExt*/,
5126 VariableIdx->getNameStart(), &I);
5127 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005128 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005129}
5130
5131
Reid Spencere4d87aa2006-12-23 06:05:41 +00005132/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005133/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005134Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5135 ICmpInst::Predicate Cond,
5136 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005137 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005138
Chris Lattner10c0d912008-04-22 02:53:33 +00005139 // Look through bitcasts.
5140 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5141 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005142
Chris Lattner574da9b2005-01-13 20:14:25 +00005143 Value *PtrBase = GEPLHS->getOperand(0);
5144 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005145 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005146 // This transformation (ignoring the base and scales) is valid because we
5147 // know pointers can't overflow. See if we can output an optimized form.
5148 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5149
5150 // If not, synthesize the offset the hard way.
5151 if (Offset == 0)
5152 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005153 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5154 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005155 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005156 // If the base pointers are different, but the indices are the same, just
5157 // compare the base pointer.
5158 if (PtrBase != GEPRHS->getOperand(0)) {
5159 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005160 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005161 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005162 if (IndicesTheSame)
5163 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5164 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5165 IndicesTheSame = false;
5166 break;
5167 }
5168
5169 // If all indices are the same, just compare the base pointers.
5170 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005171 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5172 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005173
5174 // Otherwise, the base pointers are different and the indices are
5175 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005176 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005177 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005178
Chris Lattnere9d782b2005-01-13 22:25:21 +00005179 // If one of the GEPs has all zero indices, recurse.
5180 bool AllZeros = true;
5181 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5182 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5183 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5184 AllZeros = false;
5185 break;
5186 }
5187 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005188 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5189 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005190
5191 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005192 AllZeros = true;
5193 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5194 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5195 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5196 AllZeros = false;
5197 break;
5198 }
5199 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005200 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005201
Chris Lattner4401c9c2005-01-14 00:20:05 +00005202 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5203 // If the GEPs only differ by one index, compare it.
5204 unsigned NumDifferences = 0; // Keep track of # differences.
5205 unsigned DiffOperand = 0; // The operand that differs.
5206 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5207 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005208 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5209 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005210 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005211 NumDifferences = 2;
5212 break;
5213 } else {
5214 if (NumDifferences++) break;
5215 DiffOperand = i;
5216 }
5217 }
5218
5219 if (NumDifferences == 0) // SAME GEP?
5220 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005221 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005222 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005223
Chris Lattner4401c9c2005-01-14 00:20:05 +00005224 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005225 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5226 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005227 // Make sure we do a signed comparison here.
5228 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005229 }
5230 }
5231
Reid Spencere4d87aa2006-12-23 06:05:41 +00005232 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005233 // the result to fold to a constant!
5234 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5235 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5236 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5237 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5238 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005239 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005240 }
5241 }
5242 return 0;
5243}
5244
Chris Lattnera5406232008-05-19 20:18:56 +00005245/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5246///
5247Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5248 Instruction *LHSI,
5249 Constant *RHSC) {
5250 if (!isa<ConstantFP>(RHSC)) return 0;
5251 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5252
5253 // Get the width of the mantissa. We don't want to hack on conversions that
5254 // might lose information from the integer, e.g. "i64 -> float"
5255 int MantissaWidth = GetFPMantissaWidth(LHSI->getType());
5256 if (MantissaWidth == -1) return 0; // Unknown.
5257
5258 // Check to see that the input is converted from an integer type that is small
5259 // enough that preserves all bits. TODO: check here for "known" sign bits.
5260 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5261 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5262
5263 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5264 if (isa<UIToFPInst>(LHSI))
5265 ++InputSize;
5266
5267 // If the conversion would lose info, don't hack on this.
5268 if ((int)InputSize > MantissaWidth)
5269 return 0;
5270
5271 // Otherwise, we can potentially simplify the comparison. We know that it
5272 // will always come through as an integer value and we know the constant is
5273 // not a NAN (it would have been previously simplified).
5274 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5275
5276 ICmpInst::Predicate Pred;
5277 switch (I.getPredicate()) {
5278 default: assert(0 && "Unexpected predicate!");
5279 case FCmpInst::FCMP_UEQ:
5280 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5281 case FCmpInst::FCMP_UGT:
5282 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5283 case FCmpInst::FCMP_UGE:
5284 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5285 case FCmpInst::FCMP_ULT:
5286 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5287 case FCmpInst::FCMP_ULE:
5288 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5289 case FCmpInst::FCMP_UNE:
5290 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5291 case FCmpInst::FCMP_ORD:
5292 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5293 case FCmpInst::FCMP_UNO:
5294 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5295 }
5296
5297 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5298
5299 // Now we know that the APFloat is a normal number, zero or inf.
5300
5301 // See if the FP constant is top large for the integer. For example,
5302 // comparing an i8 to 300.0.
5303 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5304
5305 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5306 // and large values.
5307 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5308 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5309 APFloat::rmNearestTiesToEven);
5310 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5311 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5312 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5313 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5314 }
5315
5316 // See if the RHS value is < SignedMin.
5317 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5318 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5319 APFloat::rmNearestTiesToEven);
5320 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5321 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5322 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5323 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5324 }
5325
5326 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5327 // it may still be fractional. See if it is fractional by casting the FP
5328 // value to the integer value and back, checking for equality. Don't do this
5329 // for zero, because -0.0 is not fractional.
5330 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5331 if (!RHS.isZero() &&
5332 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5333 // If we had a comparison against a fractional value, we have to adjust
5334 // the compare predicate and sometimes the value. RHSC is rounded towards
5335 // zero at this point.
5336 switch (Pred) {
5337 default: assert(0 && "Unexpected integer comparison!");
5338 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5339 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5340 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5341 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5342 case ICmpInst::ICMP_SLE:
5343 // (float)int <= 4.4 --> int <= 4
5344 // (float)int <= -4.4 --> int < -4
5345 if (RHS.isNegative())
5346 Pred = ICmpInst::ICMP_SLT;
5347 break;
5348 case ICmpInst::ICMP_SLT:
5349 // (float)int < -4.4 --> int < -4
5350 // (float)int < 4.4 --> int <= 4
5351 if (!RHS.isNegative())
5352 Pred = ICmpInst::ICMP_SLE;
5353 break;
5354 case ICmpInst::ICMP_SGT:
5355 // (float)int > 4.4 --> int > 4
5356 // (float)int > -4.4 --> int >= -4
5357 if (RHS.isNegative())
5358 Pred = ICmpInst::ICMP_SGE;
5359 break;
5360 case ICmpInst::ICMP_SGE:
5361 // (float)int >= -4.4 --> int >= -4
5362 // (float)int >= 4.4 --> int > 4
5363 if (!RHS.isNegative())
5364 Pred = ICmpInst::ICMP_SGT;
5365 break;
5366 }
5367 }
5368
5369 // Lower this FP comparison into an appropriate integer version of the
5370 // comparison.
5371 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5372}
5373
Reid Spencere4d87aa2006-12-23 06:05:41 +00005374Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5375 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005376 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005377
Chris Lattner58e97462007-01-14 19:42:17 +00005378 // Fold trivial predicates.
5379 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5380 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5381 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5382 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5383
5384 // Simplify 'fcmp pred X, X'
5385 if (Op0 == Op1) {
5386 switch (I.getPredicate()) {
5387 default: assert(0 && "Unknown predicate!");
5388 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5389 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5390 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5391 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5392 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5393 case FCmpInst::FCMP_OLT: // True if ordered and less than
5394 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5395 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5396
5397 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5398 case FCmpInst::FCMP_ULT: // True if unordered or less than
5399 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5400 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5401 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5402 I.setPredicate(FCmpInst::FCMP_UNO);
5403 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5404 return &I;
5405
5406 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5407 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5408 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5409 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5410 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5411 I.setPredicate(FCmpInst::FCMP_ORD);
5412 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5413 return &I;
5414 }
5415 }
5416
Reid Spencere4d87aa2006-12-23 06:05:41 +00005417 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005418 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005419
Reid Spencere4d87aa2006-12-23 06:05:41 +00005420 // Handle fcmp with constant RHS
5421 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005422 // If the constant is a nan, see if we can fold the comparison based on it.
5423 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5424 if (CFP->getValueAPF().isNaN()) {
5425 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5426 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5427 if (FCmpInst::isUnordered(I.getPredicate())) // True if unordered or...
5428 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5429 if (FCmpInst::isUnordered(I.getPredicate())) // Undef on unordered.
5430 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5431 }
5432 }
5433
Reid Spencere4d87aa2006-12-23 06:05:41 +00005434 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5435 switch (LHSI->getOpcode()) {
5436 case Instruction::PHI:
5437 if (Instruction *NV = FoldOpIntoPhi(I))
5438 return NV;
5439 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005440 case Instruction::SIToFP:
5441 case Instruction::UIToFP:
5442 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5443 return NV;
5444 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005445 case Instruction::Select:
5446 // If either operand of the select is a constant, we can fold the
5447 // comparison into the select arms, which will cause one to be
5448 // constant folded and the select turned into a bitwise or.
5449 Value *Op1 = 0, *Op2 = 0;
5450 if (LHSI->hasOneUse()) {
5451 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5452 // Fold the known value into the constant operand.
5453 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5454 // Insert a new FCmp of the other select operand.
5455 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5456 LHSI->getOperand(2), RHSC,
5457 I.getName()), I);
5458 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5459 // Fold the known value into the constant operand.
5460 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5461 // Insert a new FCmp of the other select operand.
5462 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5463 LHSI->getOperand(1), RHSC,
5464 I.getName()), I);
5465 }
5466 }
5467
5468 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005469 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005470 break;
5471 }
5472 }
5473
5474 return Changed ? &I : 0;
5475}
5476
5477Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5478 bool Changed = SimplifyCompare(I);
5479 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5480 const Type *Ty = Op0->getType();
5481
5482 // icmp X, X
5483 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005484 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005485 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005486
5487 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005488 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005489
Reid Spencere4d87aa2006-12-23 06:05:41 +00005490 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005491 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005492 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5493 isa<ConstantPointerNull>(Op0)) &&
5494 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005495 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005496 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005497 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005498
Reid Spencere4d87aa2006-12-23 06:05:41 +00005499 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005500 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005501 switch (I.getPredicate()) {
5502 default: assert(0 && "Invalid icmp instruction!");
5503 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005504 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005505 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005506 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005507 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005508 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005509 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005510
Reid Spencere4d87aa2006-12-23 06:05:41 +00005511 case ICmpInst::ICMP_UGT:
5512 case ICmpInst::ICMP_SGT:
5513 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005514 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005515 case ICmpInst::ICMP_ULT:
5516 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005517 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005518 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005519 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005520 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005521 case ICmpInst::ICMP_UGE:
5522 case ICmpInst::ICMP_SGE:
5523 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005524 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005525 case ICmpInst::ICMP_ULE:
5526 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005527 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005528 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005529 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005530 }
5531 }
Chris Lattner8b170942002-08-09 23:47:40 +00005532 }
5533
Chris Lattner2be51ae2004-06-09 04:24:29 +00005534 // See if we are doing a comparison between a constant and an instruction that
5535 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005536 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005537 Value *A, *B;
5538
Chris Lattnerb6566012008-01-05 01:18:20 +00005539 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5540 if (I.isEquality() && CI->isNullValue() &&
5541 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5542 // (icmp cond A B) if cond is equality
5543 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005544 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005545
Reid Spencere4d87aa2006-12-23 06:05:41 +00005546 switch (I.getPredicate()) {
5547 default: break;
5548 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5549 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005550 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005551 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5552 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5553 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5554 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005555 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5556 if (CI->isMinValue(true))
5557 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5558 ConstantInt::getAllOnesValue(Op0->getType()));
5559
Reid Spencere4d87aa2006-12-23 06:05:41 +00005560 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005561
Reid Spencere4d87aa2006-12-23 06:05:41 +00005562 case ICmpInst::ICMP_SLT:
5563 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005564 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005565 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5566 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5567 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5568 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5569 break;
5570
5571 case ICmpInst::ICMP_UGT:
5572 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005573 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005574 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5575 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5576 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5577 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005578
5579 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5580 if (CI->isMaxValue(true))
5581 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5582 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005583 break;
5584
5585 case ICmpInst::ICMP_SGT:
5586 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005587 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005588 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5589 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5590 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5591 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5592 break;
5593
5594 case ICmpInst::ICMP_ULE:
5595 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005596 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005597 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5598 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5599 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5600 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5601 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005602
Reid Spencere4d87aa2006-12-23 06:05:41 +00005603 case ICmpInst::ICMP_SLE:
5604 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005605 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005606 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5607 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5608 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5609 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5610 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005611
Reid Spencere4d87aa2006-12-23 06:05:41 +00005612 case ICmpInst::ICMP_UGE:
5613 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005614 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005615 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5616 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5617 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5618 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5619 break;
5620
5621 case ICmpInst::ICMP_SGE:
5622 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005623 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005624 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5625 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5626 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5627 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5628 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005629 }
5630
Reid Spencere4d87aa2006-12-23 06:05:41 +00005631 // If we still have a icmp le or icmp ge instruction, turn it into the
5632 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005633 // already been handled above, this requires little checking.
5634 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005635 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005636 default: break;
5637 case ICmpInst::ICMP_ULE:
5638 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5639 case ICmpInst::ICMP_SLE:
5640 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5641 case ICmpInst::ICMP_UGE:
5642 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5643 case ICmpInst::ICMP_SGE:
5644 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005645 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005646
5647 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005648 // in the input. If this comparison is a normal comparison, it demands all
5649 // bits, if it is a sign bit comparison, it only demands the sign bit.
5650
5651 bool UnusedBit;
5652 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5653
Reid Spencer0460fb32007-03-22 20:36:03 +00005654 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5655 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005656 if (SimplifyDemandedBits(Op0,
5657 isSignBit ? APInt::getSignBit(BitWidth)
5658 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005659 KnownZero, KnownOne, 0))
5660 return &I;
5661
5662 // Given the known and unknown bits, compute a range that the LHS could be
5663 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005664 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005665 // Compute the Min, Max and RHS values based on the known bits. For the
5666 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005667 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5668 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005669 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005670 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5671 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005672 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005673 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5674 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005675 }
5676 switch (I.getPredicate()) { // LE/GE have been folded already.
5677 default: assert(0 && "Unknown icmp opcode!");
5678 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005679 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005680 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005681 break;
5682 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005683 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005684 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005685 break;
5686 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005687 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005688 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005689 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005690 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005691 break;
5692 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005693 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005694 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005695 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005696 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005697 break;
5698 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005699 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005700 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005701 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005702 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005703 break;
5704 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005705 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005706 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005707 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005708 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005709 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005710 }
5711 }
5712
Reid Spencere4d87aa2006-12-23 06:05:41 +00005713 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005714 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005715 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005716 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005717 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5718 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005719 }
5720
Chris Lattner01deb9d2007-04-03 17:43:25 +00005721 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005722 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5723 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5724 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005725 case Instruction::GetElementPtr:
5726 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005727 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005728 bool isAllZeros = true;
5729 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5730 if (!isa<Constant>(LHSI->getOperand(i)) ||
5731 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5732 isAllZeros = false;
5733 break;
5734 }
5735 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005736 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005737 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5738 }
5739 break;
5740
Chris Lattner6970b662005-04-23 15:31:55 +00005741 case Instruction::PHI:
5742 if (Instruction *NV = FoldOpIntoPhi(I))
5743 return NV;
5744 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005745 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005746 // If either operand of the select is a constant, we can fold the
5747 // comparison into the select arms, which will cause one to be
5748 // constant folded and the select turned into a bitwise or.
5749 Value *Op1 = 0, *Op2 = 0;
5750 if (LHSI->hasOneUse()) {
5751 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5752 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005753 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5754 // Insert a new ICmp of the other select operand.
5755 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5756 LHSI->getOperand(2), RHSC,
5757 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005758 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5759 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005760 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5761 // Insert a new ICmp of the other select operand.
5762 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5763 LHSI->getOperand(1), RHSC,
5764 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005765 }
5766 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005767
Chris Lattner6970b662005-04-23 15:31:55 +00005768 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005769 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005770 break;
5771 }
Chris Lattner4802d902007-04-06 18:57:34 +00005772 case Instruction::Malloc:
5773 // If we have (malloc != null), and if the malloc has a single use, we
5774 // can assume it is successful and remove the malloc.
5775 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5776 AddToWorkList(LHSI);
5777 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005778 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00005779 }
5780 break;
5781 }
Chris Lattner6970b662005-04-23 15:31:55 +00005782 }
5783
Reid Spencere4d87aa2006-12-23 06:05:41 +00005784 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005785 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005786 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005787 return NI;
5788 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005789 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5790 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005791 return NI;
5792
Reid Spencere4d87aa2006-12-23 06:05:41 +00005793 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005794 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5795 // now.
5796 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5797 if (isa<PointerType>(Op0->getType()) &&
5798 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005799 // We keep moving the cast from the left operand over to the right
5800 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005801 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005802
Chris Lattner57d86372007-01-06 01:45:59 +00005803 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5804 // so eliminate it as well.
5805 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5806 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005807
Chris Lattnerde90b762003-11-03 04:25:02 +00005808 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005809 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005810 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005811 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005812 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005813 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005814 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005815 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005816 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005817 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005818 }
Chris Lattner57d86372007-01-06 01:45:59 +00005819 }
5820
5821 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005822 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005823 // This comes up when you have code like
5824 // int X = A < B;
5825 // if (X) ...
5826 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005827 // with a constant or another cast from the same type.
5828 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005829 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005830 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005831 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005832
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005833 // ~x < ~y --> y < x
5834 { Value *A, *B;
5835 if (match(Op0, m_Not(m_Value(A))) &&
5836 match(Op1, m_Not(m_Value(B))))
5837 return new ICmpInst(I.getPredicate(), B, A);
5838 }
5839
Chris Lattner65b72ba2006-09-18 04:22:48 +00005840 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005841 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005842
5843 // -x == -y --> x == y
5844 if (match(Op0, m_Neg(m_Value(A))) &&
5845 match(Op1, m_Neg(m_Value(B))))
5846 return new ICmpInst(I.getPredicate(), A, B);
5847
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005848 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5849 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5850 Value *OtherVal = A == Op1 ? B : A;
5851 return new ICmpInst(I.getPredicate(), OtherVal,
5852 Constant::getNullValue(A->getType()));
5853 }
5854
5855 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5856 // A^c1 == C^c2 --> A == C^(c1^c2)
5857 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5858 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5859 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005860 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005861 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005862 return new ICmpInst(I.getPredicate(), A,
5863 InsertNewInstBefore(Xor, I));
5864 }
5865
5866 // A^B == A^D -> B == D
5867 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5868 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5869 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5870 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5871 }
5872 }
5873
5874 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5875 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005876 // A == (A^B) -> B == 0
5877 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005878 return new ICmpInst(I.getPredicate(), OtherVal,
5879 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005880 }
5881 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005882 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005883 return new ICmpInst(I.getPredicate(), B,
5884 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005885 }
5886 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005887 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005888 return new ICmpInst(I.getPredicate(), B,
5889 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005890 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005891
Chris Lattner9c2328e2006-11-14 06:06:06 +00005892 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5893 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5894 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5895 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5896 Value *X = 0, *Y = 0, *Z = 0;
5897
5898 if (A == C) {
5899 X = B; Y = D; Z = A;
5900 } else if (A == D) {
5901 X = B; Y = C; Z = A;
5902 } else if (B == C) {
5903 X = A; Y = D; Z = B;
5904 } else if (B == D) {
5905 X = A; Y = C; Z = B;
5906 }
5907
5908 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005909 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5910 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00005911 I.setOperand(0, Op1);
5912 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5913 return &I;
5914 }
5915 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005916 }
Chris Lattner7e708292002-06-25 16:13:24 +00005917 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005918}
5919
Chris Lattner562ef782007-06-20 23:46:26 +00005920
5921/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5922/// and CmpRHS are both known to be integer constants.
5923Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5924 ConstantInt *DivRHS) {
5925 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5926 const APInt &CmpRHSV = CmpRHS->getValue();
5927
5928 // FIXME: If the operand types don't match the type of the divide
5929 // then don't attempt this transform. The code below doesn't have the
5930 // logic to deal with a signed divide and an unsigned compare (and
5931 // vice versa). This is because (x /s C1) <s C2 produces different
5932 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5933 // (x /u C1) <u C2. Simply casting the operands and result won't
5934 // work. :( The if statement below tests that condition and bails
5935 // if it finds it.
5936 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5937 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5938 return 0;
5939 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005940 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005941
5942 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5943 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5944 // C2 (CI). By solving for X we can turn this into a range check
5945 // instead of computing a divide.
5946 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5947
5948 // Determine if the product overflows by seeing if the product is
5949 // not equal to the divide. Make sure we do the same kind of divide
5950 // as in the LHS instruction that we're folding.
5951 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5952 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5953
5954 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005955 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005956
Chris Lattner1dbfd482007-06-21 18:11:19 +00005957 // Figure out the interval that is being checked. For example, a comparison
5958 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5959 // Compute this interval based on the constants involved and the signedness of
5960 // the compare/divide. This computes a half-open interval, keeping track of
5961 // whether either value in the interval overflows. After analysis each
5962 // overflow variable is set to 0 if it's corresponding bound variable is valid
5963 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5964 int LoOverflow = 0, HiOverflow = 0;
5965 ConstantInt *LoBound = 0, *HiBound = 0;
5966
5967
Chris Lattner562ef782007-06-20 23:46:26 +00005968 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005969 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005970 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005971 HiOverflow = LoOverflow = ProdOV;
5972 if (!HiOverflow)
5973 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005974 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005975 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005976 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005977 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5978 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005979 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005980 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5981 HiOverflow = LoOverflow = ProdOV;
5982 if (!HiOverflow)
5983 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005984 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005985 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005986 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5987 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005988 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005989 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005990 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005991 }
Dan Gohman76491272008-02-13 22:09:18 +00005992 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005993 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005994 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005995 LoBound = AddOne(DivRHS);
5996 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005997 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5998 HiOverflow = 1; // [INTMIN+1, overflow)
5999 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6000 }
Dan Gohman76491272008-02-13 22:09:18 +00006001 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006002 // e.g. X/-5 op 3 --> [-19, -14)
6003 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006004 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006005 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00006006 HiBound = AddOne(Prod);
6007 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006008 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006009 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006010 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006011 HiBound = Subtract(Prod, DivRHS);
6012 }
6013
Chris Lattner1dbfd482007-06-21 18:11:19 +00006014 // Dividing by a negative swaps the condition. LT <-> GT
6015 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006016 }
6017
6018 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006019 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006020 default: assert(0 && "Unhandled icmp opcode!");
6021 case ICmpInst::ICMP_EQ:
6022 if (LoOverflow && HiOverflow)
6023 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6024 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006025 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006026 ICmpInst::ICMP_UGE, X, LoBound);
6027 else if (LoOverflow)
6028 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6029 ICmpInst::ICMP_ULT, X, HiBound);
6030 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006031 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006032 case ICmpInst::ICMP_NE:
6033 if (LoOverflow && HiOverflow)
6034 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6035 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006036 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006037 ICmpInst::ICMP_ULT, X, LoBound);
6038 else if (LoOverflow)
6039 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6040 ICmpInst::ICMP_UGE, X, HiBound);
6041 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006042 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006043 case ICmpInst::ICMP_ULT:
6044 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006045 if (LoOverflow == +1) // Low bound is greater than input range.
6046 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6047 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006048 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006049 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006050 case ICmpInst::ICMP_UGT:
6051 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006052 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006053 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006054 else if (HiOverflow == -1) // High bound less than input range.
6055 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6056 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006057 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6058 else
6059 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6060 }
6061}
6062
6063
Chris Lattner01deb9d2007-04-03 17:43:25 +00006064/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6065///
6066Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6067 Instruction *LHSI,
6068 ConstantInt *RHS) {
6069 const APInt &RHSV = RHS->getValue();
6070
6071 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00006072 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006073 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6074 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6075 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006076 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6077 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006078 Value *CompareVal = LHSI->getOperand(0);
6079
6080 // If the sign bit of the XorCST is not set, there is no change to
6081 // the operation, just stop using the Xor.
6082 if (!XorCST->getValue().isNegative()) {
6083 ICI.setOperand(0, CompareVal);
6084 AddToWorkList(LHSI);
6085 return &ICI;
6086 }
6087
6088 // Was the old condition true if the operand is positive?
6089 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6090
6091 // If so, the new one isn't.
6092 isTrueIfPositive ^= true;
6093
6094 if (isTrueIfPositive)
6095 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6096 else
6097 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6098 }
6099 }
6100 break;
6101 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6102 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6103 LHSI->getOperand(0)->hasOneUse()) {
6104 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6105
6106 // If the LHS is an AND of a truncating cast, we can widen the
6107 // and/compare to be the input width without changing the value
6108 // produced, eliminating a cast.
6109 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6110 // We can do this transformation if either the AND constant does not
6111 // have its sign bit set or if it is an equality comparison.
6112 // Extending a relational comparison when we're checking the sign
6113 // bit would not work.
6114 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006115 (ICI.isEquality() ||
6116 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006117 uint32_t BitWidth =
6118 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6119 APInt NewCST = AndCST->getValue();
6120 NewCST.zext(BitWidth);
6121 APInt NewCI = RHSV;
6122 NewCI.zext(BitWidth);
6123 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006124 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006125 ConstantInt::get(NewCST),LHSI->getName());
6126 InsertNewInstBefore(NewAnd, ICI);
6127 return new ICmpInst(ICI.getPredicate(), NewAnd,
6128 ConstantInt::get(NewCI));
6129 }
6130 }
6131
6132 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6133 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6134 // happens a LOT in code produced by the C front-end, for bitfield
6135 // access.
6136 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6137 if (Shift && !Shift->isShift())
6138 Shift = 0;
6139
6140 ConstantInt *ShAmt;
6141 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6142 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6143 const Type *AndTy = AndCST->getType(); // Type of the and.
6144
6145 // We can fold this as long as we can't shift unknown bits
6146 // into the mask. This can only happen with signed shift
6147 // rights, as they sign-extend.
6148 if (ShAmt) {
6149 bool CanFold = Shift->isLogicalShift();
6150 if (!CanFold) {
6151 // To test for the bad case of the signed shr, see if any
6152 // of the bits shifted in could be tested after the mask.
6153 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6154 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6155
6156 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6157 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6158 AndCST->getValue()) == 0)
6159 CanFold = true;
6160 }
6161
6162 if (CanFold) {
6163 Constant *NewCst;
6164 if (Shift->getOpcode() == Instruction::Shl)
6165 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6166 else
6167 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6168
6169 // Check to see if we are shifting out any of the bits being
6170 // compared.
6171 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6172 // If we shifted bits out, the fold is not going to work out.
6173 // As a special case, check to see if this means that the
6174 // result is always true or false now.
6175 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6176 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6177 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6178 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6179 } else {
6180 ICI.setOperand(1, NewCst);
6181 Constant *NewAndCST;
6182 if (Shift->getOpcode() == Instruction::Shl)
6183 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6184 else
6185 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6186 LHSI->setOperand(1, NewAndCST);
6187 LHSI->setOperand(0, Shift->getOperand(0));
6188 AddToWorkList(Shift); // Shift is dead.
6189 AddUsesToWorkList(ICI);
6190 return &ICI;
6191 }
6192 }
6193 }
6194
6195 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6196 // preferable because it allows the C<<Y expression to be hoisted out
6197 // of a loop if Y is invariant and X is not.
6198 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6199 ICI.isEquality() && !Shift->isArithmeticShift() &&
6200 isa<Instruction>(Shift->getOperand(0))) {
6201 // Compute C << Y.
6202 Value *NS;
6203 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006204 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006205 Shift->getOperand(1), "tmp");
6206 } else {
6207 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006208 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006209 Shift->getOperand(1), "tmp");
6210 }
6211 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6212
6213 // Compute X & (C << Y).
6214 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006215 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006216 InsertNewInstBefore(NewAnd, ICI);
6217
6218 ICI.setOperand(0, NewAnd);
6219 return &ICI;
6220 }
6221 }
6222 break;
6223
Chris Lattnera0141b92007-07-15 20:42:37 +00006224 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6225 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6226 if (!ShAmt) break;
6227
6228 uint32_t TypeBits = RHSV.getBitWidth();
6229
6230 // Check that the shift amount is in range. If not, don't perform
6231 // undefined shifts. When the shift is visited it will be
6232 // simplified.
6233 if (ShAmt->uge(TypeBits))
6234 break;
6235
6236 if (ICI.isEquality()) {
6237 // If we are comparing against bits always shifted out, the
6238 // comparison cannot succeed.
6239 Constant *Comp =
6240 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6241 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6242 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6243 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6244 return ReplaceInstUsesWith(ICI, Cst);
6245 }
6246
6247 if (LHSI->hasOneUse()) {
6248 // Otherwise strength reduce the shift into an and.
6249 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6250 Constant *Mask =
6251 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006252
Chris Lattnera0141b92007-07-15 20:42:37 +00006253 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006254 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006255 Mask, LHSI->getName()+".mask");
6256 Value *And = InsertNewInstBefore(AndI, ICI);
6257 return new ICmpInst(ICI.getPredicate(), And,
6258 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006259 }
6260 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006261
6262 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6263 bool TrueIfSigned = false;
6264 if (LHSI->hasOneUse() &&
6265 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6266 // (X << 31) <s 0 --> (X&1) != 0
6267 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6268 (TypeBits-ShAmt->getZExtValue()-1));
6269 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006270 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006271 Mask, LHSI->getName()+".mask");
6272 Value *And = InsertNewInstBefore(AndI, ICI);
6273
6274 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6275 And, Constant::getNullValue(And->getType()));
6276 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006277 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006278 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006279
6280 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006281 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006282 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006283 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006284 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006285
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006286 // Check that the shift amount is in range. If not, don't perform
6287 // undefined shifts. When the shift is visited it will be
6288 // simplified.
6289 uint32_t TypeBits = RHSV.getBitWidth();
6290 if (ShAmt->uge(TypeBits))
6291 break;
6292
6293 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006294
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006295 // If we are comparing against bits always shifted out, the
6296 // comparison cannot succeed.
6297 APInt Comp = RHSV << ShAmtVal;
6298 if (LHSI->getOpcode() == Instruction::LShr)
6299 Comp = Comp.lshr(ShAmtVal);
6300 else
6301 Comp = Comp.ashr(ShAmtVal);
6302
6303 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6304 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6305 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6306 return ReplaceInstUsesWith(ICI, Cst);
6307 }
6308
6309 // Otherwise, check to see if the bits shifted out are known to be zero.
6310 // If so, we can compare against the unshifted value:
6311 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006312 if (LHSI->hasOneUse() &&
6313 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006314 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6315 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6316 ConstantExpr::getShl(RHS, ShAmt));
6317 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006318
Evan Chengf30752c2008-04-23 00:38:06 +00006319 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006320 // Otherwise strength reduce the shift into an and.
6321 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6322 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006323
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006324 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006325 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006326 Mask, LHSI->getName()+".mask");
6327 Value *And = InsertNewInstBefore(AndI, ICI);
6328 return new ICmpInst(ICI.getPredicate(), And,
6329 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006330 }
6331 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006332 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006333
6334 case Instruction::SDiv:
6335 case Instruction::UDiv:
6336 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6337 // Fold this div into the comparison, producing a range check.
6338 // Determine, based on the divide type, what the range is being
6339 // checked. If there is an overflow on the low or high side, remember
6340 // it, otherwise compute the range [low, hi) bounding the new value.
6341 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006342 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6343 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6344 DivRHS))
6345 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006346 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006347
6348 case Instruction::Add:
6349 // Fold: icmp pred (add, X, C1), C2
6350
6351 if (!ICI.isEquality()) {
6352 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6353 if (!LHSC) break;
6354 const APInt &LHSV = LHSC->getValue();
6355
6356 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6357 .subtract(LHSV);
6358
6359 if (ICI.isSignedPredicate()) {
6360 if (CR.getLower().isSignBit()) {
6361 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6362 ConstantInt::get(CR.getUpper()));
6363 } else if (CR.getUpper().isSignBit()) {
6364 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6365 ConstantInt::get(CR.getLower()));
6366 }
6367 } else {
6368 if (CR.getLower().isMinValue()) {
6369 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6370 ConstantInt::get(CR.getUpper()));
6371 } else if (CR.getUpper().isMinValue()) {
6372 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6373 ConstantInt::get(CR.getLower()));
6374 }
6375 }
6376 }
6377 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006378 }
6379
6380 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6381 if (ICI.isEquality()) {
6382 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6383
6384 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6385 // the second operand is a constant, simplify a bit.
6386 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6387 switch (BO->getOpcode()) {
6388 case Instruction::SRem:
6389 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6390 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6391 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6392 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6393 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006394 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006395 BO->getName());
6396 InsertNewInstBefore(NewRem, ICI);
6397 return new ICmpInst(ICI.getPredicate(), NewRem,
6398 Constant::getNullValue(BO->getType()));
6399 }
6400 }
6401 break;
6402 case Instruction::Add:
6403 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6404 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6405 if (BO->hasOneUse())
6406 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6407 Subtract(RHS, BOp1C));
6408 } else if (RHSV == 0) {
6409 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6410 // efficiently invertible, or if the add has just this one use.
6411 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6412
6413 if (Value *NegVal = dyn_castNegVal(BOp1))
6414 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6415 else if (Value *NegVal = dyn_castNegVal(BOp0))
6416 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6417 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006418 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006419 InsertNewInstBefore(Neg, ICI);
6420 Neg->takeName(BO);
6421 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6422 }
6423 }
6424 break;
6425 case Instruction::Xor:
6426 // For the xor case, we can xor two constants together, eliminating
6427 // the explicit xor.
6428 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6429 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6430 ConstantExpr::getXor(RHS, BOC));
6431
6432 // FALLTHROUGH
6433 case Instruction::Sub:
6434 // Replace (([sub|xor] A, B) != 0) with (A != B)
6435 if (RHSV == 0)
6436 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6437 BO->getOperand(1));
6438 break;
6439
6440 case Instruction::Or:
6441 // If bits are being or'd in that are not present in the constant we
6442 // are comparing against, then the comparison could never succeed!
6443 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6444 Constant *NotCI = ConstantExpr::getNot(RHS);
6445 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6446 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6447 isICMP_NE));
6448 }
6449 break;
6450
6451 case Instruction::And:
6452 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6453 // If bits are being compared against that are and'd out, then the
6454 // comparison can never succeed!
6455 if ((RHSV & ~BOC->getValue()) != 0)
6456 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6457 isICMP_NE));
6458
6459 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6460 if (RHS == BOC && RHSV.isPowerOf2())
6461 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6462 ICmpInst::ICMP_NE, LHSI,
6463 Constant::getNullValue(RHS->getType()));
6464
6465 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6466 if (isSignBit(BOC)) {
6467 Value *X = BO->getOperand(0);
6468 Constant *Zero = Constant::getNullValue(X->getType());
6469 ICmpInst::Predicate pred = isICMP_NE ?
6470 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6471 return new ICmpInst(pred, X, Zero);
6472 }
6473
6474 // ((X & ~7) == 0) --> X < 8
6475 if (RHSV == 0 && isHighOnes(BOC)) {
6476 Value *X = BO->getOperand(0);
6477 Constant *NegX = ConstantExpr::getNeg(BOC);
6478 ICmpInst::Predicate pred = isICMP_NE ?
6479 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6480 return new ICmpInst(pred, X, NegX);
6481 }
6482 }
6483 default: break;
6484 }
6485 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6486 // Handle icmp {eq|ne} <intrinsic>, intcst.
6487 if (II->getIntrinsicID() == Intrinsic::bswap) {
6488 AddToWorkList(II);
6489 ICI.setOperand(0, II->getOperand(1));
6490 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6491 return &ICI;
6492 }
6493 }
6494 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006495 // If the LHS is a cast from an integral value of the same size,
6496 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006497 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6498 Value *CastOp = Cast->getOperand(0);
6499 const Type *SrcTy = CastOp->getType();
6500 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6501 if (SrcTy->isInteger() &&
6502 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6503 // If this is an unsigned comparison, try to make the comparison use
6504 // smaller constant values.
6505 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6506 // X u< 128 => X s> -1
6507 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6508 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6509 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6510 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6511 // X u> 127 => X s< 0
6512 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6513 Constant::getNullValue(SrcTy));
6514 }
6515 }
6516 }
6517 }
6518 return 0;
6519}
6520
6521/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6522/// We only handle extending casts so far.
6523///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006524Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6525 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006526 Value *LHSCIOp = LHSCI->getOperand(0);
6527 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006528 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006529 Value *RHSCIOp;
6530
Chris Lattner8c756c12007-05-05 22:41:33 +00006531 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6532 // integer type is the same size as the pointer type.
6533 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6534 getTargetData().getPointerSizeInBits() ==
6535 cast<IntegerType>(DestTy)->getBitWidth()) {
6536 Value *RHSOp = 0;
6537 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006538 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006539 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6540 RHSOp = RHSC->getOperand(0);
6541 // If the pointer types don't match, insert a bitcast.
6542 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006543 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006544 }
6545
6546 if (RHSOp)
6547 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6548 }
6549
6550 // The code below only handles extension cast instructions, so far.
6551 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006552 if (LHSCI->getOpcode() != Instruction::ZExt &&
6553 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006554 return 0;
6555
Reid Spencere4d87aa2006-12-23 06:05:41 +00006556 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6557 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006558
Reid Spencere4d87aa2006-12-23 06:05:41 +00006559 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006560 // Not an extension from the same type?
6561 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006562 if (RHSCIOp->getType() != LHSCIOp->getType())
6563 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006564
Nick Lewycky4189a532008-01-28 03:48:02 +00006565 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006566 // and the other is a zext), then we can't handle this.
6567 if (CI->getOpcode() != LHSCI->getOpcode())
6568 return 0;
6569
Nick Lewycky4189a532008-01-28 03:48:02 +00006570 // Deal with equality cases early.
6571 if (ICI.isEquality())
6572 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6573
6574 // A signed comparison of sign extended values simplifies into a
6575 // signed comparison.
6576 if (isSignedCmp && isSignedExt)
6577 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6578
6579 // The other three cases all fold into an unsigned comparison.
6580 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006581 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006582
Reid Spencere4d87aa2006-12-23 06:05:41 +00006583 // If we aren't dealing with a constant on the RHS, exit early
6584 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6585 if (!CI)
6586 return 0;
6587
6588 // Compute the constant that would happen if we truncated to SrcTy then
6589 // reextended to DestTy.
6590 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6591 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6592
6593 // If the re-extended constant didn't change...
6594 if (Res2 == CI) {
6595 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6596 // For example, we might have:
6597 // %A = sext short %X to uint
6598 // %B = icmp ugt uint %A, 1330
6599 // It is incorrect to transform this into
6600 // %B = icmp ugt short %X, 1330
6601 // because %A may have negative value.
6602 //
6603 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6604 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006605 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006606 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6607 else
6608 return 0;
6609 }
6610
6611 // The re-extended constant changed so the constant cannot be represented
6612 // in the shorter type. Consequently, we cannot emit a simple comparison.
6613
6614 // First, handle some easy cases. We know the result cannot be equal at this
6615 // point so handle the ICI.isEquality() cases
6616 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006617 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006618 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006619 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006620
6621 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6622 // should have been folded away previously and not enter in here.
6623 Value *Result;
6624 if (isSignedCmp) {
6625 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006626 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006627 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006628 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006629 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006630 } else {
6631 // We're performing an unsigned comparison.
6632 if (isSignedExt) {
6633 // We're performing an unsigned comp with a sign extended value.
6634 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006635 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006636 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6637 NegOne, ICI.getName()), ICI);
6638 } else {
6639 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006640 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006641 }
6642 }
6643
6644 // Finally, return the value computed.
6645 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6646 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6647 return ReplaceInstUsesWith(ICI, Result);
6648 } else {
6649 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6650 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6651 "ICmp should be folded!");
6652 if (Constant *CI = dyn_cast<Constant>(Result))
6653 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6654 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006655 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006656 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006657}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006658
Reid Spencer832254e2007-02-02 02:16:23 +00006659Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6660 return commonShiftTransforms(I);
6661}
6662
6663Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6664 return commonShiftTransforms(I);
6665}
6666
6667Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006668 if (Instruction *R = commonShiftTransforms(I))
6669 return R;
6670
6671 Value *Op0 = I.getOperand(0);
6672
6673 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6674 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6675 if (CSI->isAllOnesValue())
6676 return ReplaceInstUsesWith(I, CSI);
6677
6678 // See if we can turn a signed shr into an unsigned shr.
6679 if (MaskedValueIsZero(Op0,
6680 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006681 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006682
6683 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006684}
6685
6686Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6687 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006688 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006689
6690 // shl X, 0 == X and shr X, 0 == X
6691 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006692 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006693 Op0 == Constant::getNullValue(Op0->getType()))
6694 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006695
Reid Spencere4d87aa2006-12-23 06:05:41 +00006696 if (isa<UndefValue>(Op0)) {
6697 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006698 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006699 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006700 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6701 }
6702 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006703 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6704 return ReplaceInstUsesWith(I, Op0);
6705 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006706 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006707 }
6708
Chris Lattner2eefe512004-04-09 19:05:30 +00006709 // Try to fold constant and into select arguments.
6710 if (isa<Constant>(Op0))
6711 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006712 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006713 return R;
6714
Reid Spencerb83eb642006-10-20 07:07:24 +00006715 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006716 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6717 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006718 return 0;
6719}
6720
Reid Spencerb83eb642006-10-20 07:07:24 +00006721Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006722 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006723 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006724
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006725 // See if we can simplify any instructions used by the instruction whose sole
6726 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006727 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6728 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6729 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006730 KnownZero, KnownOne))
6731 return &I;
6732
Chris Lattner4d5542c2006-01-06 07:12:35 +00006733 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6734 // of a signed value.
6735 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006736 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006737 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006738 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6739 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006740 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006741 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006742 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006743 }
6744
6745 // ((X*C1) << C2) == (X * (C1 << C2))
6746 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6747 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6748 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006749 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006750 ConstantExpr::getShl(BOOp, Op1));
6751
6752 // Try to fold constant and into select arguments.
6753 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6754 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6755 return R;
6756 if (isa<PHINode>(Op0))
6757 if (Instruction *NV = FoldOpIntoPhi(I))
6758 return NV;
6759
Chris Lattner8999dd32007-12-22 09:07:47 +00006760 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6761 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6762 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6763 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6764 // place. Don't try to do this transformation in this case. Also, we
6765 // require that the input operand is a shift-by-constant so that we have
6766 // confidence that the shifts will get folded together. We could do this
6767 // xform in more cases, but it is unlikely to be profitable.
6768 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6769 isa<ConstantInt>(TrOp->getOperand(1))) {
6770 // Okay, we'll do this xform. Make the shift of shift.
6771 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006772 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00006773 I.getName());
6774 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6775
6776 // For logical shifts, the truncation has the effect of making the high
6777 // part of the register be zeros. Emulate this by inserting an AND to
6778 // clear the top bits as needed. This 'and' will usually be zapped by
6779 // other xforms later if dead.
6780 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6781 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6782 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6783
6784 // The mask we constructed says what the trunc would do if occurring
6785 // between the shifts. We want to know the effect *after* the second
6786 // shift. We know that it is a logical shift by a constant, so adjust the
6787 // mask as appropriate.
6788 if (I.getOpcode() == Instruction::Shl)
6789 MaskV <<= Op1->getZExtValue();
6790 else {
6791 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6792 MaskV = MaskV.lshr(Op1->getZExtValue());
6793 }
6794
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006795 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00006796 TI->getName());
6797 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6798
6799 // Return the value truncated to the interesting size.
6800 return new TruncInst(And, I.getType());
6801 }
6802 }
6803
Chris Lattner4d5542c2006-01-06 07:12:35 +00006804 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006805 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6806 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6807 Value *V1, *V2;
6808 ConstantInt *CC;
6809 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006810 default: break;
6811 case Instruction::Add:
6812 case Instruction::And:
6813 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006814 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006815 // These operators commute.
6816 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006817 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6818 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006819 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006820 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006821 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006822 Op0BO->getName());
6823 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006824 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006825 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006826 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006827 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006828 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006829 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006830 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006831 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006832
Chris Lattner150f12a2005-09-18 06:30:59 +00006833 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006834 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006835 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006836 match(Op0BOOp1,
6837 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006838 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6839 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006840 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006841 Op0BO->getOperand(0), Op1,
6842 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006843 InsertNewInstBefore(YS, I); // (Y << C)
6844 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006845 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006846 V1->getName()+".mask");
6847 InsertNewInstBefore(XM, I); // X & (CC << C)
6848
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006849 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00006850 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006851 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006852
Reid Spencera07cb7d2007-02-02 14:41:37 +00006853 // FALL THROUGH.
6854 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006855 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006856 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6857 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006858 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006859 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006860 Op0BO->getOperand(1), Op1,
6861 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006862 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006863 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006864 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006865 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006866 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006867 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006868 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006869 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006870 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006871
Chris Lattner13d4ab42006-05-31 21:14:00 +00006872 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006873 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6874 match(Op0BO->getOperand(0),
6875 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006876 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006877 cast<BinaryOperator>(Op0BO->getOperand(0))
6878 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006879 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006880 Op0BO->getOperand(1), Op1,
6881 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006882 InsertNewInstBefore(YS, I); // (Y << C)
6883 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006884 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006885 V1->getName()+".mask");
6886 InsertNewInstBefore(XM, I); // X & (CC << C)
6887
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006888 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006889 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006890
Chris Lattner11021cb2005-09-18 05:12:10 +00006891 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006892 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006893 }
6894
6895
6896 // If the operand is an bitwise operator with a constant RHS, and the
6897 // shift is the only use, we can pull it out of the shift.
6898 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6899 bool isValid = true; // Valid only for And, Or, Xor
6900 bool highBitSet = false; // Transform if high bit of constant set?
6901
6902 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006903 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006904 case Instruction::Add:
6905 isValid = isLeftShift;
6906 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006907 case Instruction::Or:
6908 case Instruction::Xor:
6909 highBitSet = false;
6910 break;
6911 case Instruction::And:
6912 highBitSet = true;
6913 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006914 }
6915
6916 // If this is a signed shift right, and the high bit is modified
6917 // by the logical operation, do not perform the transformation.
6918 // The highBitSet boolean indicates the value of the high bit of
6919 // the constant which would cause it to be modified for this
6920 // operation.
6921 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006922 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006923 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006924
6925 if (isValid) {
6926 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6927
6928 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006929 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006930 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006931 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006932
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006933 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00006934 NewRHS);
6935 }
6936 }
6937 }
6938 }
6939
Chris Lattnerad0124c2006-01-06 07:52:12 +00006940 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006941 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6942 if (ShiftOp && !ShiftOp->isShift())
6943 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006944
Reid Spencerb83eb642006-10-20 07:07:24 +00006945 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006946 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006947 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6948 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006949 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6950 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6951 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006952
Zhou Sheng4351c642007-04-02 08:20:41 +00006953 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006954 if (AmtSum > TypeBits)
6955 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006956
6957 const IntegerType *Ty = cast<IntegerType>(I.getType());
6958
6959 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006960 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006961 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006962 ConstantInt::get(Ty, AmtSum));
6963 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6964 I.getOpcode() == Instruction::AShr) {
6965 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006966 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006967 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6968 I.getOpcode() == Instruction::LShr) {
6969 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6970 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006971 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006972 InsertNewInstBefore(Shift, I);
6973
Zhou Shenge9e03f62007-03-28 15:02:20 +00006974 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006975 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006976 }
6977
Chris Lattnerb87056f2007-02-05 00:57:54 +00006978 // Okay, if we get here, one shift must be left, and the other shift must be
6979 // right. See if the amounts are equal.
6980 if (ShiftAmt1 == ShiftAmt2) {
6981 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6982 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006983 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006984 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006985 }
6986 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6987 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006988 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006989 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006990 }
6991 // We can simplify ((X << C) >>s C) into a trunc + sext.
6992 // NOTE: we could do this for any C, but that would make 'unusual' integer
6993 // types. For now, just stick to ones well-supported by the code
6994 // generators.
6995 const Type *SExtType = 0;
6996 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006997 case 1 :
6998 case 8 :
6999 case 16 :
7000 case 32 :
7001 case 64 :
7002 case 128:
7003 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7004 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007005 default: break;
7006 }
7007 if (SExtType) {
7008 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7009 InsertNewInstBefore(NewTrunc, I);
7010 return new SExtInst(NewTrunc, Ty);
7011 }
7012 // Otherwise, we can't handle it yet.
7013 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007014 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007015
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007016 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007017 if (I.getOpcode() == Instruction::Shl) {
7018 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7019 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007020 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007021 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007022 InsertNewInstBefore(Shift, I);
7023
Reid Spencer55702aa2007-03-25 21:11:44 +00007024 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007025 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007026 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007027
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007028 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007029 if (I.getOpcode() == Instruction::LShr) {
7030 assert(ShiftOp->getOpcode() == Instruction::Shl);
7031 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007032 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007033 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007034
Reid Spencerd5e30f02007-03-26 17:18:58 +00007035 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007036 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007037 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007038
7039 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7040 } else {
7041 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007042 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007043
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007044 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007045 if (I.getOpcode() == Instruction::Shl) {
7046 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7047 ShiftOp->getOpcode() == Instruction::AShr);
7048 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007049 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007050 ConstantInt::get(Ty, ShiftDiff));
7051 InsertNewInstBefore(Shift, I);
7052
Reid Spencer55702aa2007-03-25 21:11:44 +00007053 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007054 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007055 }
7056
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007057 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007058 if (I.getOpcode() == Instruction::LShr) {
7059 assert(ShiftOp->getOpcode() == Instruction::Shl);
7060 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007061 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007062 InsertNewInstBefore(Shift, I);
7063
Reid Spencer68d27cf2007-03-26 23:45:51 +00007064 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007065 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007066 }
7067
7068 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007069 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007070 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007071 return 0;
7072}
7073
Chris Lattnera1be5662002-05-02 17:06:02 +00007074
Chris Lattnercfd65102005-10-29 04:36:15 +00007075/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7076/// expression. If so, decompose it, returning some value X, such that Val is
7077/// X*Scale+Offset.
7078///
7079static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007080 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007081 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007082 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007083 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007084 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007085 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007086 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7087 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7088 if (I->getOpcode() == Instruction::Shl) {
7089 // This is a value scaled by '1 << the shift amt'.
7090 Scale = 1U << RHS->getZExtValue();
7091 Offset = 0;
7092 return I->getOperand(0);
7093 } else if (I->getOpcode() == Instruction::Mul) {
7094 // This value is scaled by 'RHS'.
7095 Scale = RHS->getZExtValue();
7096 Offset = 0;
7097 return I->getOperand(0);
7098 } else if (I->getOpcode() == Instruction::Add) {
7099 // We have X+C. Check to see if we really have (X*C2)+C1,
7100 // where C1 is divisible by C2.
7101 unsigned SubScale;
7102 Value *SubVal =
7103 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7104 Offset += RHS->getZExtValue();
7105 Scale = SubScale;
7106 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007107 }
7108 }
7109 }
7110
7111 // Otherwise, we can't look past this.
7112 Scale = 1;
7113 Offset = 0;
7114 return Val;
7115}
7116
7117
Chris Lattnerb3f83972005-10-24 06:03:58 +00007118/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7119/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007120Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007121 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007122 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007123
Chris Lattnerb53c2382005-10-24 06:22:12 +00007124 // Remove any uses of AI that are dead.
7125 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007126
Chris Lattnerb53c2382005-10-24 06:22:12 +00007127 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7128 Instruction *User = cast<Instruction>(*UI++);
7129 if (isInstructionTriviallyDead(User)) {
7130 while (UI != E && *UI == User)
7131 ++UI; // If this instruction uses AI more than once, don't break UI.
7132
Chris Lattnerb53c2382005-10-24 06:22:12 +00007133 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007134 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007135 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007136 }
7137 }
7138
Chris Lattnerb3f83972005-10-24 06:03:58 +00007139 // Get the type really allocated and the type casted to.
7140 const Type *AllocElTy = AI.getAllocatedType();
7141 const Type *CastElTy = PTy->getElementType();
7142 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007143
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007144 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7145 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007146 if (CastElTyAlign < AllocElTyAlign) return 0;
7147
Chris Lattner39387a52005-10-24 06:35:18 +00007148 // If the allocation has multiple uses, only promote it if we are strictly
7149 // increasing the alignment of the resultant allocation. If we keep it the
7150 // same, we open the door to infinite loops of various kinds.
7151 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7152
Duncan Sands514ab342007-11-01 20:53:16 +00007153 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7154 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007155 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007156
Chris Lattner455fcc82005-10-29 03:19:53 +00007157 // See if we can satisfy the modulus by pulling a scale out of the array
7158 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007159 unsigned ArraySizeScale;
7160 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007161 Value *NumElements = // See if the array size is a decomposable linear expr.
7162 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7163
Chris Lattner455fcc82005-10-29 03:19:53 +00007164 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7165 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007166 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7167 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007168
Chris Lattner455fcc82005-10-29 03:19:53 +00007169 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7170 Value *Amt = 0;
7171 if (Scale == 1) {
7172 Amt = NumElements;
7173 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007174 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007175 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7176 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007177 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007178 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007179 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007180 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007181 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007182 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007183 }
7184
Jeff Cohen86796be2007-04-04 16:58:57 +00007185 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7186 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007187 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007188 Amt = InsertNewInstBefore(Tmp, AI);
7189 }
7190
Chris Lattnerb3f83972005-10-24 06:03:58 +00007191 AllocationInst *New;
7192 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007193 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007194 else
Chris Lattner6934a042007-02-11 01:23:03 +00007195 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007196 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007197 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007198
7199 // If the allocation has multiple uses, insert a cast and change all things
7200 // that used it to use the new cast. This will also hack on CI, but it will
7201 // die soon.
7202 if (!AI.hasOneUse()) {
7203 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007204 // New is the allocation instruction, pointer typed. AI is the original
7205 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7206 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007207 InsertNewInstBefore(NewCast, AI);
7208 AI.replaceAllUsesWith(NewCast);
7209 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007210 return ReplaceInstUsesWith(CI, New);
7211}
7212
Chris Lattner70074e02006-05-13 02:06:03 +00007213/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007214/// and return it as type Ty without inserting any new casts and without
7215/// changing the computed value. This is used by code that tries to decide
7216/// whether promoting or shrinking integer operations to wider or smaller types
7217/// will allow us to eliminate a truncate or extend.
7218///
7219/// This is a truncation operation if Ty is smaller than V->getType(), or an
7220/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00007221bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7222 unsigned CastOpc,
7223 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007224 // We can always evaluate constants in another type.
7225 if (isa<ConstantInt>(V))
7226 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007227
7228 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007229 if (!I) return false;
7230
7231 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007232
Chris Lattner951626b2007-08-02 06:11:14 +00007233 // If this is an extension or truncate, we can often eliminate it.
7234 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7235 // If this is a cast from the destination type, we can trivially eliminate
7236 // it, and this will remove a cast overall.
7237 if (I->getOperand(0)->getType() == Ty) {
7238 // If the first operand is itself a cast, and is eliminable, do not count
7239 // this as an eliminable cast. We would prefer to eliminate those two
7240 // casts first.
7241 if (!isa<CastInst>(I->getOperand(0)))
7242 ++NumCastsRemoved;
7243 return true;
7244 }
7245 }
7246
7247 // We can't extend or shrink something that has multiple uses: doing so would
7248 // require duplicating the instruction in general, which isn't profitable.
7249 if (!I->hasOneUse()) return false;
7250
Chris Lattner70074e02006-05-13 02:06:03 +00007251 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007252 case Instruction::Add:
7253 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00007254 case Instruction::And:
7255 case Instruction::Or:
7256 case Instruction::Xor:
7257 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007258 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7259 NumCastsRemoved) &&
7260 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7261 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007262
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007263 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007264 // A multiply can be truncated by truncating its operands.
7265 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7266 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7267 NumCastsRemoved) &&
7268 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7269 NumCastsRemoved);
7270
Chris Lattner46b96052006-11-29 07:18:39 +00007271 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007272 // If we are truncating the result of this SHL, and if it's a shift of a
7273 // constant amount, we can always perform a SHL in a smaller type.
7274 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007275 uint32_t BitWidth = Ty->getBitWidth();
7276 if (BitWidth < OrigTy->getBitWidth() &&
7277 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007278 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7279 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007280 }
7281 break;
7282 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007283 // If this is a truncate of a logical shr, we can truncate it to a smaller
7284 // lshr iff we know that the bits we would otherwise be shifting in are
7285 // already zeros.
7286 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007287 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7288 uint32_t BitWidth = Ty->getBitWidth();
7289 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007290 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007291 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7292 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007293 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7294 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007295 }
7296 }
Chris Lattner46b96052006-11-29 07:18:39 +00007297 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007298 case Instruction::ZExt:
7299 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007300 case Instruction::Trunc:
7301 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007302 // can safely replace it. Note that replacing it does not reduce the number
7303 // of casts in the input.
7304 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007305 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00007306
Reid Spencer3da59db2006-11-27 01:05:10 +00007307 break;
7308 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007309 // TODO: Can handle more cases here.
7310 break;
7311 }
7312
7313 return false;
7314}
7315
7316/// EvaluateInDifferentType - Given an expression that
7317/// CanEvaluateInDifferentType returns true for, actually insert the code to
7318/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007319Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007320 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007321 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007322 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007323
7324 // Otherwise, it must be an instruction.
7325 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007326 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007327 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007328 case Instruction::Add:
7329 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007330 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007331 case Instruction::And:
7332 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007333 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007334 case Instruction::AShr:
7335 case Instruction::LShr:
7336 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007337 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007338 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007339 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00007340 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00007341 break;
7342 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007343 case Instruction::Trunc:
7344 case Instruction::ZExt:
7345 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007346 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007347 // just return the source. There's no need to insert it because it is not
7348 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007349 if (I->getOperand(0)->getType() == Ty)
7350 return I->getOperand(0);
7351
Chris Lattner951626b2007-08-02 06:11:14 +00007352 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007353 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00007354 Ty, I->getName());
7355 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007356 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007357 // TODO: Can handle more cases here.
7358 assert(0 && "Unreachable!");
7359 break;
7360 }
7361
7362 return InsertNewInstBefore(Res, *I);
7363}
7364
Reid Spencer3da59db2006-11-27 01:05:10 +00007365/// @brief Implement the transforms common to all CastInst visitors.
7366Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007367 Value *Src = CI.getOperand(0);
7368
Dan Gohman23d9d272007-05-11 21:10:54 +00007369 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007370 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007371 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007372 if (Instruction::CastOps opc =
7373 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7374 // The first cast (CSrc) is eliminable so we need to fix up or replace
7375 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007376 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007377 }
7378 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007379
Reid Spencer3da59db2006-11-27 01:05:10 +00007380 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007381 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7382 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7383 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007384
7385 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007386 if (isa<PHINode>(Src))
7387 if (Instruction *NV = FoldOpIntoPhi(CI))
7388 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007389
Reid Spencer3da59db2006-11-27 01:05:10 +00007390 return 0;
7391}
7392
Chris Lattnerd3e28342007-04-27 17:44:50 +00007393/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7394Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7395 Value *Src = CI.getOperand(0);
7396
Chris Lattnerd3e28342007-04-27 17:44:50 +00007397 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007398 // If casting the result of a getelementptr instruction with no offset, turn
7399 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007400 if (GEP->hasAllZeroIndices()) {
7401 // Changing the cast operand is usually not a good idea but it is safe
7402 // here because the pointer operand is being replaced with another
7403 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007404 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007405 CI.setOperand(0, GEP->getOperand(0));
7406 return &CI;
7407 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007408
7409 // If the GEP has a single use, and the base pointer is a bitcast, and the
7410 // GEP computes a constant offset, see if we can convert these three
7411 // instructions into fewer. This typically happens with unions and other
7412 // non-type-safe code.
7413 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7414 if (GEP->hasAllConstantIndices()) {
7415 // We are guaranteed to get a constant from EmitGEPOffset.
7416 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7417 int64_t Offset = OffsetV->getSExtValue();
7418
7419 // Get the base pointer input of the bitcast, and the type it points to.
7420 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7421 const Type *GEPIdxTy =
7422 cast<PointerType>(OrigBase->getType())->getElementType();
7423 if (GEPIdxTy->isSized()) {
7424 SmallVector<Value*, 8> NewIndices;
7425
Chris Lattnerc42e2262007-05-05 01:59:31 +00007426 // Start with the index over the outer type. Note that the type size
7427 // might be zero (even if the offset isn't zero) if the indexed type
7428 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007429 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007430 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007431 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007432 FirstIdx = Offset/TySize;
7433 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007434
Chris Lattnerc42e2262007-05-05 01:59:31 +00007435 // Handle silly modulus not returning values values [0..TySize).
7436 if (Offset < 0) {
7437 --FirstIdx;
7438 Offset += TySize;
7439 assert(Offset >= 0);
7440 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007441 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007442 }
7443
7444 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007445
7446 // Index into the types. If we fail, set OrigBase to null.
7447 while (Offset) {
7448 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7449 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007450 if (Offset < (int64_t)SL->getSizeInBytes()) {
7451 unsigned Elt = SL->getElementContainingOffset(Offset);
7452 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007453
Chris Lattner6b6aef82007-05-15 00:16:00 +00007454 Offset -= SL->getElementOffset(Elt);
7455 GEPIdxTy = STy->getElementType(Elt);
7456 } else {
7457 // Otherwise, we can't index into this, bail out.
7458 Offset = 0;
7459 OrigBase = 0;
7460 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007461 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7462 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007463 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007464 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7465 Offset %= EltSize;
7466 } else {
7467 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7468 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007469 GEPIdxTy = STy->getElementType();
7470 } else {
7471 // Otherwise, we can't index into this, bail out.
7472 Offset = 0;
7473 OrigBase = 0;
7474 }
7475 }
7476 if (OrigBase) {
7477 // If we were able to index down into an element, create the GEP
7478 // and bitcast the result. This eliminates one bitcast, potentially
7479 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007480 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7481 NewIndices.begin(),
7482 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007483 InsertNewInstBefore(NGEP, CI);
7484 NGEP->takeName(GEP);
7485
Chris Lattner9bc14642007-04-28 00:57:34 +00007486 if (isa<BitCastInst>(CI))
7487 return new BitCastInst(NGEP, CI.getType());
7488 assert(isa<PtrToIntInst>(CI));
7489 return new PtrToIntInst(NGEP, CI.getType());
7490 }
7491 }
7492 }
7493 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007494 }
7495
7496 return commonCastTransforms(CI);
7497}
7498
7499
7500
Chris Lattnerc739cd62007-03-03 05:27:34 +00007501/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7502/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007503/// cases.
7504/// @brief Implement the transforms common to CastInst with integer operands
7505Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7506 if (Instruction *Result = commonCastTransforms(CI))
7507 return Result;
7508
7509 Value *Src = CI.getOperand(0);
7510 const Type *SrcTy = Src->getType();
7511 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007512 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7513 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007514
Reid Spencer3da59db2006-11-27 01:05:10 +00007515 // See if we can simplify any instructions used by the LHS whose sole
7516 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007517 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7518 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007519 KnownZero, KnownOne))
7520 return &CI;
7521
7522 // If the source isn't an instruction or has more than one use then we
7523 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007524 Instruction *SrcI = dyn_cast<Instruction>(Src);
7525 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007526 return 0;
7527
Chris Lattnerc739cd62007-03-03 05:27:34 +00007528 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007529 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007530 if (!isa<BitCastInst>(CI) &&
7531 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007532 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007533 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007534 // eliminates the cast, so it is always a win. If this is a zero-extension,
7535 // we need to do an AND to maintain the clear top-part of the computation,
7536 // so we require that the input have eliminated at least one cast. If this
7537 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007538 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007539 bool DoXForm;
7540 switch (CI.getOpcode()) {
7541 default:
7542 // All the others use floating point so we shouldn't actually
7543 // get here because of the check above.
7544 assert(0 && "Unknown cast type");
7545 case Instruction::Trunc:
7546 DoXForm = true;
7547 break;
7548 case Instruction::ZExt:
7549 DoXForm = NumCastsRemoved >= 1;
7550 break;
7551 case Instruction::SExt:
7552 DoXForm = NumCastsRemoved >= 2;
7553 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007554 }
7555
7556 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007557 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7558 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007559 assert(Res->getType() == DestTy);
7560 switch (CI.getOpcode()) {
7561 default: assert(0 && "Unknown cast type!");
7562 case Instruction::Trunc:
7563 case Instruction::BitCast:
7564 // Just replace this cast with the result.
7565 return ReplaceInstUsesWith(CI, Res);
7566 case Instruction::ZExt: {
7567 // We need to emit an AND to clear the high bits.
7568 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007569 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7570 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007571 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007572 }
7573 case Instruction::SExt:
7574 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007575 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007576 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7577 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007578 }
7579 }
7580 }
7581
7582 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7583 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7584
7585 switch (SrcI->getOpcode()) {
7586 case Instruction::Add:
7587 case Instruction::Mul:
7588 case Instruction::And:
7589 case Instruction::Or:
7590 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007591 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007592 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7593 // Don't insert two casts if they cannot be eliminated. We allow
7594 // two casts to be inserted if the sizes are the same. This could
7595 // only be converting signedness, which is a noop.
7596 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007597 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7598 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007599 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007600 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7601 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007602 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007603 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007604 }
7605 }
7606
7607 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7608 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7609 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007610 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007611 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007612 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007613 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007614 }
7615 break;
7616 case Instruction::SDiv:
7617 case Instruction::UDiv:
7618 case Instruction::SRem:
7619 case Instruction::URem:
7620 // If we are just changing the sign, rewrite.
7621 if (DestBitSize == SrcBitSize) {
7622 // Don't insert two casts if they cannot be eliminated. We allow
7623 // two casts to be inserted if the sizes are the same. This could
7624 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007625 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7626 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007627 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7628 Op0, DestTy, SrcI);
7629 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7630 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007631 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007632 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7633 }
7634 }
7635 break;
7636
7637 case Instruction::Shl:
7638 // Allow changing the sign of the source operand. Do not allow
7639 // changing the size of the shift, UNLESS the shift amount is a
7640 // constant. We must not change variable sized shifts to a smaller
7641 // size, because it is undefined to shift more bits out than exist
7642 // in the value.
7643 if (DestBitSize == SrcBitSize ||
7644 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007645 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7646 Instruction::BitCast : Instruction::Trunc);
7647 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007648 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007649 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007650 }
7651 break;
7652 case Instruction::AShr:
7653 // If this is a signed shr, and if all bits shifted in are about to be
7654 // truncated off, turn it into an unsigned shr to allow greater
7655 // simplifications.
7656 if (DestBitSize < SrcBitSize &&
7657 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007658 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007659 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7660 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007661 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007662 }
7663 }
7664 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007665 }
7666 return 0;
7667}
7668
Chris Lattner8a9f5712007-04-11 06:57:46 +00007669Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007670 if (Instruction *Result = commonIntCastTransforms(CI))
7671 return Result;
7672
7673 Value *Src = CI.getOperand(0);
7674 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007675 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7676 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007677
7678 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7679 switch (SrcI->getOpcode()) {
7680 default: break;
7681 case Instruction::LShr:
7682 // We can shrink lshr to something smaller if we know the bits shifted in
7683 // are already zeros.
7684 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007685 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007686
7687 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007688 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007689 Value* SrcIOp0 = SrcI->getOperand(0);
7690 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007691 if (ShAmt >= DestBitWidth) // All zeros.
7692 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7693
7694 // Okay, we can shrink this. Truncate the input, then return a new
7695 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007696 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7697 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7698 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007699 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007700 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007701 } else { // This is a variable shr.
7702
7703 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7704 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7705 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007706 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007707 Value *One = ConstantInt::get(SrcI->getType(), 1);
7708
Reid Spencer832254e2007-02-02 02:16:23 +00007709 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007710 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007711 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007712 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007713 SrcI->getOperand(0),
7714 "tmp"), CI);
7715 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007716 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007717 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007718 }
7719 break;
7720 }
7721 }
7722
7723 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007724}
7725
Evan Chengb98a10e2008-03-24 00:21:34 +00007726/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7727/// in order to eliminate the icmp.
7728Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7729 bool DoXform) {
7730 // If we are just checking for a icmp eq of a single bit and zext'ing it
7731 // to an integer, then shift the bit to the appropriate place and then
7732 // cast to integer to avoid the comparison.
7733 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7734 const APInt &Op1CV = Op1C->getValue();
7735
7736 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7737 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7738 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7739 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7740 if (!DoXform) return ICI;
7741
7742 Value *In = ICI->getOperand(0);
7743 Value *Sh = ConstantInt::get(In->getType(),
7744 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007745 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00007746 In->getName()+".lobit"),
7747 CI);
7748 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007749 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00007750 false/*ZExt*/, "tmp", &CI);
7751
7752 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7753 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007754 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00007755 In->getName()+".not"),
7756 CI);
7757 }
7758
7759 return ReplaceInstUsesWith(CI, In);
7760 }
7761
7762
7763
7764 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7765 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7766 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7767 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7768 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7769 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7770 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7771 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7772 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7773 // This only works for EQ and NE
7774 ICI->isEquality()) {
7775 // If Op1C some other power of two, convert:
7776 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7777 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7778 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7779 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7780
7781 APInt KnownZeroMask(~KnownZero);
7782 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7783 if (!DoXform) return ICI;
7784
7785 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7786 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7787 // (X&4) == 2 --> false
7788 // (X&4) != 2 --> true
7789 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7790 Res = ConstantExpr::getZExt(Res, CI.getType());
7791 return ReplaceInstUsesWith(CI, Res);
7792 }
7793
7794 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7795 Value *In = ICI->getOperand(0);
7796 if (ShiftAmt) {
7797 // Perform a logical shr by shiftamt.
7798 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007799 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00007800 ConstantInt::get(In->getType(), ShiftAmt),
7801 In->getName()+".lobit"), CI);
7802 }
7803
7804 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7805 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007806 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007807 InsertNewInstBefore(cast<Instruction>(In), CI);
7808 }
7809
7810 if (CI.getType() == In->getType())
7811 return ReplaceInstUsesWith(CI, In);
7812 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007813 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00007814 }
7815 }
7816 }
7817
7818 return 0;
7819}
7820
Chris Lattner8a9f5712007-04-11 06:57:46 +00007821Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007822 // If one of the common conversion will work ..
7823 if (Instruction *Result = commonIntCastTransforms(CI))
7824 return Result;
7825
7826 Value *Src = CI.getOperand(0);
7827
7828 // If this is a cast of a cast
7829 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007830 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7831 // types and if the sizes are just right we can convert this into a logical
7832 // 'and' which will be much cheaper than the pair of casts.
7833 if (isa<TruncInst>(CSrc)) {
7834 // Get the sizes of the types involved
7835 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007836 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7837 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7838 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007839 // If we're actually extending zero bits and the trunc is a no-op
7840 if (MidSize < DstSize && SrcSize == DstSize) {
7841 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007842 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007843 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007844 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007845 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00007846 // Unfortunately, if the type changed, we need to cast it back.
7847 if (And->getType() != CI.getType()) {
7848 And->setName(CSrc->getName()+".mask");
7849 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007850 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007851 }
7852 return And;
7853 }
7854 }
7855 }
7856
Evan Chengb98a10e2008-03-24 00:21:34 +00007857 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7858 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007859
Evan Chengb98a10e2008-03-24 00:21:34 +00007860 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7861 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7862 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7863 // of the (zext icmp) will be transformed.
7864 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7865 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7866 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7867 (transformZExtICmp(LHS, CI, false) ||
7868 transformZExtICmp(RHS, CI, false))) {
7869 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7870 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007871 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007872 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007873 }
7874
Reid Spencer3da59db2006-11-27 01:05:10 +00007875 return 0;
7876}
7877
Chris Lattner8a9f5712007-04-11 06:57:46 +00007878Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007879 if (Instruction *I = commonIntCastTransforms(CI))
7880 return I;
7881
Chris Lattner8a9f5712007-04-11 06:57:46 +00007882 Value *Src = CI.getOperand(0);
7883
7884 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7885 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7886 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7887 // If we are just checking for a icmp eq of a single bit and zext'ing it
7888 // to an integer, then shift the bit to the appropriate place and then
7889 // cast to integer to avoid the comparison.
7890 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7891 const APInt &Op1CV = Op1C->getValue();
7892
7893 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7894 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7895 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7896 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7897 Value *In = ICI->getOperand(0);
7898 Value *Sh = ConstantInt::get(In->getType(),
7899 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007900 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007901 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007902 CI);
7903 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007904 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007905 true/*SExt*/, "tmp", &CI);
7906
7907 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007908 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00007909 In->getName()+".not"), CI);
7910
7911 return ReplaceInstUsesWith(CI, In);
7912 }
7913 }
7914 }
7915
Chris Lattnerba417832007-04-11 06:12:58 +00007916 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007917}
7918
Chris Lattnerb7530652008-01-27 05:29:54 +00007919/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7920/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007921static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007922 APFloat F = CFP->getValueAPF();
7923 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007924 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007925 return 0;
7926}
7927
7928/// LookThroughFPExtensions - If this is an fp extension instruction, look
7929/// through it until we get the source value.
7930static Value *LookThroughFPExtensions(Value *V) {
7931 if (Instruction *I = dyn_cast<Instruction>(V))
7932 if (I->getOpcode() == Instruction::FPExt)
7933 return LookThroughFPExtensions(I->getOperand(0));
7934
7935 // If this value is a constant, return the constant in the smallest FP type
7936 // that can accurately represent it. This allows us to turn
7937 // (float)((double)X+2.0) into x+2.0f.
7938 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7939 if (CFP->getType() == Type::PPC_FP128Ty)
7940 return V; // No constant folding of this.
7941 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007942 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007943 return V;
7944 if (CFP->getType() == Type::DoubleTy)
7945 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007946 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007947 return V;
7948 // Don't try to shrink to various long double types.
7949 }
7950
7951 return V;
7952}
7953
7954Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7955 if (Instruction *I = commonCastTransforms(CI))
7956 return I;
7957
7958 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7959 // smaller than the destination type, we can eliminate the truncate by doing
7960 // the add as the smaller type. This applies to add/sub/mul/div as well as
7961 // many builtins (sqrt, etc).
7962 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7963 if (OpI && OpI->hasOneUse()) {
7964 switch (OpI->getOpcode()) {
7965 default: break;
7966 case Instruction::Add:
7967 case Instruction::Sub:
7968 case Instruction::Mul:
7969 case Instruction::FDiv:
7970 case Instruction::FRem:
7971 const Type *SrcTy = OpI->getType();
7972 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7973 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7974 if (LHSTrunc->getType() != SrcTy &&
7975 RHSTrunc->getType() != SrcTy) {
7976 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7977 // If the source types were both smaller than the destination type of
7978 // the cast, do this xform.
7979 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7980 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7981 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7982 CI.getType(), CI);
7983 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7984 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007985 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00007986 }
7987 }
7988 break;
7989 }
7990 }
7991 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007992}
7993
7994Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7995 return commonCastTransforms(CI);
7996}
7997
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007998Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7999 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
8000 // mantissa to accurately represent all values of X. For example, do not
8001 // do this with i64->float->i64.
8002 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8003 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8004 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8005 GetFPMantissaWidth(SrcI->getType()))
8006 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8007
8008 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008009}
8010
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008011Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8012 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
8013 // mantissa to accurately represent all values of X. For example, do not
8014 // do this with i64->float->i64.
8015 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8016 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8017 (int)FI.getType()->getPrimitiveSizeInBits() <=
8018 GetFPMantissaWidth(SrcI->getType()))
8019 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8020
8021 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008022}
8023
8024Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8025 return commonCastTransforms(CI);
8026}
8027
8028Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8029 return commonCastTransforms(CI);
8030}
8031
8032Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008033 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008034}
8035
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008036Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8037 if (Instruction *I = commonCastTransforms(CI))
8038 return I;
8039
8040 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8041 if (!DestPointee->isSized()) return 0;
8042
8043 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8044 ConstantInt *Cst;
8045 Value *X;
8046 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8047 m_ConstantInt(Cst)))) {
8048 // If the source and destination operands have the same type, see if this
8049 // is a single-index GEP.
8050 if (X->getType() == CI.getType()) {
8051 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00008052 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008053
8054 // Convert the constant to intptr type.
8055 APInt Offset = Cst->getValue();
8056 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8057
8058 // If Offset is evenly divisible by Size, we can do this xform.
8059 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8060 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008061 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008062 }
8063 }
8064 // TODO: Could handle other cases, e.g. where add is indexing into field of
8065 // struct etc.
8066 } else if (CI.getOperand(0)->hasOneUse() &&
8067 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8068 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8069 // "inttoptr+GEP" instead of "add+intptr".
8070
8071 // Get the size of the pointee type.
8072 uint64_t Size = TD->getABITypeSize(DestPointee);
8073
8074 // Convert the constant to intptr type.
8075 APInt Offset = Cst->getValue();
8076 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8077
8078 // If Offset is evenly divisible by Size, we can do this xform.
8079 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8080 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8081
8082 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8083 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008084 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008085 }
8086 }
8087 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008088}
8089
Chris Lattnerd3e28342007-04-27 17:44:50 +00008090Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008091 // If the operands are integer typed then apply the integer transforms,
8092 // otherwise just apply the common ones.
8093 Value *Src = CI.getOperand(0);
8094 const Type *SrcTy = Src->getType();
8095 const Type *DestTy = CI.getType();
8096
Chris Lattner42a75512007-01-15 02:27:26 +00008097 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008098 if (Instruction *Result = commonIntCastTransforms(CI))
8099 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008100 } else if (isa<PointerType>(SrcTy)) {
8101 if (Instruction *I = commonPointerCastTransforms(CI))
8102 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008103 } else {
8104 if (Instruction *Result = commonCastTransforms(CI))
8105 return Result;
8106 }
8107
8108
8109 // Get rid of casts from one type to the same type. These are useless and can
8110 // be replaced by the operand.
8111 if (DestTy == Src->getType())
8112 return ReplaceInstUsesWith(CI, Src);
8113
Reid Spencer3da59db2006-11-27 01:05:10 +00008114 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008115 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8116 const Type *DstElTy = DstPTy->getElementType();
8117 const Type *SrcElTy = SrcPTy->getElementType();
8118
Nate Begeman83ad90a2008-03-31 00:22:16 +00008119 // If the address spaces don't match, don't eliminate the bitcast, which is
8120 // required for changing types.
8121 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8122 return 0;
8123
Chris Lattnerd3e28342007-04-27 17:44:50 +00008124 // If we are casting a malloc or alloca to a pointer to a type of the same
8125 // size, rewrite the allocation instruction to allocate the "right" type.
8126 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8127 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8128 return V;
8129
Chris Lattnerd717c182007-05-05 22:32:24 +00008130 // If the source and destination are pointers, and this cast is equivalent
8131 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008132 // This can enhance SROA and other transforms that want type-safe pointers.
8133 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8134 unsigned NumZeros = 0;
8135 while (SrcElTy != DstElTy &&
8136 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8137 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8138 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8139 ++NumZeros;
8140 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008141
Chris Lattnerd3e28342007-04-27 17:44:50 +00008142 // If we found a path from the src to dest, create the getelementptr now.
8143 if (SrcElTy == DstElTy) {
8144 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008145 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8146 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008147 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008148 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008149
Reid Spencer3da59db2006-11-27 01:05:10 +00008150 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8151 if (SVI->hasOneUse()) {
8152 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8153 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008154 if (isa<VectorType>(DestTy) &&
8155 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00008156 SVI->getType()->getNumElements()) {
8157 CastInst *Tmp;
8158 // If either of the operands is a cast from CI.getType(), then
8159 // evaluating the shuffle in the casted destination's type will allow
8160 // us to eliminate at least one cast.
8161 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8162 Tmp->getOperand(0)->getType() == DestTy) ||
8163 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8164 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008165 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8166 SVI->getOperand(0), DestTy, &CI);
8167 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8168 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008169 // Return a new shuffle vector. Use the same element ID's, as we
8170 // know the vector types match #elts.
8171 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008172 }
8173 }
8174 }
8175 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008176 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008177}
8178
Chris Lattnere576b912004-04-09 23:46:01 +00008179/// GetSelectFoldableOperands - We want to turn code that looks like this:
8180/// %C = or %A, %B
8181/// %D = select %cond, %C, %A
8182/// into:
8183/// %C = select %cond, %B, 0
8184/// %D = or %A, %C
8185///
8186/// Assuming that the specified instruction is an operand to the select, return
8187/// a bitmask indicating which operands of this instruction are foldable if they
8188/// equal the other incoming value of the select.
8189///
8190static unsigned GetSelectFoldableOperands(Instruction *I) {
8191 switch (I->getOpcode()) {
8192 case Instruction::Add:
8193 case Instruction::Mul:
8194 case Instruction::And:
8195 case Instruction::Or:
8196 case Instruction::Xor:
8197 return 3; // Can fold through either operand.
8198 case Instruction::Sub: // Can only fold on the amount subtracted.
8199 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008200 case Instruction::LShr:
8201 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008202 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008203 default:
8204 return 0; // Cannot fold
8205 }
8206}
8207
8208/// GetSelectFoldableConstant - For the same transformation as the previous
8209/// function, return the identity constant that goes into the select.
8210static Constant *GetSelectFoldableConstant(Instruction *I) {
8211 switch (I->getOpcode()) {
8212 default: assert(0 && "This cannot happen!"); abort();
8213 case Instruction::Add:
8214 case Instruction::Sub:
8215 case Instruction::Or:
8216 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008217 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008218 case Instruction::LShr:
8219 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008220 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008221 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008222 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008223 case Instruction::Mul:
8224 return ConstantInt::get(I->getType(), 1);
8225 }
8226}
8227
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008228/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8229/// have the same opcode and only one use each. Try to simplify this.
8230Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8231 Instruction *FI) {
8232 if (TI->getNumOperands() == 1) {
8233 // If this is a non-volatile load or a cast from the same type,
8234 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008235 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008236 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8237 return 0;
8238 } else {
8239 return 0; // unknown unary op.
8240 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008241
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008242 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008243 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8244 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008245 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008246 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008247 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008248 }
8249
Reid Spencer832254e2007-02-02 02:16:23 +00008250 // Only handle binary operators here.
8251 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008252 return 0;
8253
8254 // Figure out if the operations have any operands in common.
8255 Value *MatchOp, *OtherOpT, *OtherOpF;
8256 bool MatchIsOpZero;
8257 if (TI->getOperand(0) == FI->getOperand(0)) {
8258 MatchOp = TI->getOperand(0);
8259 OtherOpT = TI->getOperand(1);
8260 OtherOpF = FI->getOperand(1);
8261 MatchIsOpZero = true;
8262 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8263 MatchOp = TI->getOperand(1);
8264 OtherOpT = TI->getOperand(0);
8265 OtherOpF = FI->getOperand(0);
8266 MatchIsOpZero = false;
8267 } else if (!TI->isCommutative()) {
8268 return 0;
8269 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8270 MatchOp = TI->getOperand(0);
8271 OtherOpT = TI->getOperand(1);
8272 OtherOpF = FI->getOperand(0);
8273 MatchIsOpZero = true;
8274 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8275 MatchOp = TI->getOperand(1);
8276 OtherOpT = TI->getOperand(0);
8277 OtherOpF = FI->getOperand(1);
8278 MatchIsOpZero = true;
8279 } else {
8280 return 0;
8281 }
8282
8283 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008284 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8285 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008286 InsertNewInstBefore(NewSI, SI);
8287
8288 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8289 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008290 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008291 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008292 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008293 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008294 assert(0 && "Shouldn't get here");
8295 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008296}
8297
Chris Lattner3d69f462004-03-12 05:52:32 +00008298Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008299 Value *CondVal = SI.getCondition();
8300 Value *TrueVal = SI.getTrueValue();
8301 Value *FalseVal = SI.getFalseValue();
8302
8303 // select true, X, Y -> X
8304 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008305 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008306 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008307
8308 // select C, X, X -> X
8309 if (TrueVal == FalseVal)
8310 return ReplaceInstUsesWith(SI, TrueVal);
8311
Chris Lattnere87597f2004-10-16 18:11:37 +00008312 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8313 return ReplaceInstUsesWith(SI, FalseVal);
8314 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8315 return ReplaceInstUsesWith(SI, TrueVal);
8316 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8317 if (isa<Constant>(TrueVal))
8318 return ReplaceInstUsesWith(SI, TrueVal);
8319 else
8320 return ReplaceInstUsesWith(SI, FalseVal);
8321 }
8322
Reid Spencer4fe16d62007-01-11 18:21:29 +00008323 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008324 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008325 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008326 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008327 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008328 } else {
8329 // Change: A = select B, false, C --> A = and !B, C
8330 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008331 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008332 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008333 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008334 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008335 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008336 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008337 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008338 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008339 } else {
8340 // Change: A = select B, C, true --> A = or !B, C
8341 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008342 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008343 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008344 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008345 }
8346 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008347
8348 // select a, b, a -> a&b
8349 // select a, a, b -> a|b
8350 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008351 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008352 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008353 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008354 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008355
Chris Lattner2eefe512004-04-09 19:05:30 +00008356 // Selecting between two integer constants?
8357 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8358 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008359 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008360 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008361 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008362 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008363 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008364 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008365 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008366 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008367 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008368 }
Chris Lattnerba417832007-04-11 06:12:58 +00008369
8370 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008371
Reid Spencere4d87aa2006-12-23 06:05:41 +00008372 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008373
Reid Spencere4d87aa2006-12-23 06:05:41 +00008374 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008375 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008376 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008377 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008378 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008379 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008380 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008381 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008382 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008383 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008384 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008385 InsertNewInstBefore(SRA, SI);
8386
Reid Spencer3da59db2006-11-27 01:05:10 +00008387 // Finally, convert to the type of the select RHS. We figure out
8388 // if this requires a SExt, Trunc or BitCast based on the sizes.
8389 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008390 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8391 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008392 if (SRASize < SISize)
8393 opc = Instruction::SExt;
8394 else if (SRASize > SISize)
8395 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008396 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008397 }
8398 }
8399
8400
8401 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008402 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008403 // non-constant value, eliminate this whole mess. This corresponds to
8404 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008405 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008406 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008407 cast<Constant>(IC->getOperand(1))->isNullValue())
8408 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8409 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008410 isa<ConstantInt>(ICA->getOperand(1)) &&
8411 (ICA->getOperand(1) == TrueValC ||
8412 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008413 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8414 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008415 // know whether we have a icmp_ne or icmp_eq and whether the
8416 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008417 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008418 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008419 Value *V = ICA;
8420 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008421 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008422 Instruction::Xor, V, ICA->getOperand(1)), SI);
8423 return ReplaceInstUsesWith(SI, V);
8424 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008425 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008426 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008427
8428 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008429 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8430 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008431 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008432 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8433 // This is not safe in general for floating point:
8434 // consider X== -0, Y== +0.
8435 // It becomes safe if either operand is a nonzero constant.
8436 ConstantFP *CFPt, *CFPf;
8437 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8438 !CFPt->getValueAPF().isZero()) ||
8439 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8440 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008441 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008442 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008443 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008444 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008445 return ReplaceInstUsesWith(SI, TrueVal);
8446 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8447
Reid Spencere4d87aa2006-12-23 06:05:41 +00008448 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008449 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008450 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8451 // This is not safe in general for floating point:
8452 // consider X== -0, Y== +0.
8453 // It becomes safe if either operand is a nonzero constant.
8454 ConstantFP *CFPt, *CFPf;
8455 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8456 !CFPt->getValueAPF().isZero()) ||
8457 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8458 !CFPf->getValueAPF().isZero()))
8459 return ReplaceInstUsesWith(SI, FalseVal);
8460 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008461 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008462 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8463 return ReplaceInstUsesWith(SI, TrueVal);
8464 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8465 }
8466 }
8467
8468 // See if we are selecting two values based on a comparison of the two values.
8469 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8470 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8471 // Transform (X == Y) ? X : Y -> Y
8472 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8473 return ReplaceInstUsesWith(SI, FalseVal);
8474 // Transform (X != Y) ? X : Y -> X
8475 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8476 return ReplaceInstUsesWith(SI, TrueVal);
8477 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8478
8479 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8480 // Transform (X == Y) ? Y : X -> X
8481 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8482 return ReplaceInstUsesWith(SI, FalseVal);
8483 // Transform (X != Y) ? Y : X -> Y
8484 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008485 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008486 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8487 }
8488 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008489
Chris Lattner87875da2005-01-13 22:52:24 +00008490 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8491 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8492 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008493 Instruction *AddOp = 0, *SubOp = 0;
8494
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008495 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8496 if (TI->getOpcode() == FI->getOpcode())
8497 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8498 return IV;
8499
8500 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8501 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008502 if (TI->getOpcode() == Instruction::Sub &&
8503 FI->getOpcode() == Instruction::Add) {
8504 AddOp = FI; SubOp = TI;
8505 } else if (FI->getOpcode() == Instruction::Sub &&
8506 TI->getOpcode() == Instruction::Add) {
8507 AddOp = TI; SubOp = FI;
8508 }
8509
8510 if (AddOp) {
8511 Value *OtherAddOp = 0;
8512 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8513 OtherAddOp = AddOp->getOperand(1);
8514 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8515 OtherAddOp = AddOp->getOperand(0);
8516 }
8517
8518 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008519 // So at this point we know we have (Y -> OtherAddOp):
8520 // select C, (add X, Y), (sub X, Z)
8521 Value *NegVal; // Compute -Z
8522 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8523 NegVal = ConstantExpr::getNeg(C);
8524 } else {
8525 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008526 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008527 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008528
8529 Value *NewTrueOp = OtherAddOp;
8530 Value *NewFalseOp = NegVal;
8531 if (AddOp != TI)
8532 std::swap(NewTrueOp, NewFalseOp);
8533 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008534 SelectInst::Create(CondVal, NewTrueOp,
8535 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008536
8537 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008538 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008539 }
8540 }
8541 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008542
Chris Lattnere576b912004-04-09 23:46:01 +00008543 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008544 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008545 // See the comment above GetSelectFoldableOperands for a description of the
8546 // transformation we are doing here.
8547 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8548 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8549 !isa<Constant>(FalseVal))
8550 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8551 unsigned OpToFold = 0;
8552 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8553 OpToFold = 1;
8554 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8555 OpToFold = 2;
8556 }
8557
8558 if (OpToFold) {
8559 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008560 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008561 SelectInst::Create(SI.getCondition(),
8562 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008563 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008564 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008565 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008566 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008567 else {
8568 assert(0 && "Unknown instruction!!");
8569 }
8570 }
8571 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008572
Chris Lattnere576b912004-04-09 23:46:01 +00008573 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8574 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8575 !isa<Constant>(TrueVal))
8576 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8577 unsigned OpToFold = 0;
8578 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8579 OpToFold = 1;
8580 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8581 OpToFold = 2;
8582 }
8583
8584 if (OpToFold) {
8585 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008586 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008587 SelectInst::Create(SI.getCondition(), C,
8588 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008589 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008590 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008591 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008592 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008593 else
Chris Lattnere576b912004-04-09 23:46:01 +00008594 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008595 }
8596 }
8597 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008598
8599 if (BinaryOperator::isNot(CondVal)) {
8600 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8601 SI.setOperand(1, FalseVal);
8602 SI.setOperand(2, TrueVal);
8603 return &SI;
8604 }
8605
Chris Lattner3d69f462004-03-12 05:52:32 +00008606 return 0;
8607}
8608
Dan Gohmaneee962e2008-04-10 18:43:06 +00008609/// EnforceKnownAlignment - If the specified pointer points to an object that
8610/// we control, modify the object's alignment to PrefAlign. This isn't
8611/// often possible though. If alignment is important, a more reliable approach
8612/// is to simply align all global variables and allocation instructions to
8613/// their preferred alignment from the beginning.
8614///
8615static unsigned EnforceKnownAlignment(Value *V,
8616 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008617
Dan Gohmaneee962e2008-04-10 18:43:06 +00008618 User *U = dyn_cast<User>(V);
8619 if (!U) return Align;
8620
8621 switch (getOpcode(U)) {
8622 default: break;
8623 case Instruction::BitCast:
8624 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8625 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008626 // If all indexes are zero, it is just the alignment of the base pointer.
8627 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008628 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8629 if (!isa<Constant>(U->getOperand(i)) ||
8630 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008631 AllZeroOperands = false;
8632 break;
8633 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008634
8635 if (AllZeroOperands) {
8636 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008637 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008638 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008639 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008640 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008641 }
8642
8643 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8644 // If there is a large requested alignment and we can, bump up the alignment
8645 // of the global.
8646 if (!GV->isDeclaration()) {
8647 GV->setAlignment(PrefAlign);
8648 Align = PrefAlign;
8649 }
8650 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8651 // If there is a requested alignment and if this is an alloca, round up. We
8652 // don't do this for malloc, because some systems can't respect the request.
8653 if (isa<AllocaInst>(AI)) {
8654 AI->setAlignment(PrefAlign);
8655 Align = PrefAlign;
8656 }
8657 }
8658
8659 return Align;
8660}
8661
8662/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8663/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8664/// and it is more than the alignment of the ultimate object, see if we can
8665/// increase the alignment of the ultimate object, making this check succeed.
8666unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8667 unsigned PrefAlign) {
8668 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8669 sizeof(PrefAlign) * CHAR_BIT;
8670 APInt Mask = APInt::getAllOnesValue(BitWidth);
8671 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8672 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8673 unsigned TrailZ = KnownZero.countTrailingOnes();
8674 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8675
8676 if (PrefAlign > Align)
8677 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8678
8679 // We don't need to make any adjustment.
8680 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008681}
8682
Chris Lattnerf497b022008-01-13 23:50:23 +00008683Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008684 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8685 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008686 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8687 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8688
8689 if (CopyAlign < MinAlign) {
8690 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8691 return MI;
8692 }
8693
8694 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8695 // load/store.
8696 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8697 if (MemOpLength == 0) return 0;
8698
Chris Lattner37ac6082008-01-14 00:28:35 +00008699 // Source and destination pointer types are always "i8*" for intrinsic. See
8700 // if the size is something we can handle with a single primitive load/store.
8701 // A single load+store correctly handles overlapping memory in the memmove
8702 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008703 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008704 if (Size == 0) return MI; // Delete this mem transfer.
8705
8706 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008707 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008708
Chris Lattner37ac6082008-01-14 00:28:35 +00008709 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008710 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008711
8712 // Memcpy forces the use of i8* for the source and destination. That means
8713 // that if you're using memcpy to move one double around, you'll get a cast
8714 // from double* to i8*. We'd much rather use a double load+store rather than
8715 // an i64 load+store, here because this improves the odds that the source or
8716 // dest address will be promotable. See if we can find a better type than the
8717 // integer datatype.
8718 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8719 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8720 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8721 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8722 // down through these levels if so.
8723 while (!SrcETy->isFirstClassType()) {
8724 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8725 if (STy->getNumElements() == 1)
8726 SrcETy = STy->getElementType(0);
8727 else
8728 break;
8729 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8730 if (ATy->getNumElements() == 1)
8731 SrcETy = ATy->getElementType();
8732 else
8733 break;
8734 } else
8735 break;
8736 }
8737
8738 if (SrcETy->isFirstClassType())
8739 NewPtrTy = PointerType::getUnqual(SrcETy);
8740 }
8741 }
8742
8743
Chris Lattnerf497b022008-01-13 23:50:23 +00008744 // If the memcpy/memmove provides better alignment info than we can
8745 // infer, use it.
8746 SrcAlign = std::max(SrcAlign, CopyAlign);
8747 DstAlign = std::max(DstAlign, CopyAlign);
8748
8749 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8750 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008751 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8752 InsertNewInstBefore(L, *MI);
8753 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8754
8755 // Set the size of the copy to 0, it will be deleted on the next iteration.
8756 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8757 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008758}
Chris Lattner3d69f462004-03-12 05:52:32 +00008759
Chris Lattner69ea9d22008-04-30 06:39:11 +00008760Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8761 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8762 if (MI->getAlignment()->getZExtValue() < Alignment) {
8763 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8764 return MI;
8765 }
8766
8767 // Extract the length and alignment and fill if they are constant.
8768 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8769 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8770 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8771 return 0;
8772 uint64_t Len = LenC->getZExtValue();
8773 Alignment = MI->getAlignment()->getZExtValue();
8774
8775 // If the length is zero, this is a no-op
8776 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8777
8778 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8779 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8780 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8781
8782 Value *Dest = MI->getDest();
8783 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8784
8785 // Alignment 0 is identity for alignment 1 for memset, but not store.
8786 if (Alignment == 0) Alignment = 1;
8787
8788 // Extract the fill value and store.
8789 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8790 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8791 Alignment), *MI);
8792
8793 // Set the size of the copy to 0, it will be deleted on the next iteration.
8794 MI->setLength(Constant::getNullValue(LenC->getType()));
8795 return MI;
8796 }
8797
8798 return 0;
8799}
8800
8801
Chris Lattner8b0ea312006-01-13 20:11:04 +00008802/// visitCallInst - CallInst simplification. This mostly only handles folding
8803/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8804/// the heavy lifting.
8805///
Chris Lattner9fe38862003-06-19 17:00:31 +00008806Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008807 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8808 if (!II) return visitCallSite(&CI);
8809
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008810 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8811 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008812 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008813 bool Changed = false;
8814
8815 // memmove/cpy/set of zero bytes is a noop.
8816 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8817 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8818
Chris Lattner35b9e482004-10-12 04:52:52 +00008819 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008820 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008821 // Replace the instruction with just byte operations. We would
8822 // transform other cases to loads/stores, but we don't know if
8823 // alignment is sufficient.
8824 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008825 }
8826
Chris Lattner35b9e482004-10-12 04:52:52 +00008827 // If we have a memmove and the source operation is a constant global,
8828 // then the source and dest pointers can't alias, so we can change this
8829 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008830 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008831 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8832 if (GVSrc->isConstant()) {
8833 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008834 Intrinsic::ID MemCpyID;
8835 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8836 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008837 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008838 MemCpyID = Intrinsic::memcpy_i64;
8839 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008840 Changed = true;
8841 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008842 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008843
Chris Lattner95a959d2006-03-06 20:18:44 +00008844 // If we can determine a pointer alignment that is bigger than currently
8845 // set, update the alignment.
8846 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008847 if (Instruction *I = SimplifyMemTransfer(MI))
8848 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008849 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8850 if (Instruction *I = SimplifyMemSet(MSI))
8851 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008852 }
8853
Chris Lattner8b0ea312006-01-13 20:11:04 +00008854 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008855 } else {
8856 switch (II->getIntrinsicID()) {
8857 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008858 case Intrinsic::ppc_altivec_lvx:
8859 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008860 case Intrinsic::x86_sse_loadu_ps:
8861 case Intrinsic::x86_sse2_loadu_pd:
8862 case Intrinsic::x86_sse2_loadu_dq:
8863 // Turn PPC lvx -> load if the pointer is known aligned.
8864 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008865 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008866 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8867 PointerType::getUnqual(II->getType()),
8868 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008869 return new LoadInst(Ptr);
8870 }
8871 break;
8872 case Intrinsic::ppc_altivec_stvx:
8873 case Intrinsic::ppc_altivec_stvxl:
8874 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008875 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008876 const Type *OpPtrTy =
8877 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008878 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008879 return new StoreInst(II->getOperand(1), Ptr);
8880 }
8881 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008882 case Intrinsic::x86_sse_storeu_ps:
8883 case Intrinsic::x86_sse2_storeu_pd:
8884 case Intrinsic::x86_sse2_storeu_dq:
8885 case Intrinsic::x86_sse2_storel_dq:
8886 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008887 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008888 const Type *OpPtrTy =
8889 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008890 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008891 return new StoreInst(II->getOperand(2), Ptr);
8892 }
8893 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008894
8895 case Intrinsic::x86_sse_cvttss2si: {
8896 // These intrinsics only demands the 0th element of its input vector. If
8897 // we can simplify the input based on that, do so now.
8898 uint64_t UndefElts;
8899 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8900 UndefElts)) {
8901 II->setOperand(1, V);
8902 return II;
8903 }
8904 break;
8905 }
8906
Chris Lattnere2ed0572006-04-06 19:19:17 +00008907 case Intrinsic::ppc_altivec_vperm:
8908 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008909 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008910 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8911
8912 // Check that all of the elements are integer constants or undefs.
8913 bool AllEltsOk = true;
8914 for (unsigned i = 0; i != 16; ++i) {
8915 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8916 !isa<UndefValue>(Mask->getOperand(i))) {
8917 AllEltsOk = false;
8918 break;
8919 }
8920 }
8921
8922 if (AllEltsOk) {
8923 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008924 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8925 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008926 Value *Result = UndefValue::get(Op0->getType());
8927
8928 // Only extract each element once.
8929 Value *ExtractedElts[32];
8930 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8931
8932 for (unsigned i = 0; i != 16; ++i) {
8933 if (isa<UndefValue>(Mask->getOperand(i)))
8934 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008935 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008936 Idx &= 31; // Match the hardware behavior.
8937
8938 if (ExtractedElts[Idx] == 0) {
8939 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008940 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008941 InsertNewInstBefore(Elt, CI);
8942 ExtractedElts[Idx] = Elt;
8943 }
8944
8945 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008946 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8947 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008948 InsertNewInstBefore(cast<Instruction>(Result), CI);
8949 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008950 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008951 }
8952 }
8953 break;
8954
Chris Lattnera728ddc2006-01-13 21:28:09 +00008955 case Intrinsic::stackrestore: {
8956 // If the save is right next to the restore, remove the restore. This can
8957 // happen when variable allocas are DCE'd.
8958 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8959 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8960 BasicBlock::iterator BI = SS;
8961 if (&*++BI == II)
8962 return EraseInstFromFunction(CI);
8963 }
8964 }
8965
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008966 // Scan down this block to see if there is another stack restore in the
8967 // same block without an intervening call/alloca.
8968 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008969 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008970 bool CannotRemove = false;
8971 for (++BI; &*BI != TI; ++BI) {
8972 if (isa<AllocaInst>(BI)) {
8973 CannotRemove = true;
8974 break;
8975 }
8976 if (isa<CallInst>(BI)) {
8977 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008978 CannotRemove = true;
8979 break;
8980 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008981 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008982 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008983 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008984 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008985
8986 // If the stack restore is in a return/unwind block and if there are no
8987 // allocas or calls between the restore and the return, nuke the restore.
8988 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8989 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008990 break;
8991 }
8992 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008993 }
8994
Chris Lattner8b0ea312006-01-13 20:11:04 +00008995 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008996}
8997
8998// InvokeInst simplification
8999//
9000Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009001 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009002}
9003
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009004/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9005/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009006static bool isSafeToEliminateVarargsCast(const CallSite CS,
9007 const CastInst * const CI,
9008 const TargetData * const TD,
9009 const int ix) {
9010 if (!CI->isLosslessCast())
9011 return false;
9012
9013 // The size of ByVal arguments is derived from the type, so we
9014 // can't change to a type with a different size. If the size were
9015 // passed explicitly we could avoid this check.
9016 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9017 return true;
9018
9019 const Type* SrcTy =
9020 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9021 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9022 if (!SrcTy->isSized() || !DstTy->isSized())
9023 return false;
9024 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9025 return false;
9026 return true;
9027}
9028
Chris Lattnera44d8a22003-10-07 22:32:43 +00009029// visitCallSite - Improvements for call and invoke instructions.
9030//
9031Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009032 bool Changed = false;
9033
9034 // If the callee is a constexpr cast of a function, attempt to move the cast
9035 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009036 if (transformConstExprCastCall(CS)) return 0;
9037
Chris Lattner6c266db2003-10-07 22:54:13 +00009038 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009039
Chris Lattner08b22ec2005-05-13 07:09:09 +00009040 if (Function *CalleeF = dyn_cast<Function>(Callee))
9041 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9042 Instruction *OldCall = CS.getInstruction();
9043 // If the call and callee calling conventions don't match, this call must
9044 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009045 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009046 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9047 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009048 if (!OldCall->use_empty())
9049 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9050 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9051 return EraseInstFromFunction(*OldCall);
9052 return 0;
9053 }
9054
Chris Lattner17be6352004-10-18 02:59:09 +00009055 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9056 // This instruction is not reachable, just remove it. We insert a store to
9057 // undef so that we know that this code is not reachable, despite the fact
9058 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009059 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009060 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009061 CS.getInstruction());
9062
9063 if (!CS.getInstruction()->use_empty())
9064 CS.getInstruction()->
9065 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9066
9067 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9068 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009069 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9070 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009071 }
Chris Lattner17be6352004-10-18 02:59:09 +00009072 return EraseInstFromFunction(*CS.getInstruction());
9073 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009074
Duncan Sandscdb6d922007-09-17 10:26:40 +00009075 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9076 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9077 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9078 return transformCallThroughTrampoline(CS);
9079
Chris Lattner6c266db2003-10-07 22:54:13 +00009080 const PointerType *PTy = cast<PointerType>(Callee->getType());
9081 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9082 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009083 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009084 // See if we can optimize any arguments passed through the varargs area of
9085 // the call.
9086 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009087 E = CS.arg_end(); I != E; ++I, ++ix) {
9088 CastInst *CI = dyn_cast<CastInst>(*I);
9089 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9090 *I = CI->getOperand(0);
9091 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009092 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009093 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009094 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009095
Duncan Sandsf0c33542007-12-19 21:13:37 +00009096 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009097 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009098 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009099 Changed = true;
9100 }
9101
Chris Lattner6c266db2003-10-07 22:54:13 +00009102 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009103}
9104
Chris Lattner9fe38862003-06-19 17:00:31 +00009105// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9106// attempt to move the cast to the arguments of the call/invoke.
9107//
9108bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9109 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9110 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009111 if (CE->getOpcode() != Instruction::BitCast ||
9112 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009113 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009114 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009115 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00009116 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00009117
9118 // Okay, this is a cast from a function to a different type. Unless doing so
9119 // would cause a type conversion of one of our arguments, change this call to
9120 // be a direct call with arguments casted to the appropriate types.
9121 //
9122 const FunctionType *FT = Callee->getFunctionType();
9123 const Type *OldRetTy = Caller->getType();
9124
Devang Patel75e6f022008-03-11 18:04:06 +00009125 if (isa<StructType>(FT->getReturnType()))
9126 return false; // TODO: Handle multiple return values.
9127
Chris Lattnerf78616b2004-01-14 06:06:08 +00009128 // Check to see if we are changing the return type...
9129 if (OldRetTy != FT->getReturnType()) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009130 if (Callee->isDeclaration() &&
Chris Lattner46013f42007-01-06 19:53:32 +00009131 // Conversion is ok if changing from pointer to int of same size.
9132 !(isa<PointerType>(FT->getReturnType()) &&
9133 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00009134 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009135
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009136 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009137 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00009138 FT->getReturnType() != Type::VoidTy &&
9139 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009140 return false; // Cannot transform this return value.
9141
Chris Lattner58d74912008-03-12 17:45:29 +00009142 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9143 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00009144 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9145 return false; // Attribute not compatible with transformed value.
9146 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009147
Chris Lattnerf78616b2004-01-14 06:06:08 +00009148 // If the callsite is an invoke instruction, and the return value is used by
9149 // a PHI node in a successor, we cannot change the return type of the call
9150 // because there is no place to put the cast instruction (without breaking
9151 // the critical edge). Bail out in this case.
9152 if (!Caller->use_empty())
9153 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9154 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9155 UI != E; ++UI)
9156 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9157 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009158 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009159 return false;
9160 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009161
9162 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9163 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009164
Chris Lattner9fe38862003-06-19 17:00:31 +00009165 CallSite::arg_iterator AI = CS.arg_begin();
9166 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9167 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009168 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009169
9170 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009171 return false; // Cannot transform this parameter value.
9172
Chris Lattner58d74912008-03-12 17:45:29 +00009173 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9174 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009175
Reid Spencer3da59db2006-11-27 01:05:10 +00009176 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009177 // Some conversions are safe even if we do not have a body.
9178 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00009179 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00009180 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00009181 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009182 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9183 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00009184 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00009185 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009186 }
9187
9188 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009189 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009190 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009191
Chris Lattner58d74912008-03-12 17:45:29 +00009192 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9193 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009194 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009195 // won't be dropping them. Check that these extra arguments have attributes
9196 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009197 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9198 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009199 break;
Chris Lattner58d74912008-03-12 17:45:29 +00009200 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00009201 if (PAttrs & ParamAttr::VarArgsIncompatible)
9202 return false;
9203 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009204
Chris Lattner9fe38862003-06-19 17:00:31 +00009205 // Okay, we decided that this is a safe thing to do: go ahead and start
9206 // inserting cast instructions as necessary...
9207 std::vector<Value*> Args;
9208 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00009209 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009210 attrVec.reserve(NumCommonArgs);
9211
9212 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009213 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009214
9215 // If the return value is not being used, the type may not be compatible
9216 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00009217 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009218
9219 // Add the new return attributes.
9220 if (RAttrs)
9221 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009222
9223 AI = CS.arg_begin();
9224 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9225 const Type *ParamTy = FT->getParamType(i);
9226 if ((*AI)->getType() == ParamTy) {
9227 Args.push_back(*AI);
9228 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009229 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009230 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009231 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009232 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009233 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009234
9235 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009236 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009237 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009238 }
9239
9240 // If the function takes more arguments than the call was taking, add them
9241 // now...
9242 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9243 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9244
9245 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009246 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009247 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009248 cerr << "WARNING: While resolving call to function '"
9249 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009250 } else {
9251 // Add all of the arguments in their promoted form to the arg list...
9252 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9253 const Type *PTy = getPromotedType((*AI)->getType());
9254 if (PTy != (*AI)->getType()) {
9255 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009256 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9257 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009258 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009259 InsertNewInstBefore(Cast, *Caller);
9260 Args.push_back(Cast);
9261 } else {
9262 Args.push_back(*AI);
9263 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009264
Duncan Sandse1e520f2008-01-13 08:02:44 +00009265 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009266 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009267 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9268 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009269 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009270 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009271
9272 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009273 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009274
Chris Lattner58d74912008-03-12 17:45:29 +00009275 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009276
Chris Lattner9fe38862003-06-19 17:00:31 +00009277 Instruction *NC;
9278 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009279 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009280 Args.begin(), Args.end(),
9281 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009282 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009283 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009284 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009285 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9286 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009287 CallInst *CI = cast<CallInst>(Caller);
9288 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009289 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009290 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009291 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009292 }
9293
Chris Lattner6934a042007-02-11 01:23:03 +00009294 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009295 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009296 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009297 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009298 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009299 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009300 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009301
9302 // If this is an invoke instruction, we should insert it after the first
9303 // non-phi, instruction in the normal successor block.
9304 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9305 BasicBlock::iterator I = II->getNormalDest()->begin();
9306 while (isa<PHINode>(I)) ++I;
9307 InsertNewInstBefore(NC, *I);
9308 } else {
9309 // Otherwise, it's a call, just insert cast right after the call instr
9310 InsertNewInstBefore(NC, *Caller);
9311 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009312 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009313 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009314 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009315 }
9316 }
9317
9318 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9319 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009320 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009321 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009322 return true;
9323}
9324
Duncan Sandscdb6d922007-09-17 10:26:40 +00009325// transformCallThroughTrampoline - Turn a call to a function created by the
9326// init_trampoline intrinsic into a direct call to the underlying function.
9327//
9328Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9329 Value *Callee = CS.getCalledValue();
9330 const PointerType *PTy = cast<PointerType>(Callee->getType());
9331 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009332 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009333
9334 // If the call already has the 'nest' attribute somewhere then give up -
9335 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009336 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009337 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009338
9339 IntrinsicInst *Tramp =
9340 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9341
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009342 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009343 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9344 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9345
Chris Lattner58d74912008-03-12 17:45:29 +00009346 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9347 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009348 unsigned NestIdx = 1;
9349 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009350 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009351
9352 // Look for a parameter marked with the 'nest' attribute.
9353 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9354 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009355 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009356 // Record the parameter type and any other attributes.
9357 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009358 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009359 break;
9360 }
9361
9362 if (NestTy) {
9363 Instruction *Caller = CS.getInstruction();
9364 std::vector<Value*> NewArgs;
9365 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9366
Chris Lattner58d74912008-03-12 17:45:29 +00009367 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9368 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009369
Duncan Sandscdb6d922007-09-17 10:26:40 +00009370 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009371 // mean appending it. Likewise for attributes.
9372
9373 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009374 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9375 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009376
Duncan Sandscdb6d922007-09-17 10:26:40 +00009377 {
9378 unsigned Idx = 1;
9379 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9380 do {
9381 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009382 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009383 Value *NestVal = Tramp->getOperand(3);
9384 if (NestVal->getType() != NestTy)
9385 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9386 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009387 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009388 }
9389
9390 if (I == E)
9391 break;
9392
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009393 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009394 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009395 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009396 NewAttrs.push_back
9397 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009398
9399 ++Idx, ++I;
9400 } while (1);
9401 }
9402
9403 // The trampoline may have been bitcast to a bogus type (FTy).
9404 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009405 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009406
Duncan Sandscdb6d922007-09-17 10:26:40 +00009407 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009408 NewTypes.reserve(FTy->getNumParams()+1);
9409
Duncan Sandscdb6d922007-09-17 10:26:40 +00009410 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009411 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009412 {
9413 unsigned Idx = 1;
9414 FunctionType::param_iterator I = FTy->param_begin(),
9415 E = FTy->param_end();
9416
9417 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009418 if (Idx == NestIdx)
9419 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009420 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009421
9422 if (I == E)
9423 break;
9424
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009425 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009426 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009427
9428 ++Idx, ++I;
9429 } while (1);
9430 }
9431
9432 // Replace the trampoline call with a direct call. Let the generic
9433 // code sort out any function type mismatches.
9434 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009435 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009436 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9437 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009438 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009439
9440 Instruction *NewCaller;
9441 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009442 NewCaller = InvokeInst::Create(NewCallee,
9443 II->getNormalDest(), II->getUnwindDest(),
9444 NewArgs.begin(), NewArgs.end(),
9445 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009446 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009447 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009448 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009449 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9450 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009451 if (cast<CallInst>(Caller)->isTailCall())
9452 cast<CallInst>(NewCaller)->setTailCall();
9453 cast<CallInst>(NewCaller)->
9454 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009455 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009456 }
9457 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9458 Caller->replaceAllUsesWith(NewCaller);
9459 Caller->eraseFromParent();
9460 RemoveFromWorkList(Caller);
9461 return 0;
9462 }
9463 }
9464
9465 // Replace the trampoline call with a direct call. Since there is no 'nest'
9466 // parameter, there is no need to adjust the argument list. Let the generic
9467 // code sort out any function type mismatches.
9468 Constant *NewCallee =
9469 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9470 CS.setCalledFunction(NewCallee);
9471 return CS.getInstruction();
9472}
9473
Chris Lattner7da52b22006-11-01 04:51:18 +00009474/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9475/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9476/// and a single binop.
9477Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9478 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009479 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9480 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009481 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009482 Value *LHSVal = FirstInst->getOperand(0);
9483 Value *RHSVal = FirstInst->getOperand(1);
9484
9485 const Type *LHSType = LHSVal->getType();
9486 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009487
9488 // Scan to see if all operands are the same opcode, all have one use, and all
9489 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009490 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009491 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009492 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009493 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009494 // types or GEP's with different index types.
9495 I->getOperand(0)->getType() != LHSType ||
9496 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009497 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009498
9499 // If they are CmpInst instructions, check their predicates
9500 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9501 if (cast<CmpInst>(I)->getPredicate() !=
9502 cast<CmpInst>(FirstInst)->getPredicate())
9503 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009504
9505 // Keep track of which operand needs a phi node.
9506 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9507 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009508 }
9509
Chris Lattner53738a42006-11-08 19:42:28 +00009510 // Otherwise, this is safe to transform, determine if it is profitable.
9511
9512 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9513 // Indexes are often folded into load/store instructions, so we don't want to
9514 // hide them behind a phi.
9515 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9516 return 0;
9517
Chris Lattner7da52b22006-11-01 04:51:18 +00009518 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009519 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009520 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009521 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009522 NewLHS = PHINode::Create(LHSType,
9523 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009524 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9525 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009526 InsertNewInstBefore(NewLHS, PN);
9527 LHSVal = NewLHS;
9528 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009529
9530 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009531 NewRHS = PHINode::Create(RHSType,
9532 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009533 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9534 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009535 InsertNewInstBefore(NewRHS, PN);
9536 RHSVal = NewRHS;
9537 }
9538
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009539 // Add all operands to the new PHIs.
9540 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9541 if (NewLHS) {
9542 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9543 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9544 }
9545 if (NewRHS) {
9546 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9547 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9548 }
9549 }
9550
Chris Lattner7da52b22006-11-01 04:51:18 +00009551 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009552 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009553 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009554 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009555 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009556 else {
9557 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009558 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009559 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009560}
9561
Chris Lattner76c73142006-11-01 07:13:54 +00009562/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9563/// of the block that defines it. This means that it must be obvious the value
9564/// of the load is not changed from the point of the load to the end of the
9565/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009566///
9567/// Finally, it is safe, but not profitable, to sink a load targetting a
9568/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9569/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009570static bool isSafeToSinkLoad(LoadInst *L) {
9571 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9572
9573 for (++BBI; BBI != E; ++BBI)
9574 if (BBI->mayWriteToMemory())
9575 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009576
9577 // Check for non-address taken alloca. If not address-taken already, it isn't
9578 // profitable to do this xform.
9579 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9580 bool isAddressTaken = false;
9581 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9582 UI != E; ++UI) {
9583 if (isa<LoadInst>(UI)) continue;
9584 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9585 // If storing TO the alloca, then the address isn't taken.
9586 if (SI->getOperand(1) == AI) continue;
9587 }
9588 isAddressTaken = true;
9589 break;
9590 }
9591
9592 if (!isAddressTaken)
9593 return false;
9594 }
9595
Chris Lattner76c73142006-11-01 07:13:54 +00009596 return true;
9597}
9598
Chris Lattner9fe38862003-06-19 17:00:31 +00009599
Chris Lattnerbac32862004-11-14 19:13:23 +00009600// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9601// operator and they all are only used by the PHI, PHI together their
9602// inputs, and do the operation once, to the result of the PHI.
9603Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9604 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9605
9606 // Scan the instruction, looking for input operations that can be folded away.
9607 // If all input operands to the phi are the same instruction (e.g. a cast from
9608 // the same type or "+42") we can pull the operation through the PHI, reducing
9609 // code size and simplifying code.
9610 Constant *ConstantOp = 0;
9611 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009612 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009613 if (isa<CastInst>(FirstInst)) {
9614 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009615 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009616 // Can fold binop, compare or shift here if the RHS is a constant,
9617 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009618 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009619 if (ConstantOp == 0)
9620 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009621 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9622 isVolatile = LI->isVolatile();
9623 // We can't sink the load if the loaded value could be modified between the
9624 // load and the PHI.
9625 if (LI->getParent() != PN.getIncomingBlock(0) ||
9626 !isSafeToSinkLoad(LI))
9627 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009628 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009629 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009630 return FoldPHIArgBinOpIntoPHI(PN);
9631 // Can't handle general GEPs yet.
9632 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009633 } else {
9634 return 0; // Cannot fold this operation.
9635 }
9636
9637 // Check to see if all arguments are the same operation.
9638 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9639 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9640 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009641 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009642 return 0;
9643 if (CastSrcTy) {
9644 if (I->getOperand(0)->getType() != CastSrcTy)
9645 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009646 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009647 // We can't sink the load if the loaded value could be modified between
9648 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009649 if (LI->isVolatile() != isVolatile ||
9650 LI->getParent() != PN.getIncomingBlock(i) ||
9651 !isSafeToSinkLoad(LI))
9652 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009653
9654 // If the PHI is volatile and its block has multiple successors, sinking
9655 // it would remove a load of the volatile value from the path through the
9656 // other successor.
9657 if (isVolatile &&
9658 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9659 return 0;
9660
9661
Chris Lattnerbac32862004-11-14 19:13:23 +00009662 } else if (I->getOperand(1) != ConstantOp) {
9663 return 0;
9664 }
9665 }
9666
9667 // Okay, they are all the same operation. Create a new PHI node of the
9668 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009669 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9670 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009671 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009672
9673 Value *InVal = FirstInst->getOperand(0);
9674 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009675
9676 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009677 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9678 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9679 if (NewInVal != InVal)
9680 InVal = 0;
9681 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9682 }
9683
9684 Value *PhiVal;
9685 if (InVal) {
9686 // The new PHI unions all of the same values together. This is really
9687 // common, so we handle it intelligently here for compile-time speed.
9688 PhiVal = InVal;
9689 delete NewPN;
9690 } else {
9691 InsertNewInstBefore(NewPN, PN);
9692 PhiVal = NewPN;
9693 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009694
Chris Lattnerbac32862004-11-14 19:13:23 +00009695 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009696 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009697 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009698 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009699 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009700 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009701 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009702 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009703 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9704
9705 // If this was a volatile load that we are merging, make sure to loop through
9706 // and mark all the input loads as non-volatile. If we don't do this, we will
9707 // insert a new volatile load and the old ones will not be deletable.
9708 if (isVolatile)
9709 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9710 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9711
9712 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009713}
Chris Lattnera1be5662002-05-02 17:06:02 +00009714
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009715/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9716/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009717static bool DeadPHICycle(PHINode *PN,
9718 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009719 if (PN->use_empty()) return true;
9720 if (!PN->hasOneUse()) return false;
9721
9722 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009723 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009724 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009725
9726 // Don't scan crazily complex things.
9727 if (PotentiallyDeadPHIs.size() == 16)
9728 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009729
9730 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9731 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009732
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009733 return false;
9734}
9735
Chris Lattnercf5008a2007-11-06 21:52:06 +00009736/// PHIsEqualValue - Return true if this phi node is always equal to
9737/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9738/// z = some value; x = phi (y, z); y = phi (x, z)
9739static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9740 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9741 // See if we already saw this PHI node.
9742 if (!ValueEqualPHIs.insert(PN))
9743 return true;
9744
9745 // Don't scan crazily complex things.
9746 if (ValueEqualPHIs.size() == 16)
9747 return false;
9748
9749 // Scan the operands to see if they are either phi nodes or are equal to
9750 // the value.
9751 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9752 Value *Op = PN->getIncomingValue(i);
9753 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9754 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9755 return false;
9756 } else if (Op != NonPhiInVal)
9757 return false;
9758 }
9759
9760 return true;
9761}
9762
9763
Chris Lattner473945d2002-05-06 18:06:38 +00009764// PHINode simplification
9765//
Chris Lattner7e708292002-06-25 16:13:24 +00009766Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009767 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009768 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009769
Owen Anderson7e057142006-07-10 22:03:18 +00009770 if (Value *V = PN.hasConstantValue())
9771 return ReplaceInstUsesWith(PN, V);
9772
Owen Anderson7e057142006-07-10 22:03:18 +00009773 // If all PHI operands are the same operation, pull them through the PHI,
9774 // reducing code size.
9775 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9776 PN.getIncomingValue(0)->hasOneUse())
9777 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9778 return Result;
9779
9780 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9781 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9782 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009783 if (PN.hasOneUse()) {
9784 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9785 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009786 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009787 PotentiallyDeadPHIs.insert(&PN);
9788 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9789 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9790 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009791
9792 // If this phi has a single use, and if that use just computes a value for
9793 // the next iteration of a loop, delete the phi. This occurs with unused
9794 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9795 // common case here is good because the only other things that catch this
9796 // are induction variable analysis (sometimes) and ADCE, which is only run
9797 // late.
9798 if (PHIUser->hasOneUse() &&
9799 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9800 PHIUser->use_back() == &PN) {
9801 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9802 }
9803 }
Owen Anderson7e057142006-07-10 22:03:18 +00009804
Chris Lattnercf5008a2007-11-06 21:52:06 +00009805 // We sometimes end up with phi cycles that non-obviously end up being the
9806 // same value, for example:
9807 // z = some value; x = phi (y, z); y = phi (x, z)
9808 // where the phi nodes don't necessarily need to be in the same block. Do a
9809 // quick check to see if the PHI node only contains a single non-phi value, if
9810 // so, scan to see if the phi cycle is actually equal to that value.
9811 {
9812 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9813 // Scan for the first non-phi operand.
9814 while (InValNo != NumOperandVals &&
9815 isa<PHINode>(PN.getIncomingValue(InValNo)))
9816 ++InValNo;
9817
9818 if (InValNo != NumOperandVals) {
9819 Value *NonPhiInVal = PN.getOperand(InValNo);
9820
9821 // Scan the rest of the operands to see if there are any conflicts, if so
9822 // there is no need to recursively scan other phis.
9823 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9824 Value *OpVal = PN.getIncomingValue(InValNo);
9825 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9826 break;
9827 }
9828
9829 // If we scanned over all operands, then we have one unique value plus
9830 // phi values. Scan PHI nodes to see if they all merge in each other or
9831 // the value.
9832 if (InValNo == NumOperandVals) {
9833 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9834 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9835 return ReplaceInstUsesWith(PN, NonPhiInVal);
9836 }
9837 }
9838 }
Chris Lattner60921c92003-12-19 05:58:40 +00009839 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009840}
9841
Reid Spencer17212df2006-12-12 09:18:51 +00009842static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9843 Instruction *InsertPoint,
9844 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009845 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9846 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009847 // We must cast correctly to the pointer type. Ensure that we
9848 // sign extend the integer value if it is smaller as this is
9849 // used for address computation.
9850 Instruction::CastOps opcode =
9851 (VTySize < PtrSize ? Instruction::SExt :
9852 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9853 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009854}
9855
Chris Lattnera1be5662002-05-02 17:06:02 +00009856
Chris Lattner7e708292002-06-25 16:13:24 +00009857Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009858 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009859 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009860 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009861 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009862 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009863
Chris Lattnere87597f2004-10-16 18:11:37 +00009864 if (isa<UndefValue>(GEP.getOperand(0)))
9865 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9866
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009867 bool HasZeroPointerIndex = false;
9868 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9869 HasZeroPointerIndex = C->isNullValue();
9870
9871 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009872 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009873
Chris Lattner28977af2004-04-05 01:30:19 +00009874 // Eliminate unneeded casts for indices.
9875 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009876
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009877 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009878 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009879 if (isa<SequentialType>(*GTI)) {
9880 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009881 if (CI->getOpcode() == Instruction::ZExt ||
9882 CI->getOpcode() == Instruction::SExt) {
9883 const Type *SrcTy = CI->getOperand(0)->getType();
9884 // We can eliminate a cast from i32 to i64 iff the target
9885 // is a 32-bit pointer target.
9886 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9887 MadeChange = true;
9888 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009889 }
9890 }
9891 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009892 // If we are using a wider index than needed for this platform, shrink it
9893 // to what we need. If the incoming value needs a cast instruction,
9894 // insert it. This explicit cast can make subsequent optimizations more
9895 // obvious.
9896 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009897 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009898 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009899 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009900 MadeChange = true;
9901 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009902 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9903 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009904 GEP.setOperand(i, Op);
9905 MadeChange = true;
9906 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009907 }
Chris Lattner28977af2004-04-05 01:30:19 +00009908 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009909 }
Chris Lattner28977af2004-04-05 01:30:19 +00009910 if (MadeChange) return &GEP;
9911
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009912 // If this GEP instruction doesn't move the pointer, and if the input operand
9913 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9914 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009915 if (GEP.hasAllZeroIndices()) {
9916 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9917 // If the bitcast is of an allocation, and the allocation will be
9918 // converted to match the type of the cast, don't touch this.
9919 if (isa<AllocationInst>(BCI->getOperand(0))) {
9920 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009921 if (Instruction *I = visitBitCast(*BCI)) {
9922 if (I != BCI) {
9923 I->takeName(BCI);
9924 BCI->getParent()->getInstList().insert(BCI, I);
9925 ReplaceInstUsesWith(*BCI, I);
9926 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009927 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009928 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009929 }
9930 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9931 }
9932 }
9933
Chris Lattner90ac28c2002-08-02 19:29:35 +00009934 // Combine Indices - If the source pointer to this getelementptr instruction
9935 // is a getelementptr instruction, combine the indices of the two
9936 // getelementptr instructions into a single instruction.
9937 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009938 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009939 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009940 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009941
9942 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009943 // Note that if our source is a gep chain itself that we wait for that
9944 // chain to be resolved before we perform this transformation. This
9945 // avoids us creating a TON of code in some cases.
9946 //
9947 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9948 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9949 return 0; // Wait until our source is folded to completion.
9950
Chris Lattner72588fc2007-02-15 22:48:32 +00009951 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009952
9953 // Find out whether the last index in the source GEP is a sequential idx.
9954 bool EndsWithSequential = false;
9955 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9956 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009957 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009958
Chris Lattner90ac28c2002-08-02 19:29:35 +00009959 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009960 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009961 // Replace: gep (gep %P, long B), long A, ...
9962 // With: T = long A+B; gep %P, T, ...
9963 //
Chris Lattner620ce142004-05-07 22:09:22 +00009964 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009965 if (SO1 == Constant::getNullValue(SO1->getType())) {
9966 Sum = GO1;
9967 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9968 Sum = SO1;
9969 } else {
9970 // If they aren't the same type, convert both to an integer of the
9971 // target's pointer size.
9972 if (SO1->getType() != GO1->getType()) {
9973 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009974 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009975 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009976 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009977 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009978 unsigned PS = TD->getPointerSizeInBits();
9979 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009980 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009981 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009982
Duncan Sands514ab342007-11-01 20:53:16 +00009983 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009984 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009985 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009986 } else {
9987 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009988 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9989 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009990 }
9991 }
9992 }
Chris Lattner620ce142004-05-07 22:09:22 +00009993 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9994 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9995 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009996 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +00009997 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009998 }
Chris Lattner28977af2004-04-05 01:30:19 +00009999 }
Chris Lattner620ce142004-05-07 22:09:22 +000010000
10001 // Recycle the GEP we already have if possible.
10002 if (SrcGEPOperands.size() == 2) {
10003 GEP.setOperand(0, SrcGEPOperands[0]);
10004 GEP.setOperand(1, Sum);
10005 return &GEP;
10006 } else {
10007 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10008 SrcGEPOperands.end()-1);
10009 Indices.push_back(Sum);
10010 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10011 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010012 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010013 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010014 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010015 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010016 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10017 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010018 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10019 }
10020
10021 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010022 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10023 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010024
Chris Lattner620ce142004-05-07 22:09:22 +000010025 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010026 // GEP of global variable. If all of the indices for this GEP are
10027 // constants, we can promote this to a constexpr instead of an instruction.
10028
10029 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010030 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010031 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10032 for (; I != E && isa<Constant>(*I); ++I)
10033 Indices.push_back(cast<Constant>(*I));
10034
10035 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010036 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10037 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010038
10039 // Replace all uses of the GEP with the new constexpr...
10040 return ReplaceInstUsesWith(GEP, CE);
10041 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010042 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010043 if (!isa<PointerType>(X->getType())) {
10044 // Not interesting. Source pointer must be a cast from pointer.
10045 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010046 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10047 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010048 //
10049 // This occurs when the program declares an array extern like "int X[];"
10050 //
10051 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10052 const PointerType *XTy = cast<PointerType>(X->getType());
10053 if (const ArrayType *XATy =
10054 dyn_cast<ArrayType>(XTy->getElementType()))
10055 if (const ArrayType *CATy =
10056 dyn_cast<ArrayType>(CPTy->getElementType()))
10057 if (CATy->getElementType() == XATy->getElementType()) {
10058 // At this point, we know that the cast source type is a pointer
10059 // to an array of the same type as the destination pointer
10060 // array. Because the array type is never stepped over (there
10061 // is a leading zero) we can fold the cast into this GEP.
10062 GEP.setOperand(0, X);
10063 return &GEP;
10064 }
10065 } else if (GEP.getNumOperands() == 2) {
10066 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010067 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10068 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010069 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10070 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10071 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +000010072 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10073 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010074 Value *Idx[2];
10075 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10076 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010077 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010078 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010079 // V and GEP are both pointer types --> BitCast
10080 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010081 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010082
10083 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010084 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010085 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010086 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010087
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010088 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010089 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +000010090 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010091
10092 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10093 // allow either a mul, shift, or constant here.
10094 Value *NewIdx = 0;
10095 ConstantInt *Scale = 0;
10096 if (ArrayEltSize == 1) {
10097 NewIdx = GEP.getOperand(1);
10098 Scale = ConstantInt::get(NewIdx->getType(), 1);
10099 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010100 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010101 Scale = CI;
10102 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10103 if (Inst->getOpcode() == Instruction::Shl &&
10104 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010105 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10106 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10107 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010108 NewIdx = Inst->getOperand(0);
10109 } else if (Inst->getOpcode() == Instruction::Mul &&
10110 isa<ConstantInt>(Inst->getOperand(1))) {
10111 Scale = cast<ConstantInt>(Inst->getOperand(1));
10112 NewIdx = Inst->getOperand(0);
10113 }
10114 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010115
Chris Lattner7835cdd2005-09-13 18:36:04 +000010116 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010117 // out, perform the transformation. Note, we don't know whether Scale is
10118 // signed or not. We'll use unsigned version of division/modulo
10119 // operation after making sure Scale doesn't have the sign bit set.
10120 if (Scale && Scale->getSExtValue() >= 0LL &&
10121 Scale->getZExtValue() % ArrayEltSize == 0) {
10122 Scale = ConstantInt::get(Scale->getType(),
10123 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010124 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010125 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010126 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010127 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010128 NewIdx = InsertNewInstBefore(Sc, GEP);
10129 }
10130
10131 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010132 Value *Idx[2];
10133 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10134 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010135 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010136 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010137 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10138 // The NewGEP must be pointer typed, so must the old one -> BitCast
10139 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010140 }
10141 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010142 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010143 }
10144
Chris Lattner8a2a3112001-12-14 16:52:21 +000010145 return 0;
10146}
10147
Chris Lattner0864acf2002-11-04 16:18:53 +000010148Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10149 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010150 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010151 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10152 const Type *NewTy =
10153 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010154 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010155
10156 // Create and insert the replacement instruction...
10157 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010158 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010159 else {
10160 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010161 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010162 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010163
10164 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010165
Chris Lattner0864acf2002-11-04 16:18:53 +000010166 // Scan to the end of the allocation instructions, to skip over a block of
10167 // allocas if possible...
10168 //
10169 BasicBlock::iterator It = New;
10170 while (isa<AllocationInst>(*It)) ++It;
10171
10172 // Now that I is pointing to the first non-allocation-inst in the block,
10173 // insert our getelementptr instruction...
10174 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010175 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010176 Value *Idx[2];
10177 Idx[0] = NullIdx;
10178 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010179 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10180 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010181
10182 // Now make everything use the getelementptr instead of the original
10183 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010184 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010185 } else if (isa<UndefValue>(AI.getArraySize())) {
10186 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010187 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010188 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010189
10190 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10191 // Note that we only do this for alloca's, because malloc should allocate and
10192 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +000010193 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +000010194 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +000010195 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10196
Chris Lattner0864acf2002-11-04 16:18:53 +000010197 return 0;
10198}
10199
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010200Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10201 Value *Op = FI.getOperand(0);
10202
Chris Lattner17be6352004-10-18 02:59:09 +000010203 // free undef -> unreachable.
10204 if (isa<UndefValue>(Op)) {
10205 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010206 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010207 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010208 return EraseInstFromFunction(FI);
10209 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010210
Chris Lattner6160e852004-02-28 04:57:37 +000010211 // If we have 'free null' delete the instruction. This can happen in stl code
10212 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010213 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010214 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010215
10216 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10217 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10218 FI.setOperand(0, CI->getOperand(0));
10219 return &FI;
10220 }
10221
10222 // Change free (gep X, 0,0,0,0) into free(X)
10223 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10224 if (GEPI->hasAllZeroIndices()) {
10225 AddToWorkList(GEPI);
10226 FI.setOperand(0, GEPI->getOperand(0));
10227 return &FI;
10228 }
10229 }
10230
10231 // Change free(malloc) into nothing, if the malloc has a single use.
10232 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10233 if (MI->hasOneUse()) {
10234 EraseInstFromFunction(FI);
10235 return EraseInstFromFunction(*MI);
10236 }
Chris Lattner6160e852004-02-28 04:57:37 +000010237
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010238 return 0;
10239}
10240
10241
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010242/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010243static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010244 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010245 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010246 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010247
Devang Patel99db6ad2007-10-18 19:52:32 +000010248 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10249 // Instead of loading constant c string, use corresponding integer value
10250 // directly if string length is small enough.
10251 const std::string &Str = CE->getOperand(0)->getStringValue();
10252 if (!Str.empty()) {
10253 unsigned len = Str.length();
10254 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10255 unsigned numBits = Ty->getPrimitiveSizeInBits();
10256 // Replace LI with immediate integer store.
10257 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010258 APInt StrVal(numBits, 0);
10259 APInt SingleChar(numBits, 0);
10260 if (TD->isLittleEndian()) {
10261 for (signed i = len-1; i >= 0; i--) {
10262 SingleChar = (uint64_t) Str[i];
10263 StrVal = (StrVal << 8) | SingleChar;
10264 }
10265 } else {
10266 for (unsigned i = 0; i < len; i++) {
10267 SingleChar = (uint64_t) Str[i];
10268 StrVal = (StrVal << 8) | SingleChar;
10269 }
10270 // Append NULL at the end.
10271 SingleChar = 0;
10272 StrVal = (StrVal << 8) | SingleChar;
10273 }
10274 Value *NL = ConstantInt::get(StrVal);
10275 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010276 }
10277 }
10278 }
10279
Chris Lattnerb89e0712004-07-13 01:49:43 +000010280 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010281 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010282 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010283
Reid Spencer42230162007-01-22 05:51:25 +000010284 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010285 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010286 // If the source is an array, the code below will not succeed. Check to
10287 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10288 // constants.
10289 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10290 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10291 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010292 Value *Idxs[2];
10293 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10294 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010295 SrcTy = cast<PointerType>(CastOp->getType());
10296 SrcPTy = SrcTy->getElementType();
10297 }
10298
Reid Spencer42230162007-01-22 05:51:25 +000010299 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010300 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010301 // Do not allow turning this into a load of an integer, which is then
10302 // casted to a pointer, this pessimizes pointer analysis a lot.
10303 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010304 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10305 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010306
Chris Lattnerf9527852005-01-31 04:50:46 +000010307 // Okay, we are casting from one integer or pointer type to another of
10308 // the same size. Instead of casting the pointer before the load, cast
10309 // the result of the loaded value.
10310 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10311 CI->getName(),
10312 LI.isVolatile()),LI);
10313 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010314 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010315 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010316 }
10317 }
10318 return 0;
10319}
10320
Chris Lattnerc10aced2004-09-19 18:43:46 +000010321/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010322/// from this value cannot trap. If it is not obviously safe to load from the
10323/// specified pointer, we do a quick local scan of the basic block containing
10324/// ScanFrom, to determine if the address is already accessed.
10325static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010326 // If it is an alloca it is always safe to load from.
10327 if (isa<AllocaInst>(V)) return true;
10328
Duncan Sands46318cd2007-09-19 10:25:38 +000010329 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010330 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010331 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010332 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010333
10334 // Otherwise, be a little bit agressive by scanning the local block where we
10335 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010336 // from/to. If so, the previous load or store would have already trapped,
10337 // so there is no harm doing an extra load (also, CSE will later eliminate
10338 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010339 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10340
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010341 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010342 --BBI;
10343
10344 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10345 if (LI->getOperand(0) == V) return true;
10346 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10347 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010348
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010349 }
Chris Lattner8a375202004-09-19 19:18:10 +000010350 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010351}
10352
Chris Lattner8d2e8882007-08-11 18:48:48 +000010353/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10354/// until we find the underlying object a pointer is referring to or something
10355/// we don't understand. Note that the returned pointer may be offset from the
10356/// input, because we ignore GEP indices.
10357static Value *GetUnderlyingObject(Value *Ptr) {
10358 while (1) {
10359 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10360 if (CE->getOpcode() == Instruction::BitCast ||
10361 CE->getOpcode() == Instruction::GetElementPtr)
10362 Ptr = CE->getOperand(0);
10363 else
10364 return Ptr;
10365 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10366 Ptr = BCI->getOperand(0);
10367 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10368 Ptr = GEP->getOperand(0);
10369 } else {
10370 return Ptr;
10371 }
10372 }
10373}
10374
Chris Lattner833b8a42003-06-26 05:06:25 +000010375Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10376 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010377
Dan Gohman9941f742007-07-20 16:34:21 +000010378 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010379 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10380 if (KnownAlign >
10381 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10382 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010383 LI.setAlignment(KnownAlign);
10384
Chris Lattner37366c12005-05-01 04:24:53 +000010385 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010386 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010387 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010388 return Res;
10389
10390 // None of the following transforms are legal for volatile loads.
10391 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010392
Chris Lattner62f254d2005-09-12 22:00:15 +000010393 if (&LI.getParent()->front() != &LI) {
10394 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010395 // If the instruction immediately before this is a store to the same
10396 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010397 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10398 if (SI->getOperand(1) == LI.getOperand(0))
10399 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010400 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10401 if (LIB->getOperand(0) == LI.getOperand(0))
10402 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010403 }
Chris Lattner37366c12005-05-01 04:24:53 +000010404
Christopher Lambb15147e2007-12-29 07:56:53 +000010405 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10406 const Value *GEPI0 = GEPI->getOperand(0);
10407 // TODO: Consider a target hook for valid address spaces for this xform.
10408 if (isa<ConstantPointerNull>(GEPI0) &&
10409 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010410 // Insert a new store to null instruction before the load to indicate
10411 // that this code is not reachable. We do this instead of inserting
10412 // an unreachable instruction directly because we cannot modify the
10413 // CFG.
10414 new StoreInst(UndefValue::get(LI.getType()),
10415 Constant::getNullValue(Op->getType()), &LI);
10416 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10417 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010418 }
Chris Lattner37366c12005-05-01 04:24:53 +000010419
Chris Lattnere87597f2004-10-16 18:11:37 +000010420 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010421 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010422 // TODO: Consider a target hook for valid address spaces for this xform.
10423 if (isa<UndefValue>(C) || (C->isNullValue() &&
10424 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010425 // Insert a new store to null instruction before the load to indicate that
10426 // this code is not reachable. We do this instead of inserting an
10427 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010428 new StoreInst(UndefValue::get(LI.getType()),
10429 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010430 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010431 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010432
Chris Lattnere87597f2004-10-16 18:11:37 +000010433 // Instcombine load (constant global) into the value loaded.
10434 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010435 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010436 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010437
Chris Lattnere87597f2004-10-16 18:11:37 +000010438 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010439 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010440 if (CE->getOpcode() == Instruction::GetElementPtr) {
10441 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010442 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010443 if (Constant *V =
10444 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010445 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010446 if (CE->getOperand(0)->isNullValue()) {
10447 // Insert a new store to null instruction before the load to indicate
10448 // that this code is not reachable. We do this instead of inserting
10449 // an unreachable instruction directly because we cannot modify the
10450 // CFG.
10451 new StoreInst(UndefValue::get(LI.getType()),
10452 Constant::getNullValue(Op->getType()), &LI);
10453 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10454 }
10455
Reid Spencer3da59db2006-11-27 01:05:10 +000010456 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010457 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010458 return Res;
10459 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010460 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010461 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010462
10463 // If this load comes from anywhere in a constant global, and if the global
10464 // is all undef or zero, we know what it loads.
10465 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10466 if (GV->isConstant() && GV->hasInitializer()) {
10467 if (GV->getInitializer()->isNullValue())
10468 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10469 else if (isa<UndefValue>(GV->getInitializer()))
10470 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10471 }
10472 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010473
Chris Lattner37366c12005-05-01 04:24:53 +000010474 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010475 // Change select and PHI nodes to select values instead of addresses: this
10476 // helps alias analysis out a lot, allows many others simplifications, and
10477 // exposes redundancy in the code.
10478 //
10479 // Note that we cannot do the transformation unless we know that the
10480 // introduced loads cannot trap! Something like this is valid as long as
10481 // the condition is always false: load (select bool %C, int* null, int* %G),
10482 // but it would not be valid if we transformed it to load from null
10483 // unconditionally.
10484 //
10485 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10486 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010487 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10488 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010489 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010490 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010491 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010492 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010493 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010494 }
10495
Chris Lattner684fe212004-09-23 15:46:00 +000010496 // load (select (cond, null, P)) -> load P
10497 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10498 if (C->isNullValue()) {
10499 LI.setOperand(0, SI->getOperand(2));
10500 return &LI;
10501 }
10502
10503 // load (select (cond, P, null)) -> load P
10504 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10505 if (C->isNullValue()) {
10506 LI.setOperand(0, SI->getOperand(1));
10507 return &LI;
10508 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010509 }
10510 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010511 return 0;
10512}
10513
Reid Spencer55af2b52007-01-19 21:20:31 +000010514/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010515/// when possible.
10516static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10517 User *CI = cast<User>(SI.getOperand(1));
10518 Value *CastOp = CI->getOperand(0);
10519
10520 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10521 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10522 const Type *SrcPTy = SrcTy->getElementType();
10523
Reid Spencer42230162007-01-22 05:51:25 +000010524 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010525 // If the source is an array, the code below will not succeed. Check to
10526 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10527 // constants.
10528 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10529 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10530 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010531 Value* Idxs[2];
10532 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10533 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010534 SrcTy = cast<PointerType>(CastOp->getType());
10535 SrcPTy = SrcTy->getElementType();
10536 }
10537
Reid Spencer67f827c2007-01-20 23:35:48 +000010538 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10539 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10540 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010541
10542 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010543 // the same size. Instead of casting the pointer before
10544 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010545 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010546 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010547 Instruction::CastOps opcode = Instruction::BitCast;
10548 const Type* CastSrcTy = SIOp0->getType();
10549 const Type* CastDstTy = SrcPTy;
10550 if (isa<PointerType>(CastDstTy)) {
10551 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010552 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010553 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010554 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010555 opcode = Instruction::PtrToInt;
10556 }
10557 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010558 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010559 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010560 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010561 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010562 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010563 return new StoreInst(NewCast, CastOp);
10564 }
10565 }
10566 }
10567 return 0;
10568}
10569
Chris Lattner2f503e62005-01-31 05:36:43 +000010570Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10571 Value *Val = SI.getOperand(0);
10572 Value *Ptr = SI.getOperand(1);
10573
10574 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010575 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010576 ++NumCombined;
10577 return 0;
10578 }
Chris Lattner836692d2007-01-15 06:51:56 +000010579
10580 // If the RHS is an alloca with a single use, zapify the store, making the
10581 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010582 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010583 if (isa<AllocaInst>(Ptr)) {
10584 EraseInstFromFunction(SI);
10585 ++NumCombined;
10586 return 0;
10587 }
10588
10589 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10590 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10591 GEP->getOperand(0)->hasOneUse()) {
10592 EraseInstFromFunction(SI);
10593 ++NumCombined;
10594 return 0;
10595 }
10596 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010597
Dan Gohman9941f742007-07-20 16:34:21 +000010598 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010599 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10600 if (KnownAlign >
10601 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10602 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010603 SI.setAlignment(KnownAlign);
10604
Chris Lattner9ca96412006-02-08 03:25:32 +000010605 // Do really simple DSE, to catch cases where there are several consequtive
10606 // stores to the same location, separated by a few arithmetic operations. This
10607 // situation often occurs with bitfield accesses.
10608 BasicBlock::iterator BBI = &SI;
10609 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10610 --ScanInsts) {
10611 --BBI;
10612
10613 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10614 // Prev store isn't volatile, and stores to the same location?
10615 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10616 ++NumDeadStore;
10617 ++BBI;
10618 EraseInstFromFunction(*PrevSI);
10619 continue;
10620 }
10621 break;
10622 }
10623
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010624 // If this is a load, we have to stop. However, if the loaded value is from
10625 // the pointer we're loading and is producing the pointer we're storing,
10626 // then *this* store is dead (X = load P; store X -> P).
10627 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010628 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010629 EraseInstFromFunction(SI);
10630 ++NumCombined;
10631 return 0;
10632 }
10633 // Otherwise, this is a load from some other location. Stores before it
10634 // may not be dead.
10635 break;
10636 }
10637
Chris Lattner9ca96412006-02-08 03:25:32 +000010638 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010639 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010640 break;
10641 }
10642
10643
10644 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010645
10646 // store X, null -> turns into 'unreachable' in SimplifyCFG
10647 if (isa<ConstantPointerNull>(Ptr)) {
10648 if (!isa<UndefValue>(Val)) {
10649 SI.setOperand(0, UndefValue::get(Val->getType()));
10650 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010651 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010652 ++NumCombined;
10653 }
10654 return 0; // Do not modify these!
10655 }
10656
10657 // store undef, Ptr -> noop
10658 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010659 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010660 ++NumCombined;
10661 return 0;
10662 }
10663
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010664 // If the pointer destination is a cast, see if we can fold the cast into the
10665 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010666 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010667 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10668 return Res;
10669 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010670 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010671 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10672 return Res;
10673
Chris Lattner408902b2005-09-12 23:23:25 +000010674
10675 // If this store is the last instruction in the basic block, and if the block
10676 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010677 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010678 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010679 if (BI->isUnconditional())
10680 if (SimplifyStoreAtEndOfBlock(SI))
10681 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010682
Chris Lattner2f503e62005-01-31 05:36:43 +000010683 return 0;
10684}
10685
Chris Lattner3284d1f2007-04-15 00:07:55 +000010686/// SimplifyStoreAtEndOfBlock - Turn things like:
10687/// if () { *P = v1; } else { *P = v2 }
10688/// into a phi node with a store in the successor.
10689///
Chris Lattner31755a02007-04-15 01:02:18 +000010690/// Simplify things like:
10691/// *P = v1; if () { *P = v2; }
10692/// into a phi node with a store in the successor.
10693///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010694bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10695 BasicBlock *StoreBB = SI.getParent();
10696
10697 // Check to see if the successor block has exactly two incoming edges. If
10698 // so, see if the other predecessor contains a store to the same location.
10699 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010700 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010701
10702 // Determine whether Dest has exactly two predecessors and, if so, compute
10703 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010704 pred_iterator PI = pred_begin(DestBB);
10705 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010706 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010707 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010708 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010709 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010710 return false;
10711
10712 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010713 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010714 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010715 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010716 }
Chris Lattner31755a02007-04-15 01:02:18 +000010717 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010718 return false;
10719
10720
Chris Lattner31755a02007-04-15 01:02:18 +000010721 // Verify that the other block ends in a branch and is not otherwise empty.
10722 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010723 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010724 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010725 return false;
10726
Chris Lattner31755a02007-04-15 01:02:18 +000010727 // If the other block ends in an unconditional branch, check for the 'if then
10728 // else' case. there is an instruction before the branch.
10729 StoreInst *OtherStore = 0;
10730 if (OtherBr->isUnconditional()) {
10731 // If this isn't a store, or isn't a store to the same location, bail out.
10732 --BBI;
10733 OtherStore = dyn_cast<StoreInst>(BBI);
10734 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10735 return false;
10736 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010737 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010738 // destinations is StoreBB, then we have the if/then case.
10739 if (OtherBr->getSuccessor(0) != StoreBB &&
10740 OtherBr->getSuccessor(1) != StoreBB)
10741 return false;
10742
10743 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010744 // if/then triangle. See if there is a store to the same ptr as SI that
10745 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010746 for (;; --BBI) {
10747 // Check to see if we find the matching store.
10748 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10749 if (OtherStore->getOperand(1) != SI.getOperand(1))
10750 return false;
10751 break;
10752 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010753 // If we find something that may be using the stored value, or if we run
10754 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010755 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10756 BBI == OtherBB->begin())
10757 return false;
10758 }
10759
10760 // In order to eliminate the store in OtherBr, we have to
10761 // make sure nothing reads the stored value in StoreBB.
10762 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10763 // FIXME: This should really be AA driven.
10764 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10765 return false;
10766 }
10767 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010768
Chris Lattner31755a02007-04-15 01:02:18 +000010769 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010770 Value *MergedVal = OtherStore->getOperand(0);
10771 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010772 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010773 PN->reserveOperandSpace(2);
10774 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010775 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10776 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010777 }
10778
10779 // Advance to a place where it is safe to insert the new store and
10780 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010781 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010782 while (isa<PHINode>(BBI)) ++BBI;
10783 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10784 OtherStore->isVolatile()), *BBI);
10785
10786 // Nuke the old stores.
10787 EraseInstFromFunction(SI);
10788 EraseInstFromFunction(*OtherStore);
10789 ++NumCombined;
10790 return true;
10791}
10792
Chris Lattner2f503e62005-01-31 05:36:43 +000010793
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010794Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10795 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010796 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010797 BasicBlock *TrueDest;
10798 BasicBlock *FalseDest;
10799 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10800 !isa<Constant>(X)) {
10801 // Swap Destinations and condition...
10802 BI.setCondition(X);
10803 BI.setSuccessor(0, FalseDest);
10804 BI.setSuccessor(1, TrueDest);
10805 return &BI;
10806 }
10807
Reid Spencere4d87aa2006-12-23 06:05:41 +000010808 // Cannonicalize fcmp_one -> fcmp_oeq
10809 FCmpInst::Predicate FPred; Value *Y;
10810 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10811 TrueDest, FalseDest)))
10812 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10813 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10814 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010815 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010816 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10817 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010818 // Swap Destinations and condition...
10819 BI.setCondition(NewSCC);
10820 BI.setSuccessor(0, FalseDest);
10821 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010822 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010823 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010824 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010825 return &BI;
10826 }
10827
10828 // Cannonicalize icmp_ne -> icmp_eq
10829 ICmpInst::Predicate IPred;
10830 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10831 TrueDest, FalseDest)))
10832 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10833 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10834 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10835 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010836 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010837 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10838 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010839 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010840 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010841 BI.setSuccessor(0, FalseDest);
10842 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010843 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010844 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010845 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010846 return &BI;
10847 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010848
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010849 return 0;
10850}
Chris Lattner0864acf2002-11-04 16:18:53 +000010851
Chris Lattner46238a62004-07-03 00:26:11 +000010852Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10853 Value *Cond = SI.getCondition();
10854 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10855 if (I->getOpcode() == Instruction::Add)
10856 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10857 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10858 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010859 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010860 AddRHS));
10861 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010862 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010863 return &SI;
10864 }
10865 }
10866 return 0;
10867}
10868
Chris Lattner220b0cf2006-03-05 00:22:33 +000010869/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10870/// is to leave as a vector operation.
10871static bool CheapToScalarize(Value *V, bool isConstant) {
10872 if (isa<ConstantAggregateZero>(V))
10873 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010874 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010875 if (isConstant) return true;
10876 // If all elts are the same, we can extract.
10877 Constant *Op0 = C->getOperand(0);
10878 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10879 if (C->getOperand(i) != Op0)
10880 return false;
10881 return true;
10882 }
10883 Instruction *I = dyn_cast<Instruction>(V);
10884 if (!I) return false;
10885
10886 // Insert element gets simplified to the inserted element or is deleted if
10887 // this is constant idx extract element and its a constant idx insertelt.
10888 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10889 isa<ConstantInt>(I->getOperand(2)))
10890 return true;
10891 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10892 return true;
10893 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10894 if (BO->hasOneUse() &&
10895 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10896 CheapToScalarize(BO->getOperand(1), isConstant)))
10897 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010898 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10899 if (CI->hasOneUse() &&
10900 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10901 CheapToScalarize(CI->getOperand(1), isConstant)))
10902 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010903
10904 return false;
10905}
10906
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010907/// Read and decode a shufflevector mask.
10908///
10909/// It turns undef elements into values that are larger than the number of
10910/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010911static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10912 unsigned NElts = SVI->getType()->getNumElements();
10913 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10914 return std::vector<unsigned>(NElts, 0);
10915 if (isa<UndefValue>(SVI->getOperand(2)))
10916 return std::vector<unsigned>(NElts, 2*NElts);
10917
10918 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010919 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010920 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10921 if (isa<UndefValue>(CP->getOperand(i)))
10922 Result.push_back(NElts*2); // undef -> 8
10923 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010924 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010925 return Result;
10926}
10927
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010928/// FindScalarElement - Given a vector and an element number, see if the scalar
10929/// value is already around as a register, for example if it were inserted then
10930/// extracted from the vector.
10931static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010932 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10933 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010934 unsigned Width = PTy->getNumElements();
10935 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010936 return UndefValue::get(PTy->getElementType());
10937
10938 if (isa<UndefValue>(V))
10939 return UndefValue::get(PTy->getElementType());
10940 else if (isa<ConstantAggregateZero>(V))
10941 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010942 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010943 return CP->getOperand(EltNo);
10944 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10945 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010946 if (!isa<ConstantInt>(III->getOperand(2)))
10947 return 0;
10948 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010949
10950 // If this is an insert to the element we are looking for, return the
10951 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010952 if (EltNo == IIElt)
10953 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010954
10955 // Otherwise, the insertelement doesn't modify the value, recurse on its
10956 // vector input.
10957 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010958 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010959 unsigned InEl = getShuffleMask(SVI)[EltNo];
10960 if (InEl < Width)
10961 return FindScalarElement(SVI->getOperand(0), InEl);
10962 else if (InEl < Width*2)
10963 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10964 else
10965 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010966 }
10967
10968 // Otherwise, we don't know.
10969 return 0;
10970}
10971
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010972Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010973
Dan Gohman07a96762007-07-16 14:29:03 +000010974 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010975 if (isa<UndefValue>(EI.getOperand(0)))
10976 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10977
Dan Gohman07a96762007-07-16 14:29:03 +000010978 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010979 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10980 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10981
Reid Spencer9d6565a2007-02-15 02:26:10 +000010982 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010983 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010984 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010985 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010986 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010987 if (C->getOperand(i) != op0) {
10988 op0 = 0;
10989 break;
10990 }
10991 if (op0)
10992 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010993 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010994
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010995 // If extracting a specified index from the vector, see if we can recursively
10996 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010997 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010998 unsigned IndexVal = IdxC->getZExtValue();
10999 unsigned VectorWidth =
11000 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11001
11002 // If this is extracting an invalid index, turn this into undef, to avoid
11003 // crashing the code below.
11004 if (IndexVal >= VectorWidth)
11005 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11006
Chris Lattner867b99f2006-10-05 06:55:50 +000011007 // This instruction only demands the single element from the input vector.
11008 // If the input vector has a single use, simplify it based on this use
11009 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011010 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011011 uint64_t UndefElts;
11012 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000011013 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000011014 UndefElts)) {
11015 EI.setOperand(0, V);
11016 return &EI;
11017 }
11018 }
11019
Reid Spencerb83eb642006-10-20 07:07:24 +000011020 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011021 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011022
11023 // If the this extractelement is directly using a bitcast from a vector of
11024 // the same number of elements, see if we can find the source element from
11025 // it. In this case, we will end up needing to bitcast the scalars.
11026 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11027 if (const VectorType *VT =
11028 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11029 if (VT->getNumElements() == VectorWidth)
11030 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11031 return new BitCastInst(Elt, EI.getType());
11032 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011033 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011034
Chris Lattner73fa49d2006-05-25 22:53:38 +000011035 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011036 if (I->hasOneUse()) {
11037 // Push extractelement into predecessor operation if legal and
11038 // profitable to do so
11039 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011040 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11041 if (CheapToScalarize(BO, isConstantElt)) {
11042 ExtractElementInst *newEI0 =
11043 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11044 EI.getName()+".lhs");
11045 ExtractElementInst *newEI1 =
11046 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11047 EI.getName()+".rhs");
11048 InsertNewInstBefore(newEI0, EI);
11049 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011050 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011051 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011052 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011053 unsigned AS =
11054 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011055 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11056 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011057 GetElementPtrInst *GEP =
11058 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011059 InsertNewInstBefore(GEP, EI);
11060 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011061 }
11062 }
11063 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11064 // Extracting the inserted element?
11065 if (IE->getOperand(2) == EI.getOperand(1))
11066 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11067 // If the inserted and extracted elements are constants, they must not
11068 // be the same value, extract from the pre-inserted value instead.
11069 if (isa<Constant>(IE->getOperand(2)) &&
11070 isa<Constant>(EI.getOperand(1))) {
11071 AddUsesToWorkList(EI);
11072 EI.setOperand(0, IE->getOperand(0));
11073 return &EI;
11074 }
11075 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11076 // If this is extracting an element from a shufflevector, figure out where
11077 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011078 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11079 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011080 Value *Src;
11081 if (SrcIdx < SVI->getType()->getNumElements())
11082 Src = SVI->getOperand(0);
11083 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11084 SrcIdx -= SVI->getType()->getNumElements();
11085 Src = SVI->getOperand(1);
11086 } else {
11087 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011088 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011089 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011090 }
11091 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011092 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011093 return 0;
11094}
11095
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011096/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11097/// elements from either LHS or RHS, return the shuffle mask and true.
11098/// Otherwise, return false.
11099static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11100 std::vector<Constant*> &Mask) {
11101 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11102 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011103 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011104
11105 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011106 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011107 return true;
11108 } else if (V == LHS) {
11109 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011110 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011111 return true;
11112 } else if (V == RHS) {
11113 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011114 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011115 return true;
11116 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11117 // If this is an insert of an extract from some other vector, include it.
11118 Value *VecOp = IEI->getOperand(0);
11119 Value *ScalarOp = IEI->getOperand(1);
11120 Value *IdxOp = IEI->getOperand(2);
11121
Chris Lattnerd929f062006-04-27 21:14:21 +000011122 if (!isa<ConstantInt>(IdxOp))
11123 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011124 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011125
11126 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11127 // Okay, we can handle this if the vector we are insertinting into is
11128 // transitively ok.
11129 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11130 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011131 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011132 return true;
11133 }
11134 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11135 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011136 EI->getOperand(0)->getType() == V->getType()) {
11137 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011138 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011139
11140 // This must be extracting from either LHS or RHS.
11141 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11142 // Okay, we can handle this if the vector we are insertinting into is
11143 // transitively ok.
11144 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11145 // If so, update the mask to reflect the inserted value.
11146 if (EI->getOperand(0) == LHS) {
11147 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011148 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011149 } else {
11150 assert(EI->getOperand(0) == RHS);
11151 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011152 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011153
11154 }
11155 return true;
11156 }
11157 }
11158 }
11159 }
11160 }
11161 // TODO: Handle shufflevector here!
11162
11163 return false;
11164}
11165
11166/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11167/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11168/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011169static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011170 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011171 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011172 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011173 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011174 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011175
11176 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011177 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011178 return V;
11179 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011180 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011181 return V;
11182 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11183 // If this is an insert of an extract from some other vector, include it.
11184 Value *VecOp = IEI->getOperand(0);
11185 Value *ScalarOp = IEI->getOperand(1);
11186 Value *IdxOp = IEI->getOperand(2);
11187
11188 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11189 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11190 EI->getOperand(0)->getType() == V->getType()) {
11191 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011192 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11193 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011194
11195 // Either the extracted from or inserted into vector must be RHSVec,
11196 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011197 if (EI->getOperand(0) == RHS || RHS == 0) {
11198 RHS = EI->getOperand(0);
11199 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011200 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011201 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011202 return V;
11203 }
11204
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011205 if (VecOp == RHS) {
11206 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011207 // Everything but the extracted element is replaced with the RHS.
11208 for (unsigned i = 0; i != NumElts; ++i) {
11209 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011210 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011211 }
11212 return V;
11213 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011214
11215 // If this insertelement is a chain that comes from exactly these two
11216 // vectors, return the vector and the effective shuffle.
11217 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11218 return EI->getOperand(0);
11219
Chris Lattnerefb47352006-04-15 01:39:45 +000011220 }
11221 }
11222 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011223 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011224
11225 // Otherwise, can't do anything fancy. Return an identity vector.
11226 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011227 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011228 return V;
11229}
11230
11231Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11232 Value *VecOp = IE.getOperand(0);
11233 Value *ScalarOp = IE.getOperand(1);
11234 Value *IdxOp = IE.getOperand(2);
11235
Chris Lattner599ded12007-04-09 01:11:16 +000011236 // Inserting an undef or into an undefined place, remove this.
11237 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11238 ReplaceInstUsesWith(IE, VecOp);
11239
Chris Lattnerefb47352006-04-15 01:39:45 +000011240 // If the inserted element was extracted from some other vector, and if the
11241 // indexes are constant, try to turn this into a shufflevector operation.
11242 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11243 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11244 EI->getOperand(0)->getType() == IE.getType()) {
11245 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011246 unsigned ExtractedIdx =
11247 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011248 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011249
11250 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11251 return ReplaceInstUsesWith(IE, VecOp);
11252
11253 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11254 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11255
11256 // If we are extracting a value from a vector, then inserting it right
11257 // back into the same place, just use the input vector.
11258 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11259 return ReplaceInstUsesWith(IE, VecOp);
11260
11261 // We could theoretically do this for ANY input. However, doing so could
11262 // turn chains of insertelement instructions into a chain of shufflevector
11263 // instructions, and right now we do not merge shufflevectors. As such,
11264 // only do this in a situation where it is clear that there is benefit.
11265 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11266 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11267 // the values of VecOp, except then one read from EIOp0.
11268 // Build a new shuffle mask.
11269 std::vector<Constant*> Mask;
11270 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011271 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011272 else {
11273 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011274 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011275 NumVectorElts));
11276 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011277 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011278 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011279 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011280 }
11281
11282 // If this insertelement isn't used by some other insertelement, turn it
11283 // (and any insertelements it points to), into one big shuffle.
11284 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11285 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011286 Value *RHS = 0;
11287 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11288 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11289 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011290 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011291 }
11292 }
11293 }
11294
11295 return 0;
11296}
11297
11298
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011299Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11300 Value *LHS = SVI.getOperand(0);
11301 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011302 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011303
11304 bool MadeChange = false;
11305
Chris Lattner867b99f2006-10-05 06:55:50 +000011306 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011307 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011308 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11309
Chris Lattnere4929dd2007-01-05 07:36:08 +000011310 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011311 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011312 if (isa<UndefValue>(SVI.getOperand(1))) {
11313 // Scan to see if there are any references to the RHS. If so, replace them
11314 // with undef element refs and set MadeChange to true.
11315 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11316 if (Mask[i] >= e && Mask[i] != 2*e) {
11317 Mask[i] = 2*e;
11318 MadeChange = true;
11319 }
11320 }
11321
11322 if (MadeChange) {
11323 // Remap any references to RHS to use LHS.
11324 std::vector<Constant*> Elts;
11325 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11326 if (Mask[i] == 2*e)
11327 Elts.push_back(UndefValue::get(Type::Int32Ty));
11328 else
11329 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11330 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011331 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011332 }
11333 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011334
Chris Lattner863bcff2006-05-25 23:48:38 +000011335 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11336 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11337 if (LHS == RHS || isa<UndefValue>(LHS)) {
11338 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011339 // shuffle(undef,undef,mask) -> undef.
11340 return ReplaceInstUsesWith(SVI, LHS);
11341 }
11342
Chris Lattner863bcff2006-05-25 23:48:38 +000011343 // Remap any references to RHS to use LHS.
11344 std::vector<Constant*> Elts;
11345 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011346 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011347 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011348 else {
11349 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11350 (Mask[i] < e && isa<UndefValue>(LHS)))
11351 Mask[i] = 2*e; // Turn into undef.
11352 else
11353 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011354 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011355 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011356 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011357 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011358 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011359 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011360 LHS = SVI.getOperand(0);
11361 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011362 MadeChange = true;
11363 }
11364
Chris Lattner7b2e27922006-05-26 00:29:06 +000011365 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011366 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011367
Chris Lattner863bcff2006-05-25 23:48:38 +000011368 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11369 if (Mask[i] >= e*2) continue; // Ignore undef values.
11370 // Is this an identity shuffle of the LHS value?
11371 isLHSID &= (Mask[i] == i);
11372
11373 // Is this an identity shuffle of the RHS value?
11374 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011375 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011376
Chris Lattner863bcff2006-05-25 23:48:38 +000011377 // Eliminate identity shuffles.
11378 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11379 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011380
Chris Lattner7b2e27922006-05-26 00:29:06 +000011381 // If the LHS is a shufflevector itself, see if we can combine it with this
11382 // one without producing an unusual shuffle. Here we are really conservative:
11383 // we are absolutely afraid of producing a shuffle mask not in the input
11384 // program, because the code gen may not be smart enough to turn a merged
11385 // shuffle into two specific shuffles: it may produce worse code. As such,
11386 // we only merge two shuffles if the result is one of the two input shuffle
11387 // masks. In this case, merging the shuffles just removes one instruction,
11388 // which we know is safe. This is good for things like turning:
11389 // (splat(splat)) -> splat.
11390 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11391 if (isa<UndefValue>(RHS)) {
11392 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11393
11394 std::vector<unsigned> NewMask;
11395 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11396 if (Mask[i] >= 2*e)
11397 NewMask.push_back(2*e);
11398 else
11399 NewMask.push_back(LHSMask[Mask[i]]);
11400
11401 // If the result mask is equal to the src shuffle or this shuffle mask, do
11402 // the replacement.
11403 if (NewMask == LHSMask || NewMask == Mask) {
11404 std::vector<Constant*> Elts;
11405 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11406 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011407 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011408 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011409 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011410 }
11411 }
11412 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11413 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011414 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011415 }
11416 }
11417 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011418
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011419 return MadeChange ? &SVI : 0;
11420}
11421
11422
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011423
Chris Lattnerea1c4542004-12-08 23:43:58 +000011424
11425/// TryToSinkInstruction - Try to move the specified instruction from its
11426/// current block into the beginning of DestBlock, which can only happen if it's
11427/// safe to move the instruction past all of the instructions between it and the
11428/// end of its block.
11429static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11430 assert(I->hasOneUse() && "Invariants didn't hold!");
11431
Chris Lattner108e9022005-10-27 17:13:11 +000011432 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011433 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11434 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011435
Chris Lattnerea1c4542004-12-08 23:43:58 +000011436 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011437 if (isa<AllocaInst>(I) && I->getParent() ==
11438 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011439 return false;
11440
Chris Lattner96a52a62004-12-09 07:14:34 +000011441 // We can only sink load instructions if there is nothing between the load and
11442 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011443 if (I->mayReadFromMemory()) {
11444 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011445 Scan != E; ++Scan)
11446 if (Scan->mayWriteToMemory())
11447 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011448 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011449
11450 BasicBlock::iterator InsertPos = DestBlock->begin();
11451 while (isa<PHINode>(InsertPos)) ++InsertPos;
11452
Chris Lattner4bc5f802005-08-08 19:11:57 +000011453 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011454 ++NumSunkInst;
11455 return true;
11456}
11457
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011458
11459/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11460/// all reachable code to the worklist.
11461///
11462/// This has a couple of tricks to make the code faster and more powerful. In
11463/// particular, we constant fold and DCE instructions as we go, to avoid adding
11464/// them to the worklist (this significantly speeds up instcombine on code where
11465/// many instructions are dead or constant). Additionally, if we find a branch
11466/// whose condition is a known constant, we only visit the reachable successors.
11467///
11468static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011469 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011470 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011471 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011472 std::vector<BasicBlock*> Worklist;
11473 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011474
Chris Lattner2c7718a2007-03-23 19:17:18 +000011475 while (!Worklist.empty()) {
11476 BB = Worklist.back();
11477 Worklist.pop_back();
11478
11479 // We have now visited this block! If we've already been here, ignore it.
11480 if (!Visited.insert(BB)) continue;
11481
11482 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11483 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011484
Chris Lattner2c7718a2007-03-23 19:17:18 +000011485 // DCE instruction if trivially dead.
11486 if (isInstructionTriviallyDead(Inst)) {
11487 ++NumDeadInst;
11488 DOUT << "IC: DCE: " << *Inst;
11489 Inst->eraseFromParent();
11490 continue;
11491 }
11492
11493 // ConstantProp instruction if trivially constant.
11494 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11495 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11496 Inst->replaceAllUsesWith(C);
11497 ++NumConstProp;
11498 Inst->eraseFromParent();
11499 continue;
11500 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011501
Chris Lattner2c7718a2007-03-23 19:17:18 +000011502 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011503 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011504
11505 // Recursively visit successors. If this is a branch or switch on a
11506 // constant, only visit the reachable successor.
11507 TerminatorInst *TI = BB->getTerminator();
11508 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11509 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11510 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011511 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011512 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011513 continue;
11514 }
11515 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11516 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11517 // See if this is an explicit destination.
11518 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11519 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011520 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011521 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011522 continue;
11523 }
11524
11525 // Otherwise it is the default destination.
11526 Worklist.push_back(SI->getSuccessor(0));
11527 continue;
11528 }
11529 }
11530
11531 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11532 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011533 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011534}
11535
Chris Lattnerec9c3582007-03-03 02:04:50 +000011536bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011537 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011538 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011539
11540 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11541 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011542
Chris Lattnerb3d59702005-07-07 20:40:38 +000011543 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011544 // Do a depth-first traversal of the function, populate the worklist with
11545 // the reachable instructions. Ignore blocks that are not reachable. Keep
11546 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011547 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011548 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011549
Chris Lattnerb3d59702005-07-07 20:40:38 +000011550 // Do a quick scan over the function. If we find any blocks that are
11551 // unreachable, remove any instructions inside of them. This prevents
11552 // the instcombine code from having to deal with some bad special cases.
11553 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11554 if (!Visited.count(BB)) {
11555 Instruction *Term = BB->getTerminator();
11556 while (Term != BB->begin()) { // Remove instrs bottom-up
11557 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011558
Bill Wendlingb7427032006-11-26 09:46:52 +000011559 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011560 ++NumDeadInst;
11561
11562 if (!I->use_empty())
11563 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11564 I->eraseFromParent();
11565 }
11566 }
11567 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011568
Chris Lattnerdbab3862007-03-02 21:28:56 +000011569 while (!Worklist.empty()) {
11570 Instruction *I = RemoveOneFromWorkList();
11571 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011572
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011573 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011574 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011575 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011576 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011577 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011578 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011579
Bill Wendlingb7427032006-11-26 09:46:52 +000011580 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011581
11582 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011583 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011584 continue;
11585 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011586
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011587 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011588 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011589 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011590
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011591 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011592 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011593 ReplaceInstUsesWith(*I, C);
11594
Chris Lattner62b14df2002-09-02 04:59:56 +000011595 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011596 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011597 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011598 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011599 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011600
Chris Lattnerea1c4542004-12-08 23:43:58 +000011601 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011602 // FIXME: Remove GetResultInst test when first class support for aggregates
11603 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011604 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011605 BasicBlock *BB = I->getParent();
11606 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11607 if (UserParent != BB) {
11608 bool UserIsSuccessor = false;
11609 // See if the user is one of our successors.
11610 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11611 if (*SI == UserParent) {
11612 UserIsSuccessor = true;
11613 break;
11614 }
11615
11616 // If the user is one of our immediate successors, and if that successor
11617 // only has us as a predecessors (we'd have to split the critical edge
11618 // otherwise), we can keep going.
11619 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11620 next(pred_begin(UserParent)) == pred_end(UserParent))
11621 // Okay, the CFG is simple enough, try to sink this instruction.
11622 Changed |= TryToSinkInstruction(I, UserParent);
11623 }
11624 }
11625
Chris Lattner8a2a3112001-12-14 16:52:21 +000011626 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011627#ifndef NDEBUG
11628 std::string OrigI;
11629#endif
11630 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011631 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011632 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011633 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011634 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011635 DOUT << "IC: Old = " << *I
11636 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011637
Chris Lattnerf523d062004-06-09 05:08:07 +000011638 // Everything uses the new instruction now.
11639 I->replaceAllUsesWith(Result);
11640
11641 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011642 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011643 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011644
Chris Lattner6934a042007-02-11 01:23:03 +000011645 // Move the name to the new instruction first.
11646 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011647
11648 // Insert the new instruction into the basic block...
11649 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011650 BasicBlock::iterator InsertPos = I;
11651
11652 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11653 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11654 ++InsertPos;
11655
11656 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011657
Chris Lattner00d51312004-05-01 23:27:23 +000011658 // Make sure that we reprocess all operands now that we reduced their
11659 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011660 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011661
Chris Lattnerf523d062004-06-09 05:08:07 +000011662 // Instructions can end up on the worklist more than once. Make sure
11663 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011664 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011665
11666 // Erase the old instruction.
11667 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011668 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011669#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011670 DOUT << "IC: Mod = " << OrigI
11671 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011672#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011673
Chris Lattner90ac28c2002-08-02 19:29:35 +000011674 // If the instruction was modified, it's possible that it is now dead.
11675 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011676 if (isInstructionTriviallyDead(I)) {
11677 // Make sure we process all operands now that we are reducing their
11678 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011679 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011680
Chris Lattner00d51312004-05-01 23:27:23 +000011681 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011682 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011683 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011684 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011685 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011686 AddToWorkList(I);
11687 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011688 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011689 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011690 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011691 }
11692 }
11693
Chris Lattnerec9c3582007-03-03 02:04:50 +000011694 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011695
11696 // Do an explicit clear, this shrinks the map if needed.
11697 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011698 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011699}
11700
Chris Lattnerec9c3582007-03-03 02:04:50 +000011701
11702bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011703 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11704
Chris Lattnerec9c3582007-03-03 02:04:50 +000011705 bool EverMadeChange = false;
11706
11707 // Iterate while there is work to do.
11708 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011709 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011710 EverMadeChange = true;
11711 return EverMadeChange;
11712}
11713
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011714FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011715 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011716}
Brian Gaeked0fde302003-11-11 22:41:34 +000011717