blob: 10d3344598da04baa9b17d2f02a7c33b7e97b7ba [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;
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000837 // FALL THROUGH and handle them the same as zext/trunc.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000838 case Instruction::ZExt:
Zhou Sheng771dbf72007-03-13 02:23:10 +0000839 case Instruction::Trunc: {
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000840 // Note that we handle pointer operands here because of inttoptr/ptrtoint
841 // which fall through here.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000842 const Type *SrcTy = I->getOperand(0)->getType();
843 uint32_t SrcBitWidth = TD ?
844 TD->getTypeSizeInBits(SrcTy) :
845 SrcTy->getPrimitiveSizeInBits();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000846 APInt MaskIn(Mask);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000847 MaskIn.zextOrTrunc(SrcBitWidth);
848 KnownZero.zextOrTrunc(SrcBitWidth);
849 KnownOne.zextOrTrunc(SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000850 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000851 KnownZero.zextOrTrunc(BitWidth);
852 KnownOne.zextOrTrunc(BitWidth);
853 // Any top bits are known to be zero.
854 if (BitWidth > SrcBitWidth)
855 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000856 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000857 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000858 case Instruction::BitCast: {
859 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000860 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000861 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
862 return;
863 }
864 break;
865 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000866 case Instruction::SExt: {
867 // Compute the bits in the result that are not present in the input.
868 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000869 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000870
Zhou Shengaa305ab2007-03-28 02:19:03 +0000871 APInt MaskIn(Mask);
872 MaskIn.trunc(SrcBitWidth);
873 KnownZero.trunc(SrcBitWidth);
874 KnownOne.trunc(SrcBitWidth);
875 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000876 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000877 KnownZero.zext(BitWidth);
878 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000879
880 // If the sign bit of the input is known set or clear, then we know the
881 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000882 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000883 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000884 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000885 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000886 return;
887 }
888 case Instruction::Shl:
889 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
890 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000891 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000892 APInt Mask2(Mask.lshr(ShiftAmt));
893 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000894 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000895 KnownZero <<= ShiftAmt;
896 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000897 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000898 return;
899 }
900 break;
901 case Instruction::LShr:
902 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
903 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
904 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000905 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000906
907 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000908 APInt Mask2(Mask.shl(ShiftAmt));
909 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000910 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
911 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
912 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000913 // high bits known zero.
914 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000915 return;
916 }
917 break;
918 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000919 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000920 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
921 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000922 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000923
924 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000925 APInt Mask2(Mask.shl(ShiftAmt));
926 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000927 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
928 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
929 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
930
Zhou Shengaa305ab2007-03-28 02:19:03 +0000931 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
932 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000933 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000934 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000935 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000936 return;
937 }
938 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000939 case Instruction::Sub: {
940 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
941 // We know that the top bits of C-X are clear if X contains less bits
942 // than C (i.e. no wrap-around can happen). For example, 20-X is
943 // positive if we can prove that X is >= 0 and < 16.
944 if (!CLHS->getValue().isNegative()) {
945 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
946 // NLZ can't be BitWidth with no sign bit
947 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000948 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
949 Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000950
Dan Gohman23e8b712008-04-28 17:02:21 +0000951 // If all of the MaskV bits are known to be zero, then we know the
952 // output top bits are zero, because we now know that the output is
953 // from [0-C].
954 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohmaneee962e2008-04-10 18:43:06 +0000955 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
956 // Top bits known zero.
957 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000958 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000959 }
960 }
961 }
962 // fall through
Duncan Sands1d57a752008-03-21 08:32:17 +0000963 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000964 // Output known-0 bits are known if clear or set in both the low clear bits
965 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
966 // low 3 bits clear.
Dan Gohman23e8b712008-04-28 17:02:21 +0000967 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
968 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
969 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
970 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
971
972 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
973 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
974 KnownZeroOut = std::min(KnownZeroOut,
975 KnownZero2.countTrailingOnes());
976
977 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000978 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000979 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000980 case Instruction::SRem:
981 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
982 APInt RA = Rem->getValue();
983 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +0000984 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000985 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
986 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
987
988 // The sign of a remainder is equal to the sign of the first
989 // operand (zero being positive).
990 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
991 KnownZero2 |= ~LowBits;
992 else if (KnownOne2[BitWidth-1])
993 KnownOne2 |= ~LowBits;
994
995 KnownZero |= KnownZero2 & Mask;
996 KnownOne |= KnownOne2 & Mask;
997
998 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
999 }
1000 }
1001 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001002 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001003 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1004 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001005 if (RA.isPowerOf2()) {
1006 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001007 APInt Mask2 = LowBits & Mask;
1008 KnownZero |= ~LowBits & Mask;
1009 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1010 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001011 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001012 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001013 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001014
1015 // Since the result is less than or equal to either operand, any leading
1016 // zero bits in either operand must also exist in the result.
1017 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1018 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1019 Depth+1);
1020 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1021 Depth+1);
1022
1023 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1024 KnownZero2.countLeadingOnes());
1025 KnownOne.clear();
1026 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001027 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001028 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00001029
1030 case Instruction::Alloca:
1031 case Instruction::Malloc: {
1032 AllocationInst *AI = cast<AllocationInst>(V);
1033 unsigned Align = AI->getAlignment();
1034 if (Align == 0 && TD) {
1035 if (isa<AllocaInst>(AI))
1036 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1037 else if (isa<MallocInst>(AI)) {
1038 // Malloc returns maximally aligned memory.
1039 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1040 Align =
1041 std::max(Align,
1042 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1043 Align =
1044 std::max(Align,
1045 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1046 }
1047 }
1048
1049 if (Align > 0)
1050 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1051 CountTrailingZeros_32(Align));
1052 break;
1053 }
1054 case Instruction::GetElementPtr: {
1055 // Analyze all of the subscripts of this getelementptr instruction
1056 // to determine if we can prove known low zero bits.
1057 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1058 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1059 ComputeMaskedBits(I->getOperand(0), LocalMask,
1060 LocalKnownZero, LocalKnownOne, Depth+1);
1061 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1062
1063 gep_type_iterator GTI = gep_type_begin(I);
1064 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1065 Value *Index = I->getOperand(i);
1066 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1067 // Handle struct member offset arithmetic.
1068 if (!TD) return;
1069 const StructLayout *SL = TD->getStructLayout(STy);
1070 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1071 uint64_t Offset = SL->getElementOffset(Idx);
1072 TrailZ = std::min(TrailZ,
1073 CountTrailingZeros_64(Offset));
1074 } else {
1075 // Handle array index arithmetic.
1076 const Type *IndexedTy = GTI.getIndexedType();
1077 if (!IndexedTy->isSized()) return;
1078 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1079 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1080 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1081 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1082 ComputeMaskedBits(Index, LocalMask,
1083 LocalKnownZero, LocalKnownOne, Depth+1);
1084 TrailZ = std::min(TrailZ,
1085 CountTrailingZeros_64(TypeSize) +
1086 LocalKnownZero.countTrailingOnes());
1087 }
1088 }
1089
1090 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1091 break;
1092 }
1093 case Instruction::PHI: {
1094 PHINode *P = cast<PHINode>(I);
1095 // Handle the case of a simple two-predecessor recurrence PHI.
1096 // There's a lot more that could theoretically be done here, but
1097 // this is sufficient to catch some interesting cases.
1098 if (P->getNumIncomingValues() == 2) {
1099 for (unsigned i = 0; i != 2; ++i) {
1100 Value *L = P->getIncomingValue(i);
1101 Value *R = P->getIncomingValue(!i);
1102 User *LU = dyn_cast<User>(L);
1103 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1104 // Check for operations that have the property that if
1105 // both their operands have low zero bits, the result
1106 // will have low zero bits.
1107 if (Opcode == Instruction::Add ||
1108 Opcode == Instruction::Sub ||
1109 Opcode == Instruction::And ||
1110 Opcode == Instruction::Or ||
1111 Opcode == Instruction::Mul) {
1112 Value *LL = LU->getOperand(0);
1113 Value *LR = LU->getOperand(1);
1114 // Find a recurrence.
1115 if (LL == I)
1116 L = LR;
1117 else if (LR == I)
1118 L = LL;
1119 else
1120 break;
1121 // Ok, we have a PHI of the form L op= R. Check for low
1122 // zero bits.
1123 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1124 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1125 Mask2 = APInt::getLowBitsSet(BitWidth,
1126 KnownZero2.countTrailingOnes());
1127 KnownOne2.clear();
1128 KnownZero2.clear();
1129 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1130 KnownZero = Mask &
1131 APInt::getLowBitsSet(BitWidth,
1132 KnownZero2.countTrailingOnes());
1133 break;
1134 }
1135 }
1136 }
1137 break;
1138 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001139 case Instruction::Call:
1140 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1141 switch (II->getIntrinsicID()) {
1142 default: break;
1143 case Intrinsic::ctpop:
1144 case Intrinsic::ctlz:
1145 case Intrinsic::cttz: {
1146 unsigned LowBits = Log2_32(BitWidth)+1;
1147 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1148 break;
1149 }
1150 }
1151 }
1152 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +00001153 }
1154}
1155
Reid Spencere7816b52007-03-08 01:52:58 +00001156/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1157/// this predicate to simplify operations downstream. Mask is known to be zero
1158/// for bits that V cannot have.
Dan Gohmaneee962e2008-04-10 18:43:06 +00001159bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1160 unsigned Depth) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001161 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001162 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1163 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1164 return (KnownZero & Mask) == Mask;
1165}
1166
Chris Lattner255d8912006-02-11 09:31:47 +00001167/// ShrinkDemandedConstant - Check to see if the specified operand of the
1168/// specified instruction is a constant integer. If so, check to see if there
1169/// are any bits set in the constant that are not demanded. If so, shrink the
1170/// constant and return true.
1171static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001172 APInt Demanded) {
1173 assert(I && "No instruction?");
1174 assert(OpNo < I->getNumOperands() && "Operand index too large");
1175
1176 // If the operand is not a constant integer, nothing to do.
1177 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1178 if (!OpC) return false;
1179
1180 // If there are no bits set that aren't demanded, nothing to do.
1181 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1182 if ((~Demanded & OpC->getValue()) == 0)
1183 return false;
1184
1185 // This instruction is producing bits that are not demanded. Shrink the RHS.
1186 Demanded &= OpC->getValue();
1187 I->setOperand(OpNo, ConstantInt::get(Demanded));
1188 return true;
1189}
1190
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001191// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1192// set of known zero and one bits, compute the maximum and minimum values that
1193// could have the specified known zero and known one bits, returning them in
1194// min/max.
1195static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +00001196 const APInt& KnownZero,
1197 const APInt& KnownOne,
1198 APInt& Min, APInt& Max) {
1199 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1200 assert(KnownZero.getBitWidth() == BitWidth &&
1201 KnownOne.getBitWidth() == BitWidth &&
1202 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1203 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001204 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001205
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001206 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1207 // bit if it is unknown.
1208 Min = KnownOne;
1209 Max = KnownOne|UnknownBits;
1210
Zhou Sheng4acf1552007-03-28 05:15:57 +00001211 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001212 Min.set(BitWidth-1);
1213 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001214 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001215}
1216
1217// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1218// a set of known zero and one bits, compute the maximum and minimum values that
1219// could have the specified known zero and known one bits, returning them in
1220// min/max.
1221static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001222 const APInt &KnownZero,
1223 const APInt &KnownOne,
1224 APInt &Min, APInt &Max) {
1225 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +00001226 assert(KnownZero.getBitWidth() == BitWidth &&
1227 KnownOne.getBitWidth() == BitWidth &&
1228 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1229 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001230 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001231
1232 // The minimum value is when the unknown bits are all zeros.
1233 Min = KnownOne;
1234 // The maximum value is when the unknown bits are all ones.
1235 Max = KnownOne|UnknownBits;
1236}
Chris Lattner255d8912006-02-11 09:31:47 +00001237
Reid Spencer8cb68342007-03-12 17:25:59 +00001238/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1239/// value based on the demanded bits. When this function is called, it is known
1240/// that only the bits set in DemandedMask of the result of V are ever used
1241/// downstream. Consequently, depending on the mask and V, it may be possible
1242/// to replace V with a constant or one of its operands. In such cases, this
1243/// function does the replacement and returns true. In all other cases, it
1244/// returns false after analyzing the expression and setting KnownOne and known
1245/// to be one in the expression. KnownZero contains all the bits that are known
1246/// to be zero in the expression. These are provided to potentially allow the
1247/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1248/// the expression. KnownOne and KnownZero always follow the invariant that
1249/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1250/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1251/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1252/// and KnownOne must all be the same.
1253bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1254 APInt& KnownZero, APInt& KnownOne,
1255 unsigned Depth) {
1256 assert(V != 0 && "Null pointer of Value???");
1257 assert(Depth <= 6 && "Limit Search Depth");
1258 uint32_t BitWidth = DemandedMask.getBitWidth();
1259 const IntegerType *VTy = cast<IntegerType>(V->getType());
1260 assert(VTy->getBitWidth() == BitWidth &&
1261 KnownZero.getBitWidth() == BitWidth &&
1262 KnownOne.getBitWidth() == BitWidth &&
1263 "Value *V, DemandedMask, KnownZero and KnownOne \
1264 must have same BitWidth");
1265 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1266 // We know all of the bits for a constant!
1267 KnownOne = CI->getValue() & DemandedMask;
1268 KnownZero = ~KnownOne & DemandedMask;
1269 return false;
1270 }
1271
Zhou Sheng96704452007-03-14 03:21:24 +00001272 KnownZero.clear();
1273 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001274 if (!V->hasOneUse()) { // Other users may use these bits.
1275 if (Depth != 0) { // Not at the root.
1276 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1277 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1278 return false;
1279 }
1280 // If this is the root being simplified, allow it to have multiple uses,
1281 // just set the DemandedMask to all bits.
1282 DemandedMask = APInt::getAllOnesValue(BitWidth);
1283 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1284 if (V != UndefValue::get(VTy))
1285 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1286 return false;
1287 } else if (Depth == 6) { // Limit search depth.
1288 return false;
1289 }
1290
1291 Instruction *I = dyn_cast<Instruction>(V);
1292 if (!I) return false; // Only analyze instructions.
1293
Reid Spencer8cb68342007-03-12 17:25:59 +00001294 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1295 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1296 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001297 default:
1298 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1299 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001300 case Instruction::And:
1301 // If either the LHS or the RHS are Zero, the result is zero.
1302 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1303 RHSKnownZero, RHSKnownOne, Depth+1))
1304 return true;
1305 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1306 "Bits known to be one AND zero?");
1307
1308 // If something is known zero on the RHS, the bits aren't demanded on the
1309 // LHS.
1310 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1311 LHSKnownZero, LHSKnownOne, Depth+1))
1312 return true;
1313 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1314 "Bits known to be one AND zero?");
1315
1316 // If all of the demanded bits are known 1 on one side, return the other.
1317 // These bits cannot contribute to the result of the 'and'.
1318 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1319 (DemandedMask & ~LHSKnownZero))
1320 return UpdateValueUsesWith(I, I->getOperand(0));
1321 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1322 (DemandedMask & ~RHSKnownZero))
1323 return UpdateValueUsesWith(I, I->getOperand(1));
1324
1325 // If all of the demanded bits in the inputs are known zeros, return zero.
1326 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1327 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1328
1329 // If the RHS is a constant, see if we can simplify it.
1330 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1331 return UpdateValueUsesWith(I, I);
1332
1333 // Output known-1 bits are only known if set in both the LHS & RHS.
1334 RHSKnownOne &= LHSKnownOne;
1335 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1336 RHSKnownZero |= LHSKnownZero;
1337 break;
1338 case Instruction::Or:
1339 // If either the LHS or the RHS are One, the result is One.
1340 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1341 RHSKnownZero, RHSKnownOne, Depth+1))
1342 return true;
1343 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1344 "Bits known to be one AND zero?");
1345 // If something is known one on the RHS, the bits aren't demanded on the
1346 // LHS.
1347 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1348 LHSKnownZero, LHSKnownOne, Depth+1))
1349 return true;
1350 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1351 "Bits known to be one AND zero?");
1352
1353 // If all of the demanded bits are known zero on one side, return the other.
1354 // These bits cannot contribute to the result of the 'or'.
1355 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1356 (DemandedMask & ~LHSKnownOne))
1357 return UpdateValueUsesWith(I, I->getOperand(0));
1358 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1359 (DemandedMask & ~RHSKnownOne))
1360 return UpdateValueUsesWith(I, I->getOperand(1));
1361
1362 // If all of the potentially set bits on one side are known to be set on
1363 // the other side, just use the 'other' side.
1364 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1365 (DemandedMask & (~RHSKnownZero)))
1366 return UpdateValueUsesWith(I, I->getOperand(0));
1367 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1368 (DemandedMask & (~LHSKnownZero)))
1369 return UpdateValueUsesWith(I, I->getOperand(1));
1370
1371 // If the RHS is a constant, see if we can simplify it.
1372 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1373 return UpdateValueUsesWith(I, I);
1374
1375 // Output known-0 bits are only known if clear in both the LHS & RHS.
1376 RHSKnownZero &= LHSKnownZero;
1377 // Output known-1 are known to be set if set in either the LHS | RHS.
1378 RHSKnownOne |= LHSKnownOne;
1379 break;
1380 case Instruction::Xor: {
1381 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1382 RHSKnownZero, RHSKnownOne, Depth+1))
1383 return true;
1384 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1385 "Bits known to be one AND zero?");
1386 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1387 LHSKnownZero, LHSKnownOne, Depth+1))
1388 return true;
1389 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1390 "Bits known to be one AND zero?");
1391
1392 // If all of the demanded bits are known zero on one side, return the other.
1393 // These bits cannot contribute to the result of the 'xor'.
1394 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1395 return UpdateValueUsesWith(I, I->getOperand(0));
1396 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1397 return UpdateValueUsesWith(I, I->getOperand(1));
1398
1399 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1400 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1401 (RHSKnownOne & LHSKnownOne);
1402 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1403 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1404 (RHSKnownOne & LHSKnownZero);
1405
1406 // If all of the demanded bits are known to be zero on one side or the
1407 // other, turn this into an *inclusive* or.
1408 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1409 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1410 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001411 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001412 I->getName());
1413 InsertNewInstBefore(Or, *I);
1414 return UpdateValueUsesWith(I, Or);
1415 }
1416
1417 // If all of the demanded bits on one side are known, and all of the set
1418 // bits on that side are also known to be set on the other side, turn this
1419 // into an AND, as we know the bits will be cleared.
1420 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1421 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1422 // all known
1423 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1424 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1425 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001426 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +00001427 InsertNewInstBefore(And, *I);
1428 return UpdateValueUsesWith(I, And);
1429 }
1430 }
1431
1432 // If the RHS is a constant, see if we can simplify it.
1433 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1434 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1435 return UpdateValueUsesWith(I, I);
1436
1437 RHSKnownZero = KnownZeroOut;
1438 RHSKnownOne = KnownOneOut;
1439 break;
1440 }
1441 case Instruction::Select:
1442 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1443 RHSKnownZero, RHSKnownOne, Depth+1))
1444 return true;
1445 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1446 LHSKnownZero, LHSKnownOne, Depth+1))
1447 return true;
1448 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1449 "Bits known to be one AND zero?");
1450 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1451 "Bits known to be one AND zero?");
1452
1453 // If the operands are constants, see if we can simplify them.
1454 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1455 return UpdateValueUsesWith(I, I);
1456 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1457 return UpdateValueUsesWith(I, I);
1458
1459 // Only known if known in both the LHS and RHS.
1460 RHSKnownOne &= LHSKnownOne;
1461 RHSKnownZero &= LHSKnownZero;
1462 break;
1463 case Instruction::Trunc: {
1464 uint32_t truncBf =
1465 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001466 DemandedMask.zext(truncBf);
1467 RHSKnownZero.zext(truncBf);
1468 RHSKnownOne.zext(truncBf);
1469 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1470 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001471 return true;
1472 DemandedMask.trunc(BitWidth);
1473 RHSKnownZero.trunc(BitWidth);
1474 RHSKnownOne.trunc(BitWidth);
1475 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1476 "Bits known to be one AND zero?");
1477 break;
1478 }
1479 case Instruction::BitCast:
1480 if (!I->getOperand(0)->getType()->isInteger())
1481 return false;
1482
1483 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1484 RHSKnownZero, RHSKnownOne, Depth+1))
1485 return true;
1486 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1487 "Bits known to be one AND zero?");
1488 break;
1489 case Instruction::ZExt: {
1490 // Compute the bits in the result that are not present in the input.
1491 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001492 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001493
Zhou Shengd48653a2007-03-29 04:45:55 +00001494 DemandedMask.trunc(SrcBitWidth);
1495 RHSKnownZero.trunc(SrcBitWidth);
1496 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001497 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1498 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001499 return true;
1500 DemandedMask.zext(BitWidth);
1501 RHSKnownZero.zext(BitWidth);
1502 RHSKnownOne.zext(BitWidth);
1503 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1504 "Bits known to be one AND zero?");
1505 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001506 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001507 break;
1508 }
1509 case Instruction::SExt: {
1510 // Compute the bits in the result that are not present in the input.
1511 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001512 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001513
Reid Spencer8cb68342007-03-12 17:25:59 +00001514 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001515 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001516
Zhou Sheng01542f32007-03-29 02:26:30 +00001517 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001518 // If any of the sign extended bits are demanded, we know that the sign
1519 // bit is demanded.
1520 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001521 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001522
Zhou Shengd48653a2007-03-29 04:45:55 +00001523 InputDemandedBits.trunc(SrcBitWidth);
1524 RHSKnownZero.trunc(SrcBitWidth);
1525 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001526 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1527 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001528 return true;
1529 InputDemandedBits.zext(BitWidth);
1530 RHSKnownZero.zext(BitWidth);
1531 RHSKnownOne.zext(BitWidth);
1532 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1533 "Bits known to be one AND zero?");
1534
1535 // If the sign bit of the input is known set or clear, then we know the
1536 // top bits of the result.
1537
1538 // If the input sign bit is known zero, or if the NewBits are not demanded
1539 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001540 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001541 {
1542 // Convert to ZExt cast
1543 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1544 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001545 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001546 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001547 }
1548 break;
1549 }
1550 case Instruction::Add: {
1551 // Figure out what the input bits are. If the top bits of the and result
1552 // are not demanded, then the add doesn't demand them from its input
1553 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001554 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001555
1556 // If there is a constant on the RHS, there are a variety of xformations
1557 // we can do.
1558 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1559 // If null, this should be simplified elsewhere. Some of the xforms here
1560 // won't work if the RHS is zero.
1561 if (RHS->isZero())
1562 break;
1563
1564 // If the top bit of the output is demanded, demand everything from the
1565 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001566 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001567
1568 // Find information about known zero/one bits in the input.
1569 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1570 LHSKnownZero, LHSKnownOne, Depth+1))
1571 return true;
1572
1573 // If the RHS of the add has bits set that can't affect the input, reduce
1574 // the constant.
1575 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1576 return UpdateValueUsesWith(I, I);
1577
1578 // Avoid excess work.
1579 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1580 break;
1581
1582 // Turn it into OR if input bits are zero.
1583 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1584 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001585 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001586 I->getName());
1587 InsertNewInstBefore(Or, *I);
1588 return UpdateValueUsesWith(I, Or);
1589 }
1590
1591 // We can say something about the output known-zero and known-one bits,
1592 // depending on potential carries from the input constant and the
1593 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1594 // bits set and the RHS constant is 0x01001, then we know we have a known
1595 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1596
1597 // To compute this, we first compute the potential carry bits. These are
1598 // the bits which may be modified. I'm not aware of a better way to do
1599 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001600 const APInt& RHSVal = RHS->getValue();
1601 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001602
1603 // Now that we know which bits have carries, compute the known-1/0 sets.
1604
1605 // Bits are known one if they are known zero in one operand and one in the
1606 // other, and there is no input carry.
1607 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1608 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1609
1610 // Bits are known zero if they are known zero in both operands and there
1611 // is no input carry.
1612 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1613 } else {
1614 // If the high-bits of this ADD are not demanded, then it does not demand
1615 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001616 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001617 // Right fill the mask of bits for this ADD to demand the most
1618 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001619 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001620 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1621 LHSKnownZero, LHSKnownOne, Depth+1))
1622 return true;
1623 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1624 LHSKnownZero, LHSKnownOne, Depth+1))
1625 return true;
1626 }
1627 }
1628 break;
1629 }
1630 case Instruction::Sub:
1631 // If the high-bits of this SUB are not demanded, then it does not demand
1632 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001633 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001634 // Right fill the mask of bits for this SUB to demand the most
1635 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001636 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001637 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001638 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1639 LHSKnownZero, LHSKnownOne, Depth+1))
1640 return true;
1641 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1642 LHSKnownZero, LHSKnownOne, Depth+1))
1643 return true;
1644 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001645 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1646 // the known zeros and ones.
1647 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001648 break;
1649 case Instruction::Shl:
1650 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001651 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001652 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1653 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001654 RHSKnownZero, RHSKnownOne, Depth+1))
1655 return true;
1656 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1657 "Bits known to be one AND zero?");
1658 RHSKnownZero <<= ShiftAmt;
1659 RHSKnownOne <<= ShiftAmt;
1660 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001661 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001662 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001663 }
1664 break;
1665 case Instruction::LShr:
1666 // For a logical shift right
1667 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001668 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001669
Reid Spencer8cb68342007-03-12 17:25:59 +00001670 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001671 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1672 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001673 RHSKnownZero, RHSKnownOne, Depth+1))
1674 return true;
1675 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1676 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001677 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1678 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001679 if (ShiftAmt) {
1680 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001681 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001682 RHSKnownZero |= HighBits; // high bits known zero.
1683 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001684 }
1685 break;
1686 case Instruction::AShr:
1687 // If this is an arithmetic shift right and only the low-bit is set, we can
1688 // always convert this into a logical shr, even if the shift amount is
1689 // variable. The low bit of the shift cannot be an input sign bit unless
1690 // the shift amount is >= the size of the datatype, which is undefined.
1691 if (DemandedMask == 1) {
1692 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001693 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001694 I->getOperand(0), I->getOperand(1), I->getName());
1695 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1696 return UpdateValueUsesWith(I, NewVal);
1697 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001698
1699 // If the sign bit is the only bit demanded by this ashr, then there is no
1700 // need to do it, the shift doesn't change the high bit.
1701 if (DemandedMask.isSignBit())
1702 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001703
1704 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001705 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001706
Reid Spencer8cb68342007-03-12 17:25:59 +00001707 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001708 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001709 // If any of the "high bits" are demanded, we should set the sign bit as
1710 // demanded.
1711 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1712 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001713 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001714 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001715 RHSKnownZero, RHSKnownOne, Depth+1))
1716 return true;
1717 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1718 "Bits known to be one AND zero?");
1719 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001720 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001721 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1722 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1723
1724 // Handle the sign bits.
1725 APInt SignBit(APInt::getSignBit(BitWidth));
1726 // Adjust to where it is now in the mask.
1727 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1728
1729 // If the input sign bit is known to be zero, or if none of the top bits
1730 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001731 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001732 (HighBits & ~DemandedMask) == HighBits) {
1733 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001734 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001735 I->getOperand(0), SA, I->getName());
1736 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1737 return UpdateValueUsesWith(I, NewVal);
1738 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1739 RHSKnownOne |= HighBits;
1740 }
1741 }
1742 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001743 case Instruction::SRem:
1744 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1745 APInt RA = Rem->getValue();
1746 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001747 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001748 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1749 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1750 LHSKnownZero, LHSKnownOne, Depth+1))
1751 return true;
1752
1753 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1754 LHSKnownZero |= ~LowBits;
1755 else if (LHSKnownOne[BitWidth-1])
1756 LHSKnownOne |= ~LowBits;
1757
1758 KnownZero |= LHSKnownZero & DemandedMask;
1759 KnownOne |= LHSKnownOne & DemandedMask;
1760
1761 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1762 }
1763 }
1764 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001765 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001766 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1767 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001768 if (RA.isPowerOf2()) {
1769 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001770 APInt Mask2 = LowBits & DemandedMask;
1771 KnownZero |= ~LowBits & DemandedMask;
1772 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1773 KnownZero, KnownOne, Depth+1))
1774 return true;
1775
1776 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001777 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001778 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001779 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001780
1781 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1782 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001783 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1784 KnownZero2, KnownOne2, Depth+1))
1785 return true;
1786
Dan Gohman23e8b712008-04-28 17:02:21 +00001787 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001788 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001789 KnownZero2, KnownOne2, Depth+1))
1790 return true;
1791
1792 Leaders = std::max(Leaders,
1793 KnownZero2.countLeadingOnes());
1794 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001795 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001796 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001797 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001798
1799 // If the client is only demanding bits that we know, return the known
1800 // constant.
1801 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1802 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1803 return false;
1804}
1805
Chris Lattner867b99f2006-10-05 06:55:50 +00001806
1807/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1808/// 64 or fewer elements. DemandedElts contains the set of elements that are
1809/// actually used by the caller. This method analyzes which elements of the
1810/// operand are undef and returns that information in UndefElts.
1811///
1812/// If the information about demanded elements can be used to simplify the
1813/// operation, the operation is simplified, then the resultant value is
1814/// returned. This returns null if no change was made.
1815Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1816 uint64_t &UndefElts,
1817 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001818 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001819 assert(VWidth <= 64 && "Vector too wide to analyze!");
1820 uint64_t EltMask = ~0ULL >> (64-VWidth);
1821 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1822 "Invalid DemandedElts!");
1823
1824 if (isa<UndefValue>(V)) {
1825 // If the entire vector is undefined, just return this info.
1826 UndefElts = EltMask;
1827 return 0;
1828 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1829 UndefElts = EltMask;
1830 return UndefValue::get(V->getType());
1831 }
1832
1833 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001834 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1835 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001836 Constant *Undef = UndefValue::get(EltTy);
1837
1838 std::vector<Constant*> Elts;
1839 for (unsigned i = 0; i != VWidth; ++i)
1840 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1841 Elts.push_back(Undef);
1842 UndefElts |= (1ULL << i);
1843 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1844 Elts.push_back(Undef);
1845 UndefElts |= (1ULL << i);
1846 } else { // Otherwise, defined.
1847 Elts.push_back(CP->getOperand(i));
1848 }
1849
1850 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001851 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001852 return NewCP != CP ? NewCP : 0;
1853 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001854 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001855 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001856 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001857 Constant *Zero = Constant::getNullValue(EltTy);
1858 Constant *Undef = UndefValue::get(EltTy);
1859 std::vector<Constant*> Elts;
1860 for (unsigned i = 0; i != VWidth; ++i)
1861 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1862 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001863 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001864 }
1865
1866 if (!V->hasOneUse()) { // Other users may use these bits.
1867 if (Depth != 0) { // Not at the root.
1868 // TODO: Just compute the UndefElts information recursively.
1869 return false;
1870 }
1871 return false;
1872 } else if (Depth == 10) { // Limit search depth.
1873 return false;
1874 }
1875
1876 Instruction *I = dyn_cast<Instruction>(V);
1877 if (!I) return false; // Only analyze instructions.
1878
1879 bool MadeChange = false;
1880 uint64_t UndefElts2;
1881 Value *TmpV;
1882 switch (I->getOpcode()) {
1883 default: break;
1884
1885 case Instruction::InsertElement: {
1886 // If this is a variable index, we don't know which element it overwrites.
1887 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001888 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001889 if (Idx == 0) {
1890 // Note that we can't propagate undef elt info, because we don't know
1891 // which elt is getting updated.
1892 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1893 UndefElts2, Depth+1);
1894 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1895 break;
1896 }
1897
1898 // If this is inserting an element that isn't demanded, remove this
1899 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001900 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001901 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1902 return AddSoonDeadInstToWorklist(*I, 0);
1903
1904 // Otherwise, the element inserted overwrites whatever was there, so the
1905 // input demanded set is simpler than the output set.
1906 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1907 DemandedElts & ~(1ULL << IdxNo),
1908 UndefElts, Depth+1);
1909 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1910
1911 // The inserted element is defined.
1912 UndefElts |= 1ULL << IdxNo;
1913 break;
1914 }
Chris Lattner69878332007-04-14 22:29:23 +00001915 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001916 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001917 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1918 if (!VTy) break;
1919 unsigned InVWidth = VTy->getNumElements();
1920 uint64_t InputDemandedElts = 0;
1921 unsigned Ratio;
1922
1923 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001924 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001925 // elements as are demanded of us.
1926 Ratio = 1;
1927 InputDemandedElts = DemandedElts;
1928 } else if (VWidth > InVWidth) {
1929 // Untested so far.
1930 break;
1931
1932 // If there are more elements in the result than there are in the source,
1933 // then an input element is live if any of the corresponding output
1934 // elements are live.
1935 Ratio = VWidth/InVWidth;
1936 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1937 if (DemandedElts & (1ULL << OutIdx))
1938 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1939 }
1940 } else {
1941 // Untested so far.
1942 break;
1943
1944 // If there are more elements in the source than there are in the result,
1945 // then an input element is live if the corresponding output element is
1946 // live.
1947 Ratio = InVWidth/VWidth;
1948 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1949 if (DemandedElts & (1ULL << InIdx/Ratio))
1950 InputDemandedElts |= 1ULL << InIdx;
1951 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001952
Chris Lattner69878332007-04-14 22:29:23 +00001953 // div/rem demand all inputs, because they don't want divide by zero.
1954 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1955 UndefElts2, Depth+1);
1956 if (TmpV) {
1957 I->setOperand(0, TmpV);
1958 MadeChange = true;
1959 }
1960
1961 UndefElts = UndefElts2;
1962 if (VWidth > InVWidth) {
1963 assert(0 && "Unimp");
1964 // If there are more elements in the result than there are in the source,
1965 // then an output element is undef if the corresponding input element is
1966 // undef.
1967 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1968 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1969 UndefElts |= 1ULL << OutIdx;
1970 } else if (VWidth < InVWidth) {
1971 assert(0 && "Unimp");
1972 // If there are more elements in the source than there are in the result,
1973 // then a result element is undef if all of the corresponding input
1974 // elements are undef.
1975 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1976 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1977 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1978 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1979 }
1980 break;
1981 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001982 case Instruction::And:
1983 case Instruction::Or:
1984 case Instruction::Xor:
1985 case Instruction::Add:
1986 case Instruction::Sub:
1987 case Instruction::Mul:
1988 // div/rem demand all inputs, because they don't want divide by zero.
1989 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1990 UndefElts, Depth+1);
1991 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1992 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1993 UndefElts2, Depth+1);
1994 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1995
1996 // Output elements are undefined if both are undefined. Consider things
1997 // like undef&0. The result is known zero, not undef.
1998 UndefElts &= UndefElts2;
1999 break;
2000
2001 case Instruction::Call: {
2002 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2003 if (!II) break;
2004 switch (II->getIntrinsicID()) {
2005 default: break;
2006
2007 // Binary vector operations that work column-wise. A dest element is a
2008 // function of the corresponding input elements from the two inputs.
2009 case Intrinsic::x86_sse_sub_ss:
2010 case Intrinsic::x86_sse_mul_ss:
2011 case Intrinsic::x86_sse_min_ss:
2012 case Intrinsic::x86_sse_max_ss:
2013 case Intrinsic::x86_sse2_sub_sd:
2014 case Intrinsic::x86_sse2_mul_sd:
2015 case Intrinsic::x86_sse2_min_sd:
2016 case Intrinsic::x86_sse2_max_sd:
2017 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2018 UndefElts, Depth+1);
2019 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2020 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2021 UndefElts2, Depth+1);
2022 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2023
2024 // If only the low elt is demanded and this is a scalarizable intrinsic,
2025 // scalarize it now.
2026 if (DemandedElts == 1) {
2027 switch (II->getIntrinsicID()) {
2028 default: break;
2029 case Intrinsic::x86_sse_sub_ss:
2030 case Intrinsic::x86_sse_mul_ss:
2031 case Intrinsic::x86_sse2_sub_sd:
2032 case Intrinsic::x86_sse2_mul_sd:
2033 // TODO: Lower MIN/MAX/ABS/etc
2034 Value *LHS = II->getOperand(1);
2035 Value *RHS = II->getOperand(2);
2036 // Extract the element as scalars.
2037 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2038 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2039
2040 switch (II->getIntrinsicID()) {
2041 default: assert(0 && "Case stmts out of sync!");
2042 case Intrinsic::x86_sse_sub_ss:
2043 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002044 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002045 II->getName()), *II);
2046 break;
2047 case Intrinsic::x86_sse_mul_ss:
2048 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002049 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002050 II->getName()), *II);
2051 break;
2052 }
2053
2054 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00002055 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2056 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00002057 InsertNewInstBefore(New, *II);
2058 AddSoonDeadInstToWorklist(*II, 0);
2059 return New;
2060 }
2061 }
2062
2063 // Output elements are undefined if both are undefined. Consider things
2064 // like undef&0. The result is known zero, not undef.
2065 UndefElts &= UndefElts2;
2066 break;
2067 }
2068 break;
2069 }
2070 }
2071 return MadeChange ? I : 0;
2072}
2073
Chris Lattner564a7272003-08-13 19:01:45 +00002074/// AssociativeOpt - Perform an optimization on an associative operator. This
2075/// function is designed to check a chain of associative operators for a
2076/// potential to apply a certain optimization. Since the optimization may be
2077/// applicable if the expression was reassociated, this checks the chain, then
2078/// reassociates the expression as necessary to expose the optimization
2079/// opportunity. This makes use of a special Functor, which must define
2080/// 'shouldApply' and 'apply' methods.
2081///
2082template<typename Functor>
2083Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2084 unsigned Opcode = Root.getOpcode();
2085 Value *LHS = Root.getOperand(0);
2086
2087 // Quick check, see if the immediate LHS matches...
2088 if (F.shouldApply(LHS))
2089 return F.apply(Root);
2090
2091 // Otherwise, if the LHS is not of the same opcode as the root, return.
2092 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002093 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002094 // Should we apply this transform to the RHS?
2095 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2096
2097 // If not to the RHS, check to see if we should apply to the LHS...
2098 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2099 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2100 ShouldApply = true;
2101 }
2102
2103 // If the functor wants to apply the optimization to the RHS of LHSI,
2104 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2105 if (ShouldApply) {
2106 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002107
Chris Lattner564a7272003-08-13 19:01:45 +00002108 // Now all of the instructions are in the current basic block, go ahead
2109 // and perform the reassociation.
2110 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2111
2112 // First move the selected RHS to the LHS of the root...
2113 Root.setOperand(0, LHSI->getOperand(1));
2114
2115 // Make what used to be the LHS of the root be the user of the root...
2116 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002117 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002118 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2119 return 0;
2120 }
Chris Lattner65725312004-04-16 18:08:07 +00002121 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002122 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002123 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2124 BasicBlock::iterator ARI = &Root; ++ARI;
2125 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2126 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002127
2128 // Now propagate the ExtraOperand down the chain of instructions until we
2129 // get to LHSI.
2130 while (TmpLHSI != LHSI) {
2131 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002132 // Move the instruction to immediately before the chain we are
2133 // constructing to avoid breaking dominance properties.
2134 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2135 BB->getInstList().insert(ARI, NextLHSI);
2136 ARI = NextLHSI;
2137
Chris Lattner564a7272003-08-13 19:01:45 +00002138 Value *NextOp = NextLHSI->getOperand(1);
2139 NextLHSI->setOperand(1, ExtraOperand);
2140 TmpLHSI = NextLHSI;
2141 ExtraOperand = NextOp;
2142 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002143
Chris Lattner564a7272003-08-13 19:01:45 +00002144 // Now that the instructions are reassociated, have the functor perform
2145 // the transformation...
2146 return F.apply(Root);
2147 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002148
Chris Lattner564a7272003-08-13 19:01:45 +00002149 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2150 }
2151 return 0;
2152}
2153
Dan Gohman844731a2008-05-13 00:00:25 +00002154namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002155
2156// AddRHS - Implements: X + X --> X << 1
2157struct AddRHS {
2158 Value *RHS;
2159 AddRHS(Value *rhs) : RHS(rhs) {}
2160 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2161 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002162 return BinaryOperator::CreateShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00002163 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002164 }
2165};
2166
2167// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2168// iff C1&C2 == 0
2169struct AddMaskingAnd {
2170 Constant *C2;
2171 AddMaskingAnd(Constant *c) : C2(c) {}
2172 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002173 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002174 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002175 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002176 }
2177 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002178 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002179 }
2180};
2181
Dan Gohman844731a2008-05-13 00:00:25 +00002182}
2183
Chris Lattner6e7ba452005-01-01 16:22:27 +00002184static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002185 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002186 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002187 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002188 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002189
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002190 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00002191 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002192 }
2193
Chris Lattner2eefe512004-04-09 19:05:30 +00002194 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002195 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2196 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002197
Chris Lattner2eefe512004-04-09 19:05:30 +00002198 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2199 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002200 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2201 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002202 }
2203
2204 Value *Op0 = SO, *Op1 = ConstOperand;
2205 if (!ConstIsRHS)
2206 std::swap(Op0, Op1);
2207 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002208 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002209 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002210 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002211 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002212 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002213 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002214 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002215 abort();
2216 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002217 return IC->InsertNewInstBefore(New, I);
2218}
2219
2220// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2221// constant as the other operand, try to fold the binary operator into the
2222// select arguments. This also works for Cast instructions, which obviously do
2223// not have a second operand.
2224static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2225 InstCombiner *IC) {
2226 // Don't modify shared select instructions
2227 if (!SI->hasOneUse()) return 0;
2228 Value *TV = SI->getOperand(1);
2229 Value *FV = SI->getOperand(2);
2230
2231 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002232 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002233 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002234
Chris Lattner6e7ba452005-01-01 16:22:27 +00002235 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2236 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2237
Gabor Greif051a9502008-04-06 20:25:17 +00002238 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2239 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002240 }
2241 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002242}
2243
Chris Lattner4e998b22004-09-29 05:07:12 +00002244
2245/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2246/// node as operand #0, see if we can fold the instruction into the PHI (which
2247/// is only possible if all operands to the PHI are constants).
2248Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2249 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002250 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002251 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002252
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002253 // Check to see if all of the operands of the PHI are constants. If there is
2254 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002255 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002256 BasicBlock *NonConstBB = 0;
2257 for (unsigned i = 0; i != NumPHIValues; ++i)
2258 if (!isa<Constant>(PN->getIncomingValue(i))) {
2259 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002260 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002261 NonConstBB = PN->getIncomingBlock(i);
2262
2263 // If the incoming non-constant value is in I's block, we have an infinite
2264 // loop.
2265 if (NonConstBB == I.getParent())
2266 return 0;
2267 }
2268
2269 // If there is exactly one non-constant value, we can insert a copy of the
2270 // operation in that block. However, if this is a critical edge, we would be
2271 // inserting the computation one some other paths (e.g. inside a loop). Only
2272 // do this if the pred block is unconditionally branching into the phi block.
2273 if (NonConstBB) {
2274 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2275 if (!BI || !BI->isUnconditional()) return 0;
2276 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002277
2278 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002279 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002280 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002281 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002282 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002283
2284 // Next, add all of the operands to the PHI.
2285 if (I.getNumOperands() == 2) {
2286 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002287 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002288 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002289 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002290 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2291 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2292 else
2293 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002294 } else {
2295 assert(PN->getIncomingBlock(i) == NonConstBB);
2296 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002297 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002298 PN->getIncomingValue(i), C, "phitmp",
2299 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002300 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002301 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002302 CI->getPredicate(),
2303 PN->getIncomingValue(i), C, "phitmp",
2304 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002305 else
2306 assert(0 && "Unknown binop!");
2307
Chris Lattnerdbab3862007-03-02 21:28:56 +00002308 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002309 }
2310 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002311 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002312 } else {
2313 CastInst *CI = cast<CastInst>(&I);
2314 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002315 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002316 Value *InV;
2317 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002318 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002319 } else {
2320 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002321 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002322 I.getType(), "phitmp",
2323 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002324 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002325 }
2326 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002327 }
2328 }
2329 return ReplaceInstUsesWith(I, NewPN);
2330}
2331
Chris Lattner2454a2e2008-01-29 06:52:45 +00002332
2333/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2334/// value is never equal to -0.0.
2335///
2336/// Note that this function will need to be revisited when we support nondefault
2337/// rounding modes!
2338///
2339static bool CannotBeNegativeZero(const Value *V) {
2340 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2341 return !CFP->getValueAPF().isNegZero();
2342
Chris Lattner2454a2e2008-01-29 06:52:45 +00002343 if (const Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002344 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Chris Lattner2454a2e2008-01-29 06:52:45 +00002345 if (I->getOpcode() == Instruction::Add &&
2346 isa<ConstantFP>(I->getOperand(1)) &&
2347 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2348 return true;
2349
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002350 // sitofp and uitofp turn into +0.0 for zero.
2351 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2352 return true;
2353
Chris Lattner2454a2e2008-01-29 06:52:45 +00002354 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2355 if (II->getIntrinsicID() == Intrinsic::sqrt)
2356 return CannotBeNegativeZero(II->getOperand(1));
2357
2358 if (const CallInst *CI = dyn_cast<CallInst>(I))
2359 if (const Function *F = CI->getCalledFunction()) {
2360 if (F->isDeclaration()) {
2361 switch (F->getNameLen()) {
2362 case 3: // abs(x) != -0.0
2363 if (!strcmp(F->getNameStart(), "abs")) return true;
2364 break;
2365 case 4: // abs[lf](x) != -0.0
2366 if (!strcmp(F->getNameStart(), "absf")) return true;
2367 if (!strcmp(F->getNameStart(), "absl")) return true;
2368 break;
2369 }
2370 }
2371 }
2372 }
2373
2374 return false;
2375}
2376
2377
Chris Lattner7e708292002-06-25 16:13:24 +00002378Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002379 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002380 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002381
Chris Lattner66331a42004-04-10 22:01:55 +00002382 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002383 // X + undef -> undef
2384 if (isa<UndefValue>(RHS))
2385 return ReplaceInstUsesWith(I, RHS);
2386
Chris Lattner66331a42004-04-10 22:01:55 +00002387 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002388 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002389 if (RHSC->isNullValue())
2390 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002391 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002392 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2393 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002394 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002395 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002396
Chris Lattner66331a42004-04-10 22:01:55 +00002397 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002398 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002399 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002400 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002401 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002402 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002403
2404 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2405 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002406 if (!isa<VectorType>(I.getType())) {
2407 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2408 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2409 KnownZero, KnownOne))
2410 return &I;
2411 }
Chris Lattner66331a42004-04-10 22:01:55 +00002412 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002413
2414 if (isa<PHINode>(LHS))
2415 if (Instruction *NV = FoldOpIntoPhi(I))
2416 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002417
Chris Lattner4f637d42006-01-06 17:59:59 +00002418 ConstantInt *XorRHS = 0;
2419 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002420 if (isa<ConstantInt>(RHSC) &&
2421 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002422 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002423 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002424
Zhou Sheng4351c642007-04-02 08:20:41 +00002425 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002426 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2427 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002428 do {
2429 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002430 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2431 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002432 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2433 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002434 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002435 if (!MaskedValueIsZero(XorLHS,
2436 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002437 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002438 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002439 }
2440 }
2441 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002442 C0080Val = APIntOps::lshr(C0080Val, Size);
2443 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2444 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002445
Reid Spencer35c38852007-03-28 01:36:16 +00002446 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002447 // with funny bit widths then this switch statement should be removed. It
2448 // is just here to get the size of the "middle" type back up to something
2449 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002450 const Type *MiddleType = 0;
2451 switch (Size) {
2452 default: break;
2453 case 32: MiddleType = Type::Int32Ty; break;
2454 case 16: MiddleType = Type::Int16Ty; break;
2455 case 8: MiddleType = Type::Int8Ty; break;
2456 }
2457 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002458 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002459 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002460 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002461 }
2462 }
Chris Lattner66331a42004-04-10 22:01:55 +00002463 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002464
Chris Lattner564a7272003-08-13 19:01:45 +00002465 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002466 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002467 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002468
2469 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2470 if (RHSI->getOpcode() == Instruction::Sub)
2471 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2472 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2473 }
2474 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2475 if (LHSI->getOpcode() == Instruction::Sub)
2476 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2477 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2478 }
Robert Bocchino71698282004-07-27 21:02:21 +00002479 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002480
Chris Lattner5c4afb92002-05-08 22:46:53 +00002481 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002482 // -A + -B --> -(A + B)
2483 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002484 if (LHS->getType()->isIntOrIntVector()) {
2485 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002486 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002487 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002488 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002489 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002490 }
2491
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002492 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002493 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002494
2495 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002496 if (!isa<Constant>(RHS))
2497 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002498 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002499
Misha Brukmanfd939082005-04-21 23:48:37 +00002500
Chris Lattner50af16a2004-11-13 19:50:12 +00002501 ConstantInt *C2;
2502 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2503 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002504 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002505
2506 // X*C1 + X*C2 --> X * (C1+C2)
2507 ConstantInt *C1;
2508 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002509 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002510 }
2511
2512 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002513 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002514 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002515
Chris Lattnere617c9e2007-01-05 02:17:46 +00002516 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002517 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2518 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002519
Chris Lattnerad3448c2003-02-18 19:57:07 +00002520
Chris Lattner564a7272003-08-13 19:01:45 +00002521 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002522 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002523 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2524 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002525
2526 // A+B --> A|B iff A and B have no bits set in common.
2527 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2528 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2529 APInt LHSKnownOne(IT->getBitWidth(), 0);
2530 APInt LHSKnownZero(IT->getBitWidth(), 0);
2531 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2532 if (LHSKnownZero != 0) {
2533 APInt RHSKnownOne(IT->getBitWidth(), 0);
2534 APInt RHSKnownZero(IT->getBitWidth(), 0);
2535 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2536
2537 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002538 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002539 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002540 }
2541 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002542
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002543 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002544 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002545 Value *W, *X, *Y, *Z;
2546 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2547 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2548 if (W != Y) {
2549 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002550 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002551 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002552 std::swap(W, X);
2553 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002554 std::swap(Y, Z);
2555 std::swap(W, X);
2556 }
2557 }
2558
2559 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002560 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002561 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002562 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002563 }
2564 }
2565 }
2566
Chris Lattner6b032052003-10-02 15:11:26 +00002567 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002568 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002569 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002570 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002571
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002572 // (X & FF00) + xx00 -> (X+xx00) & FF00
2573 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002574 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002575 if (Anded == CRHS) {
2576 // See if all bits from the first bit set in the Add RHS up are included
2577 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002578 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002579
2580 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002581 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002582
2583 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002584 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002585
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002586 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2587 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002588 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002589 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002590 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002591 }
2592 }
2593 }
2594
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002595 // Try to fold constant add into select arguments.
2596 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002597 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002598 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002599 }
2600
Reid Spencer1628cec2006-10-26 06:15:43 +00002601 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002602 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002603 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002604 CastInst *CI = dyn_cast<CastInst>(LHS);
2605 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002606 if (!CI) {
2607 CI = dyn_cast<CastInst>(RHS);
2608 Other = LHS;
2609 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002610 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002611 (CI->getType()->getPrimitiveSizeInBits() ==
2612 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002613 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002614 unsigned AS =
2615 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002616 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2617 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002618 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002619 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002620 }
2621 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002622
Chris Lattner42790482007-12-20 01:56:58 +00002623 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002624 {
2625 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2626 Value *Other = RHS;
2627 if (!SI) {
2628 SI = dyn_cast<SelectInst>(RHS);
2629 Other = LHS;
2630 }
Chris Lattner42790482007-12-20 01:56:58 +00002631 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002632 Value *TV = SI->getTrueValue();
2633 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002634 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002635
2636 // Can we fold the add into the argument of the select?
2637 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002638 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2639 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002640 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002641 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2642 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002643 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002644 }
2645 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002646
2647 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2648 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2649 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2650 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002651
Chris Lattner7e708292002-06-25 16:13:24 +00002652 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002653}
2654
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002655// isSignBit - Return true if the value represented by the constant only has the
2656// highest order bit set.
2657static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002658 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002659 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002660}
2661
Chris Lattner7e708292002-06-25 16:13:24 +00002662Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002663 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002664
Chris Lattner233f7dc2002-08-12 21:17:25 +00002665 if (Op0 == Op1) // sub X, X -> 0
2666 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002667
Chris Lattner233f7dc2002-08-12 21:17:25 +00002668 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002669 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002670 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002671
Chris Lattnere87597f2004-10-16 18:11:37 +00002672 if (isa<UndefValue>(Op0))
2673 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2674 if (isa<UndefValue>(Op1))
2675 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2676
Chris Lattnerd65460f2003-11-05 01:06:05 +00002677 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2678 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002679 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002680 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002681
Chris Lattnerd65460f2003-11-05 01:06:05 +00002682 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002683 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002684 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002685 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002686
Chris Lattner76b7a062007-01-15 07:02:54 +00002687 // -(X >>u 31) -> (X >>s 31)
2688 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002689 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002690 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002691 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002692 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002693 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002694 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002695 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002696 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002697 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002698 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002699 }
2700 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002701 }
2702 else if (SI->getOpcode() == Instruction::AShr) {
2703 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2704 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002705 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002706 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002707 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002708 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002709 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002710 }
2711 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002712 }
2713 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002714 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002715
2716 // Try to fold constant sub into select arguments.
2717 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002718 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002719 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002720
2721 if (isa<PHINode>(Op0))
2722 if (Instruction *NV = FoldOpIntoPhi(I))
2723 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002724 }
2725
Chris Lattner43d84d62005-04-07 16:15:25 +00002726 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2727 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002728 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002729 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002730 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002731 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002732 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002733 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2734 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2735 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002736 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002737 Op1I->getOperand(0));
2738 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002739 }
2740
Chris Lattnerfd059242003-10-15 16:48:29 +00002741 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002742 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2743 // is not used by anyone else...
2744 //
Chris Lattner0517e722004-02-02 20:09:56 +00002745 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002746 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002747 // Swap the two operands of the subexpr...
2748 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2749 Op1I->setOperand(0, IIOp1);
2750 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002751
Chris Lattnera2881962003-02-18 19:28:33 +00002752 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002753 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002754 }
2755
2756 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2757 //
2758 if (Op1I->getOpcode() == Instruction::And &&
2759 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2760 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2761
Chris Lattnerf523d062004-06-09 05:08:07 +00002762 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002763 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2764 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002765 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002766
Reid Spencerac5209e2006-10-16 23:08:08 +00002767 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002768 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002769 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002770 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002771 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002772 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002773 ConstantExpr::getNeg(DivRHS));
2774
Chris Lattnerad3448c2003-02-18 19:57:07 +00002775 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002776 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002777 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002778 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002779 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002780 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002781
2782 // X - ((X / Y) * Y) --> X % Y
2783 if (Op1I->getOpcode() == Instruction::Mul)
2784 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2785 if (Op0 == I->getOperand(0) &&
2786 Op1I->getOperand(1) == I->getOperand(1)) {
2787 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002788 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002789 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002790 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002791 }
Chris Lattner40371712002-05-09 01:29:19 +00002792 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002793 }
Chris Lattnera2881962003-02-18 19:28:33 +00002794
Chris Lattner9919e3d2006-12-02 00:13:08 +00002795 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002796 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002797 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002798 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2799 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2800 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2801 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002802 } else if (Op0I->getOpcode() == Instruction::Sub) {
2803 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002804 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002805 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002806 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002807
Chris Lattner50af16a2004-11-13 19:50:12 +00002808 ConstantInt *C1;
2809 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002810 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002811 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002812
Chris Lattner50af16a2004-11-13 19:50:12 +00002813 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2814 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002815 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002816 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002817 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002818}
2819
Chris Lattnera0141b92007-07-15 20:42:37 +00002820/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2821/// comparison only checks the sign bit. If it only checks the sign bit, set
2822/// TrueIfSigned if the result of the comparison is true when the input value is
2823/// signed.
2824static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2825 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002826 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002827 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2828 TrueIfSigned = true;
2829 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002830 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2831 TrueIfSigned = true;
2832 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002833 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2834 TrueIfSigned = false;
2835 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002836 case ICmpInst::ICMP_UGT:
2837 // True if LHS u> RHS and RHS == high-bit-mask - 1
2838 TrueIfSigned = true;
2839 return RHS->getValue() ==
2840 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2841 case ICmpInst::ICMP_UGE:
2842 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2843 TrueIfSigned = true;
2844 return RHS->getValue() ==
2845 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002846 default:
2847 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002848 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002849}
2850
Chris Lattner7e708292002-06-25 16:13:24 +00002851Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002852 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002853 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002854
Chris Lattnere87597f2004-10-16 18:11:37 +00002855 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2856 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2857
Chris Lattner233f7dc2002-08-12 21:17:25 +00002858 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002859 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2860 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002861
2862 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002863 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002864 if (SI->getOpcode() == Instruction::Shl)
2865 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002866 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002867 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002868
Zhou Sheng843f07672007-04-19 05:39:12 +00002869 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002870 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2871 if (CI->equalsInt(1)) // X * 1 == X
2872 return ReplaceInstUsesWith(I, Op0);
2873 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002874 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002875
Zhou Sheng97b52c22007-03-29 01:57:21 +00002876 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002877 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002878 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002879 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002880 }
Robert Bocchino71698282004-07-27 21:02:21 +00002881 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002882 if (Op1F->isNullValue())
2883 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002884
Chris Lattnera2881962003-02-18 19:28:33 +00002885 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2886 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002887 // We need a better interface for long double here.
2888 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2889 if (Op1F->isExactlyValue(1.0))
2890 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002891 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002892
2893 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2894 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002895 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002896 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002897 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002898 Op1, "tmp");
2899 InsertNewInstBefore(Add, I);
2900 Value *C1C2 = ConstantExpr::getMul(Op1,
2901 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002902 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002903
2904 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002905
2906 // Try to fold constant mul into select arguments.
2907 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002908 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002909 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002910
2911 if (isa<PHINode>(Op0))
2912 if (Instruction *NV = FoldOpIntoPhi(I))
2913 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002914 }
2915
Chris Lattnera4f445b2003-03-10 23:23:04 +00002916 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2917 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002918 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002919
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002920 // If one of the operands of the multiply is a cast from a boolean value, then
2921 // we know the bool is either zero or one, so this is a 'masking' multiply.
2922 // See if we can simplify things based on how the boolean was originally
2923 // formed.
2924 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002925 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002926 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002927 BoolCast = CI;
2928 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002929 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002930 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002931 BoolCast = CI;
2932 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002933 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002934 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2935 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002936 bool TIS = false;
2937
Reid Spencere4d87aa2006-12-23 06:05:41 +00002938 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002939 // multiply into a shift/and combination.
2940 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002941 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2942 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002943 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002944 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002945 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002946 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002947 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002948 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002949 BoolCast->getOperand(0)->getName()+
2950 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002951
2952 // If the multiply type is not the same as the source type, sign extend
2953 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002954 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002955 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2956 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002957 Instruction::CastOps opcode =
2958 (SrcBits == DstBits ? Instruction::BitCast :
2959 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2960 V = InsertCastBefore(opcode, V, I.getType(), I);
2961 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002962
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002963 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002964 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002965 }
2966 }
2967 }
2968
Chris Lattner7e708292002-06-25 16:13:24 +00002969 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002970}
2971
Reid Spencer1628cec2006-10-26 06:15:43 +00002972/// This function implements the transforms on div instructions that work
2973/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2974/// used by the visitors to those instructions.
2975/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002976Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002977 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002978
Chris Lattner50b2ca42008-02-19 06:12:18 +00002979 // undef / X -> 0 for integer.
2980 // undef / X -> undef for FP (the undef could be a snan).
2981 if (isa<UndefValue>(Op0)) {
2982 if (Op0->getType()->isFPOrFPVector())
2983 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002984 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002985 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002986
2987 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002988 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002989 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002990
Chris Lattner25feae52008-01-28 00:58:18 +00002991 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2992 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002993 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002994 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2995 // the same basic block, then we replace the select with Y, and the
2996 // condition of the select with false (if the cond value is in the same BB).
2997 // If the select has uses other than the div, this allows them to be
2998 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2999 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003000 if (ST->isNullValue()) {
3001 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3002 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003003 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00003004 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3005 I.setOperand(1, SI->getOperand(2));
3006 else
3007 UpdateValueUsesWith(SI, SI->getOperand(2));
3008 return &I;
3009 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003010
Chris Lattner25feae52008-01-28 00:58:18 +00003011 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3012 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003013 if (ST->isNullValue()) {
3014 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3015 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003016 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00003017 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3018 I.setOperand(1, SI->getOperand(1));
3019 else
3020 UpdateValueUsesWith(SI, SI->getOperand(1));
3021 return &I;
3022 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003023 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003024
Reid Spencer1628cec2006-10-26 06:15:43 +00003025 return 0;
3026}
Misha Brukmanfd939082005-04-21 23:48:37 +00003027
Reid Spencer1628cec2006-10-26 06:15:43 +00003028/// This function implements the transforms common to both integer division
3029/// instructions (udiv and sdiv). It is called by the visitors to those integer
3030/// division instructions.
3031/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003032Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003033 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3034
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003035 // (sdiv X, X) --> 1 (udiv X, X) --> 1
3036 if (Op0 == Op1)
3037 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
3038
Reid Spencer1628cec2006-10-26 06:15:43 +00003039 if (Instruction *Common = commonDivTransforms(I))
3040 return Common;
3041
3042 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3043 // div X, 1 == X
3044 if (RHS->equalsInt(1))
3045 return ReplaceInstUsesWith(I, Op0);
3046
3047 // (X / C1) / C2 -> X / (C1*C2)
3048 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3049 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3050 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003051 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3052 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3053 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003054 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003055 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003056 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003057
Reid Spencerbca0e382007-03-23 20:05:17 +00003058 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003059 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3060 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3061 return R;
3062 if (isa<PHINode>(Op0))
3063 if (Instruction *NV = FoldOpIntoPhi(I))
3064 return NV;
3065 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003066 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003067
Chris Lattnera2881962003-02-18 19:28:33 +00003068 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003069 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003070 if (LHS->equalsInt(0))
3071 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3072
Reid Spencer1628cec2006-10-26 06:15:43 +00003073 return 0;
3074}
3075
3076Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3077 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3078
3079 // Handle the integer div common cases
3080 if (Instruction *Common = commonIDivTransforms(I))
3081 return Common;
3082
3083 // X udiv C^2 -> X >> C
3084 // Check to see if this is an unsigned division with an exact power of 2,
3085 // if so, convert to a right shift.
3086 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00003087 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003088 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003089 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003090 }
3091
3092 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003093 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003094 if (RHSI->getOpcode() == Instruction::Shl &&
3095 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003096 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003097 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003098 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003099 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003100 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003101 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003102 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003103 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003104 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003105 }
3106 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003107 }
3108
Reid Spencer1628cec2006-10-26 06:15:43 +00003109 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3110 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003111 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003112 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003113 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003114 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003115 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003116 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003117 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003118 // Construct the "on true" case of the select
3119 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003120 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003121 Op0, TC, SI->getName()+".t");
3122 TSI = InsertNewInstBefore(TSI, I);
3123
3124 // Construct the "on false" case of the select
3125 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003126 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003127 Op0, FC, SI->getName()+".f");
3128 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003129
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003130 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003131 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003132 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003133 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003134 return 0;
3135}
3136
Reid Spencer1628cec2006-10-26 06:15:43 +00003137Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3138 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3139
3140 // Handle the integer div common cases
3141 if (Instruction *Common = commonIDivTransforms(I))
3142 return Common;
3143
3144 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3145 // sdiv X, -1 == -X
3146 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003147 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003148
3149 // -X/C -> X/-C
3150 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003151 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003152 }
3153
3154 // If the sign bits of both operands are zero (i.e. we can prove they are
3155 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003156 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003157 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003158 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003159 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003160 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003161 }
3162 }
3163
3164 return 0;
3165}
3166
3167Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3168 return commonDivTransforms(I);
3169}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003170
Reid Spencer0a783f72006-11-02 01:53:59 +00003171/// This function implements the transforms on rem instructions that work
3172/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3173/// is used by the visitors to those instructions.
3174/// @brief Transforms common to all three rem instructions
3175Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003176 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003177
Chris Lattner50b2ca42008-02-19 06:12:18 +00003178 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003179 if (Constant *LHS = dyn_cast<Constant>(Op0))
3180 if (LHS->isNullValue())
3181 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3182
Chris Lattner50b2ca42008-02-19 06:12:18 +00003183 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3184 if (I.getType()->isFPOrFPVector())
3185 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003186 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003187 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003188 if (isa<UndefValue>(Op1))
3189 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003190
3191 // Handle cases involving: rem X, (select Cond, Y, Z)
3192 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3193 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3194 // the same basic block, then we replace the select with Y, and the
3195 // condition of the select with false (if the cond value is in the same
3196 // BB). If the select has uses other than the div, this allows them to be
3197 // simplified also.
3198 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3199 if (ST->isNullValue()) {
3200 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3201 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003202 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003203 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3204 I.setOperand(1, SI->getOperand(2));
3205 else
3206 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003207 return &I;
3208 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003209 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3210 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3211 if (ST->isNullValue()) {
3212 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3213 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003214 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003215 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3216 I.setOperand(1, SI->getOperand(1));
3217 else
3218 UpdateValueUsesWith(SI, SI->getOperand(1));
3219 return &I;
3220 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003221 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003222
Reid Spencer0a783f72006-11-02 01:53:59 +00003223 return 0;
3224}
3225
3226/// This function implements the transforms common to both integer remainder
3227/// instructions (urem and srem). It is called by the visitors to those integer
3228/// remainder instructions.
3229/// @brief Common integer remainder transforms
3230Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3231 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3232
3233 if (Instruction *common = commonRemTransforms(I))
3234 return common;
3235
Chris Lattner857e8cd2004-12-12 21:48:58 +00003236 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003237 // X % 0 == undef, we don't need to preserve faults!
3238 if (RHS->equalsInt(0))
3239 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3240
Chris Lattnera2881962003-02-18 19:28:33 +00003241 if (RHS->equalsInt(1)) // X % 1 == 0
3242 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3243
Chris Lattner97943922006-02-28 05:49:21 +00003244 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3245 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3246 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3247 return R;
3248 } else if (isa<PHINode>(Op0I)) {
3249 if (Instruction *NV = FoldOpIntoPhi(I))
3250 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003251 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003252
3253 // See if we can fold away this rem instruction.
3254 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3255 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3256 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3257 KnownZero, KnownOne))
3258 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003259 }
Chris Lattnera2881962003-02-18 19:28:33 +00003260 }
3261
Reid Spencer0a783f72006-11-02 01:53:59 +00003262 return 0;
3263}
3264
3265Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3266 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3267
3268 if (Instruction *common = commonIRemTransforms(I))
3269 return common;
3270
3271 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3272 // X urem C^2 -> X and C
3273 // Check to see if this is an unsigned remainder with an exact power of 2,
3274 // if so, convert to a bitwise and.
3275 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003276 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003277 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003278 }
3279
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003280 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003281 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3282 if (RHSI->getOpcode() == Instruction::Shl &&
3283 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003284 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003285 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003286 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003287 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003288 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003289 }
3290 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003291 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003292
Reid Spencer0a783f72006-11-02 01:53:59 +00003293 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3294 // where C1&C2 are powers of two.
3295 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3296 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3297 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3298 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003299 if ((STO->getValue().isPowerOf2()) &&
3300 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003301 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003302 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003303 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003304 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003305 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003306 }
3307 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003308 }
3309
Chris Lattner3f5b8772002-05-06 16:14:14 +00003310 return 0;
3311}
3312
Reid Spencer0a783f72006-11-02 01:53:59 +00003313Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3314 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3315
Dan Gohmancff55092007-11-05 23:16:33 +00003316 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003317 if (Instruction *common = commonIRemTransforms(I))
3318 return common;
3319
3320 if (Value *RHSNeg = dyn_castNegVal(Op1))
3321 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003322 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003323 // X % -Y -> X % Y
3324 AddUsesToWorkList(I);
3325 I.setOperand(1, RHSNeg);
3326 return &I;
3327 }
3328
Dan Gohmancff55092007-11-05 23:16:33 +00003329 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003330 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003331 if (I.getType()->isInteger()) {
3332 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3333 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3334 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003335 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003336 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003337 }
3338
3339 return 0;
3340}
3341
3342Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003343 return commonRemTransforms(I);
3344}
3345
Chris Lattner8b170942002-08-09 23:47:40 +00003346// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003347static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003348 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003349 if (!isSigned)
3350 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3351 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003352}
3353
3354// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003355static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003356 if (!isSigned)
3357 return C->getValue() == 1; // unsigned
3358
3359 // Calculate 1111111111000000000000
3360 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3361 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003362}
3363
Chris Lattner457dd822004-06-09 07:59:58 +00003364// isOneBitSet - Return true if there is exactly one bit set in the specified
3365// constant.
3366static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003367 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003368}
3369
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003370// isHighOnes - Return true if the constant is of the form 1+0+.
3371// This is the same as lowones(~X).
3372static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003373 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003374}
3375
Reid Spencere4d87aa2006-12-23 06:05:41 +00003376/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003377/// are carefully arranged to allow folding of expressions such as:
3378///
3379/// (A < B) | (A > B) --> (A != B)
3380///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003381/// Note that this is only valid if the first and second predicates have the
3382/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003383///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003384/// Three bits are used to represent the condition, as follows:
3385/// 0 A > B
3386/// 1 A == B
3387/// 2 A < B
3388///
3389/// <=> Value Definition
3390/// 000 0 Always false
3391/// 001 1 A > B
3392/// 010 2 A == B
3393/// 011 3 A >= B
3394/// 100 4 A < B
3395/// 101 5 A != B
3396/// 110 6 A <= B
3397/// 111 7 Always true
3398///
3399static unsigned getICmpCode(const ICmpInst *ICI) {
3400 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003401 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003402 case ICmpInst::ICMP_UGT: return 1; // 001
3403 case ICmpInst::ICMP_SGT: return 1; // 001
3404 case ICmpInst::ICMP_EQ: return 2; // 010
3405 case ICmpInst::ICMP_UGE: return 3; // 011
3406 case ICmpInst::ICMP_SGE: return 3; // 011
3407 case ICmpInst::ICMP_ULT: return 4; // 100
3408 case ICmpInst::ICMP_SLT: return 4; // 100
3409 case ICmpInst::ICMP_NE: return 5; // 101
3410 case ICmpInst::ICMP_ULE: return 6; // 110
3411 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003412 // True -> 7
3413 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003414 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003415 return 0;
3416 }
3417}
3418
Reid Spencere4d87aa2006-12-23 06:05:41 +00003419/// getICmpValue - This is the complement of getICmpCode, which turns an
3420/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003421/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003422/// of predicate to use in new icmp instructions.
3423static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3424 switch (code) {
3425 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003426 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003427 case 1:
3428 if (sign)
3429 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3430 else
3431 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3432 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3433 case 3:
3434 if (sign)
3435 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3436 else
3437 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3438 case 4:
3439 if (sign)
3440 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3441 else
3442 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3443 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3444 case 6:
3445 if (sign)
3446 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3447 else
3448 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003449 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003450 }
3451}
3452
Reid Spencere4d87aa2006-12-23 06:05:41 +00003453static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3454 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3455 (ICmpInst::isSignedPredicate(p1) &&
3456 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3457 (ICmpInst::isSignedPredicate(p2) &&
3458 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3459}
3460
3461namespace {
3462// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3463struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003464 InstCombiner &IC;
3465 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003466 ICmpInst::Predicate pred;
3467 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3468 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3469 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003470 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003471 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3472 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003473 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3474 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003475 return false;
3476 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003477 Instruction *apply(Instruction &Log) const {
3478 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3479 if (ICI->getOperand(0) != LHS) {
3480 assert(ICI->getOperand(1) == LHS);
3481 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003482 }
3483
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003484 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003485 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003486 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003487 unsigned Code;
3488 switch (Log.getOpcode()) {
3489 case Instruction::And: Code = LHSCode & RHSCode; break;
3490 case Instruction::Or: Code = LHSCode | RHSCode; break;
3491 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003492 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003493 }
3494
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003495 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3496 ICmpInst::isSignedPredicate(ICI->getPredicate());
3497
3498 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003499 if (Instruction *I = dyn_cast<Instruction>(RV))
3500 return I;
3501 // Otherwise, it's a constant boolean value...
3502 return IC.ReplaceInstUsesWith(Log, RV);
3503 }
3504};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003505} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003506
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003507// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3508// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003509// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003510Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003511 ConstantInt *OpRHS,
3512 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003513 BinaryOperator &TheAnd) {
3514 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003515 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003516 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003517 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003518
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003519 switch (Op->getOpcode()) {
3520 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003521 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003522 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003523 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003524 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003525 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003526 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003527 }
3528 break;
3529 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003530 if (Together == AndRHS) // (X | C) & C --> C
3531 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003532
Chris Lattner6e7ba452005-01-01 16:22:27 +00003533 if (Op->hasOneUse() && Together != OpRHS) {
3534 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003535 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003536 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003537 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003538 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003539 }
3540 break;
3541 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003542 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003543 // Adding a one to a single bit bit-field should be turned into an XOR
3544 // of the bit. First thing to check is to see if this AND is with a
3545 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003546 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003547
3548 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003549 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003550 // Ok, at this point, we know that we are masking the result of the
3551 // ADD down to exactly one bit. If the constant we are adding has
3552 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003553 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003554
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003555 // Check to see if any bits below the one bit set in AndRHSV are set.
3556 if ((AddRHS & (AndRHSV-1)) == 0) {
3557 // If not, the only thing that can effect the output of the AND is
3558 // the bit specified by AndRHSV. If that bit is set, the effect of
3559 // the XOR is to toggle the bit. If it is clear, then the ADD has
3560 // no effect.
3561 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3562 TheAnd.setOperand(0, X);
3563 return &TheAnd;
3564 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003565 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003566 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003567 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003568 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003569 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003570 }
3571 }
3572 }
3573 }
3574 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003575
3576 case Instruction::Shl: {
3577 // We know that the AND will not produce any of the bits shifted in, so if
3578 // the anded constant includes them, clear them now!
3579 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003580 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003581 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003582 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3583 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003584
Zhou Sheng290bec52007-03-29 08:15:12 +00003585 if (CI->getValue() == ShlMask) {
3586 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003587 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3588 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003589 TheAnd.setOperand(1, CI);
3590 return &TheAnd;
3591 }
3592 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003593 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003594 case Instruction::LShr:
3595 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003596 // We know that the AND will not produce any of the bits shifted in, so if
3597 // the anded constant includes them, clear them now! This only applies to
3598 // unsigned shifts, because a signed shr may bring in set bits!
3599 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003600 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003601 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003602 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3603 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003604
Zhou Sheng290bec52007-03-29 08:15:12 +00003605 if (CI->getValue() == ShrMask) {
3606 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003607 return ReplaceInstUsesWith(TheAnd, Op);
3608 } else if (CI != AndRHS) {
3609 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3610 return &TheAnd;
3611 }
3612 break;
3613 }
3614 case Instruction::AShr:
3615 // Signed shr.
3616 // See if this is shifting in some sign extension, then masking it out
3617 // with an and.
3618 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003619 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003620 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003621 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3622 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003623 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003624 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003625 // Make the argument unsigned.
3626 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003627 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003628 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003629 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003630 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003631 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003632 }
3633 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003634 }
3635 return 0;
3636}
3637
Chris Lattner8b170942002-08-09 23:47:40 +00003638
Chris Lattnera96879a2004-09-29 17:40:11 +00003639/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3640/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003641/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3642/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003643/// insert new instructions.
3644Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003645 bool isSigned, bool Inside,
3646 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003647 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003648 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003649 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003650
Chris Lattnera96879a2004-09-29 17:40:11 +00003651 if (Inside) {
3652 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003653 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003654
Reid Spencere4d87aa2006-12-23 06:05:41 +00003655 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003656 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003657 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003658 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3659 return new ICmpInst(pred, V, Hi);
3660 }
3661
3662 // Emit V-Lo <u Hi-Lo
3663 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003664 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003665 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003666 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3667 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003668 }
3669
3670 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003671 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003672
Reid Spencere4e40032007-03-21 23:19:50 +00003673 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003674 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003675 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003676 ICmpInst::Predicate pred = (isSigned ?
3677 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3678 return new ICmpInst(pred, V, Hi);
3679 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003680
Reid Spencere4e40032007-03-21 23:19:50 +00003681 // Emit V-Lo >u Hi-1-Lo
3682 // Note that Hi has already had one subtracted from it, above.
3683 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003684 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003685 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003686 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3687 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003688}
3689
Chris Lattner7203e152005-09-18 07:22:02 +00003690// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3691// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3692// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3693// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003694static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003695 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003696 uint32_t BitWidth = Val->getType()->getBitWidth();
3697 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003698
3699 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003700 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003701 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003702 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003703 return true;
3704}
3705
Chris Lattner7203e152005-09-18 07:22:02 +00003706/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3707/// where isSub determines whether the operator is a sub. If we can fold one of
3708/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003709///
3710/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3711/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3712/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3713///
3714/// return (A +/- B).
3715///
3716Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003717 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003718 Instruction &I) {
3719 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3720 if (!LHSI || LHSI->getNumOperands() != 2 ||
3721 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3722
3723 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3724
3725 switch (LHSI->getOpcode()) {
3726 default: return 0;
3727 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003728 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003729 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003730 if ((Mask->getValue().countLeadingZeros() +
3731 Mask->getValue().countPopulation()) ==
3732 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003733 break;
3734
3735 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3736 // part, we don't need any explicit masks to take them out of A. If that
3737 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003738 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003739 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003740 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003741 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003742 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003743 break;
3744 }
3745 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003746 return 0;
3747 case Instruction::Or:
3748 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003749 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003750 if ((Mask->getValue().countLeadingZeros() +
3751 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003752 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003753 break;
3754 return 0;
3755 }
3756
3757 Instruction *New;
3758 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003759 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003760 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003761 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003762 return InsertNewInstBefore(New, I);
3763}
3764
Chris Lattner7e708292002-06-25 16:13:24 +00003765Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003766 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003767 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003768
Chris Lattnere87597f2004-10-16 18:11:37 +00003769 if (isa<UndefValue>(Op1)) // X & undef -> 0
3770 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3771
Chris Lattner6e7ba452005-01-01 16:22:27 +00003772 // and X, X = X
3773 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003774 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003775
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003776 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003777 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003778 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003779 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3780 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3781 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003782 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003783 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003784 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003785 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003786 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003787 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003788 } else if (isa<ConstantAggregateZero>(Op1)) {
3789 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003790 }
3791 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003792
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003793 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003794 const APInt& AndRHSMask = AndRHS->getValue();
3795 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003796
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003797 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003798 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003799 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003800 Value *Op0LHS = Op0I->getOperand(0);
3801 Value *Op0RHS = Op0I->getOperand(1);
3802 switch (Op0I->getOpcode()) {
3803 case Instruction::Xor:
3804 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003805 // If the mask is only needed on one incoming arm, push it up.
3806 if (Op0I->hasOneUse()) {
3807 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3808 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003809 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003810 Op0RHS->getName()+".masked");
3811 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003812 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003813 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003814 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003815 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003816 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3817 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003818 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003819 Op0LHS->getName()+".masked");
3820 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003821 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003822 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3823 }
3824 }
3825
Chris Lattner6e7ba452005-01-01 16:22:27 +00003826 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003827 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003828 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3829 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3830 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3831 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003832 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003833 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003834 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003835 break;
3836
3837 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003838 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3839 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3840 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3841 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003842 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003843 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003844 }
3845
Chris Lattner58403262003-07-23 19:25:52 +00003846 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003847 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003848 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003849 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003850 // If this is an integer truncation or change from signed-to-unsigned, and
3851 // if the source is an and/or with immediate, transform it. This
3852 // frequently occurs for bitfield accesses.
3853 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003854 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003855 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003856 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003857 if (CastOp->getOpcode() == Instruction::And) {
3858 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003859 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3860 // This will fold the two constants together, which may allow
3861 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003862 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003863 CastOp->getOperand(0), I.getType(),
3864 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003865 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003866 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003867 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003868 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003869 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003870 } else if (CastOp->getOpcode() == Instruction::Or) {
3871 // Change: and (cast (or X, C1) to T), C2
3872 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003873 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003874 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3875 return ReplaceInstUsesWith(I, AndRHS);
3876 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003877 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003878 }
Chris Lattner06782f82003-07-23 19:36:21 +00003879 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003880
3881 // Try to fold constant and into select arguments.
3882 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003883 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003884 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003885 if (isa<PHINode>(Op0))
3886 if (Instruction *NV = FoldOpIntoPhi(I))
3887 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003888 }
3889
Chris Lattner8d969642003-03-10 23:06:50 +00003890 Value *Op0NotVal = dyn_castNotVal(Op0);
3891 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003892
Chris Lattner5b62aa72004-06-18 06:07:51 +00003893 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3894 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3895
Misha Brukmancb6267b2004-07-30 12:50:08 +00003896 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003897 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003898 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003899 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003900 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003901 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003902 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003903
3904 {
Chris Lattner003b6202007-06-15 05:58:24 +00003905 Value *A = 0, *B = 0, *C = 0, *D = 0;
3906 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003907 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3908 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003909
3910 // (A|B) & ~(A&B) -> A^B
3911 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3912 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003913 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003914 }
3915 }
3916
3917 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003918 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3919 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003920
3921 // ~(A&B) & (A|B) -> A^B
3922 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3923 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003924 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003925 }
3926 }
Chris Lattner64daab52006-04-01 08:03:55 +00003927
3928 if (Op0->hasOneUse() &&
3929 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3930 if (A == Op1) { // (A^B)&A -> A&(A^B)
3931 I.swapOperands(); // Simplify below
3932 std::swap(Op0, Op1);
3933 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3934 cast<BinaryOperator>(Op0)->swapOperands();
3935 I.swapOperands(); // Simplify below
3936 std::swap(Op0, Op1);
3937 }
3938 }
3939 if (Op1->hasOneUse() &&
3940 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3941 if (B == Op0) { // B&(A^B) -> B&(B^A)
3942 cast<BinaryOperator>(Op1)->swapOperands();
3943 std::swap(A, B);
3944 }
3945 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003946 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00003947 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003948 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00003949 }
3950 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003951 }
3952
Reid Spencere4d87aa2006-12-23 06:05:41 +00003953 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3954 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3955 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003956 return R;
3957
Chris Lattner955f3312004-09-28 21:48:02 +00003958 Value *LHSVal, *RHSVal;
3959 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003960 ICmpInst::Predicate LHSCC, RHSCC;
3961 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3962 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3963 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3964 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3965 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3966 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3967 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003968 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3969
3970 // Don't try to fold ICMP_SLT + ICMP_ULT.
3971 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3972 ICmpInst::isSignedPredicate(LHSCC) ==
3973 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003974 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003975 ICmpInst::Predicate GT;
3976 if (ICmpInst::isSignedPredicate(LHSCC) ||
3977 (ICmpInst::isEquality(LHSCC) &&
3978 ICmpInst::isSignedPredicate(RHSCC)))
3979 GT = ICmpInst::ICMP_SGT;
3980 else
3981 GT = ICmpInst::ICMP_UGT;
3982
Reid Spencere4d87aa2006-12-23 06:05:41 +00003983 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3984 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003985 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003986 std::swap(LHS, RHS);
3987 std::swap(LHSCst, RHSCst);
3988 std::swap(LHSCC, RHSCC);
3989 }
3990
Reid Spencere4d87aa2006-12-23 06:05:41 +00003991 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003992 // comparing a value against two constants and and'ing the result
3993 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003994 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3995 // (from the FoldICmpLogical check above), that the two constants
3996 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003997 assert(LHSCst != RHSCst && "Compares not folded above?");
3998
3999 switch (LHSCC) {
4000 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004001 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00004002 switch (RHSCC) {
4003 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004004 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4005 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4006 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004007 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004008 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4009 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4010 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00004011 return ReplaceInstUsesWith(I, LHS);
4012 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004013 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00004014 switch (RHSCC) {
4015 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004016 case ICmpInst::ICMP_ULT:
4017 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4018 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4019 break; // (X != 13 & X u< 15) -> no change
4020 case ICmpInst::ICMP_SLT:
4021 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4022 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4023 break; // (X != 13 & X s< 15) -> no change
4024 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4025 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4026 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00004027 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004028 case ICmpInst::ICMP_NE:
4029 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00004030 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004031 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00004032 LHSVal->getName()+".off");
4033 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00004034 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4035 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00004036 }
4037 break; // (X != 13 & X != 15) -> no change
4038 }
4039 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004040 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00004041 switch (RHSCC) {
4042 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004043 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4044 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004045 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004046 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4047 break;
4048 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4049 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00004050 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004051 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4052 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004053 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004054 break;
4055 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00004056 switch (RHSCC) {
4057 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004058 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4059 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004060 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004061 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4062 break;
4063 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4064 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00004065 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004066 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4067 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004068 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004069 break;
4070 case ICmpInst::ICMP_UGT:
4071 switch (RHSCC) {
4072 default: assert(0 && "Unknown integer condition code!");
4073 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4074 return ReplaceInstUsesWith(I, LHS);
4075 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4076 return ReplaceInstUsesWith(I, RHS);
4077 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4078 break;
4079 case ICmpInst::ICMP_NE:
4080 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4081 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4082 break; // (X u> 13 & X != 15) -> no change
4083 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4084 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4085 true, I);
4086 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4087 break;
4088 }
4089 break;
4090 case ICmpInst::ICMP_SGT:
4091 switch (RHSCC) {
4092 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004093 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004094 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4095 return ReplaceInstUsesWith(I, RHS);
4096 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4097 break;
4098 case ICmpInst::ICMP_NE:
4099 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4100 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4101 break; // (X s> 13 & X != 15) -> no change
4102 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4103 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4104 true, I);
4105 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4106 break;
4107 }
4108 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004109 }
4110 }
4111 }
4112
Chris Lattner6fc205f2006-05-05 06:39:07 +00004113 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004114 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4115 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4116 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4117 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004118 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004119 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004120 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4121 I.getType(), TD) &&
4122 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4123 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004124 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004125 Op1C->getOperand(0),
4126 I.getName());
4127 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004128 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004129 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004130 }
Chris Lattnere511b742006-11-14 07:46:50 +00004131
4132 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004133 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4134 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4135 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004136 SI0->getOperand(1) == SI1->getOperand(1) &&
4137 (SI0->hasOneUse() || SI1->hasOneUse())) {
4138 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004139 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004140 SI1->getOperand(0),
4141 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004142 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004143 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004144 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004145 }
4146
Chris Lattner99c65742007-10-24 05:38:08 +00004147 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4148 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4149 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4150 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4151 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4152 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4153 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4154 // If either of the constants are nans, then the whole thing returns
4155 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004156 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004157 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4158 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4159 RHS->getOperand(0));
4160 }
4161 }
4162 }
4163
Chris Lattner7e708292002-06-25 16:13:24 +00004164 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004165}
4166
Chris Lattnerafe91a52006-06-15 19:07:26 +00004167/// CollectBSwapParts - Look to see if the specified value defines a single byte
4168/// in the result. If it does, and if the specified byte hasn't been filled in
4169/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004170static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004171 Instruction *I = dyn_cast<Instruction>(V);
4172 if (I == 0) return true;
4173
4174 // If this is an or instruction, it is an inner node of the bswap.
4175 if (I->getOpcode() == Instruction::Or)
4176 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4177 CollectBSwapParts(I->getOperand(1), ByteValues);
4178
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004179 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004180 // If this is a shift by a constant int, and it is "24", then its operand
4181 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004182 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004183 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004184 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004185 8*(ByteValues.size()-1))
4186 return true;
4187
4188 unsigned DestNo;
4189 if (I->getOpcode() == Instruction::Shl) {
4190 // X << 24 defines the top byte with the lowest of the input bytes.
4191 DestNo = ByteValues.size()-1;
4192 } else {
4193 // X >>u 24 defines the low byte with the highest of the input bytes.
4194 DestNo = 0;
4195 }
4196
4197 // If the destination byte value is already defined, the values are or'd
4198 // together, which isn't a bswap (unless it's an or of the same bits).
4199 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4200 return true;
4201 ByteValues[DestNo] = I->getOperand(0);
4202 return false;
4203 }
4204
4205 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4206 // don't have this.
4207 Value *Shift = 0, *ShiftLHS = 0;
4208 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4209 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4210 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4211 return true;
4212 Instruction *SI = cast<Instruction>(Shift);
4213
4214 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004215 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4216 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004217 return true;
4218
4219 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4220 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004221 if (AndAmt->getValue().getActiveBits() > 64)
4222 return true;
4223 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004224 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004225 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004226 break;
4227 // Unknown mask for bswap.
4228 if (DestByte == ByteValues.size()) return true;
4229
Reid Spencerb83eb642006-10-20 07:07:24 +00004230 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004231 unsigned SrcByte;
4232 if (SI->getOpcode() == Instruction::Shl)
4233 SrcByte = DestByte - ShiftBytes;
4234 else
4235 SrcByte = DestByte + ShiftBytes;
4236
4237 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4238 if (SrcByte != ByteValues.size()-DestByte-1)
4239 return true;
4240
4241 // If the destination byte value is already defined, the values are or'd
4242 // together, which isn't a bswap (unless it's an or of the same bits).
4243 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4244 return true;
4245 ByteValues[DestByte] = SI->getOperand(0);
4246 return false;
4247}
4248
4249/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4250/// If so, insert the new bswap intrinsic and return it.
4251Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004252 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4253 if (!ITy || ITy->getBitWidth() % 16)
4254 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004255
4256 /// ByteValues - For each byte of the result, we keep track of which value
4257 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004258 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004259 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004260
4261 // Try to find all the pieces corresponding to the bswap.
4262 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4263 CollectBSwapParts(I.getOperand(1), ByteValues))
4264 return 0;
4265
4266 // Check to see if all of the bytes come from the same value.
4267 Value *V = ByteValues[0];
4268 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4269
4270 // Check to make sure that all of the bytes come from the same value.
4271 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4272 if (ByteValues[i] != V)
4273 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004274 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004275 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004276 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004277 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004278}
4279
4280
Chris Lattner7e708292002-06-25 16:13:24 +00004281Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004282 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004283 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004284
Chris Lattner42593e62007-03-24 23:56:43 +00004285 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004286 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004287
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004288 // or X, X = X
4289 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004290 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004291
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004292 // See if we can simplify any instructions used by the instruction whose sole
4293 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004294 if (!isa<VectorType>(I.getType())) {
4295 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4296 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4297 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4298 KnownZero, KnownOne))
4299 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004300 } else if (isa<ConstantAggregateZero>(Op1)) {
4301 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4302 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4303 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4304 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004305 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004306
4307
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004308
Chris Lattner3f5b8772002-05-06 16:14:14 +00004309 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004310 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004311 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004312 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4313 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004314 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004315 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004316 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004317 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004318 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004319 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004320
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004321 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4322 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004323 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004324 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004325 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004326 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004327 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004328 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004329
4330 // Try to fold constant and into select arguments.
4331 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004332 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004333 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004334 if (isa<PHINode>(Op0))
4335 if (Instruction *NV = FoldOpIntoPhi(I))
4336 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004337 }
4338
Chris Lattner4f637d42006-01-06 17:59:59 +00004339 Value *A = 0, *B = 0;
4340 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004341
4342 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4343 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4344 return ReplaceInstUsesWith(I, Op1);
4345 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4346 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4347 return ReplaceInstUsesWith(I, Op0);
4348
Chris Lattner6423d4c2006-07-10 20:25:24 +00004349 // (A | B) | C and A | (B | C) -> bswap if possible.
4350 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004351 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004352 match(Op1, m_Or(m_Value(), m_Value())) ||
4353 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4354 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004355 if (Instruction *BSwap = MatchBSwap(I))
4356 return BSwap;
4357 }
4358
Chris Lattner6e4c6492005-05-09 04:58:36 +00004359 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4360 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004361 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004362 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004363 InsertNewInstBefore(NOr, I);
4364 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004365 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004366 }
4367
4368 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4369 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004370 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004371 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004372 InsertNewInstBefore(NOr, I);
4373 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004374 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004375 }
4376
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004377 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004378 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004379 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4380 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004381 Value *V1 = 0, *V2 = 0, *V3 = 0;
4382 C1 = dyn_cast<ConstantInt>(C);
4383 C2 = dyn_cast<ConstantInt>(D);
4384 if (C1 && C2) { // (A & C1)|(B & C2)
4385 // If we have: ((V + N) & C1) | (V & C2)
4386 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4387 // replace with V+N.
4388 if (C1->getValue() == ~C2->getValue()) {
4389 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4390 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4391 // Add commutes, try both ways.
4392 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4393 return ReplaceInstUsesWith(I, A);
4394 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4395 return ReplaceInstUsesWith(I, A);
4396 }
4397 // Or commutes, try both ways.
4398 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4399 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4400 // Add commutes, try both ways.
4401 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4402 return ReplaceInstUsesWith(I, B);
4403 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4404 return ReplaceInstUsesWith(I, B);
4405 }
4406 }
Chris Lattner044e5332007-04-08 08:01:49 +00004407 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004408 }
4409
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004410 // Check to see if we have any common things being and'ed. If so, find the
4411 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004412 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4413 if (A == B) // (A & C)|(A & D) == A & (C|D)
4414 V1 = A, V2 = C, V3 = D;
4415 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4416 V1 = A, V2 = B, V3 = C;
4417 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4418 V1 = C, V2 = A, V3 = D;
4419 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4420 V1 = C, V2 = A, V3 = B;
4421
4422 if (V1) {
4423 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004424 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4425 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004426 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004427 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004428 }
Chris Lattnere511b742006-11-14 07:46:50 +00004429
4430 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004431 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4432 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4433 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004434 SI0->getOperand(1) == SI1->getOperand(1) &&
4435 (SI0->hasOneUse() || SI1->hasOneUse())) {
4436 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004437 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004438 SI1->getOperand(0),
4439 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004440 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004441 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004442 }
4443 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004444
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004445 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4446 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004447 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004448 } else {
4449 A = 0;
4450 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004451 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004452 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4453 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004454 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004455
Misha Brukmancb6267b2004-07-30 12:50:08 +00004456 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004457 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004458 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004459 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004460 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004461 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004462 }
Chris Lattnera2881962003-02-18 19:28:33 +00004463
Reid Spencere4d87aa2006-12-23 06:05:41 +00004464 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4465 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4466 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004467 return R;
4468
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004469 Value *LHSVal, *RHSVal;
4470 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004471 ICmpInst::Predicate LHSCC, RHSCC;
4472 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4473 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4474 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4475 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4476 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4477 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4478 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004479 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4480 // We can't fold (ugt x, C) | (sgt x, C2).
4481 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004482 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004483 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004484 bool NeedsSwap;
4485 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004486 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004487 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004488 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004489
4490 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004491 std::swap(LHS, RHS);
4492 std::swap(LHSCst, RHSCst);
4493 std::swap(LHSCC, RHSCC);
4494 }
4495
Reid Spencere4d87aa2006-12-23 06:05:41 +00004496 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004497 // comparing a value against two constants and or'ing the result
4498 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004499 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4500 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004501 // equal.
4502 assert(LHSCst != RHSCst && "Compares not folded above?");
4503
4504 switch (LHSCC) {
4505 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004506 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004507 switch (RHSCC) {
4508 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004509 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004510 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4511 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004512 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004513 LHSVal->getName()+".off");
4514 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004515 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004516 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004517 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004518 break; // (X == 13 | X == 15) -> no change
4519 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4520 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004521 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004522 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4523 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4524 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004525 return ReplaceInstUsesWith(I, RHS);
4526 }
4527 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004528 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004529 switch (RHSCC) {
4530 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004531 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4532 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4533 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004534 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004535 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4536 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4537 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004538 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004539 }
4540 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004541 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004542 switch (RHSCC) {
4543 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004544 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004545 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004546 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004547 // If RHSCst is [us]MAXINT, it is always false. Not handling
4548 // this can cause overflow.
4549 if (RHSCst->isMaxValue(false))
4550 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004551 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4552 false, I);
4553 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4554 break;
4555 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4556 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004557 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004558 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4559 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004560 }
4561 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004562 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004563 switch (RHSCC) {
4564 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004565 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4566 break;
4567 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004568 // If RHSCst is [us]MAXINT, it is always false. Not handling
4569 // this can cause overflow.
4570 if (RHSCst->isMaxValue(true))
4571 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004572 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4573 false, I);
4574 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4575 break;
4576 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4577 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4578 return ReplaceInstUsesWith(I, RHS);
4579 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4580 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004581 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004582 break;
4583 case ICmpInst::ICMP_UGT:
4584 switch (RHSCC) {
4585 default: assert(0 && "Unknown integer condition code!");
4586 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4587 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4588 return ReplaceInstUsesWith(I, LHS);
4589 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4590 break;
4591 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4592 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004593 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004594 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4595 break;
4596 }
4597 break;
4598 case ICmpInst::ICMP_SGT:
4599 switch (RHSCC) {
4600 default: assert(0 && "Unknown integer condition code!");
4601 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4602 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4603 return ReplaceInstUsesWith(I, LHS);
4604 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4605 break;
4606 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4607 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004608 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004609 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4610 break;
4611 }
4612 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004613 }
4614 }
4615 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004616
4617 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004618 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004619 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004620 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004621 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4622 !isa<ICmpInst>(Op1C->getOperand(0))) {
4623 const Type *SrcTy = Op0C->getOperand(0)->getType();
4624 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4625 // Only do this if the casts both really cause code to be
4626 // generated.
4627 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4628 I.getType(), TD) &&
4629 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4630 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004631 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004632 Op1C->getOperand(0),
4633 I.getName());
4634 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004635 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004636 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004637 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004638 }
Chris Lattner99c65742007-10-24 05:38:08 +00004639 }
4640
4641
4642 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4643 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4644 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4645 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004646 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4647 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004648 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4649 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4650 // If either of the constants are nans, then the whole thing returns
4651 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004652 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004653 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4654
4655 // Otherwise, no need to compare the two constants, compare the
4656 // rest.
4657 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4658 RHS->getOperand(0));
4659 }
4660 }
4661 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004662
Chris Lattner7e708292002-06-25 16:13:24 +00004663 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004664}
4665
Dan Gohman844731a2008-05-13 00:00:25 +00004666namespace {
4667
Chris Lattnerc317d392004-02-16 01:20:27 +00004668// XorSelf - Implements: X ^ X --> 0
4669struct XorSelf {
4670 Value *RHS;
4671 XorSelf(Value *rhs) : RHS(rhs) {}
4672 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4673 Instruction *apply(BinaryOperator &Xor) const {
4674 return &Xor;
4675 }
4676};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004677
Dan Gohman844731a2008-05-13 00:00:25 +00004678}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004679
Chris Lattner7e708292002-06-25 16:13:24 +00004680Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004681 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004682 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004683
Evan Chengd34af782008-03-25 20:07:13 +00004684 if (isa<UndefValue>(Op1)) {
4685 if (isa<UndefValue>(Op0))
4686 // Handle undef ^ undef -> 0 special case. This is a common
4687 // idiom (misuse).
4688 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004689 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004690 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004691
Chris Lattnerc317d392004-02-16 01:20:27 +00004692 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4693 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004694 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004695 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004696 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004697
4698 // See if we can simplify any instructions used by the instruction whose sole
4699 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004700 if (!isa<VectorType>(I.getType())) {
4701 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4702 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4703 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4704 KnownZero, KnownOne))
4705 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004706 } else if (isa<ConstantAggregateZero>(Op1)) {
4707 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004708 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004709
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004710 // Is this a ~ operation?
4711 if (Value *NotOp = dyn_castNotVal(&I)) {
4712 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4713 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4714 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4715 if (Op0I->getOpcode() == Instruction::And ||
4716 Op0I->getOpcode() == Instruction::Or) {
4717 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4718 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4719 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004720 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004721 Op0I->getOperand(1)->getName()+".not");
4722 InsertNewInstBefore(NotY, I);
4723 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004724 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004725 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004726 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004727 }
4728 }
4729 }
4730 }
4731
4732
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004733 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004734 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4735 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4736 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004737 return new ICmpInst(ICI->getInversePredicate(),
4738 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004739
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004740 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4741 return new FCmpInst(FCI->getInversePredicate(),
4742 FCI->getOperand(0), FCI->getOperand(1));
4743 }
4744
Reid Spencere4d87aa2006-12-23 06:05:41 +00004745 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004746 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004747 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4748 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004749 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4750 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004751 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004752 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004753 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004754
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004755 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004756 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004757 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004758 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004759 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004760 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004761 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004762 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004763 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004764 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004765 // (X + C) ^ signbit -> (X + C + signbit)
4766 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004767 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004768
Chris Lattner7c4049c2004-01-12 19:35:11 +00004769 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004770 } else if (Op0I->getOpcode() == Instruction::Or) {
4771 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004772 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004773 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4774 // Anything in both C1 and C2 is known to be zero, remove it from
4775 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004776 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004777 NewRHS = ConstantExpr::getAnd(NewRHS,
4778 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004779 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004780 I.setOperand(0, Op0I->getOperand(0));
4781 I.setOperand(1, NewRHS);
4782 return &I;
4783 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004784 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004785 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004786 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004787
4788 // Try to fold constant and into select arguments.
4789 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004790 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004791 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004792 if (isa<PHINode>(Op0))
4793 if (Instruction *NV = FoldOpIntoPhi(I))
4794 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004795 }
4796
Chris Lattner8d969642003-03-10 23:06:50 +00004797 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004798 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004799 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004800
Chris Lattner8d969642003-03-10 23:06:50 +00004801 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004802 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004803 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004804
Chris Lattner318bf792007-03-18 22:51:34 +00004805
4806 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4807 if (Op1I) {
4808 Value *A, *B;
4809 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4810 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004811 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004812 I.swapOperands();
4813 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004814 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004815 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004816 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004817 }
Chris Lattner318bf792007-03-18 22:51:34 +00004818 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4819 if (Op0 == A) // A^(A^B) == B
4820 return ReplaceInstUsesWith(I, B);
4821 else if (Op0 == B) // A^(B^A) == B
4822 return ReplaceInstUsesWith(I, A);
4823 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004824 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004825 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004826 std::swap(A, B);
4827 }
Chris Lattner318bf792007-03-18 22:51:34 +00004828 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004829 I.swapOperands(); // Simplified below.
4830 std::swap(Op0, Op1);
4831 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004832 }
Chris Lattner318bf792007-03-18 22:51:34 +00004833 }
4834
4835 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4836 if (Op0I) {
4837 Value *A, *B;
4838 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4839 if (A == Op1) // (B|A)^B == (A|B)^B
4840 std::swap(A, B);
4841 if (B == Op1) { // (A|B)^B == A & ~B
4842 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004843 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4844 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004845 }
Chris Lattner318bf792007-03-18 22:51:34 +00004846 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4847 if (Op1 == A) // (A^B)^A == B
4848 return ReplaceInstUsesWith(I, B);
4849 else if (Op1 == B) // (B^A)^A == B
4850 return ReplaceInstUsesWith(I, A);
4851 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4852 if (A == Op1) // (A&B)^A -> (B&A)^A
4853 std::swap(A, B);
4854 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004855 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004856 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004857 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4858 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004859 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004860 }
Chris Lattner318bf792007-03-18 22:51:34 +00004861 }
4862
4863 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4864 if (Op0I && Op1I && Op0I->isShift() &&
4865 Op0I->getOpcode() == Op1I->getOpcode() &&
4866 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4867 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4868 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004869 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00004870 Op1I->getOperand(0),
4871 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004872 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00004873 Op1I->getOperand(1));
4874 }
4875
4876 if (Op0I && Op1I) {
4877 Value *A, *B, *C, *D;
4878 // (A & B)^(A | B) -> A ^ B
4879 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4880 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4881 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004882 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004883 }
4884 // (A | B)^(A & B) -> A ^ B
4885 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4886 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4887 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004888 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004889 }
4890
4891 // (A & B)^(C & D)
4892 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4893 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4894 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4895 // (X & Y)^(X & Y) -> (Y^Z) & X
4896 Value *X = 0, *Y = 0, *Z = 0;
4897 if (A == C)
4898 X = A, Y = B, Z = D;
4899 else if (A == D)
4900 X = A, Y = B, Z = C;
4901 else if (B == C)
4902 X = B, Y = A, Z = D;
4903 else if (B == D)
4904 X = B, Y = A, Z = C;
4905
4906 if (X) {
4907 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004908 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4909 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00004910 }
4911 }
4912 }
4913
Reid Spencere4d87aa2006-12-23 06:05:41 +00004914 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4915 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4916 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004917 return R;
4918
Chris Lattner6fc205f2006-05-05 06:39:07 +00004919 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004920 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004921 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004922 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4923 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004924 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004925 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004926 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4927 I.getType(), TD) &&
4928 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4929 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004930 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004931 Op1C->getOperand(0),
4932 I.getName());
4933 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004934 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004935 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004936 }
Chris Lattner99c65742007-10-24 05:38:08 +00004937 }
Chris Lattner7e708292002-06-25 16:13:24 +00004938 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004939}
4940
Chris Lattnera96879a2004-09-29 17:40:11 +00004941/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4942/// overflowed for this type.
4943static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004944 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004945 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004946
Reid Spencere4e40032007-03-21 23:19:50 +00004947 if (IsSigned)
4948 if (In2->getValue().isNegative())
4949 return Result->getValue().sgt(In1->getValue());
4950 else
4951 return Result->getValue().slt(In1->getValue());
4952 else
4953 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004954}
4955
Chris Lattner574da9b2005-01-13 20:14:25 +00004956/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4957/// code necessary to compute the offset from the base pointer (without adding
4958/// in the base pointer). Return the result as a signed integer of intptr size.
4959static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4960 TargetData &TD = IC.getTargetData();
4961 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004962 const Type *IntPtrTy = TD.getIntPtrType();
4963 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004964
4965 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00004966 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00004967 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004968
Chris Lattner574da9b2005-01-13 20:14:25 +00004969 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4970 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004971 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004972 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4973 if (OpC->isZero()) continue;
4974
4975 // Handle a struct index, which adds its field offset to the pointer.
4976 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4977 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4978
4979 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4980 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004981 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004982 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004983 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004984 ConstantInt::get(IntPtrTy, Size),
4985 GEP->getName()+".offs"), I);
4986 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004987 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004988
4989 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4990 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4991 Scale = ConstantExpr::getMul(OC, Scale);
4992 if (Constant *RC = dyn_cast<Constant>(Result))
4993 Result = ConstantExpr::getAdd(RC, Scale);
4994 else {
4995 // Emit an add instruction.
4996 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004997 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004998 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004999 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005000 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005001 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005002 // Convert to correct type.
5003 if (Op->getType() != IntPtrTy) {
5004 if (Constant *OpC = dyn_cast<Constant>(Op))
5005 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5006 else
5007 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5008 Op->getName()+".c"), I);
5009 }
5010 if (Size != 1) {
5011 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5012 if (Constant *OpC = dyn_cast<Constant>(Op))
5013 Op = ConstantExpr::getMul(OpC, Scale);
5014 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005015 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005016 GEP->getName()+".idx"), I);
5017 }
5018
5019 // Emit an add instruction.
5020 if (isa<Constant>(Op) && isa<Constant>(Result))
5021 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5022 cast<Constant>(Result));
5023 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005024 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005025 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005026 }
5027 return Result;
5028}
5029
Chris Lattner10c0d912008-04-22 02:53:33 +00005030
5031/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5032/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5033/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5034/// complex, and scales are involved. The above expression would also be legal
5035/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5036/// later form is less amenable to optimization though, and we are allowed to
5037/// generate the first by knowing that pointer arithmetic doesn't overflow.
5038///
5039/// If we can't emit an optimized form for this expression, this returns null.
5040///
5041static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5042 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005043 TargetData &TD = IC.getTargetData();
5044 gep_type_iterator GTI = gep_type_begin(GEP);
5045
5046 // Check to see if this gep only has a single variable index. If so, and if
5047 // any constant indices are a multiple of its scale, then we can compute this
5048 // in terms of the scale of the variable index. For example, if the GEP
5049 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5050 // because the expression will cross zero at the same point.
5051 unsigned i, e = GEP->getNumOperands();
5052 int64_t Offset = 0;
5053 for (i = 1; i != e; ++i, ++GTI) {
5054 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5055 // Compute the aggregate offset of constant indices.
5056 if (CI->isZero()) continue;
5057
5058 // Handle a struct index, which adds its field offset to the pointer.
5059 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5060 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5061 } else {
5062 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5063 Offset += Size*CI->getSExtValue();
5064 }
5065 } else {
5066 // Found our variable index.
5067 break;
5068 }
5069 }
5070
5071 // If there are no variable indices, we must have a constant offset, just
5072 // evaluate it the general way.
5073 if (i == e) return 0;
5074
5075 Value *VariableIdx = GEP->getOperand(i);
5076 // Determine the scale factor of the variable element. For example, this is
5077 // 4 if the variable index is into an array of i32.
5078 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5079
5080 // Verify that there are no other variable indices. If so, emit the hard way.
5081 for (++i, ++GTI; i != e; ++i, ++GTI) {
5082 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5083 if (!CI) return 0;
5084
5085 // Compute the aggregate offset of constant indices.
5086 if (CI->isZero()) continue;
5087
5088 // Handle a struct index, which adds its field offset to the pointer.
5089 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5090 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5091 } else {
5092 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5093 Offset += Size*CI->getSExtValue();
5094 }
5095 }
5096
5097 // Okay, we know we have a single variable index, which must be a
5098 // pointer/array/vector index. If there is no offset, life is simple, return
5099 // the index.
5100 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5101 if (Offset == 0) {
5102 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5103 // we don't need to bother extending: the extension won't affect where the
5104 // computation crosses zero.
5105 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5106 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5107 VariableIdx->getNameStart(), &I);
5108 return VariableIdx;
5109 }
5110
5111 // Otherwise, there is an index. The computation we will do will be modulo
5112 // the pointer size, so get it.
5113 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5114
5115 Offset &= PtrSizeMask;
5116 VariableScale &= PtrSizeMask;
5117
5118 // To do this transformation, any constant index must be a multiple of the
5119 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5120 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5121 // multiple of the variable scale.
5122 int64_t NewOffs = Offset / (int64_t)VariableScale;
5123 if (Offset != NewOffs*(int64_t)VariableScale)
5124 return 0;
5125
5126 // Okay, we can do this evaluation. Start by converting the index to intptr.
5127 const Type *IntPtrTy = TD.getIntPtrType();
5128 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005129 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005130 true /*SExt*/,
5131 VariableIdx->getNameStart(), &I);
5132 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005133 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005134}
5135
5136
Reid Spencere4d87aa2006-12-23 06:05:41 +00005137/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005138/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005139Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5140 ICmpInst::Predicate Cond,
5141 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005142 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005143
Chris Lattner10c0d912008-04-22 02:53:33 +00005144 // Look through bitcasts.
5145 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5146 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005147
Chris Lattner574da9b2005-01-13 20:14:25 +00005148 Value *PtrBase = GEPLHS->getOperand(0);
5149 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005150 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005151 // This transformation (ignoring the base and scales) is valid because we
5152 // know pointers can't overflow. See if we can output an optimized form.
5153 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5154
5155 // If not, synthesize the offset the hard way.
5156 if (Offset == 0)
5157 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005158 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5159 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005160 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005161 // If the base pointers are different, but the indices are the same, just
5162 // compare the base pointer.
5163 if (PtrBase != GEPRHS->getOperand(0)) {
5164 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005165 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005166 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005167 if (IndicesTheSame)
5168 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5169 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5170 IndicesTheSame = false;
5171 break;
5172 }
5173
5174 // If all indices are the same, just compare the base pointers.
5175 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005176 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5177 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005178
5179 // Otherwise, the base pointers are different and the indices are
5180 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005181 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005182 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005183
Chris Lattnere9d782b2005-01-13 22:25:21 +00005184 // If one of the GEPs has all zero indices, recurse.
5185 bool AllZeros = true;
5186 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5187 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5188 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5189 AllZeros = false;
5190 break;
5191 }
5192 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005193 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5194 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005195
5196 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005197 AllZeros = true;
5198 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5199 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5200 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5201 AllZeros = false;
5202 break;
5203 }
5204 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005205 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005206
Chris Lattner4401c9c2005-01-14 00:20:05 +00005207 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5208 // If the GEPs only differ by one index, compare it.
5209 unsigned NumDifferences = 0; // Keep track of # differences.
5210 unsigned DiffOperand = 0; // The operand that differs.
5211 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5212 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005213 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5214 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005215 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005216 NumDifferences = 2;
5217 break;
5218 } else {
5219 if (NumDifferences++) break;
5220 DiffOperand = i;
5221 }
5222 }
5223
5224 if (NumDifferences == 0) // SAME GEP?
5225 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005226 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005227 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005228
Chris Lattner4401c9c2005-01-14 00:20:05 +00005229 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005230 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5231 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005232 // Make sure we do a signed comparison here.
5233 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005234 }
5235 }
5236
Reid Spencere4d87aa2006-12-23 06:05:41 +00005237 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005238 // the result to fold to a constant!
5239 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5240 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5241 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5242 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5243 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005244 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005245 }
5246 }
5247 return 0;
5248}
5249
Chris Lattnera5406232008-05-19 20:18:56 +00005250/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5251///
5252Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5253 Instruction *LHSI,
5254 Constant *RHSC) {
5255 if (!isa<ConstantFP>(RHSC)) return 0;
5256 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5257
5258 // Get the width of the mantissa. We don't want to hack on conversions that
5259 // might lose information from the integer, e.g. "i64 -> float"
5260 int MantissaWidth = GetFPMantissaWidth(LHSI->getType());
5261 if (MantissaWidth == -1) return 0; // Unknown.
5262
5263 // Check to see that the input is converted from an integer type that is small
5264 // enough that preserves all bits. TODO: check here for "known" sign bits.
5265 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5266 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5267
5268 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5269 if (isa<UIToFPInst>(LHSI))
5270 ++InputSize;
5271
5272 // If the conversion would lose info, don't hack on this.
5273 if ((int)InputSize > MantissaWidth)
5274 return 0;
5275
5276 // Otherwise, we can potentially simplify the comparison. We know that it
5277 // will always come through as an integer value and we know the constant is
5278 // not a NAN (it would have been previously simplified).
5279 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5280
5281 ICmpInst::Predicate Pred;
5282 switch (I.getPredicate()) {
5283 default: assert(0 && "Unexpected predicate!");
5284 case FCmpInst::FCMP_UEQ:
5285 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5286 case FCmpInst::FCMP_UGT:
5287 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5288 case FCmpInst::FCMP_UGE:
5289 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5290 case FCmpInst::FCMP_ULT:
5291 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5292 case FCmpInst::FCMP_ULE:
5293 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5294 case FCmpInst::FCMP_UNE:
5295 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5296 case FCmpInst::FCMP_ORD:
5297 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5298 case FCmpInst::FCMP_UNO:
5299 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5300 }
5301
5302 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5303
5304 // Now we know that the APFloat is a normal number, zero or inf.
5305
5306 // See if the FP constant is top large for the integer. For example,
5307 // comparing an i8 to 300.0.
5308 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5309
5310 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5311 // and large values.
5312 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5313 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5314 APFloat::rmNearestTiesToEven);
5315 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5316 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5317 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5318 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5319 }
5320
5321 // See if the RHS value is < SignedMin.
5322 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5323 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5324 APFloat::rmNearestTiesToEven);
5325 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5326 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5327 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5328 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5329 }
5330
5331 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5332 // it may still be fractional. See if it is fractional by casting the FP
5333 // value to the integer value and back, checking for equality. Don't do this
5334 // for zero, because -0.0 is not fractional.
5335 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5336 if (!RHS.isZero() &&
5337 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5338 // If we had a comparison against a fractional value, we have to adjust
5339 // the compare predicate and sometimes the value. RHSC is rounded towards
5340 // zero at this point.
5341 switch (Pred) {
5342 default: assert(0 && "Unexpected integer comparison!");
5343 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5344 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5345 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5346 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5347 case ICmpInst::ICMP_SLE:
5348 // (float)int <= 4.4 --> int <= 4
5349 // (float)int <= -4.4 --> int < -4
5350 if (RHS.isNegative())
5351 Pred = ICmpInst::ICMP_SLT;
5352 break;
5353 case ICmpInst::ICMP_SLT:
5354 // (float)int < -4.4 --> int < -4
5355 // (float)int < 4.4 --> int <= 4
5356 if (!RHS.isNegative())
5357 Pred = ICmpInst::ICMP_SLE;
5358 break;
5359 case ICmpInst::ICMP_SGT:
5360 // (float)int > 4.4 --> int > 4
5361 // (float)int > -4.4 --> int >= -4
5362 if (RHS.isNegative())
5363 Pred = ICmpInst::ICMP_SGE;
5364 break;
5365 case ICmpInst::ICMP_SGE:
5366 // (float)int >= -4.4 --> int >= -4
5367 // (float)int >= 4.4 --> int > 4
5368 if (!RHS.isNegative())
5369 Pred = ICmpInst::ICMP_SGT;
5370 break;
5371 }
5372 }
5373
5374 // Lower this FP comparison into an appropriate integer version of the
5375 // comparison.
5376 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5377}
5378
Reid Spencere4d87aa2006-12-23 06:05:41 +00005379Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5380 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005381 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005382
Chris Lattner58e97462007-01-14 19:42:17 +00005383 // Fold trivial predicates.
5384 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5385 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5386 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5387 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5388
5389 // Simplify 'fcmp pred X, X'
5390 if (Op0 == Op1) {
5391 switch (I.getPredicate()) {
5392 default: assert(0 && "Unknown predicate!");
5393 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5394 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5395 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5396 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5397 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5398 case FCmpInst::FCMP_OLT: // True if ordered and less than
5399 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5400 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5401
5402 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5403 case FCmpInst::FCMP_ULT: // True if unordered or less than
5404 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5405 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5406 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5407 I.setPredicate(FCmpInst::FCMP_UNO);
5408 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5409 return &I;
5410
5411 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5412 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5413 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5414 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5415 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5416 I.setPredicate(FCmpInst::FCMP_ORD);
5417 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5418 return &I;
5419 }
5420 }
5421
Reid Spencere4d87aa2006-12-23 06:05:41 +00005422 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005423 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005424
Reid Spencere4d87aa2006-12-23 06:05:41 +00005425 // Handle fcmp with constant RHS
5426 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005427 // If the constant is a nan, see if we can fold the comparison based on it.
5428 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5429 if (CFP->getValueAPF().isNaN()) {
5430 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5431 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5432 if (FCmpInst::isUnordered(I.getPredicate())) // True if unordered or...
5433 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5434 if (FCmpInst::isUnordered(I.getPredicate())) // Undef on unordered.
5435 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5436 }
5437 }
5438
Reid Spencere4d87aa2006-12-23 06:05:41 +00005439 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5440 switch (LHSI->getOpcode()) {
5441 case Instruction::PHI:
5442 if (Instruction *NV = FoldOpIntoPhi(I))
5443 return NV;
5444 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005445 case Instruction::SIToFP:
5446 case Instruction::UIToFP:
5447 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5448 return NV;
5449 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005450 case Instruction::Select:
5451 // If either operand of the select is a constant, we can fold the
5452 // comparison into the select arms, which will cause one to be
5453 // constant folded and the select turned into a bitwise or.
5454 Value *Op1 = 0, *Op2 = 0;
5455 if (LHSI->hasOneUse()) {
5456 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5457 // Fold the known value into the constant operand.
5458 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5459 // Insert a new FCmp of the other select operand.
5460 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5461 LHSI->getOperand(2), RHSC,
5462 I.getName()), I);
5463 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5464 // Fold the known value into the constant operand.
5465 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5466 // Insert a new FCmp of the other select operand.
5467 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5468 LHSI->getOperand(1), RHSC,
5469 I.getName()), I);
5470 }
5471 }
5472
5473 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005474 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005475 break;
5476 }
5477 }
5478
5479 return Changed ? &I : 0;
5480}
5481
5482Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5483 bool Changed = SimplifyCompare(I);
5484 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5485 const Type *Ty = Op0->getType();
5486
5487 // icmp X, X
5488 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005489 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005490 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005491
5492 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005493 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005494
Reid Spencere4d87aa2006-12-23 06:05:41 +00005495 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005496 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005497 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5498 isa<ConstantPointerNull>(Op0)) &&
5499 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005500 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005501 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005502 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005503
Reid Spencere4d87aa2006-12-23 06:05:41 +00005504 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005505 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005506 switch (I.getPredicate()) {
5507 default: assert(0 && "Invalid icmp instruction!");
5508 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005509 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005510 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005511 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005512 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005513 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005514 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005515
Reid Spencere4d87aa2006-12-23 06:05:41 +00005516 case ICmpInst::ICMP_UGT:
5517 case ICmpInst::ICMP_SGT:
5518 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005519 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005520 case ICmpInst::ICMP_ULT:
5521 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005522 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005523 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005524 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005525 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005526 case ICmpInst::ICMP_UGE:
5527 case ICmpInst::ICMP_SGE:
5528 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005529 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005530 case ICmpInst::ICMP_ULE:
5531 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005532 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005533 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005534 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005535 }
5536 }
Chris Lattner8b170942002-08-09 23:47:40 +00005537 }
5538
Chris Lattner2be51ae2004-06-09 04:24:29 +00005539 // See if we are doing a comparison between a constant and an instruction that
5540 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005541 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005542 Value *A, *B;
5543
Chris Lattnerb6566012008-01-05 01:18:20 +00005544 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5545 if (I.isEquality() && CI->isNullValue() &&
5546 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5547 // (icmp cond A B) if cond is equality
5548 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005549 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005550
Reid Spencere4d87aa2006-12-23 06:05:41 +00005551 switch (I.getPredicate()) {
5552 default: break;
5553 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5554 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005555 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005556 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5557 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5558 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5559 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005560 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5561 if (CI->isMinValue(true))
5562 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5563 ConstantInt::getAllOnesValue(Op0->getType()));
5564
Reid Spencere4d87aa2006-12-23 06:05:41 +00005565 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005566
Reid Spencere4d87aa2006-12-23 06:05:41 +00005567 case ICmpInst::ICMP_SLT:
5568 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005569 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005570 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5571 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5572 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5573 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5574 break;
5575
5576 case ICmpInst::ICMP_UGT:
5577 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005578 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005579 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5580 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5581 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5582 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005583
5584 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5585 if (CI->isMaxValue(true))
5586 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5587 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005588 break;
5589
5590 case ICmpInst::ICMP_SGT:
5591 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005592 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005593 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5594 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5595 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5596 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5597 break;
5598
5599 case ICmpInst::ICMP_ULE:
5600 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005601 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005602 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5603 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5604 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5605 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5606 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005607
Reid Spencere4d87aa2006-12-23 06:05:41 +00005608 case ICmpInst::ICMP_SLE:
5609 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005610 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005611 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5612 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5613 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5614 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5615 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005616
Reid Spencere4d87aa2006-12-23 06:05:41 +00005617 case ICmpInst::ICMP_UGE:
5618 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005619 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005620 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5621 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5622 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5623 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5624 break;
5625
5626 case ICmpInst::ICMP_SGE:
5627 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005628 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005629 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5630 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5631 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5632 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5633 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005634 }
5635
Reid Spencere4d87aa2006-12-23 06:05:41 +00005636 // If we still have a icmp le or icmp ge instruction, turn it into the
5637 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005638 // already been handled above, this requires little checking.
5639 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005640 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005641 default: break;
5642 case ICmpInst::ICMP_ULE:
5643 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5644 case ICmpInst::ICMP_SLE:
5645 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5646 case ICmpInst::ICMP_UGE:
5647 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5648 case ICmpInst::ICMP_SGE:
5649 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005650 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005651
5652 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005653 // in the input. If this comparison is a normal comparison, it demands all
5654 // bits, if it is a sign bit comparison, it only demands the sign bit.
5655
5656 bool UnusedBit;
5657 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5658
Reid Spencer0460fb32007-03-22 20:36:03 +00005659 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5660 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005661 if (SimplifyDemandedBits(Op0,
5662 isSignBit ? APInt::getSignBit(BitWidth)
5663 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005664 KnownZero, KnownOne, 0))
5665 return &I;
5666
5667 // Given the known and unknown bits, compute a range that the LHS could be
5668 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005669 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005670 // Compute the Min, Max and RHS values based on the known bits. For the
5671 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005672 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5673 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005674 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005675 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5676 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005677 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005678 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5679 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005680 }
5681 switch (I.getPredicate()) { // LE/GE have been folded already.
5682 default: assert(0 && "Unknown icmp opcode!");
5683 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005684 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005685 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005686 break;
5687 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005688 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005689 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005690 break;
5691 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005692 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005693 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005694 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005695 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005696 break;
5697 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005698 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005699 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005700 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005701 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005702 break;
5703 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005704 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005705 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005706 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005707 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005708 break;
5709 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005710 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005711 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005712 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005713 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005714 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005715 }
5716 }
5717
Reid Spencere4d87aa2006-12-23 06:05:41 +00005718 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005719 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005720 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005721 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005722 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5723 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005724 }
5725
Chris Lattner01deb9d2007-04-03 17:43:25 +00005726 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005727 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5728 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5729 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005730 case Instruction::GetElementPtr:
5731 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005732 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005733 bool isAllZeros = true;
5734 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5735 if (!isa<Constant>(LHSI->getOperand(i)) ||
5736 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5737 isAllZeros = false;
5738 break;
5739 }
5740 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005741 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005742 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5743 }
5744 break;
5745
Chris Lattner6970b662005-04-23 15:31:55 +00005746 case Instruction::PHI:
5747 if (Instruction *NV = FoldOpIntoPhi(I))
5748 return NV;
5749 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005750 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005751 // If either operand of the select is a constant, we can fold the
5752 // comparison into the select arms, which will cause one to be
5753 // constant folded and the select turned into a bitwise or.
5754 Value *Op1 = 0, *Op2 = 0;
5755 if (LHSI->hasOneUse()) {
5756 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5757 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005758 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5759 // Insert a new ICmp of the other select operand.
5760 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5761 LHSI->getOperand(2), RHSC,
5762 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005763 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5764 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005765 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5766 // Insert a new ICmp of the other select operand.
5767 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5768 LHSI->getOperand(1), RHSC,
5769 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005770 }
5771 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005772
Chris Lattner6970b662005-04-23 15:31:55 +00005773 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005774 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005775 break;
5776 }
Chris Lattner4802d902007-04-06 18:57:34 +00005777 case Instruction::Malloc:
5778 // If we have (malloc != null), and if the malloc has a single use, we
5779 // can assume it is successful and remove the malloc.
5780 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5781 AddToWorkList(LHSI);
5782 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005783 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00005784 }
5785 break;
5786 }
Chris Lattner6970b662005-04-23 15:31:55 +00005787 }
5788
Reid Spencere4d87aa2006-12-23 06:05:41 +00005789 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005790 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005791 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005792 return NI;
5793 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005794 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5795 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005796 return NI;
5797
Reid Spencere4d87aa2006-12-23 06:05:41 +00005798 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005799 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5800 // now.
5801 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5802 if (isa<PointerType>(Op0->getType()) &&
5803 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005804 // We keep moving the cast from the left operand over to the right
5805 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005806 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005807
Chris Lattner57d86372007-01-06 01:45:59 +00005808 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5809 // so eliminate it as well.
5810 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5811 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005812
Chris Lattnerde90b762003-11-03 04:25:02 +00005813 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005814 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005815 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005816 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005817 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005818 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005819 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005820 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005821 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005822 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005823 }
Chris Lattner57d86372007-01-06 01:45:59 +00005824 }
5825
5826 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005827 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005828 // This comes up when you have code like
5829 // int X = A < B;
5830 // if (X) ...
5831 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005832 // with a constant or another cast from the same type.
5833 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005834 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005835 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005836 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005837
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005838 // ~x < ~y --> y < x
5839 { Value *A, *B;
5840 if (match(Op0, m_Not(m_Value(A))) &&
5841 match(Op1, m_Not(m_Value(B))))
5842 return new ICmpInst(I.getPredicate(), B, A);
5843 }
5844
Chris Lattner65b72ba2006-09-18 04:22:48 +00005845 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005846 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005847
5848 // -x == -y --> x == y
5849 if (match(Op0, m_Neg(m_Value(A))) &&
5850 match(Op1, m_Neg(m_Value(B))))
5851 return new ICmpInst(I.getPredicate(), A, B);
5852
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005853 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5854 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5855 Value *OtherVal = A == Op1 ? B : A;
5856 return new ICmpInst(I.getPredicate(), OtherVal,
5857 Constant::getNullValue(A->getType()));
5858 }
5859
5860 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5861 // A^c1 == C^c2 --> A == C^(c1^c2)
5862 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5863 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5864 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005865 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005866 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005867 return new ICmpInst(I.getPredicate(), A,
5868 InsertNewInstBefore(Xor, I));
5869 }
5870
5871 // A^B == A^D -> B == D
5872 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5873 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5874 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5875 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5876 }
5877 }
5878
5879 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5880 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005881 // A == (A^B) -> B == 0
5882 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005883 return new ICmpInst(I.getPredicate(), OtherVal,
5884 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005885 }
5886 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005887 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005888 return new ICmpInst(I.getPredicate(), B,
5889 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005890 }
5891 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005892 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005893 return new ICmpInst(I.getPredicate(), B,
5894 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005895 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005896
Chris Lattner9c2328e2006-11-14 06:06:06 +00005897 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5898 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5899 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5900 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5901 Value *X = 0, *Y = 0, *Z = 0;
5902
5903 if (A == C) {
5904 X = B; Y = D; Z = A;
5905 } else if (A == D) {
5906 X = B; Y = C; Z = A;
5907 } else if (B == C) {
5908 X = A; Y = D; Z = B;
5909 } else if (B == D) {
5910 X = A; Y = C; Z = B;
5911 }
5912
5913 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005914 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5915 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00005916 I.setOperand(0, Op1);
5917 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5918 return &I;
5919 }
5920 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005921 }
Chris Lattner7e708292002-06-25 16:13:24 +00005922 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005923}
5924
Chris Lattner562ef782007-06-20 23:46:26 +00005925
5926/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5927/// and CmpRHS are both known to be integer constants.
5928Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5929 ConstantInt *DivRHS) {
5930 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5931 const APInt &CmpRHSV = CmpRHS->getValue();
5932
5933 // FIXME: If the operand types don't match the type of the divide
5934 // then don't attempt this transform. The code below doesn't have the
5935 // logic to deal with a signed divide and an unsigned compare (and
5936 // vice versa). This is because (x /s C1) <s C2 produces different
5937 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5938 // (x /u C1) <u C2. Simply casting the operands and result won't
5939 // work. :( The if statement below tests that condition and bails
5940 // if it finds it.
5941 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5942 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5943 return 0;
5944 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005945 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005946
5947 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5948 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5949 // C2 (CI). By solving for X we can turn this into a range check
5950 // instead of computing a divide.
5951 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5952
5953 // Determine if the product overflows by seeing if the product is
5954 // not equal to the divide. Make sure we do the same kind of divide
5955 // as in the LHS instruction that we're folding.
5956 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5957 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5958
5959 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005960 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005961
Chris Lattner1dbfd482007-06-21 18:11:19 +00005962 // Figure out the interval that is being checked. For example, a comparison
5963 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5964 // Compute this interval based on the constants involved and the signedness of
5965 // the compare/divide. This computes a half-open interval, keeping track of
5966 // whether either value in the interval overflows. After analysis each
5967 // overflow variable is set to 0 if it's corresponding bound variable is valid
5968 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5969 int LoOverflow = 0, HiOverflow = 0;
5970 ConstantInt *LoBound = 0, *HiBound = 0;
5971
5972
Chris Lattner562ef782007-06-20 23:46:26 +00005973 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005974 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005975 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005976 HiOverflow = LoOverflow = ProdOV;
5977 if (!HiOverflow)
5978 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005979 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005980 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005981 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005982 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5983 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005984 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005985 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5986 HiOverflow = LoOverflow = ProdOV;
5987 if (!HiOverflow)
5988 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005989 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005990 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005991 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5992 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005993 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005994 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005995 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005996 }
Dan Gohman76491272008-02-13 22:09:18 +00005997 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005998 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005999 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006000 LoBound = AddOne(DivRHS);
6001 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006002 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6003 HiOverflow = 1; // [INTMIN+1, overflow)
6004 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6005 }
Dan Gohman76491272008-02-13 22:09:18 +00006006 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006007 // e.g. X/-5 op 3 --> [-19, -14)
6008 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006009 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006010 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00006011 HiBound = AddOne(Prod);
6012 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006013 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006014 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006015 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006016 HiBound = Subtract(Prod, DivRHS);
6017 }
6018
Chris Lattner1dbfd482007-06-21 18:11:19 +00006019 // Dividing by a negative swaps the condition. LT <-> GT
6020 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006021 }
6022
6023 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006024 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006025 default: assert(0 && "Unhandled icmp opcode!");
6026 case ICmpInst::ICMP_EQ:
6027 if (LoOverflow && HiOverflow)
6028 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6029 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006030 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006031 ICmpInst::ICMP_UGE, X, LoBound);
6032 else if (LoOverflow)
6033 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6034 ICmpInst::ICMP_ULT, X, HiBound);
6035 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006036 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006037 case ICmpInst::ICMP_NE:
6038 if (LoOverflow && HiOverflow)
6039 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6040 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006041 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006042 ICmpInst::ICMP_ULT, X, LoBound);
6043 else if (LoOverflow)
6044 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6045 ICmpInst::ICMP_UGE, X, HiBound);
6046 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006047 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006048 case ICmpInst::ICMP_ULT:
6049 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006050 if (LoOverflow == +1) // Low bound is greater than input range.
6051 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6052 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006053 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006054 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006055 case ICmpInst::ICMP_UGT:
6056 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006057 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006058 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006059 else if (HiOverflow == -1) // High bound less than input range.
6060 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6061 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006062 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6063 else
6064 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6065 }
6066}
6067
6068
Chris Lattner01deb9d2007-04-03 17:43:25 +00006069/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6070///
6071Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6072 Instruction *LHSI,
6073 ConstantInt *RHS) {
6074 const APInt &RHSV = RHS->getValue();
6075
6076 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00006077 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006078 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6079 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6080 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006081 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6082 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006083 Value *CompareVal = LHSI->getOperand(0);
6084
6085 // If the sign bit of the XorCST is not set, there is no change to
6086 // the operation, just stop using the Xor.
6087 if (!XorCST->getValue().isNegative()) {
6088 ICI.setOperand(0, CompareVal);
6089 AddToWorkList(LHSI);
6090 return &ICI;
6091 }
6092
6093 // Was the old condition true if the operand is positive?
6094 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6095
6096 // If so, the new one isn't.
6097 isTrueIfPositive ^= true;
6098
6099 if (isTrueIfPositive)
6100 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6101 else
6102 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6103 }
6104 }
6105 break;
6106 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6107 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6108 LHSI->getOperand(0)->hasOneUse()) {
6109 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6110
6111 // If the LHS is an AND of a truncating cast, we can widen the
6112 // and/compare to be the input width without changing the value
6113 // produced, eliminating a cast.
6114 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6115 // We can do this transformation if either the AND constant does not
6116 // have its sign bit set or if it is an equality comparison.
6117 // Extending a relational comparison when we're checking the sign
6118 // bit would not work.
6119 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006120 (ICI.isEquality() ||
6121 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006122 uint32_t BitWidth =
6123 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6124 APInt NewCST = AndCST->getValue();
6125 NewCST.zext(BitWidth);
6126 APInt NewCI = RHSV;
6127 NewCI.zext(BitWidth);
6128 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006129 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006130 ConstantInt::get(NewCST),LHSI->getName());
6131 InsertNewInstBefore(NewAnd, ICI);
6132 return new ICmpInst(ICI.getPredicate(), NewAnd,
6133 ConstantInt::get(NewCI));
6134 }
6135 }
6136
6137 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6138 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6139 // happens a LOT in code produced by the C front-end, for bitfield
6140 // access.
6141 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6142 if (Shift && !Shift->isShift())
6143 Shift = 0;
6144
6145 ConstantInt *ShAmt;
6146 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6147 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6148 const Type *AndTy = AndCST->getType(); // Type of the and.
6149
6150 // We can fold this as long as we can't shift unknown bits
6151 // into the mask. This can only happen with signed shift
6152 // rights, as they sign-extend.
6153 if (ShAmt) {
6154 bool CanFold = Shift->isLogicalShift();
6155 if (!CanFold) {
6156 // To test for the bad case of the signed shr, see if any
6157 // of the bits shifted in could be tested after the mask.
6158 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6159 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6160
6161 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6162 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6163 AndCST->getValue()) == 0)
6164 CanFold = true;
6165 }
6166
6167 if (CanFold) {
6168 Constant *NewCst;
6169 if (Shift->getOpcode() == Instruction::Shl)
6170 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6171 else
6172 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6173
6174 // Check to see if we are shifting out any of the bits being
6175 // compared.
6176 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6177 // If we shifted bits out, the fold is not going to work out.
6178 // As a special case, check to see if this means that the
6179 // result is always true or false now.
6180 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6181 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6182 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6183 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6184 } else {
6185 ICI.setOperand(1, NewCst);
6186 Constant *NewAndCST;
6187 if (Shift->getOpcode() == Instruction::Shl)
6188 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6189 else
6190 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6191 LHSI->setOperand(1, NewAndCST);
6192 LHSI->setOperand(0, Shift->getOperand(0));
6193 AddToWorkList(Shift); // Shift is dead.
6194 AddUsesToWorkList(ICI);
6195 return &ICI;
6196 }
6197 }
6198 }
6199
6200 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6201 // preferable because it allows the C<<Y expression to be hoisted out
6202 // of a loop if Y is invariant and X is not.
6203 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6204 ICI.isEquality() && !Shift->isArithmeticShift() &&
6205 isa<Instruction>(Shift->getOperand(0))) {
6206 // Compute C << Y.
6207 Value *NS;
6208 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006209 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006210 Shift->getOperand(1), "tmp");
6211 } else {
6212 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006213 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006214 Shift->getOperand(1), "tmp");
6215 }
6216 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6217
6218 // Compute X & (C << Y).
6219 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006220 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006221 InsertNewInstBefore(NewAnd, ICI);
6222
6223 ICI.setOperand(0, NewAnd);
6224 return &ICI;
6225 }
6226 }
6227 break;
6228
Chris Lattnera0141b92007-07-15 20:42:37 +00006229 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6230 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6231 if (!ShAmt) break;
6232
6233 uint32_t TypeBits = RHSV.getBitWidth();
6234
6235 // Check that the shift amount is in range. If not, don't perform
6236 // undefined shifts. When the shift is visited it will be
6237 // simplified.
6238 if (ShAmt->uge(TypeBits))
6239 break;
6240
6241 if (ICI.isEquality()) {
6242 // If we are comparing against bits always shifted out, the
6243 // comparison cannot succeed.
6244 Constant *Comp =
6245 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6246 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6247 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6248 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6249 return ReplaceInstUsesWith(ICI, Cst);
6250 }
6251
6252 if (LHSI->hasOneUse()) {
6253 // Otherwise strength reduce the shift into an and.
6254 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6255 Constant *Mask =
6256 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006257
Chris Lattnera0141b92007-07-15 20:42:37 +00006258 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006259 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006260 Mask, LHSI->getName()+".mask");
6261 Value *And = InsertNewInstBefore(AndI, ICI);
6262 return new ICmpInst(ICI.getPredicate(), And,
6263 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006264 }
6265 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006266
6267 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6268 bool TrueIfSigned = false;
6269 if (LHSI->hasOneUse() &&
6270 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6271 // (X << 31) <s 0 --> (X&1) != 0
6272 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6273 (TypeBits-ShAmt->getZExtValue()-1));
6274 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006275 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006276 Mask, LHSI->getName()+".mask");
6277 Value *And = InsertNewInstBefore(AndI, ICI);
6278
6279 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6280 And, Constant::getNullValue(And->getType()));
6281 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006282 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006283 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006284
6285 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006286 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006287 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006288 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006289 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006290
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006291 // Check that the shift amount is in range. If not, don't perform
6292 // undefined shifts. When the shift is visited it will be
6293 // simplified.
6294 uint32_t TypeBits = RHSV.getBitWidth();
6295 if (ShAmt->uge(TypeBits))
6296 break;
6297
6298 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006299
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006300 // If we are comparing against bits always shifted out, the
6301 // comparison cannot succeed.
6302 APInt Comp = RHSV << ShAmtVal;
6303 if (LHSI->getOpcode() == Instruction::LShr)
6304 Comp = Comp.lshr(ShAmtVal);
6305 else
6306 Comp = Comp.ashr(ShAmtVal);
6307
6308 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6309 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6310 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6311 return ReplaceInstUsesWith(ICI, Cst);
6312 }
6313
6314 // Otherwise, check to see if the bits shifted out are known to be zero.
6315 // If so, we can compare against the unshifted value:
6316 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006317 if (LHSI->hasOneUse() &&
6318 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006319 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6320 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6321 ConstantExpr::getShl(RHS, ShAmt));
6322 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006323
Evan Chengf30752c2008-04-23 00:38:06 +00006324 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006325 // Otherwise strength reduce the shift into an and.
6326 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6327 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006328
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006329 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006330 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006331 Mask, LHSI->getName()+".mask");
6332 Value *And = InsertNewInstBefore(AndI, ICI);
6333 return new ICmpInst(ICI.getPredicate(), And,
6334 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006335 }
6336 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006337 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006338
6339 case Instruction::SDiv:
6340 case Instruction::UDiv:
6341 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6342 // Fold this div into the comparison, producing a range check.
6343 // Determine, based on the divide type, what the range is being
6344 // checked. If there is an overflow on the low or high side, remember
6345 // it, otherwise compute the range [low, hi) bounding the new value.
6346 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006347 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6348 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6349 DivRHS))
6350 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006351 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006352
6353 case Instruction::Add:
6354 // Fold: icmp pred (add, X, C1), C2
6355
6356 if (!ICI.isEquality()) {
6357 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6358 if (!LHSC) break;
6359 const APInt &LHSV = LHSC->getValue();
6360
6361 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6362 .subtract(LHSV);
6363
6364 if (ICI.isSignedPredicate()) {
6365 if (CR.getLower().isSignBit()) {
6366 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6367 ConstantInt::get(CR.getUpper()));
6368 } else if (CR.getUpper().isSignBit()) {
6369 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6370 ConstantInt::get(CR.getLower()));
6371 }
6372 } else {
6373 if (CR.getLower().isMinValue()) {
6374 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6375 ConstantInt::get(CR.getUpper()));
6376 } else if (CR.getUpper().isMinValue()) {
6377 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6378 ConstantInt::get(CR.getLower()));
6379 }
6380 }
6381 }
6382 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006383 }
6384
6385 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6386 if (ICI.isEquality()) {
6387 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6388
6389 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6390 // the second operand is a constant, simplify a bit.
6391 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6392 switch (BO->getOpcode()) {
6393 case Instruction::SRem:
6394 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6395 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6396 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6397 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6398 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006399 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006400 BO->getName());
6401 InsertNewInstBefore(NewRem, ICI);
6402 return new ICmpInst(ICI.getPredicate(), NewRem,
6403 Constant::getNullValue(BO->getType()));
6404 }
6405 }
6406 break;
6407 case Instruction::Add:
6408 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6409 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6410 if (BO->hasOneUse())
6411 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6412 Subtract(RHS, BOp1C));
6413 } else if (RHSV == 0) {
6414 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6415 // efficiently invertible, or if the add has just this one use.
6416 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6417
6418 if (Value *NegVal = dyn_castNegVal(BOp1))
6419 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6420 else if (Value *NegVal = dyn_castNegVal(BOp0))
6421 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6422 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006423 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006424 InsertNewInstBefore(Neg, ICI);
6425 Neg->takeName(BO);
6426 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6427 }
6428 }
6429 break;
6430 case Instruction::Xor:
6431 // For the xor case, we can xor two constants together, eliminating
6432 // the explicit xor.
6433 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6434 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6435 ConstantExpr::getXor(RHS, BOC));
6436
6437 // FALLTHROUGH
6438 case Instruction::Sub:
6439 // Replace (([sub|xor] A, B) != 0) with (A != B)
6440 if (RHSV == 0)
6441 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6442 BO->getOperand(1));
6443 break;
6444
6445 case Instruction::Or:
6446 // If bits are being or'd in that are not present in the constant we
6447 // are comparing against, then the comparison could never succeed!
6448 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6449 Constant *NotCI = ConstantExpr::getNot(RHS);
6450 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6451 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6452 isICMP_NE));
6453 }
6454 break;
6455
6456 case Instruction::And:
6457 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6458 // If bits are being compared against that are and'd out, then the
6459 // comparison can never succeed!
6460 if ((RHSV & ~BOC->getValue()) != 0)
6461 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6462 isICMP_NE));
6463
6464 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6465 if (RHS == BOC && RHSV.isPowerOf2())
6466 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6467 ICmpInst::ICMP_NE, LHSI,
6468 Constant::getNullValue(RHS->getType()));
6469
6470 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6471 if (isSignBit(BOC)) {
6472 Value *X = BO->getOperand(0);
6473 Constant *Zero = Constant::getNullValue(X->getType());
6474 ICmpInst::Predicate pred = isICMP_NE ?
6475 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6476 return new ICmpInst(pred, X, Zero);
6477 }
6478
6479 // ((X & ~7) == 0) --> X < 8
6480 if (RHSV == 0 && isHighOnes(BOC)) {
6481 Value *X = BO->getOperand(0);
6482 Constant *NegX = ConstantExpr::getNeg(BOC);
6483 ICmpInst::Predicate pred = isICMP_NE ?
6484 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6485 return new ICmpInst(pred, X, NegX);
6486 }
6487 }
6488 default: break;
6489 }
6490 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6491 // Handle icmp {eq|ne} <intrinsic>, intcst.
6492 if (II->getIntrinsicID() == Intrinsic::bswap) {
6493 AddToWorkList(II);
6494 ICI.setOperand(0, II->getOperand(1));
6495 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6496 return &ICI;
6497 }
6498 }
6499 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006500 // If the LHS is a cast from an integral value of the same size,
6501 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006502 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6503 Value *CastOp = Cast->getOperand(0);
6504 const Type *SrcTy = CastOp->getType();
6505 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6506 if (SrcTy->isInteger() &&
6507 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6508 // If this is an unsigned comparison, try to make the comparison use
6509 // smaller constant values.
6510 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6511 // X u< 128 => X s> -1
6512 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6513 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6514 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6515 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6516 // X u> 127 => X s< 0
6517 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6518 Constant::getNullValue(SrcTy));
6519 }
6520 }
6521 }
6522 }
6523 return 0;
6524}
6525
6526/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6527/// We only handle extending casts so far.
6528///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006529Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6530 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006531 Value *LHSCIOp = LHSCI->getOperand(0);
6532 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006533 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006534 Value *RHSCIOp;
6535
Chris Lattner8c756c12007-05-05 22:41:33 +00006536 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6537 // integer type is the same size as the pointer type.
6538 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6539 getTargetData().getPointerSizeInBits() ==
6540 cast<IntegerType>(DestTy)->getBitWidth()) {
6541 Value *RHSOp = 0;
6542 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006543 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006544 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6545 RHSOp = RHSC->getOperand(0);
6546 // If the pointer types don't match, insert a bitcast.
6547 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006548 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006549 }
6550
6551 if (RHSOp)
6552 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6553 }
6554
6555 // The code below only handles extension cast instructions, so far.
6556 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006557 if (LHSCI->getOpcode() != Instruction::ZExt &&
6558 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006559 return 0;
6560
Reid Spencere4d87aa2006-12-23 06:05:41 +00006561 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6562 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006563
Reid Spencere4d87aa2006-12-23 06:05:41 +00006564 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006565 // Not an extension from the same type?
6566 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006567 if (RHSCIOp->getType() != LHSCIOp->getType())
6568 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006569
Nick Lewycky4189a532008-01-28 03:48:02 +00006570 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006571 // and the other is a zext), then we can't handle this.
6572 if (CI->getOpcode() != LHSCI->getOpcode())
6573 return 0;
6574
Nick Lewycky4189a532008-01-28 03:48:02 +00006575 // Deal with equality cases early.
6576 if (ICI.isEquality())
6577 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6578
6579 // A signed comparison of sign extended values simplifies into a
6580 // signed comparison.
6581 if (isSignedCmp && isSignedExt)
6582 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6583
6584 // The other three cases all fold into an unsigned comparison.
6585 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006586 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006587
Reid Spencere4d87aa2006-12-23 06:05:41 +00006588 // If we aren't dealing with a constant on the RHS, exit early
6589 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6590 if (!CI)
6591 return 0;
6592
6593 // Compute the constant that would happen if we truncated to SrcTy then
6594 // reextended to DestTy.
6595 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6596 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6597
6598 // If the re-extended constant didn't change...
6599 if (Res2 == CI) {
6600 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6601 // For example, we might have:
6602 // %A = sext short %X to uint
6603 // %B = icmp ugt uint %A, 1330
6604 // It is incorrect to transform this into
6605 // %B = icmp ugt short %X, 1330
6606 // because %A may have negative value.
6607 //
6608 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6609 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006610 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006611 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6612 else
6613 return 0;
6614 }
6615
6616 // The re-extended constant changed so the constant cannot be represented
6617 // in the shorter type. Consequently, we cannot emit a simple comparison.
6618
6619 // First, handle some easy cases. We know the result cannot be equal at this
6620 // point so handle the ICI.isEquality() cases
6621 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006622 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006623 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006624 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006625
6626 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6627 // should have been folded away previously and not enter in here.
6628 Value *Result;
6629 if (isSignedCmp) {
6630 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006631 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006632 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006633 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006634 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006635 } else {
6636 // We're performing an unsigned comparison.
6637 if (isSignedExt) {
6638 // We're performing an unsigned comp with a sign extended value.
6639 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006640 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006641 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6642 NegOne, ICI.getName()), ICI);
6643 } else {
6644 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006645 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006646 }
6647 }
6648
6649 // Finally, return the value computed.
6650 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6651 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6652 return ReplaceInstUsesWith(ICI, Result);
6653 } else {
6654 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6655 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6656 "ICmp should be folded!");
6657 if (Constant *CI = dyn_cast<Constant>(Result))
6658 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6659 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006660 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006661 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006662}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006663
Reid Spencer832254e2007-02-02 02:16:23 +00006664Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6665 return commonShiftTransforms(I);
6666}
6667
6668Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6669 return commonShiftTransforms(I);
6670}
6671
6672Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006673 if (Instruction *R = commonShiftTransforms(I))
6674 return R;
6675
6676 Value *Op0 = I.getOperand(0);
6677
6678 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6679 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6680 if (CSI->isAllOnesValue())
6681 return ReplaceInstUsesWith(I, CSI);
6682
6683 // See if we can turn a signed shr into an unsigned shr.
6684 if (MaskedValueIsZero(Op0,
6685 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006686 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006687
6688 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006689}
6690
6691Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6692 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006693 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006694
6695 // shl X, 0 == X and shr X, 0 == X
6696 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006697 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006698 Op0 == Constant::getNullValue(Op0->getType()))
6699 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006700
Reid Spencere4d87aa2006-12-23 06:05:41 +00006701 if (isa<UndefValue>(Op0)) {
6702 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006703 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006704 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006705 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6706 }
6707 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006708 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6709 return ReplaceInstUsesWith(I, Op0);
6710 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006711 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006712 }
6713
Chris Lattner2eefe512004-04-09 19:05:30 +00006714 // Try to fold constant and into select arguments.
6715 if (isa<Constant>(Op0))
6716 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006717 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006718 return R;
6719
Reid Spencerb83eb642006-10-20 07:07:24 +00006720 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006721 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6722 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006723 return 0;
6724}
6725
Reid Spencerb83eb642006-10-20 07:07:24 +00006726Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006727 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006728 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006729
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006730 // See if we can simplify any instructions used by the instruction whose sole
6731 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006732 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6733 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6734 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006735 KnownZero, KnownOne))
6736 return &I;
6737
Chris Lattner4d5542c2006-01-06 07:12:35 +00006738 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6739 // of a signed value.
6740 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006741 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006742 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006743 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6744 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006745 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006746 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006747 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006748 }
6749
6750 // ((X*C1) << C2) == (X * (C1 << C2))
6751 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6752 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6753 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006754 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006755 ConstantExpr::getShl(BOOp, Op1));
6756
6757 // Try to fold constant and into select arguments.
6758 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6759 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6760 return R;
6761 if (isa<PHINode>(Op0))
6762 if (Instruction *NV = FoldOpIntoPhi(I))
6763 return NV;
6764
Chris Lattner8999dd32007-12-22 09:07:47 +00006765 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6766 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6767 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6768 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6769 // place. Don't try to do this transformation in this case. Also, we
6770 // require that the input operand is a shift-by-constant so that we have
6771 // confidence that the shifts will get folded together. We could do this
6772 // xform in more cases, but it is unlikely to be profitable.
6773 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6774 isa<ConstantInt>(TrOp->getOperand(1))) {
6775 // Okay, we'll do this xform. Make the shift of shift.
6776 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006777 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00006778 I.getName());
6779 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6780
6781 // For logical shifts, the truncation has the effect of making the high
6782 // part of the register be zeros. Emulate this by inserting an AND to
6783 // clear the top bits as needed. This 'and' will usually be zapped by
6784 // other xforms later if dead.
6785 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6786 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6787 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6788
6789 // The mask we constructed says what the trunc would do if occurring
6790 // between the shifts. We want to know the effect *after* the second
6791 // shift. We know that it is a logical shift by a constant, so adjust the
6792 // mask as appropriate.
6793 if (I.getOpcode() == Instruction::Shl)
6794 MaskV <<= Op1->getZExtValue();
6795 else {
6796 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6797 MaskV = MaskV.lshr(Op1->getZExtValue());
6798 }
6799
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006800 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00006801 TI->getName());
6802 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6803
6804 // Return the value truncated to the interesting size.
6805 return new TruncInst(And, I.getType());
6806 }
6807 }
6808
Chris Lattner4d5542c2006-01-06 07:12:35 +00006809 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006810 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6811 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6812 Value *V1, *V2;
6813 ConstantInt *CC;
6814 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006815 default: break;
6816 case Instruction::Add:
6817 case Instruction::And:
6818 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006819 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006820 // These operators commute.
6821 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006822 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6823 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006824 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006825 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006826 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006827 Op0BO->getName());
6828 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006829 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006830 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006831 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006832 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006833 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006834 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006835 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006836 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006837
Chris Lattner150f12a2005-09-18 06:30:59 +00006838 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006839 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006840 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006841 match(Op0BOOp1,
6842 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006843 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6844 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006845 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006846 Op0BO->getOperand(0), Op1,
6847 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006848 InsertNewInstBefore(YS, I); // (Y << C)
6849 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006850 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006851 V1->getName()+".mask");
6852 InsertNewInstBefore(XM, I); // X & (CC << C)
6853
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006854 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00006855 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006856 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006857
Reid Spencera07cb7d2007-02-02 14:41:37 +00006858 // FALL THROUGH.
6859 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006860 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006861 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6862 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006863 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006864 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006865 Op0BO->getOperand(1), Op1,
6866 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006867 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006868 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006869 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006870 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006871 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006872 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006873 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006874 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006875 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006876
Chris Lattner13d4ab42006-05-31 21:14:00 +00006877 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006878 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6879 match(Op0BO->getOperand(0),
6880 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006881 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006882 cast<BinaryOperator>(Op0BO->getOperand(0))
6883 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006884 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006885 Op0BO->getOperand(1), Op1,
6886 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006887 InsertNewInstBefore(YS, I); // (Y << C)
6888 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006889 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006890 V1->getName()+".mask");
6891 InsertNewInstBefore(XM, I); // X & (CC << C)
6892
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006893 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006894 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006895
Chris Lattner11021cb2005-09-18 05:12:10 +00006896 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006897 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006898 }
6899
6900
6901 // If the operand is an bitwise operator with a constant RHS, and the
6902 // shift is the only use, we can pull it out of the shift.
6903 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6904 bool isValid = true; // Valid only for And, Or, Xor
6905 bool highBitSet = false; // Transform if high bit of constant set?
6906
6907 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006908 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006909 case Instruction::Add:
6910 isValid = isLeftShift;
6911 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006912 case Instruction::Or:
6913 case Instruction::Xor:
6914 highBitSet = false;
6915 break;
6916 case Instruction::And:
6917 highBitSet = true;
6918 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006919 }
6920
6921 // If this is a signed shift right, and the high bit is modified
6922 // by the logical operation, do not perform the transformation.
6923 // The highBitSet boolean indicates the value of the high bit of
6924 // the constant which would cause it to be modified for this
6925 // operation.
6926 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006927 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006928 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006929
6930 if (isValid) {
6931 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6932
6933 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006934 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006935 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006936 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006937
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006938 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00006939 NewRHS);
6940 }
6941 }
6942 }
6943 }
6944
Chris Lattnerad0124c2006-01-06 07:52:12 +00006945 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006946 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6947 if (ShiftOp && !ShiftOp->isShift())
6948 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006949
Reid Spencerb83eb642006-10-20 07:07:24 +00006950 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006951 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006952 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6953 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006954 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6955 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6956 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006957
Zhou Sheng4351c642007-04-02 08:20:41 +00006958 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006959 if (AmtSum > TypeBits)
6960 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006961
6962 const IntegerType *Ty = cast<IntegerType>(I.getType());
6963
6964 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006965 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006966 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006967 ConstantInt::get(Ty, AmtSum));
6968 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6969 I.getOpcode() == Instruction::AShr) {
6970 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006971 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006972 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6973 I.getOpcode() == Instruction::LShr) {
6974 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6975 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006976 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006977 InsertNewInstBefore(Shift, I);
6978
Zhou Shenge9e03f62007-03-28 15:02:20 +00006979 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006980 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006981 }
6982
Chris Lattnerb87056f2007-02-05 00:57:54 +00006983 // Okay, if we get here, one shift must be left, and the other shift must be
6984 // right. See if the amounts are equal.
6985 if (ShiftAmt1 == ShiftAmt2) {
6986 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6987 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006988 APInt Mask(APInt::getHighBitsSet(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 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6992 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006993 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006994 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006995 }
6996 // We can simplify ((X << C) >>s C) into a trunc + sext.
6997 // NOTE: we could do this for any C, but that would make 'unusual' integer
6998 // types. For now, just stick to ones well-supported by the code
6999 // generators.
7000 const Type *SExtType = 0;
7001 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007002 case 1 :
7003 case 8 :
7004 case 16 :
7005 case 32 :
7006 case 64 :
7007 case 128:
7008 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7009 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007010 default: break;
7011 }
7012 if (SExtType) {
7013 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7014 InsertNewInstBefore(NewTrunc, I);
7015 return new SExtInst(NewTrunc, Ty);
7016 }
7017 // Otherwise, we can't handle it yet.
7018 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007019 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007020
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007021 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007022 if (I.getOpcode() == Instruction::Shl) {
7023 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7024 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007025 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007026 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007027 InsertNewInstBefore(Shift, I);
7028
Reid Spencer55702aa2007-03-25 21:11:44 +00007029 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007030 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007031 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007032
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007033 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007034 if (I.getOpcode() == Instruction::LShr) {
7035 assert(ShiftOp->getOpcode() == Instruction::Shl);
7036 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007037 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007038 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007039
Reid Spencerd5e30f02007-03-26 17:18:58 +00007040 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007041 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007042 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007043
7044 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7045 } else {
7046 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007047 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007048
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007049 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007050 if (I.getOpcode() == Instruction::Shl) {
7051 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7052 ShiftOp->getOpcode() == Instruction::AShr);
7053 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007054 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007055 ConstantInt::get(Ty, ShiftDiff));
7056 InsertNewInstBefore(Shift, I);
7057
Reid Spencer55702aa2007-03-25 21:11:44 +00007058 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007059 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007060 }
7061
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007062 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007063 if (I.getOpcode() == Instruction::LShr) {
7064 assert(ShiftOp->getOpcode() == Instruction::Shl);
7065 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007066 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007067 InsertNewInstBefore(Shift, I);
7068
Reid Spencer68d27cf2007-03-26 23:45:51 +00007069 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007070 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007071 }
7072
7073 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007074 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007075 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007076 return 0;
7077}
7078
Chris Lattnera1be5662002-05-02 17:06:02 +00007079
Chris Lattnercfd65102005-10-29 04:36:15 +00007080/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7081/// expression. If so, decompose it, returning some value X, such that Val is
7082/// X*Scale+Offset.
7083///
7084static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007085 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007086 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007087 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007088 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007089 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007090 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007091 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7092 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7093 if (I->getOpcode() == Instruction::Shl) {
7094 // This is a value scaled by '1 << the shift amt'.
7095 Scale = 1U << RHS->getZExtValue();
7096 Offset = 0;
7097 return I->getOperand(0);
7098 } else if (I->getOpcode() == Instruction::Mul) {
7099 // This value is scaled by 'RHS'.
7100 Scale = RHS->getZExtValue();
7101 Offset = 0;
7102 return I->getOperand(0);
7103 } else if (I->getOpcode() == Instruction::Add) {
7104 // We have X+C. Check to see if we really have (X*C2)+C1,
7105 // where C1 is divisible by C2.
7106 unsigned SubScale;
7107 Value *SubVal =
7108 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7109 Offset += RHS->getZExtValue();
7110 Scale = SubScale;
7111 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007112 }
7113 }
7114 }
7115
7116 // Otherwise, we can't look past this.
7117 Scale = 1;
7118 Offset = 0;
7119 return Val;
7120}
7121
7122
Chris Lattnerb3f83972005-10-24 06:03:58 +00007123/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7124/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007125Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007126 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007127 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007128
Chris Lattnerb53c2382005-10-24 06:22:12 +00007129 // Remove any uses of AI that are dead.
7130 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007131
Chris Lattnerb53c2382005-10-24 06:22:12 +00007132 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7133 Instruction *User = cast<Instruction>(*UI++);
7134 if (isInstructionTriviallyDead(User)) {
7135 while (UI != E && *UI == User)
7136 ++UI; // If this instruction uses AI more than once, don't break UI.
7137
Chris Lattnerb53c2382005-10-24 06:22:12 +00007138 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007139 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007140 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007141 }
7142 }
7143
Chris Lattnerb3f83972005-10-24 06:03:58 +00007144 // Get the type really allocated and the type casted to.
7145 const Type *AllocElTy = AI.getAllocatedType();
7146 const Type *CastElTy = PTy->getElementType();
7147 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007148
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007149 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7150 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007151 if (CastElTyAlign < AllocElTyAlign) return 0;
7152
Chris Lattner39387a52005-10-24 06:35:18 +00007153 // If the allocation has multiple uses, only promote it if we are strictly
7154 // increasing the alignment of the resultant allocation. If we keep it the
7155 // same, we open the door to infinite loops of various kinds.
7156 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7157
Duncan Sands514ab342007-11-01 20:53:16 +00007158 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7159 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007160 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007161
Chris Lattner455fcc82005-10-29 03:19:53 +00007162 // See if we can satisfy the modulus by pulling a scale out of the array
7163 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007164 unsigned ArraySizeScale;
7165 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007166 Value *NumElements = // See if the array size is a decomposable linear expr.
7167 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7168
Chris Lattner455fcc82005-10-29 03:19:53 +00007169 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7170 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007171 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7172 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007173
Chris Lattner455fcc82005-10-29 03:19:53 +00007174 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7175 Value *Amt = 0;
7176 if (Scale == 1) {
7177 Amt = NumElements;
7178 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007179 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007180 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7181 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007182 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007183 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007184 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007185 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007186 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007187 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007188 }
7189
Jeff Cohen86796be2007-04-04 16:58:57 +00007190 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7191 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007192 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007193 Amt = InsertNewInstBefore(Tmp, AI);
7194 }
7195
Chris Lattnerb3f83972005-10-24 06:03:58 +00007196 AllocationInst *New;
7197 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007198 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007199 else
Chris Lattner6934a042007-02-11 01:23:03 +00007200 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007201 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007202 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007203
7204 // If the allocation has multiple uses, insert a cast and change all things
7205 // that used it to use the new cast. This will also hack on CI, but it will
7206 // die soon.
7207 if (!AI.hasOneUse()) {
7208 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007209 // New is the allocation instruction, pointer typed. AI is the original
7210 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7211 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007212 InsertNewInstBefore(NewCast, AI);
7213 AI.replaceAllUsesWith(NewCast);
7214 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007215 return ReplaceInstUsesWith(CI, New);
7216}
7217
Chris Lattner70074e02006-05-13 02:06:03 +00007218/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007219/// and return it as type Ty without inserting any new casts and without
7220/// changing the computed value. This is used by code that tries to decide
7221/// whether promoting or shrinking integer operations to wider or smaller types
7222/// will allow us to eliminate a truncate or extend.
7223///
7224/// This is a truncation operation if Ty is smaller than V->getType(), or an
7225/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00007226bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7227 unsigned CastOpc,
7228 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007229 // We can always evaluate constants in another type.
7230 if (isa<ConstantInt>(V))
7231 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007232
7233 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007234 if (!I) return false;
7235
7236 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007237
Chris Lattner951626b2007-08-02 06:11:14 +00007238 // If this is an extension or truncate, we can often eliminate it.
7239 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7240 // If this is a cast from the destination type, we can trivially eliminate
7241 // it, and this will remove a cast overall.
7242 if (I->getOperand(0)->getType() == Ty) {
7243 // If the first operand is itself a cast, and is eliminable, do not count
7244 // this as an eliminable cast. We would prefer to eliminate those two
7245 // casts first.
7246 if (!isa<CastInst>(I->getOperand(0)))
7247 ++NumCastsRemoved;
7248 return true;
7249 }
7250 }
7251
7252 // We can't extend or shrink something that has multiple uses: doing so would
7253 // require duplicating the instruction in general, which isn't profitable.
7254 if (!I->hasOneUse()) return false;
7255
Chris Lattner70074e02006-05-13 02:06:03 +00007256 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007257 case Instruction::Add:
7258 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00007259 case Instruction::And:
7260 case Instruction::Or:
7261 case Instruction::Xor:
7262 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007263 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7264 NumCastsRemoved) &&
7265 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7266 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007267
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007268 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007269 // A multiply can be truncated by truncating its operands.
7270 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7271 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7272 NumCastsRemoved) &&
7273 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7274 NumCastsRemoved);
7275
Chris Lattner46b96052006-11-29 07:18:39 +00007276 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007277 // If we are truncating the result of this SHL, and if it's a shift of a
7278 // constant amount, we can always perform a SHL in a smaller type.
7279 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007280 uint32_t BitWidth = Ty->getBitWidth();
7281 if (BitWidth < OrigTy->getBitWidth() &&
7282 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007283 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7284 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007285 }
7286 break;
7287 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007288 // If this is a truncate of a logical shr, we can truncate it to a smaller
7289 // lshr iff we know that the bits we would otherwise be shifting in are
7290 // already zeros.
7291 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007292 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7293 uint32_t BitWidth = Ty->getBitWidth();
7294 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007295 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007296 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7297 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007298 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7299 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007300 }
7301 }
Chris Lattner46b96052006-11-29 07:18:39 +00007302 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007303 case Instruction::ZExt:
7304 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007305 case Instruction::Trunc:
7306 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007307 // can safely replace it. Note that replacing it does not reduce the number
7308 // of casts in the input.
7309 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007310 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00007311
Reid Spencer3da59db2006-11-27 01:05:10 +00007312 break;
7313 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007314 // TODO: Can handle more cases here.
7315 break;
7316 }
7317
7318 return false;
7319}
7320
7321/// EvaluateInDifferentType - Given an expression that
7322/// CanEvaluateInDifferentType returns true for, actually insert the code to
7323/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007324Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007325 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007326 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007327 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007328
7329 // Otherwise, it must be an instruction.
7330 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007331 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007332 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007333 case Instruction::Add:
7334 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007335 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007336 case Instruction::And:
7337 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007338 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007339 case Instruction::AShr:
7340 case Instruction::LShr:
7341 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007342 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007343 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007344 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00007345 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00007346 break;
7347 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007348 case Instruction::Trunc:
7349 case Instruction::ZExt:
7350 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007351 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007352 // just return the source. There's no need to insert it because it is not
7353 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007354 if (I->getOperand(0)->getType() == Ty)
7355 return I->getOperand(0);
7356
Chris Lattner951626b2007-08-02 06:11:14 +00007357 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007358 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00007359 Ty, I->getName());
7360 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007361 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007362 // TODO: Can handle more cases here.
7363 assert(0 && "Unreachable!");
7364 break;
7365 }
7366
7367 return InsertNewInstBefore(Res, *I);
7368}
7369
Reid Spencer3da59db2006-11-27 01:05:10 +00007370/// @brief Implement the transforms common to all CastInst visitors.
7371Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007372 Value *Src = CI.getOperand(0);
7373
Dan Gohman23d9d272007-05-11 21:10:54 +00007374 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007375 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007376 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007377 if (Instruction::CastOps opc =
7378 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7379 // The first cast (CSrc) is eliminable so we need to fix up or replace
7380 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007381 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007382 }
7383 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007384
Reid Spencer3da59db2006-11-27 01:05:10 +00007385 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007386 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7387 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7388 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007389
7390 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007391 if (isa<PHINode>(Src))
7392 if (Instruction *NV = FoldOpIntoPhi(CI))
7393 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007394
Reid Spencer3da59db2006-11-27 01:05:10 +00007395 return 0;
7396}
7397
Chris Lattnerd3e28342007-04-27 17:44:50 +00007398/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7399Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7400 Value *Src = CI.getOperand(0);
7401
Chris Lattnerd3e28342007-04-27 17:44:50 +00007402 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007403 // If casting the result of a getelementptr instruction with no offset, turn
7404 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007405 if (GEP->hasAllZeroIndices()) {
7406 // Changing the cast operand is usually not a good idea but it is safe
7407 // here because the pointer operand is being replaced with another
7408 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007409 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007410 CI.setOperand(0, GEP->getOperand(0));
7411 return &CI;
7412 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007413
7414 // If the GEP has a single use, and the base pointer is a bitcast, and the
7415 // GEP computes a constant offset, see if we can convert these three
7416 // instructions into fewer. This typically happens with unions and other
7417 // non-type-safe code.
7418 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7419 if (GEP->hasAllConstantIndices()) {
7420 // We are guaranteed to get a constant from EmitGEPOffset.
7421 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7422 int64_t Offset = OffsetV->getSExtValue();
7423
7424 // Get the base pointer input of the bitcast, and the type it points to.
7425 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7426 const Type *GEPIdxTy =
7427 cast<PointerType>(OrigBase->getType())->getElementType();
7428 if (GEPIdxTy->isSized()) {
7429 SmallVector<Value*, 8> NewIndices;
7430
Chris Lattnerc42e2262007-05-05 01:59:31 +00007431 // Start with the index over the outer type. Note that the type size
7432 // might be zero (even if the offset isn't zero) if the indexed type
7433 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007434 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007435 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007436 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007437 FirstIdx = Offset/TySize;
7438 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007439
Chris Lattnerc42e2262007-05-05 01:59:31 +00007440 // Handle silly modulus not returning values values [0..TySize).
7441 if (Offset < 0) {
7442 --FirstIdx;
7443 Offset += TySize;
7444 assert(Offset >= 0);
7445 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007446 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007447 }
7448
7449 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007450
7451 // Index into the types. If we fail, set OrigBase to null.
7452 while (Offset) {
7453 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7454 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007455 if (Offset < (int64_t)SL->getSizeInBytes()) {
7456 unsigned Elt = SL->getElementContainingOffset(Offset);
7457 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007458
Chris Lattner6b6aef82007-05-15 00:16:00 +00007459 Offset -= SL->getElementOffset(Elt);
7460 GEPIdxTy = STy->getElementType(Elt);
7461 } else {
7462 // Otherwise, we can't index into this, bail out.
7463 Offset = 0;
7464 OrigBase = 0;
7465 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007466 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7467 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007468 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007469 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7470 Offset %= EltSize;
7471 } else {
7472 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7473 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007474 GEPIdxTy = STy->getElementType();
7475 } else {
7476 // Otherwise, we can't index into this, bail out.
7477 Offset = 0;
7478 OrigBase = 0;
7479 }
7480 }
7481 if (OrigBase) {
7482 // If we were able to index down into an element, create the GEP
7483 // and bitcast the result. This eliminates one bitcast, potentially
7484 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007485 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7486 NewIndices.begin(),
7487 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007488 InsertNewInstBefore(NGEP, CI);
7489 NGEP->takeName(GEP);
7490
Chris Lattner9bc14642007-04-28 00:57:34 +00007491 if (isa<BitCastInst>(CI))
7492 return new BitCastInst(NGEP, CI.getType());
7493 assert(isa<PtrToIntInst>(CI));
7494 return new PtrToIntInst(NGEP, CI.getType());
7495 }
7496 }
7497 }
7498 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007499 }
7500
7501 return commonCastTransforms(CI);
7502}
7503
7504
7505
Chris Lattnerc739cd62007-03-03 05:27:34 +00007506/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7507/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007508/// cases.
7509/// @brief Implement the transforms common to CastInst with integer operands
7510Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7511 if (Instruction *Result = commonCastTransforms(CI))
7512 return Result;
7513
7514 Value *Src = CI.getOperand(0);
7515 const Type *SrcTy = Src->getType();
7516 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007517 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7518 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007519
Reid Spencer3da59db2006-11-27 01:05:10 +00007520 // See if we can simplify any instructions used by the LHS whose sole
7521 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007522 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7523 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007524 KnownZero, KnownOne))
7525 return &CI;
7526
7527 // If the source isn't an instruction or has more than one use then we
7528 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007529 Instruction *SrcI = dyn_cast<Instruction>(Src);
7530 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007531 return 0;
7532
Chris Lattnerc739cd62007-03-03 05:27:34 +00007533 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007534 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007535 if (!isa<BitCastInst>(CI) &&
7536 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007537 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007538 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007539 // eliminates the cast, so it is always a win. If this is a zero-extension,
7540 // we need to do an AND to maintain the clear top-part of the computation,
7541 // so we require that the input have eliminated at least one cast. If this
7542 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007543 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007544 bool DoXForm;
7545 switch (CI.getOpcode()) {
7546 default:
7547 // All the others use floating point so we shouldn't actually
7548 // get here because of the check above.
7549 assert(0 && "Unknown cast type");
7550 case Instruction::Trunc:
7551 DoXForm = true;
7552 break;
7553 case Instruction::ZExt:
7554 DoXForm = NumCastsRemoved >= 1;
7555 break;
7556 case Instruction::SExt:
7557 DoXForm = NumCastsRemoved >= 2;
7558 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007559 }
7560
7561 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007562 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7563 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007564 assert(Res->getType() == DestTy);
7565 switch (CI.getOpcode()) {
7566 default: assert(0 && "Unknown cast type!");
7567 case Instruction::Trunc:
7568 case Instruction::BitCast:
7569 // Just replace this cast with the result.
7570 return ReplaceInstUsesWith(CI, Res);
7571 case Instruction::ZExt: {
7572 // We need to emit an AND to clear the high bits.
7573 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007574 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7575 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007576 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007577 }
7578 case Instruction::SExt:
7579 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007580 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007581 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7582 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007583 }
7584 }
7585 }
7586
7587 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7588 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7589
7590 switch (SrcI->getOpcode()) {
7591 case Instruction::Add:
7592 case Instruction::Mul:
7593 case Instruction::And:
7594 case Instruction::Or:
7595 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007596 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007597 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7598 // Don't insert two casts if they cannot be eliminated. We allow
7599 // two casts to be inserted if the sizes are the same. This could
7600 // only be converting signedness, which is a noop.
7601 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007602 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7603 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007604 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007605 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7606 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007607 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007608 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007609 }
7610 }
7611
7612 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7613 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7614 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007615 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007616 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007617 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007618 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007619 }
7620 break;
7621 case Instruction::SDiv:
7622 case Instruction::UDiv:
7623 case Instruction::SRem:
7624 case Instruction::URem:
7625 // If we are just changing the sign, rewrite.
7626 if (DestBitSize == SrcBitSize) {
7627 // Don't insert two casts if they cannot be eliminated. We allow
7628 // two casts to be inserted if the sizes are the same. This could
7629 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007630 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7631 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007632 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7633 Op0, DestTy, SrcI);
7634 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7635 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007636 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007637 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7638 }
7639 }
7640 break;
7641
7642 case Instruction::Shl:
7643 // Allow changing the sign of the source operand. Do not allow
7644 // changing the size of the shift, UNLESS the shift amount is a
7645 // constant. We must not change variable sized shifts to a smaller
7646 // size, because it is undefined to shift more bits out than exist
7647 // in the value.
7648 if (DestBitSize == SrcBitSize ||
7649 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007650 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7651 Instruction::BitCast : Instruction::Trunc);
7652 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007653 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007654 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007655 }
7656 break;
7657 case Instruction::AShr:
7658 // If this is a signed shr, and if all bits shifted in are about to be
7659 // truncated off, turn it into an unsigned shr to allow greater
7660 // simplifications.
7661 if (DestBitSize < SrcBitSize &&
7662 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007663 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007664 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7665 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007666 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007667 }
7668 }
7669 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007670 }
7671 return 0;
7672}
7673
Chris Lattner8a9f5712007-04-11 06:57:46 +00007674Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007675 if (Instruction *Result = commonIntCastTransforms(CI))
7676 return Result;
7677
7678 Value *Src = CI.getOperand(0);
7679 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007680 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7681 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007682
7683 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7684 switch (SrcI->getOpcode()) {
7685 default: break;
7686 case Instruction::LShr:
7687 // We can shrink lshr to something smaller if we know the bits shifted in
7688 // are already zeros.
7689 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007690 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007691
7692 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007693 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007694 Value* SrcIOp0 = SrcI->getOperand(0);
7695 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007696 if (ShAmt >= DestBitWidth) // All zeros.
7697 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7698
7699 // Okay, we can shrink this. Truncate the input, then return a new
7700 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007701 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7702 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7703 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007704 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007705 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007706 } else { // This is a variable shr.
7707
7708 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7709 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7710 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007711 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007712 Value *One = ConstantInt::get(SrcI->getType(), 1);
7713
Reid Spencer832254e2007-02-02 02:16:23 +00007714 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007715 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007716 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007717 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007718 SrcI->getOperand(0),
7719 "tmp"), CI);
7720 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007721 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007722 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007723 }
7724 break;
7725 }
7726 }
7727
7728 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007729}
7730
Evan Chengb98a10e2008-03-24 00:21:34 +00007731/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7732/// in order to eliminate the icmp.
7733Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7734 bool DoXform) {
7735 // If we are just checking for a icmp eq of a single bit and zext'ing it
7736 // to an integer, then shift the bit to the appropriate place and then
7737 // cast to integer to avoid the comparison.
7738 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7739 const APInt &Op1CV = Op1C->getValue();
7740
7741 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7742 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7743 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7744 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7745 if (!DoXform) return ICI;
7746
7747 Value *In = ICI->getOperand(0);
7748 Value *Sh = ConstantInt::get(In->getType(),
7749 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007750 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00007751 In->getName()+".lobit"),
7752 CI);
7753 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007754 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00007755 false/*ZExt*/, "tmp", &CI);
7756
7757 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7758 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007759 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00007760 In->getName()+".not"),
7761 CI);
7762 }
7763
7764 return ReplaceInstUsesWith(CI, In);
7765 }
7766
7767
7768
7769 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7770 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7771 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7772 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7773 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7774 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7775 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7776 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7777 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7778 // This only works for EQ and NE
7779 ICI->isEquality()) {
7780 // If Op1C some other power of two, convert:
7781 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7782 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7783 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7784 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7785
7786 APInt KnownZeroMask(~KnownZero);
7787 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7788 if (!DoXform) return ICI;
7789
7790 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7791 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7792 // (X&4) == 2 --> false
7793 // (X&4) != 2 --> true
7794 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7795 Res = ConstantExpr::getZExt(Res, CI.getType());
7796 return ReplaceInstUsesWith(CI, Res);
7797 }
7798
7799 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7800 Value *In = ICI->getOperand(0);
7801 if (ShiftAmt) {
7802 // Perform a logical shr by shiftamt.
7803 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007804 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00007805 ConstantInt::get(In->getType(), ShiftAmt),
7806 In->getName()+".lobit"), CI);
7807 }
7808
7809 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7810 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007811 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007812 InsertNewInstBefore(cast<Instruction>(In), CI);
7813 }
7814
7815 if (CI.getType() == In->getType())
7816 return ReplaceInstUsesWith(CI, In);
7817 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007818 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00007819 }
7820 }
7821 }
7822
7823 return 0;
7824}
7825
Chris Lattner8a9f5712007-04-11 06:57:46 +00007826Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007827 // If one of the common conversion will work ..
7828 if (Instruction *Result = commonIntCastTransforms(CI))
7829 return Result;
7830
7831 Value *Src = CI.getOperand(0);
7832
7833 // If this is a cast of a cast
7834 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007835 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7836 // types and if the sizes are just right we can convert this into a logical
7837 // 'and' which will be much cheaper than the pair of casts.
7838 if (isa<TruncInst>(CSrc)) {
7839 // Get the sizes of the types involved
7840 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007841 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7842 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7843 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007844 // If we're actually extending zero bits and the trunc is a no-op
7845 if (MidSize < DstSize && SrcSize == DstSize) {
7846 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007847 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007848 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007849 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007850 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00007851 // Unfortunately, if the type changed, we need to cast it back.
7852 if (And->getType() != CI.getType()) {
7853 And->setName(CSrc->getName()+".mask");
7854 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007855 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007856 }
7857 return And;
7858 }
7859 }
7860 }
7861
Evan Chengb98a10e2008-03-24 00:21:34 +00007862 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7863 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007864
Evan Chengb98a10e2008-03-24 00:21:34 +00007865 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7866 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7867 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7868 // of the (zext icmp) will be transformed.
7869 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7870 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7871 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7872 (transformZExtICmp(LHS, CI, false) ||
7873 transformZExtICmp(RHS, CI, false))) {
7874 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7875 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007876 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007877 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007878 }
7879
Reid Spencer3da59db2006-11-27 01:05:10 +00007880 return 0;
7881}
7882
Chris Lattner8a9f5712007-04-11 06:57:46 +00007883Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007884 if (Instruction *I = commonIntCastTransforms(CI))
7885 return I;
7886
Chris Lattner8a9f5712007-04-11 06:57:46 +00007887 Value *Src = CI.getOperand(0);
7888
7889 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7890 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7891 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7892 // If we are just checking for a icmp eq of a single bit and zext'ing it
7893 // to an integer, then shift the bit to the appropriate place and then
7894 // cast to integer to avoid the comparison.
7895 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7896 const APInt &Op1CV = Op1C->getValue();
7897
7898 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7899 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7900 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7901 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7902 Value *In = ICI->getOperand(0);
7903 Value *Sh = ConstantInt::get(In->getType(),
7904 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007905 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007906 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007907 CI);
7908 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007909 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007910 true/*SExt*/, "tmp", &CI);
7911
7912 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007913 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00007914 In->getName()+".not"), CI);
7915
7916 return ReplaceInstUsesWith(CI, In);
7917 }
7918 }
7919 }
7920
Chris Lattnerba417832007-04-11 06:12:58 +00007921 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007922}
7923
Chris Lattnerb7530652008-01-27 05:29:54 +00007924/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7925/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007926static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007927 APFloat F = CFP->getValueAPF();
7928 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007929 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007930 return 0;
7931}
7932
7933/// LookThroughFPExtensions - If this is an fp extension instruction, look
7934/// through it until we get the source value.
7935static Value *LookThroughFPExtensions(Value *V) {
7936 if (Instruction *I = dyn_cast<Instruction>(V))
7937 if (I->getOpcode() == Instruction::FPExt)
7938 return LookThroughFPExtensions(I->getOperand(0));
7939
7940 // If this value is a constant, return the constant in the smallest FP type
7941 // that can accurately represent it. This allows us to turn
7942 // (float)((double)X+2.0) into x+2.0f.
7943 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7944 if (CFP->getType() == Type::PPC_FP128Ty)
7945 return V; // No constant folding of this.
7946 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007947 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007948 return V;
7949 if (CFP->getType() == Type::DoubleTy)
7950 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007951 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007952 return V;
7953 // Don't try to shrink to various long double types.
7954 }
7955
7956 return V;
7957}
7958
7959Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7960 if (Instruction *I = commonCastTransforms(CI))
7961 return I;
7962
7963 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7964 // smaller than the destination type, we can eliminate the truncate by doing
7965 // the add as the smaller type. This applies to add/sub/mul/div as well as
7966 // many builtins (sqrt, etc).
7967 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7968 if (OpI && OpI->hasOneUse()) {
7969 switch (OpI->getOpcode()) {
7970 default: break;
7971 case Instruction::Add:
7972 case Instruction::Sub:
7973 case Instruction::Mul:
7974 case Instruction::FDiv:
7975 case Instruction::FRem:
7976 const Type *SrcTy = OpI->getType();
7977 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7978 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7979 if (LHSTrunc->getType() != SrcTy &&
7980 RHSTrunc->getType() != SrcTy) {
7981 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7982 // If the source types were both smaller than the destination type of
7983 // the cast, do this xform.
7984 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7985 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7986 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7987 CI.getType(), CI);
7988 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7989 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007990 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00007991 }
7992 }
7993 break;
7994 }
7995 }
7996 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007997}
7998
7999Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8000 return commonCastTransforms(CI);
8001}
8002
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008003Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8004 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
8005 // mantissa to accurately represent all values of X. For example, do not
8006 // do this with i64->float->i64.
8007 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8008 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8009 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8010 GetFPMantissaWidth(SrcI->getType()))
8011 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8012
8013 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008014}
8015
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008016Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8017 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
8018 // mantissa to accurately represent all values of X. For example, do not
8019 // do this with i64->float->i64.
8020 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8021 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8022 (int)FI.getType()->getPrimitiveSizeInBits() <=
8023 GetFPMantissaWidth(SrcI->getType()))
8024 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8025
8026 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008027}
8028
8029Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8030 return commonCastTransforms(CI);
8031}
8032
8033Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8034 return commonCastTransforms(CI);
8035}
8036
8037Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008038 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008039}
8040
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008041Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8042 if (Instruction *I = commonCastTransforms(CI))
8043 return I;
8044
8045 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8046 if (!DestPointee->isSized()) return 0;
8047
8048 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8049 ConstantInt *Cst;
8050 Value *X;
8051 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8052 m_ConstantInt(Cst)))) {
8053 // If the source and destination operands have the same type, see if this
8054 // is a single-index GEP.
8055 if (X->getType() == CI.getType()) {
8056 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00008057 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008058
8059 // Convert the constant to intptr type.
8060 APInt Offset = Cst->getValue();
8061 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8062
8063 // If Offset is evenly divisible by Size, we can do this xform.
8064 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8065 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008066 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008067 }
8068 }
8069 // TODO: Could handle other cases, e.g. where add is indexing into field of
8070 // struct etc.
8071 } else if (CI.getOperand(0)->hasOneUse() &&
8072 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8073 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8074 // "inttoptr+GEP" instead of "add+intptr".
8075
8076 // Get the size of the pointee type.
8077 uint64_t Size = TD->getABITypeSize(DestPointee);
8078
8079 // Convert the constant to intptr type.
8080 APInt Offset = Cst->getValue();
8081 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8082
8083 // If Offset is evenly divisible by Size, we can do this xform.
8084 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8085 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8086
8087 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8088 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008089 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008090 }
8091 }
8092 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008093}
8094
Chris Lattnerd3e28342007-04-27 17:44:50 +00008095Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008096 // If the operands are integer typed then apply the integer transforms,
8097 // otherwise just apply the common ones.
8098 Value *Src = CI.getOperand(0);
8099 const Type *SrcTy = Src->getType();
8100 const Type *DestTy = CI.getType();
8101
Chris Lattner42a75512007-01-15 02:27:26 +00008102 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008103 if (Instruction *Result = commonIntCastTransforms(CI))
8104 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008105 } else if (isa<PointerType>(SrcTy)) {
8106 if (Instruction *I = commonPointerCastTransforms(CI))
8107 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008108 } else {
8109 if (Instruction *Result = commonCastTransforms(CI))
8110 return Result;
8111 }
8112
8113
8114 // Get rid of casts from one type to the same type. These are useless and can
8115 // be replaced by the operand.
8116 if (DestTy == Src->getType())
8117 return ReplaceInstUsesWith(CI, Src);
8118
Reid Spencer3da59db2006-11-27 01:05:10 +00008119 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008120 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8121 const Type *DstElTy = DstPTy->getElementType();
8122 const Type *SrcElTy = SrcPTy->getElementType();
8123
Nate Begeman83ad90a2008-03-31 00:22:16 +00008124 // If the address spaces don't match, don't eliminate the bitcast, which is
8125 // required for changing types.
8126 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8127 return 0;
8128
Chris Lattnerd3e28342007-04-27 17:44:50 +00008129 // If we are casting a malloc or alloca to a pointer to a type of the same
8130 // size, rewrite the allocation instruction to allocate the "right" type.
8131 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8132 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8133 return V;
8134
Chris Lattnerd717c182007-05-05 22:32:24 +00008135 // If the source and destination are pointers, and this cast is equivalent
8136 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008137 // This can enhance SROA and other transforms that want type-safe pointers.
8138 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8139 unsigned NumZeros = 0;
8140 while (SrcElTy != DstElTy &&
8141 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8142 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8143 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8144 ++NumZeros;
8145 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008146
Chris Lattnerd3e28342007-04-27 17:44:50 +00008147 // If we found a path from the src to dest, create the getelementptr now.
8148 if (SrcElTy == DstElTy) {
8149 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008150 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8151 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008152 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008153 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008154
Reid Spencer3da59db2006-11-27 01:05:10 +00008155 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8156 if (SVI->hasOneUse()) {
8157 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8158 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008159 if (isa<VectorType>(DestTy) &&
8160 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00008161 SVI->getType()->getNumElements()) {
8162 CastInst *Tmp;
8163 // If either of the operands is a cast from CI.getType(), then
8164 // evaluating the shuffle in the casted destination's type will allow
8165 // us to eliminate at least one cast.
8166 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8167 Tmp->getOperand(0)->getType() == DestTy) ||
8168 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8169 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008170 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8171 SVI->getOperand(0), DestTy, &CI);
8172 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8173 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008174 // Return a new shuffle vector. Use the same element ID's, as we
8175 // know the vector types match #elts.
8176 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008177 }
8178 }
8179 }
8180 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008181 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008182}
8183
Chris Lattnere576b912004-04-09 23:46:01 +00008184/// GetSelectFoldableOperands - We want to turn code that looks like this:
8185/// %C = or %A, %B
8186/// %D = select %cond, %C, %A
8187/// into:
8188/// %C = select %cond, %B, 0
8189/// %D = or %A, %C
8190///
8191/// Assuming that the specified instruction is an operand to the select, return
8192/// a bitmask indicating which operands of this instruction are foldable if they
8193/// equal the other incoming value of the select.
8194///
8195static unsigned GetSelectFoldableOperands(Instruction *I) {
8196 switch (I->getOpcode()) {
8197 case Instruction::Add:
8198 case Instruction::Mul:
8199 case Instruction::And:
8200 case Instruction::Or:
8201 case Instruction::Xor:
8202 return 3; // Can fold through either operand.
8203 case Instruction::Sub: // Can only fold on the amount subtracted.
8204 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008205 case Instruction::LShr:
8206 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008207 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008208 default:
8209 return 0; // Cannot fold
8210 }
8211}
8212
8213/// GetSelectFoldableConstant - For the same transformation as the previous
8214/// function, return the identity constant that goes into the select.
8215static Constant *GetSelectFoldableConstant(Instruction *I) {
8216 switch (I->getOpcode()) {
8217 default: assert(0 && "This cannot happen!"); abort();
8218 case Instruction::Add:
8219 case Instruction::Sub:
8220 case Instruction::Or:
8221 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008222 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008223 case Instruction::LShr:
8224 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008225 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008226 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008227 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008228 case Instruction::Mul:
8229 return ConstantInt::get(I->getType(), 1);
8230 }
8231}
8232
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008233/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8234/// have the same opcode and only one use each. Try to simplify this.
8235Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8236 Instruction *FI) {
8237 if (TI->getNumOperands() == 1) {
8238 // If this is a non-volatile load or a cast from the same type,
8239 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008240 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008241 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8242 return 0;
8243 } else {
8244 return 0; // unknown unary op.
8245 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008246
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008247 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008248 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8249 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008250 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008251 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008252 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008253 }
8254
Reid Spencer832254e2007-02-02 02:16:23 +00008255 // Only handle binary operators here.
8256 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008257 return 0;
8258
8259 // Figure out if the operations have any operands in common.
8260 Value *MatchOp, *OtherOpT, *OtherOpF;
8261 bool MatchIsOpZero;
8262 if (TI->getOperand(0) == FI->getOperand(0)) {
8263 MatchOp = TI->getOperand(0);
8264 OtherOpT = TI->getOperand(1);
8265 OtherOpF = FI->getOperand(1);
8266 MatchIsOpZero = true;
8267 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8268 MatchOp = TI->getOperand(1);
8269 OtherOpT = TI->getOperand(0);
8270 OtherOpF = FI->getOperand(0);
8271 MatchIsOpZero = false;
8272 } else if (!TI->isCommutative()) {
8273 return 0;
8274 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8275 MatchOp = TI->getOperand(0);
8276 OtherOpT = TI->getOperand(1);
8277 OtherOpF = FI->getOperand(0);
8278 MatchIsOpZero = true;
8279 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8280 MatchOp = TI->getOperand(1);
8281 OtherOpT = TI->getOperand(0);
8282 OtherOpF = FI->getOperand(1);
8283 MatchIsOpZero = true;
8284 } else {
8285 return 0;
8286 }
8287
8288 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008289 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8290 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008291 InsertNewInstBefore(NewSI, SI);
8292
8293 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8294 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008295 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008296 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008297 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008298 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008299 assert(0 && "Shouldn't get here");
8300 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008301}
8302
Chris Lattner3d69f462004-03-12 05:52:32 +00008303Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008304 Value *CondVal = SI.getCondition();
8305 Value *TrueVal = SI.getTrueValue();
8306 Value *FalseVal = SI.getFalseValue();
8307
8308 // select true, X, Y -> X
8309 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008310 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008311 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008312
8313 // select C, X, X -> X
8314 if (TrueVal == FalseVal)
8315 return ReplaceInstUsesWith(SI, TrueVal);
8316
Chris Lattnere87597f2004-10-16 18:11:37 +00008317 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8318 return ReplaceInstUsesWith(SI, FalseVal);
8319 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8320 return ReplaceInstUsesWith(SI, TrueVal);
8321 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8322 if (isa<Constant>(TrueVal))
8323 return ReplaceInstUsesWith(SI, TrueVal);
8324 else
8325 return ReplaceInstUsesWith(SI, FalseVal);
8326 }
8327
Reid Spencer4fe16d62007-01-11 18:21:29 +00008328 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008329 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008330 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008331 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008332 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008333 } else {
8334 // Change: A = select B, false, C --> A = and !B, C
8335 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008336 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008337 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008338 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008339 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008340 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008341 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008342 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008343 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008344 } else {
8345 // Change: A = select B, C, true --> A = or !B, C
8346 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008347 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008348 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008349 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008350 }
8351 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008352
8353 // select a, b, a -> a&b
8354 // select a, a, b -> a|b
8355 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008356 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008357 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008358 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008359 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008360
Chris Lattner2eefe512004-04-09 19:05:30 +00008361 // Selecting between two integer constants?
8362 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8363 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008364 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008365 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008366 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008367 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008368 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008369 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008370 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008371 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008372 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008373 }
Chris Lattnerba417832007-04-11 06:12:58 +00008374
8375 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008376
Reid Spencere4d87aa2006-12-23 06:05:41 +00008377 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008378
Reid Spencere4d87aa2006-12-23 06:05:41 +00008379 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008380 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008381 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008382 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008383 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008384 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008385 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008386 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008387 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008388 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008389 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008390 InsertNewInstBefore(SRA, SI);
8391
Reid Spencer3da59db2006-11-27 01:05:10 +00008392 // Finally, convert to the type of the select RHS. We figure out
8393 // if this requires a SExt, Trunc or BitCast based on the sizes.
8394 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008395 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8396 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008397 if (SRASize < SISize)
8398 opc = Instruction::SExt;
8399 else if (SRASize > SISize)
8400 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008401 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008402 }
8403 }
8404
8405
8406 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008407 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008408 // non-constant value, eliminate this whole mess. This corresponds to
8409 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008410 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008411 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008412 cast<Constant>(IC->getOperand(1))->isNullValue())
8413 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8414 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008415 isa<ConstantInt>(ICA->getOperand(1)) &&
8416 (ICA->getOperand(1) == TrueValC ||
8417 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008418 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8419 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008420 // know whether we have a icmp_ne or icmp_eq and whether the
8421 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008422 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008423 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008424 Value *V = ICA;
8425 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008426 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008427 Instruction::Xor, V, ICA->getOperand(1)), SI);
8428 return ReplaceInstUsesWith(SI, V);
8429 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008430 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008431 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008432
8433 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008434 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8435 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008436 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008437 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8438 // This is not safe in general for floating point:
8439 // consider X== -0, Y== +0.
8440 // It becomes safe if either operand is a nonzero constant.
8441 ConstantFP *CFPt, *CFPf;
8442 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8443 !CFPt->getValueAPF().isZero()) ||
8444 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8445 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008446 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008447 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008448 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008449 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008450 return ReplaceInstUsesWith(SI, TrueVal);
8451 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8452
Reid Spencere4d87aa2006-12-23 06:05:41 +00008453 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008454 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008455 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8456 // This is not safe in general for floating point:
8457 // consider X== -0, Y== +0.
8458 // It becomes safe if either operand is a nonzero constant.
8459 ConstantFP *CFPt, *CFPf;
8460 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8461 !CFPt->getValueAPF().isZero()) ||
8462 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8463 !CFPf->getValueAPF().isZero()))
8464 return ReplaceInstUsesWith(SI, FalseVal);
8465 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008466 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008467 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8468 return ReplaceInstUsesWith(SI, TrueVal);
8469 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8470 }
8471 }
8472
8473 // See if we are selecting two values based on a comparison of the two values.
8474 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8475 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8476 // Transform (X == Y) ? X : Y -> Y
8477 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8478 return ReplaceInstUsesWith(SI, FalseVal);
8479 // Transform (X != Y) ? X : Y -> X
8480 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8481 return ReplaceInstUsesWith(SI, TrueVal);
8482 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8483
8484 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8485 // Transform (X == Y) ? Y : X -> X
8486 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8487 return ReplaceInstUsesWith(SI, FalseVal);
8488 // Transform (X != Y) ? Y : X -> Y
8489 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008490 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008491 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8492 }
8493 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008494
Chris Lattner87875da2005-01-13 22:52:24 +00008495 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8496 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8497 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008498 Instruction *AddOp = 0, *SubOp = 0;
8499
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008500 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8501 if (TI->getOpcode() == FI->getOpcode())
8502 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8503 return IV;
8504
8505 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8506 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008507 if (TI->getOpcode() == Instruction::Sub &&
8508 FI->getOpcode() == Instruction::Add) {
8509 AddOp = FI; SubOp = TI;
8510 } else if (FI->getOpcode() == Instruction::Sub &&
8511 TI->getOpcode() == Instruction::Add) {
8512 AddOp = TI; SubOp = FI;
8513 }
8514
8515 if (AddOp) {
8516 Value *OtherAddOp = 0;
8517 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8518 OtherAddOp = AddOp->getOperand(1);
8519 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8520 OtherAddOp = AddOp->getOperand(0);
8521 }
8522
8523 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008524 // So at this point we know we have (Y -> OtherAddOp):
8525 // select C, (add X, Y), (sub X, Z)
8526 Value *NegVal; // Compute -Z
8527 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8528 NegVal = ConstantExpr::getNeg(C);
8529 } else {
8530 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008531 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008532 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008533
8534 Value *NewTrueOp = OtherAddOp;
8535 Value *NewFalseOp = NegVal;
8536 if (AddOp != TI)
8537 std::swap(NewTrueOp, NewFalseOp);
8538 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008539 SelectInst::Create(CondVal, NewTrueOp,
8540 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008541
8542 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008543 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008544 }
8545 }
8546 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008547
Chris Lattnere576b912004-04-09 23:46:01 +00008548 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008549 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008550 // See the comment above GetSelectFoldableOperands for a description of the
8551 // transformation we are doing here.
8552 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8553 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8554 !isa<Constant>(FalseVal))
8555 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8556 unsigned OpToFold = 0;
8557 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8558 OpToFold = 1;
8559 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8560 OpToFold = 2;
8561 }
8562
8563 if (OpToFold) {
8564 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008565 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008566 SelectInst::Create(SI.getCondition(),
8567 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008568 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008569 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008570 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008571 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008572 else {
8573 assert(0 && "Unknown instruction!!");
8574 }
8575 }
8576 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008577
Chris Lattnere576b912004-04-09 23:46:01 +00008578 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8579 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8580 !isa<Constant>(TrueVal))
8581 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8582 unsigned OpToFold = 0;
8583 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8584 OpToFold = 1;
8585 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8586 OpToFold = 2;
8587 }
8588
8589 if (OpToFold) {
8590 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008591 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008592 SelectInst::Create(SI.getCondition(), C,
8593 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008594 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008595 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008596 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008597 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008598 else
Chris Lattnere576b912004-04-09 23:46:01 +00008599 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008600 }
8601 }
8602 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008603
8604 if (BinaryOperator::isNot(CondVal)) {
8605 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8606 SI.setOperand(1, FalseVal);
8607 SI.setOperand(2, TrueVal);
8608 return &SI;
8609 }
8610
Chris Lattner3d69f462004-03-12 05:52:32 +00008611 return 0;
8612}
8613
Dan Gohmaneee962e2008-04-10 18:43:06 +00008614/// EnforceKnownAlignment - If the specified pointer points to an object that
8615/// we control, modify the object's alignment to PrefAlign. This isn't
8616/// often possible though. If alignment is important, a more reliable approach
8617/// is to simply align all global variables and allocation instructions to
8618/// their preferred alignment from the beginning.
8619///
8620static unsigned EnforceKnownAlignment(Value *V,
8621 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008622
Dan Gohmaneee962e2008-04-10 18:43:06 +00008623 User *U = dyn_cast<User>(V);
8624 if (!U) return Align;
8625
8626 switch (getOpcode(U)) {
8627 default: break;
8628 case Instruction::BitCast:
8629 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8630 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008631 // If all indexes are zero, it is just the alignment of the base pointer.
8632 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008633 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8634 if (!isa<Constant>(U->getOperand(i)) ||
8635 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008636 AllZeroOperands = false;
8637 break;
8638 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008639
8640 if (AllZeroOperands) {
8641 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008642 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008643 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008644 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008645 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008646 }
8647
8648 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8649 // If there is a large requested alignment and we can, bump up the alignment
8650 // of the global.
8651 if (!GV->isDeclaration()) {
8652 GV->setAlignment(PrefAlign);
8653 Align = PrefAlign;
8654 }
8655 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8656 // If there is a requested alignment and if this is an alloca, round up. We
8657 // don't do this for malloc, because some systems can't respect the request.
8658 if (isa<AllocaInst>(AI)) {
8659 AI->setAlignment(PrefAlign);
8660 Align = PrefAlign;
8661 }
8662 }
8663
8664 return Align;
8665}
8666
8667/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8668/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8669/// and it is more than the alignment of the ultimate object, see if we can
8670/// increase the alignment of the ultimate object, making this check succeed.
8671unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8672 unsigned PrefAlign) {
8673 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8674 sizeof(PrefAlign) * CHAR_BIT;
8675 APInt Mask = APInt::getAllOnesValue(BitWidth);
8676 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8677 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8678 unsigned TrailZ = KnownZero.countTrailingOnes();
8679 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8680
8681 if (PrefAlign > Align)
8682 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8683
8684 // We don't need to make any adjustment.
8685 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008686}
8687
Chris Lattnerf497b022008-01-13 23:50:23 +00008688Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008689 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8690 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008691 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8692 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8693
8694 if (CopyAlign < MinAlign) {
8695 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8696 return MI;
8697 }
8698
8699 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8700 // load/store.
8701 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8702 if (MemOpLength == 0) return 0;
8703
Chris Lattner37ac6082008-01-14 00:28:35 +00008704 // Source and destination pointer types are always "i8*" for intrinsic. See
8705 // if the size is something we can handle with a single primitive load/store.
8706 // A single load+store correctly handles overlapping memory in the memmove
8707 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008708 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008709 if (Size == 0) return MI; // Delete this mem transfer.
8710
8711 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008712 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008713
Chris Lattner37ac6082008-01-14 00:28:35 +00008714 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008715 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008716
8717 // Memcpy forces the use of i8* for the source and destination. That means
8718 // that if you're using memcpy to move one double around, you'll get a cast
8719 // from double* to i8*. We'd much rather use a double load+store rather than
8720 // an i64 load+store, here because this improves the odds that the source or
8721 // dest address will be promotable. See if we can find a better type than the
8722 // integer datatype.
8723 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8724 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8725 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8726 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8727 // down through these levels if so.
8728 while (!SrcETy->isFirstClassType()) {
8729 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8730 if (STy->getNumElements() == 1)
8731 SrcETy = STy->getElementType(0);
8732 else
8733 break;
8734 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8735 if (ATy->getNumElements() == 1)
8736 SrcETy = ATy->getElementType();
8737 else
8738 break;
8739 } else
8740 break;
8741 }
8742
8743 if (SrcETy->isFirstClassType())
8744 NewPtrTy = PointerType::getUnqual(SrcETy);
8745 }
8746 }
8747
8748
Chris Lattnerf497b022008-01-13 23:50:23 +00008749 // If the memcpy/memmove provides better alignment info than we can
8750 // infer, use it.
8751 SrcAlign = std::max(SrcAlign, CopyAlign);
8752 DstAlign = std::max(DstAlign, CopyAlign);
8753
8754 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8755 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008756 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8757 InsertNewInstBefore(L, *MI);
8758 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8759
8760 // Set the size of the copy to 0, it will be deleted on the next iteration.
8761 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8762 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008763}
Chris Lattner3d69f462004-03-12 05:52:32 +00008764
Chris Lattner69ea9d22008-04-30 06:39:11 +00008765Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8766 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8767 if (MI->getAlignment()->getZExtValue() < Alignment) {
8768 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8769 return MI;
8770 }
8771
8772 // Extract the length and alignment and fill if they are constant.
8773 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8774 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8775 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8776 return 0;
8777 uint64_t Len = LenC->getZExtValue();
8778 Alignment = MI->getAlignment()->getZExtValue();
8779
8780 // If the length is zero, this is a no-op
8781 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8782
8783 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8784 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8785 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8786
8787 Value *Dest = MI->getDest();
8788 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8789
8790 // Alignment 0 is identity for alignment 1 for memset, but not store.
8791 if (Alignment == 0) Alignment = 1;
8792
8793 // Extract the fill value and store.
8794 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8795 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8796 Alignment), *MI);
8797
8798 // Set the size of the copy to 0, it will be deleted on the next iteration.
8799 MI->setLength(Constant::getNullValue(LenC->getType()));
8800 return MI;
8801 }
8802
8803 return 0;
8804}
8805
8806
Chris Lattner8b0ea312006-01-13 20:11:04 +00008807/// visitCallInst - CallInst simplification. This mostly only handles folding
8808/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8809/// the heavy lifting.
8810///
Chris Lattner9fe38862003-06-19 17:00:31 +00008811Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008812 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8813 if (!II) return visitCallSite(&CI);
8814
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008815 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8816 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008817 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008818 bool Changed = false;
8819
8820 // memmove/cpy/set of zero bytes is a noop.
8821 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8822 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8823
Chris Lattner35b9e482004-10-12 04:52:52 +00008824 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008825 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008826 // Replace the instruction with just byte operations. We would
8827 // transform other cases to loads/stores, but we don't know if
8828 // alignment is sufficient.
8829 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008830 }
8831
Chris Lattner35b9e482004-10-12 04:52:52 +00008832 // If we have a memmove and the source operation is a constant global,
8833 // then the source and dest pointers can't alias, so we can change this
8834 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008835 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008836 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8837 if (GVSrc->isConstant()) {
8838 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008839 Intrinsic::ID MemCpyID;
8840 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8841 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008842 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008843 MemCpyID = Intrinsic::memcpy_i64;
8844 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008845 Changed = true;
8846 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008847 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008848
Chris Lattner95a959d2006-03-06 20:18:44 +00008849 // If we can determine a pointer alignment that is bigger than currently
8850 // set, update the alignment.
8851 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008852 if (Instruction *I = SimplifyMemTransfer(MI))
8853 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008854 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8855 if (Instruction *I = SimplifyMemSet(MSI))
8856 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008857 }
8858
Chris Lattner8b0ea312006-01-13 20:11:04 +00008859 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008860 } else {
8861 switch (II->getIntrinsicID()) {
8862 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008863 case Intrinsic::ppc_altivec_lvx:
8864 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008865 case Intrinsic::x86_sse_loadu_ps:
8866 case Intrinsic::x86_sse2_loadu_pd:
8867 case Intrinsic::x86_sse2_loadu_dq:
8868 // Turn PPC lvx -> load if the pointer is known aligned.
8869 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008870 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008871 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8872 PointerType::getUnqual(II->getType()),
8873 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008874 return new LoadInst(Ptr);
8875 }
8876 break;
8877 case Intrinsic::ppc_altivec_stvx:
8878 case Intrinsic::ppc_altivec_stvxl:
8879 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008880 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008881 const Type *OpPtrTy =
8882 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008883 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008884 return new StoreInst(II->getOperand(1), Ptr);
8885 }
8886 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008887 case Intrinsic::x86_sse_storeu_ps:
8888 case Intrinsic::x86_sse2_storeu_pd:
8889 case Intrinsic::x86_sse2_storeu_dq:
8890 case Intrinsic::x86_sse2_storel_dq:
8891 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008892 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008893 const Type *OpPtrTy =
8894 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008895 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008896 return new StoreInst(II->getOperand(2), Ptr);
8897 }
8898 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008899
8900 case Intrinsic::x86_sse_cvttss2si: {
8901 // These intrinsics only demands the 0th element of its input vector. If
8902 // we can simplify the input based on that, do so now.
8903 uint64_t UndefElts;
8904 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8905 UndefElts)) {
8906 II->setOperand(1, V);
8907 return II;
8908 }
8909 break;
8910 }
8911
Chris Lattnere2ed0572006-04-06 19:19:17 +00008912 case Intrinsic::ppc_altivec_vperm:
8913 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008914 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008915 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8916
8917 // Check that all of the elements are integer constants or undefs.
8918 bool AllEltsOk = true;
8919 for (unsigned i = 0; i != 16; ++i) {
8920 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8921 !isa<UndefValue>(Mask->getOperand(i))) {
8922 AllEltsOk = false;
8923 break;
8924 }
8925 }
8926
8927 if (AllEltsOk) {
8928 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008929 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8930 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008931 Value *Result = UndefValue::get(Op0->getType());
8932
8933 // Only extract each element once.
8934 Value *ExtractedElts[32];
8935 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8936
8937 for (unsigned i = 0; i != 16; ++i) {
8938 if (isa<UndefValue>(Mask->getOperand(i)))
8939 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008940 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008941 Idx &= 31; // Match the hardware behavior.
8942
8943 if (ExtractedElts[Idx] == 0) {
8944 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008945 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008946 InsertNewInstBefore(Elt, CI);
8947 ExtractedElts[Idx] = Elt;
8948 }
8949
8950 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008951 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8952 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008953 InsertNewInstBefore(cast<Instruction>(Result), CI);
8954 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008955 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008956 }
8957 }
8958 break;
8959
Chris Lattnera728ddc2006-01-13 21:28:09 +00008960 case Intrinsic::stackrestore: {
8961 // If the save is right next to the restore, remove the restore. This can
8962 // happen when variable allocas are DCE'd.
8963 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8964 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8965 BasicBlock::iterator BI = SS;
8966 if (&*++BI == II)
8967 return EraseInstFromFunction(CI);
8968 }
8969 }
8970
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008971 // Scan down this block to see if there is another stack restore in the
8972 // same block without an intervening call/alloca.
8973 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008974 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008975 bool CannotRemove = false;
8976 for (++BI; &*BI != TI; ++BI) {
8977 if (isa<AllocaInst>(BI)) {
8978 CannotRemove = true;
8979 break;
8980 }
8981 if (isa<CallInst>(BI)) {
8982 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008983 CannotRemove = true;
8984 break;
8985 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008986 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008987 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008988 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008989 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008990
8991 // If the stack restore is in a return/unwind block and if there are no
8992 // allocas or calls between the restore and the return, nuke the restore.
8993 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8994 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008995 break;
8996 }
8997 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008998 }
8999
Chris Lattner8b0ea312006-01-13 20:11:04 +00009000 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009001}
9002
9003// InvokeInst simplification
9004//
9005Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009006 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009007}
9008
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009009/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9010/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009011static bool isSafeToEliminateVarargsCast(const CallSite CS,
9012 const CastInst * const CI,
9013 const TargetData * const TD,
9014 const int ix) {
9015 if (!CI->isLosslessCast())
9016 return false;
9017
9018 // The size of ByVal arguments is derived from the type, so we
9019 // can't change to a type with a different size. If the size were
9020 // passed explicitly we could avoid this check.
9021 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9022 return true;
9023
9024 const Type* SrcTy =
9025 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9026 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9027 if (!SrcTy->isSized() || !DstTy->isSized())
9028 return false;
9029 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9030 return false;
9031 return true;
9032}
9033
Chris Lattnera44d8a22003-10-07 22:32:43 +00009034// visitCallSite - Improvements for call and invoke instructions.
9035//
9036Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009037 bool Changed = false;
9038
9039 // If the callee is a constexpr cast of a function, attempt to move the cast
9040 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009041 if (transformConstExprCastCall(CS)) return 0;
9042
Chris Lattner6c266db2003-10-07 22:54:13 +00009043 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009044
Chris Lattner08b22ec2005-05-13 07:09:09 +00009045 if (Function *CalleeF = dyn_cast<Function>(Callee))
9046 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9047 Instruction *OldCall = CS.getInstruction();
9048 // If the call and callee calling conventions don't match, this call must
9049 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009050 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009051 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9052 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009053 if (!OldCall->use_empty())
9054 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9055 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9056 return EraseInstFromFunction(*OldCall);
9057 return 0;
9058 }
9059
Chris Lattner17be6352004-10-18 02:59:09 +00009060 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9061 // This instruction is not reachable, just remove it. We insert a store to
9062 // undef so that we know that this code is not reachable, despite the fact
9063 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009064 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009065 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009066 CS.getInstruction());
9067
9068 if (!CS.getInstruction()->use_empty())
9069 CS.getInstruction()->
9070 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9071
9072 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9073 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009074 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9075 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009076 }
Chris Lattner17be6352004-10-18 02:59:09 +00009077 return EraseInstFromFunction(*CS.getInstruction());
9078 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009079
Duncan Sandscdb6d922007-09-17 10:26:40 +00009080 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9081 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9082 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9083 return transformCallThroughTrampoline(CS);
9084
Chris Lattner6c266db2003-10-07 22:54:13 +00009085 const PointerType *PTy = cast<PointerType>(Callee->getType());
9086 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9087 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009088 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009089 // See if we can optimize any arguments passed through the varargs area of
9090 // the call.
9091 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009092 E = CS.arg_end(); I != E; ++I, ++ix) {
9093 CastInst *CI = dyn_cast<CastInst>(*I);
9094 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9095 *I = CI->getOperand(0);
9096 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009097 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009098 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009099 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009100
Duncan Sandsf0c33542007-12-19 21:13:37 +00009101 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009102 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009103 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009104 Changed = true;
9105 }
9106
Chris Lattner6c266db2003-10-07 22:54:13 +00009107 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009108}
9109
Chris Lattner9fe38862003-06-19 17:00:31 +00009110// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9111// attempt to move the cast to the arguments of the call/invoke.
9112//
9113bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9114 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9115 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009116 if (CE->getOpcode() != Instruction::BitCast ||
9117 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009118 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009119 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009120 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00009121 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00009122
9123 // Okay, this is a cast from a function to a different type. Unless doing so
9124 // would cause a type conversion of one of our arguments, change this call to
9125 // be a direct call with arguments casted to the appropriate types.
9126 //
9127 const FunctionType *FT = Callee->getFunctionType();
9128 const Type *OldRetTy = Caller->getType();
9129
Devang Patel75e6f022008-03-11 18:04:06 +00009130 if (isa<StructType>(FT->getReturnType()))
9131 return false; // TODO: Handle multiple return values.
9132
Chris Lattnerf78616b2004-01-14 06:06:08 +00009133 // Check to see if we are changing the return type...
9134 if (OldRetTy != FT->getReturnType()) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009135 if (Callee->isDeclaration() &&
Chris Lattner46013f42007-01-06 19:53:32 +00009136 // Conversion is ok if changing from pointer to int of same size.
9137 !(isa<PointerType>(FT->getReturnType()) &&
9138 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00009139 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009140
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009141 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009142 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00009143 FT->getReturnType() != Type::VoidTy &&
9144 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009145 return false; // Cannot transform this return value.
9146
Chris Lattner58d74912008-03-12 17:45:29 +00009147 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9148 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00009149 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9150 return false; // Attribute not compatible with transformed value.
9151 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009152
Chris Lattnerf78616b2004-01-14 06:06:08 +00009153 // If the callsite is an invoke instruction, and the return value is used by
9154 // a PHI node in a successor, we cannot change the return type of the call
9155 // because there is no place to put the cast instruction (without breaking
9156 // the critical edge). Bail out in this case.
9157 if (!Caller->use_empty())
9158 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9159 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9160 UI != E; ++UI)
9161 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9162 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009163 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009164 return false;
9165 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009166
9167 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9168 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009169
Chris Lattner9fe38862003-06-19 17:00:31 +00009170 CallSite::arg_iterator AI = CS.arg_begin();
9171 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9172 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009173 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009174
9175 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009176 return false; // Cannot transform this parameter value.
9177
Chris Lattner58d74912008-03-12 17:45:29 +00009178 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9179 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009180
Reid Spencer3da59db2006-11-27 01:05:10 +00009181 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009182 // Some conversions are safe even if we do not have a body.
9183 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00009184 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00009185 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00009186 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009187 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9188 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00009189 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00009190 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009191 }
9192
9193 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009194 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009195 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009196
Chris Lattner58d74912008-03-12 17:45:29 +00009197 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9198 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009199 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009200 // won't be dropping them. Check that these extra arguments have attributes
9201 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009202 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9203 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009204 break;
Chris Lattner58d74912008-03-12 17:45:29 +00009205 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00009206 if (PAttrs & ParamAttr::VarArgsIncompatible)
9207 return false;
9208 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009209
Chris Lattner9fe38862003-06-19 17:00:31 +00009210 // Okay, we decided that this is a safe thing to do: go ahead and start
9211 // inserting cast instructions as necessary...
9212 std::vector<Value*> Args;
9213 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00009214 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009215 attrVec.reserve(NumCommonArgs);
9216
9217 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009218 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009219
9220 // If the return value is not being used, the type may not be compatible
9221 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00009222 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009223
9224 // Add the new return attributes.
9225 if (RAttrs)
9226 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009227
9228 AI = CS.arg_begin();
9229 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9230 const Type *ParamTy = FT->getParamType(i);
9231 if ((*AI)->getType() == ParamTy) {
9232 Args.push_back(*AI);
9233 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009234 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009235 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009236 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009237 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009238 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009239
9240 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009241 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009242 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009243 }
9244
9245 // If the function takes more arguments than the call was taking, add them
9246 // now...
9247 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9248 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9249
9250 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009251 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009252 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009253 cerr << "WARNING: While resolving call to function '"
9254 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009255 } else {
9256 // Add all of the arguments in their promoted form to the arg list...
9257 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9258 const Type *PTy = getPromotedType((*AI)->getType());
9259 if (PTy != (*AI)->getType()) {
9260 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009261 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9262 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009263 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009264 InsertNewInstBefore(Cast, *Caller);
9265 Args.push_back(Cast);
9266 } else {
9267 Args.push_back(*AI);
9268 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009269
Duncan Sandse1e520f2008-01-13 08:02:44 +00009270 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009271 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009272 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9273 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009274 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009275 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009276
9277 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009278 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009279
Chris Lattner58d74912008-03-12 17:45:29 +00009280 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009281
Chris Lattner9fe38862003-06-19 17:00:31 +00009282 Instruction *NC;
9283 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009284 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009285 Args.begin(), Args.end(),
9286 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009287 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009288 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009289 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009290 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9291 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009292 CallInst *CI = cast<CallInst>(Caller);
9293 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009294 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009295 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009296 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009297 }
9298
Chris Lattner6934a042007-02-11 01:23:03 +00009299 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009300 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009301 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009302 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009303 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009304 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009305 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009306
9307 // If this is an invoke instruction, we should insert it after the first
9308 // non-phi, instruction in the normal successor block.
9309 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9310 BasicBlock::iterator I = II->getNormalDest()->begin();
9311 while (isa<PHINode>(I)) ++I;
9312 InsertNewInstBefore(NC, *I);
9313 } else {
9314 // Otherwise, it's a call, just insert cast right after the call instr
9315 InsertNewInstBefore(NC, *Caller);
9316 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009317 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009318 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009319 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009320 }
9321 }
9322
9323 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9324 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009325 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009326 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009327 return true;
9328}
9329
Duncan Sandscdb6d922007-09-17 10:26:40 +00009330// transformCallThroughTrampoline - Turn a call to a function created by the
9331// init_trampoline intrinsic into a direct call to the underlying function.
9332//
9333Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9334 Value *Callee = CS.getCalledValue();
9335 const PointerType *PTy = cast<PointerType>(Callee->getType());
9336 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009337 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009338
9339 // If the call already has the 'nest' attribute somewhere then give up -
9340 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009341 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009342 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009343
9344 IntrinsicInst *Tramp =
9345 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9346
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009347 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009348 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9349 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9350
Chris Lattner58d74912008-03-12 17:45:29 +00009351 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9352 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009353 unsigned NestIdx = 1;
9354 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009355 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009356
9357 // Look for a parameter marked with the 'nest' attribute.
9358 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9359 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009360 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009361 // Record the parameter type and any other attributes.
9362 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009363 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009364 break;
9365 }
9366
9367 if (NestTy) {
9368 Instruction *Caller = CS.getInstruction();
9369 std::vector<Value*> NewArgs;
9370 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9371
Chris Lattner58d74912008-03-12 17:45:29 +00009372 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9373 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009374
Duncan Sandscdb6d922007-09-17 10:26:40 +00009375 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009376 // mean appending it. Likewise for attributes.
9377
9378 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009379 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9380 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009381
Duncan Sandscdb6d922007-09-17 10:26:40 +00009382 {
9383 unsigned Idx = 1;
9384 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9385 do {
9386 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009387 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009388 Value *NestVal = Tramp->getOperand(3);
9389 if (NestVal->getType() != NestTy)
9390 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9391 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009392 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009393 }
9394
9395 if (I == E)
9396 break;
9397
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009398 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009399 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009400 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009401 NewAttrs.push_back
9402 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009403
9404 ++Idx, ++I;
9405 } while (1);
9406 }
9407
9408 // The trampoline may have been bitcast to a bogus type (FTy).
9409 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009410 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009411
Duncan Sandscdb6d922007-09-17 10:26:40 +00009412 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009413 NewTypes.reserve(FTy->getNumParams()+1);
9414
Duncan Sandscdb6d922007-09-17 10:26:40 +00009415 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009416 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009417 {
9418 unsigned Idx = 1;
9419 FunctionType::param_iterator I = FTy->param_begin(),
9420 E = FTy->param_end();
9421
9422 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009423 if (Idx == NestIdx)
9424 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009425 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009426
9427 if (I == E)
9428 break;
9429
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009430 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009431 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009432
9433 ++Idx, ++I;
9434 } while (1);
9435 }
9436
9437 // Replace the trampoline call with a direct call. Let the generic
9438 // code sort out any function type mismatches.
9439 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009440 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009441 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9442 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009443 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009444
9445 Instruction *NewCaller;
9446 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009447 NewCaller = InvokeInst::Create(NewCallee,
9448 II->getNormalDest(), II->getUnwindDest(),
9449 NewArgs.begin(), NewArgs.end(),
9450 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009451 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009452 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009453 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009454 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9455 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009456 if (cast<CallInst>(Caller)->isTailCall())
9457 cast<CallInst>(NewCaller)->setTailCall();
9458 cast<CallInst>(NewCaller)->
9459 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009460 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009461 }
9462 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9463 Caller->replaceAllUsesWith(NewCaller);
9464 Caller->eraseFromParent();
9465 RemoveFromWorkList(Caller);
9466 return 0;
9467 }
9468 }
9469
9470 // Replace the trampoline call with a direct call. Since there is no 'nest'
9471 // parameter, there is no need to adjust the argument list. Let the generic
9472 // code sort out any function type mismatches.
9473 Constant *NewCallee =
9474 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9475 CS.setCalledFunction(NewCallee);
9476 return CS.getInstruction();
9477}
9478
Chris Lattner7da52b22006-11-01 04:51:18 +00009479/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9480/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9481/// and a single binop.
9482Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9483 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009484 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9485 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009486 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009487 Value *LHSVal = FirstInst->getOperand(0);
9488 Value *RHSVal = FirstInst->getOperand(1);
9489
9490 const Type *LHSType = LHSVal->getType();
9491 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009492
9493 // Scan to see if all operands are the same opcode, all have one use, and all
9494 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009495 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009496 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009497 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009498 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009499 // types or GEP's with different index types.
9500 I->getOperand(0)->getType() != LHSType ||
9501 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009502 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009503
9504 // If they are CmpInst instructions, check their predicates
9505 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9506 if (cast<CmpInst>(I)->getPredicate() !=
9507 cast<CmpInst>(FirstInst)->getPredicate())
9508 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009509
9510 // Keep track of which operand needs a phi node.
9511 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9512 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009513 }
9514
Chris Lattner53738a42006-11-08 19:42:28 +00009515 // Otherwise, this is safe to transform, determine if it is profitable.
9516
9517 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9518 // Indexes are often folded into load/store instructions, so we don't want to
9519 // hide them behind a phi.
9520 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9521 return 0;
9522
Chris Lattner7da52b22006-11-01 04:51:18 +00009523 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009524 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009525 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009526 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009527 NewLHS = PHINode::Create(LHSType,
9528 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009529 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9530 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009531 InsertNewInstBefore(NewLHS, PN);
9532 LHSVal = NewLHS;
9533 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009534
9535 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009536 NewRHS = PHINode::Create(RHSType,
9537 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009538 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9539 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009540 InsertNewInstBefore(NewRHS, PN);
9541 RHSVal = NewRHS;
9542 }
9543
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009544 // Add all operands to the new PHIs.
9545 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9546 if (NewLHS) {
9547 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9548 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9549 }
9550 if (NewRHS) {
9551 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9552 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9553 }
9554 }
9555
Chris Lattner7da52b22006-11-01 04:51:18 +00009556 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009557 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009558 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009559 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009560 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009561 else {
9562 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009563 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009564 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009565}
9566
Chris Lattner76c73142006-11-01 07:13:54 +00009567/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9568/// of the block that defines it. This means that it must be obvious the value
9569/// of the load is not changed from the point of the load to the end of the
9570/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009571///
9572/// Finally, it is safe, but not profitable, to sink a load targetting a
9573/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9574/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009575static bool isSafeToSinkLoad(LoadInst *L) {
9576 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9577
9578 for (++BBI; BBI != E; ++BBI)
9579 if (BBI->mayWriteToMemory())
9580 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009581
9582 // Check for non-address taken alloca. If not address-taken already, it isn't
9583 // profitable to do this xform.
9584 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9585 bool isAddressTaken = false;
9586 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9587 UI != E; ++UI) {
9588 if (isa<LoadInst>(UI)) continue;
9589 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9590 // If storing TO the alloca, then the address isn't taken.
9591 if (SI->getOperand(1) == AI) continue;
9592 }
9593 isAddressTaken = true;
9594 break;
9595 }
9596
9597 if (!isAddressTaken)
9598 return false;
9599 }
9600
Chris Lattner76c73142006-11-01 07:13:54 +00009601 return true;
9602}
9603
Chris Lattner9fe38862003-06-19 17:00:31 +00009604
Chris Lattnerbac32862004-11-14 19:13:23 +00009605// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9606// operator and they all are only used by the PHI, PHI together their
9607// inputs, and do the operation once, to the result of the PHI.
9608Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9609 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9610
9611 // Scan the instruction, looking for input operations that can be folded away.
9612 // If all input operands to the phi are the same instruction (e.g. a cast from
9613 // the same type or "+42") we can pull the operation through the PHI, reducing
9614 // code size and simplifying code.
9615 Constant *ConstantOp = 0;
9616 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009617 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009618 if (isa<CastInst>(FirstInst)) {
9619 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009620 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009621 // Can fold binop, compare or shift here if the RHS is a constant,
9622 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009623 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009624 if (ConstantOp == 0)
9625 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009626 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9627 isVolatile = LI->isVolatile();
9628 // We can't sink the load if the loaded value could be modified between the
9629 // load and the PHI.
9630 if (LI->getParent() != PN.getIncomingBlock(0) ||
9631 !isSafeToSinkLoad(LI))
9632 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009633 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009634 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009635 return FoldPHIArgBinOpIntoPHI(PN);
9636 // Can't handle general GEPs yet.
9637 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009638 } else {
9639 return 0; // Cannot fold this operation.
9640 }
9641
9642 // Check to see if all arguments are the same operation.
9643 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9644 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9645 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009646 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009647 return 0;
9648 if (CastSrcTy) {
9649 if (I->getOperand(0)->getType() != CastSrcTy)
9650 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009651 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009652 // We can't sink the load if the loaded value could be modified between
9653 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009654 if (LI->isVolatile() != isVolatile ||
9655 LI->getParent() != PN.getIncomingBlock(i) ||
9656 !isSafeToSinkLoad(LI))
9657 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009658
9659 // If the PHI is volatile and its block has multiple successors, sinking
9660 // it would remove a load of the volatile value from the path through the
9661 // other successor.
9662 if (isVolatile &&
9663 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9664 return 0;
9665
9666
Chris Lattnerbac32862004-11-14 19:13:23 +00009667 } else if (I->getOperand(1) != ConstantOp) {
9668 return 0;
9669 }
9670 }
9671
9672 // Okay, they are all the same operation. Create a new PHI node of the
9673 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009674 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9675 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009676 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009677
9678 Value *InVal = FirstInst->getOperand(0);
9679 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009680
9681 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009682 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9683 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9684 if (NewInVal != InVal)
9685 InVal = 0;
9686 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9687 }
9688
9689 Value *PhiVal;
9690 if (InVal) {
9691 // The new PHI unions all of the same values together. This is really
9692 // common, so we handle it intelligently here for compile-time speed.
9693 PhiVal = InVal;
9694 delete NewPN;
9695 } else {
9696 InsertNewInstBefore(NewPN, PN);
9697 PhiVal = NewPN;
9698 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009699
Chris Lattnerbac32862004-11-14 19:13:23 +00009700 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009701 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009702 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009703 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009704 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009705 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009706 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009707 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009708 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9709
9710 // If this was a volatile load that we are merging, make sure to loop through
9711 // and mark all the input loads as non-volatile. If we don't do this, we will
9712 // insert a new volatile load and the old ones will not be deletable.
9713 if (isVolatile)
9714 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9715 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9716
9717 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009718}
Chris Lattnera1be5662002-05-02 17:06:02 +00009719
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009720/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9721/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009722static bool DeadPHICycle(PHINode *PN,
9723 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009724 if (PN->use_empty()) return true;
9725 if (!PN->hasOneUse()) return false;
9726
9727 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009728 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009729 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009730
9731 // Don't scan crazily complex things.
9732 if (PotentiallyDeadPHIs.size() == 16)
9733 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009734
9735 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9736 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009737
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009738 return false;
9739}
9740
Chris Lattnercf5008a2007-11-06 21:52:06 +00009741/// PHIsEqualValue - Return true if this phi node is always equal to
9742/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9743/// z = some value; x = phi (y, z); y = phi (x, z)
9744static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9745 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9746 // See if we already saw this PHI node.
9747 if (!ValueEqualPHIs.insert(PN))
9748 return true;
9749
9750 // Don't scan crazily complex things.
9751 if (ValueEqualPHIs.size() == 16)
9752 return false;
9753
9754 // Scan the operands to see if they are either phi nodes or are equal to
9755 // the value.
9756 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9757 Value *Op = PN->getIncomingValue(i);
9758 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9759 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9760 return false;
9761 } else if (Op != NonPhiInVal)
9762 return false;
9763 }
9764
9765 return true;
9766}
9767
9768
Chris Lattner473945d2002-05-06 18:06:38 +00009769// PHINode simplification
9770//
Chris Lattner7e708292002-06-25 16:13:24 +00009771Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009772 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009773 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009774
Owen Anderson7e057142006-07-10 22:03:18 +00009775 if (Value *V = PN.hasConstantValue())
9776 return ReplaceInstUsesWith(PN, V);
9777
Owen Anderson7e057142006-07-10 22:03:18 +00009778 // If all PHI operands are the same operation, pull them through the PHI,
9779 // reducing code size.
9780 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9781 PN.getIncomingValue(0)->hasOneUse())
9782 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9783 return Result;
9784
9785 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9786 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9787 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009788 if (PN.hasOneUse()) {
9789 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9790 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009791 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009792 PotentiallyDeadPHIs.insert(&PN);
9793 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9794 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9795 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009796
9797 // If this phi has a single use, and if that use just computes a value for
9798 // the next iteration of a loop, delete the phi. This occurs with unused
9799 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9800 // common case here is good because the only other things that catch this
9801 // are induction variable analysis (sometimes) and ADCE, which is only run
9802 // late.
9803 if (PHIUser->hasOneUse() &&
9804 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9805 PHIUser->use_back() == &PN) {
9806 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9807 }
9808 }
Owen Anderson7e057142006-07-10 22:03:18 +00009809
Chris Lattnercf5008a2007-11-06 21:52:06 +00009810 // We sometimes end up with phi cycles that non-obviously end up being the
9811 // same value, for example:
9812 // z = some value; x = phi (y, z); y = phi (x, z)
9813 // where the phi nodes don't necessarily need to be in the same block. Do a
9814 // quick check to see if the PHI node only contains a single non-phi value, if
9815 // so, scan to see if the phi cycle is actually equal to that value.
9816 {
9817 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9818 // Scan for the first non-phi operand.
9819 while (InValNo != NumOperandVals &&
9820 isa<PHINode>(PN.getIncomingValue(InValNo)))
9821 ++InValNo;
9822
9823 if (InValNo != NumOperandVals) {
9824 Value *NonPhiInVal = PN.getOperand(InValNo);
9825
9826 // Scan the rest of the operands to see if there are any conflicts, if so
9827 // there is no need to recursively scan other phis.
9828 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9829 Value *OpVal = PN.getIncomingValue(InValNo);
9830 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9831 break;
9832 }
9833
9834 // If we scanned over all operands, then we have one unique value plus
9835 // phi values. Scan PHI nodes to see if they all merge in each other or
9836 // the value.
9837 if (InValNo == NumOperandVals) {
9838 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9839 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9840 return ReplaceInstUsesWith(PN, NonPhiInVal);
9841 }
9842 }
9843 }
Chris Lattner60921c92003-12-19 05:58:40 +00009844 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009845}
9846
Reid Spencer17212df2006-12-12 09:18:51 +00009847static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9848 Instruction *InsertPoint,
9849 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009850 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9851 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009852 // We must cast correctly to the pointer type. Ensure that we
9853 // sign extend the integer value if it is smaller as this is
9854 // used for address computation.
9855 Instruction::CastOps opcode =
9856 (VTySize < PtrSize ? Instruction::SExt :
9857 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9858 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009859}
9860
Chris Lattnera1be5662002-05-02 17:06:02 +00009861
Chris Lattner7e708292002-06-25 16:13:24 +00009862Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009863 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009864 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009865 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009866 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009867 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009868
Chris Lattnere87597f2004-10-16 18:11:37 +00009869 if (isa<UndefValue>(GEP.getOperand(0)))
9870 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9871
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009872 bool HasZeroPointerIndex = false;
9873 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9874 HasZeroPointerIndex = C->isNullValue();
9875
9876 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009877 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009878
Chris Lattner28977af2004-04-05 01:30:19 +00009879 // Eliminate unneeded casts for indices.
9880 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009881
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009882 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009883 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009884 if (isa<SequentialType>(*GTI)) {
9885 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009886 if (CI->getOpcode() == Instruction::ZExt ||
9887 CI->getOpcode() == Instruction::SExt) {
9888 const Type *SrcTy = CI->getOperand(0)->getType();
9889 // We can eliminate a cast from i32 to i64 iff the target
9890 // is a 32-bit pointer target.
9891 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9892 MadeChange = true;
9893 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009894 }
9895 }
9896 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009897 // If we are using a wider index than needed for this platform, shrink it
9898 // to what we need. If the incoming value needs a cast instruction,
9899 // insert it. This explicit cast can make subsequent optimizations more
9900 // obvious.
9901 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009902 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009903 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009904 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009905 MadeChange = true;
9906 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009907 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9908 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009909 GEP.setOperand(i, Op);
9910 MadeChange = true;
9911 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009912 }
Chris Lattner28977af2004-04-05 01:30:19 +00009913 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009914 }
Chris Lattner28977af2004-04-05 01:30:19 +00009915 if (MadeChange) return &GEP;
9916
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009917 // If this GEP instruction doesn't move the pointer, and if the input operand
9918 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9919 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009920 if (GEP.hasAllZeroIndices()) {
9921 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9922 // If the bitcast is of an allocation, and the allocation will be
9923 // converted to match the type of the cast, don't touch this.
9924 if (isa<AllocationInst>(BCI->getOperand(0))) {
9925 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009926 if (Instruction *I = visitBitCast(*BCI)) {
9927 if (I != BCI) {
9928 I->takeName(BCI);
9929 BCI->getParent()->getInstList().insert(BCI, I);
9930 ReplaceInstUsesWith(*BCI, I);
9931 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009932 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009933 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009934 }
9935 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9936 }
9937 }
9938
Chris Lattner90ac28c2002-08-02 19:29:35 +00009939 // Combine Indices - If the source pointer to this getelementptr instruction
9940 // is a getelementptr instruction, combine the indices of the two
9941 // getelementptr instructions into a single instruction.
9942 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009943 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009944 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009945 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009946
9947 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009948 // Note that if our source is a gep chain itself that we wait for that
9949 // chain to be resolved before we perform this transformation. This
9950 // avoids us creating a TON of code in some cases.
9951 //
9952 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9953 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9954 return 0; // Wait until our source is folded to completion.
9955
Chris Lattner72588fc2007-02-15 22:48:32 +00009956 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009957
9958 // Find out whether the last index in the source GEP is a sequential idx.
9959 bool EndsWithSequential = false;
9960 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9961 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009962 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009963
Chris Lattner90ac28c2002-08-02 19:29:35 +00009964 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009965 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009966 // Replace: gep (gep %P, long B), long A, ...
9967 // With: T = long A+B; gep %P, T, ...
9968 //
Chris Lattner620ce142004-05-07 22:09:22 +00009969 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009970 if (SO1 == Constant::getNullValue(SO1->getType())) {
9971 Sum = GO1;
9972 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9973 Sum = SO1;
9974 } else {
9975 // If they aren't the same type, convert both to an integer of the
9976 // target's pointer size.
9977 if (SO1->getType() != GO1->getType()) {
9978 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009979 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009980 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009981 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009982 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009983 unsigned PS = TD->getPointerSizeInBits();
9984 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009985 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009986 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009987
Duncan Sands514ab342007-11-01 20:53:16 +00009988 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009989 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009990 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009991 } else {
9992 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009993 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9994 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009995 }
9996 }
9997 }
Chris Lattner620ce142004-05-07 22:09:22 +00009998 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9999 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10000 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010001 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010002 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010003 }
Chris Lattner28977af2004-04-05 01:30:19 +000010004 }
Chris Lattner620ce142004-05-07 22:09:22 +000010005
10006 // Recycle the GEP we already have if possible.
10007 if (SrcGEPOperands.size() == 2) {
10008 GEP.setOperand(0, SrcGEPOperands[0]);
10009 GEP.setOperand(1, Sum);
10010 return &GEP;
10011 } else {
10012 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10013 SrcGEPOperands.end()-1);
10014 Indices.push_back(Sum);
10015 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10016 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010017 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010018 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010019 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010020 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010021 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10022 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010023 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10024 }
10025
10026 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010027 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10028 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010029
Chris Lattner620ce142004-05-07 22:09:22 +000010030 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010031 // GEP of global variable. If all of the indices for this GEP are
10032 // constants, we can promote this to a constexpr instead of an instruction.
10033
10034 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010035 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010036 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10037 for (; I != E && isa<Constant>(*I); ++I)
10038 Indices.push_back(cast<Constant>(*I));
10039
10040 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010041 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10042 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010043
10044 // Replace all uses of the GEP with the new constexpr...
10045 return ReplaceInstUsesWith(GEP, CE);
10046 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010047 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010048 if (!isa<PointerType>(X->getType())) {
10049 // Not interesting. Source pointer must be a cast from pointer.
10050 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010051 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10052 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010053 //
10054 // This occurs when the program declares an array extern like "int X[];"
10055 //
10056 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10057 const PointerType *XTy = cast<PointerType>(X->getType());
10058 if (const ArrayType *XATy =
10059 dyn_cast<ArrayType>(XTy->getElementType()))
10060 if (const ArrayType *CATy =
10061 dyn_cast<ArrayType>(CPTy->getElementType()))
10062 if (CATy->getElementType() == XATy->getElementType()) {
10063 // At this point, we know that the cast source type is a pointer
10064 // to an array of the same type as the destination pointer
10065 // array. Because the array type is never stepped over (there
10066 // is a leading zero) we can fold the cast into this GEP.
10067 GEP.setOperand(0, X);
10068 return &GEP;
10069 }
10070 } else if (GEP.getNumOperands() == 2) {
10071 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010072 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10073 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010074 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10075 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10076 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +000010077 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10078 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010079 Value *Idx[2];
10080 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10081 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010082 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010083 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010084 // V and GEP are both pointer types --> BitCast
10085 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010086 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010087
10088 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010089 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010090 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010091 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010092
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010093 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010094 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +000010095 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010096
10097 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10098 // allow either a mul, shift, or constant here.
10099 Value *NewIdx = 0;
10100 ConstantInt *Scale = 0;
10101 if (ArrayEltSize == 1) {
10102 NewIdx = GEP.getOperand(1);
10103 Scale = ConstantInt::get(NewIdx->getType(), 1);
10104 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010105 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010106 Scale = CI;
10107 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10108 if (Inst->getOpcode() == Instruction::Shl &&
10109 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010110 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10111 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10112 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010113 NewIdx = Inst->getOperand(0);
10114 } else if (Inst->getOpcode() == Instruction::Mul &&
10115 isa<ConstantInt>(Inst->getOperand(1))) {
10116 Scale = cast<ConstantInt>(Inst->getOperand(1));
10117 NewIdx = Inst->getOperand(0);
10118 }
10119 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010120
Chris Lattner7835cdd2005-09-13 18:36:04 +000010121 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010122 // out, perform the transformation. Note, we don't know whether Scale is
10123 // signed or not. We'll use unsigned version of division/modulo
10124 // operation after making sure Scale doesn't have the sign bit set.
10125 if (Scale && Scale->getSExtValue() >= 0LL &&
10126 Scale->getZExtValue() % ArrayEltSize == 0) {
10127 Scale = ConstantInt::get(Scale->getType(),
10128 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010129 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010130 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010131 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010132 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010133 NewIdx = InsertNewInstBefore(Sc, GEP);
10134 }
10135
10136 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010137 Value *Idx[2];
10138 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10139 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010140 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010141 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010142 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10143 // The NewGEP must be pointer typed, so must the old one -> BitCast
10144 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010145 }
10146 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010147 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010148 }
10149
Chris Lattner8a2a3112001-12-14 16:52:21 +000010150 return 0;
10151}
10152
Chris Lattner0864acf2002-11-04 16:18:53 +000010153Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10154 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010155 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010156 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10157 const Type *NewTy =
10158 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010159 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010160
10161 // Create and insert the replacement instruction...
10162 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010163 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010164 else {
10165 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010166 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010167 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010168
10169 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010170
Chris Lattner0864acf2002-11-04 16:18:53 +000010171 // Scan to the end of the allocation instructions, to skip over a block of
10172 // allocas if possible...
10173 //
10174 BasicBlock::iterator It = New;
10175 while (isa<AllocationInst>(*It)) ++It;
10176
10177 // Now that I is pointing to the first non-allocation-inst in the block,
10178 // insert our getelementptr instruction...
10179 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010180 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010181 Value *Idx[2];
10182 Idx[0] = NullIdx;
10183 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010184 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10185 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010186
10187 // Now make everything use the getelementptr instead of the original
10188 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010189 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010190 } else if (isa<UndefValue>(AI.getArraySize())) {
10191 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010192 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010193 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010194
10195 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10196 // Note that we only do this for alloca's, because malloc should allocate and
10197 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +000010198 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +000010199 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +000010200 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10201
Chris Lattner0864acf2002-11-04 16:18:53 +000010202 return 0;
10203}
10204
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010205Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10206 Value *Op = FI.getOperand(0);
10207
Chris Lattner17be6352004-10-18 02:59:09 +000010208 // free undef -> unreachable.
10209 if (isa<UndefValue>(Op)) {
10210 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010211 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010212 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010213 return EraseInstFromFunction(FI);
10214 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010215
Chris Lattner6160e852004-02-28 04:57:37 +000010216 // If we have 'free null' delete the instruction. This can happen in stl code
10217 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010218 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010219 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010220
10221 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10222 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10223 FI.setOperand(0, CI->getOperand(0));
10224 return &FI;
10225 }
10226
10227 // Change free (gep X, 0,0,0,0) into free(X)
10228 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10229 if (GEPI->hasAllZeroIndices()) {
10230 AddToWorkList(GEPI);
10231 FI.setOperand(0, GEPI->getOperand(0));
10232 return &FI;
10233 }
10234 }
10235
10236 // Change free(malloc) into nothing, if the malloc has a single use.
10237 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10238 if (MI->hasOneUse()) {
10239 EraseInstFromFunction(FI);
10240 return EraseInstFromFunction(*MI);
10241 }
Chris Lattner6160e852004-02-28 04:57:37 +000010242
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010243 return 0;
10244}
10245
10246
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010247/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010248static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010249 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010250 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010251 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010252
Devang Patel99db6ad2007-10-18 19:52:32 +000010253 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10254 // Instead of loading constant c string, use corresponding integer value
10255 // directly if string length is small enough.
10256 const std::string &Str = CE->getOperand(0)->getStringValue();
10257 if (!Str.empty()) {
10258 unsigned len = Str.length();
10259 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10260 unsigned numBits = Ty->getPrimitiveSizeInBits();
10261 // Replace LI with immediate integer store.
10262 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010263 APInt StrVal(numBits, 0);
10264 APInt SingleChar(numBits, 0);
10265 if (TD->isLittleEndian()) {
10266 for (signed i = len-1; i >= 0; i--) {
10267 SingleChar = (uint64_t) Str[i];
10268 StrVal = (StrVal << 8) | SingleChar;
10269 }
10270 } else {
10271 for (unsigned i = 0; i < len; i++) {
10272 SingleChar = (uint64_t) Str[i];
10273 StrVal = (StrVal << 8) | SingleChar;
10274 }
10275 // Append NULL at the end.
10276 SingleChar = 0;
10277 StrVal = (StrVal << 8) | SingleChar;
10278 }
10279 Value *NL = ConstantInt::get(StrVal);
10280 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010281 }
10282 }
10283 }
10284
Chris Lattnerb89e0712004-07-13 01:49:43 +000010285 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010286 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010287 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010288
Reid Spencer42230162007-01-22 05:51:25 +000010289 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010290 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010291 // If the source is an array, the code below will not succeed. Check to
10292 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10293 // constants.
10294 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10295 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10296 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010297 Value *Idxs[2];
10298 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10299 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010300 SrcTy = cast<PointerType>(CastOp->getType());
10301 SrcPTy = SrcTy->getElementType();
10302 }
10303
Reid Spencer42230162007-01-22 05:51:25 +000010304 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010305 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010306 // Do not allow turning this into a load of an integer, which is then
10307 // casted to a pointer, this pessimizes pointer analysis a lot.
10308 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010309 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10310 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010311
Chris Lattnerf9527852005-01-31 04:50:46 +000010312 // Okay, we are casting from one integer or pointer type to another of
10313 // the same size. Instead of casting the pointer before the load, cast
10314 // the result of the loaded value.
10315 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10316 CI->getName(),
10317 LI.isVolatile()),LI);
10318 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010319 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010320 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010321 }
10322 }
10323 return 0;
10324}
10325
Chris Lattnerc10aced2004-09-19 18:43:46 +000010326/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010327/// from this value cannot trap. If it is not obviously safe to load from the
10328/// specified pointer, we do a quick local scan of the basic block containing
10329/// ScanFrom, to determine if the address is already accessed.
10330static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010331 // If it is an alloca it is always safe to load from.
10332 if (isa<AllocaInst>(V)) return true;
10333
Duncan Sands46318cd2007-09-19 10:25:38 +000010334 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010335 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010336 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010337 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010338
10339 // Otherwise, be a little bit agressive by scanning the local block where we
10340 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010341 // from/to. If so, the previous load or store would have already trapped,
10342 // so there is no harm doing an extra load (also, CSE will later eliminate
10343 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010344 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10345
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010346 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010347 --BBI;
10348
10349 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10350 if (LI->getOperand(0) == V) return true;
10351 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10352 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010353
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010354 }
Chris Lattner8a375202004-09-19 19:18:10 +000010355 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010356}
10357
Chris Lattner8d2e8882007-08-11 18:48:48 +000010358/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10359/// until we find the underlying object a pointer is referring to or something
10360/// we don't understand. Note that the returned pointer may be offset from the
10361/// input, because we ignore GEP indices.
10362static Value *GetUnderlyingObject(Value *Ptr) {
10363 while (1) {
10364 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10365 if (CE->getOpcode() == Instruction::BitCast ||
10366 CE->getOpcode() == Instruction::GetElementPtr)
10367 Ptr = CE->getOperand(0);
10368 else
10369 return Ptr;
10370 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10371 Ptr = BCI->getOperand(0);
10372 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10373 Ptr = GEP->getOperand(0);
10374 } else {
10375 return Ptr;
10376 }
10377 }
10378}
10379
Chris Lattner833b8a42003-06-26 05:06:25 +000010380Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10381 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010382
Dan Gohman9941f742007-07-20 16:34:21 +000010383 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010384 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10385 if (KnownAlign >
10386 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10387 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010388 LI.setAlignment(KnownAlign);
10389
Chris Lattner37366c12005-05-01 04:24:53 +000010390 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010391 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010392 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010393 return Res;
10394
10395 // None of the following transforms are legal for volatile loads.
10396 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010397
Chris Lattner62f254d2005-09-12 22:00:15 +000010398 if (&LI.getParent()->front() != &LI) {
10399 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010400 // If the instruction immediately before this is a store to the same
10401 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010402 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10403 if (SI->getOperand(1) == LI.getOperand(0))
10404 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010405 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10406 if (LIB->getOperand(0) == LI.getOperand(0))
10407 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010408 }
Chris Lattner37366c12005-05-01 04:24:53 +000010409
Christopher Lambb15147e2007-12-29 07:56:53 +000010410 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10411 const Value *GEPI0 = GEPI->getOperand(0);
10412 // TODO: Consider a target hook for valid address spaces for this xform.
10413 if (isa<ConstantPointerNull>(GEPI0) &&
10414 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010415 // Insert a new store to null instruction before the load to indicate
10416 // that this code is not reachable. We do this instead of inserting
10417 // an unreachable instruction directly because we cannot modify the
10418 // CFG.
10419 new StoreInst(UndefValue::get(LI.getType()),
10420 Constant::getNullValue(Op->getType()), &LI);
10421 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10422 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010423 }
Chris Lattner37366c12005-05-01 04:24:53 +000010424
Chris Lattnere87597f2004-10-16 18:11:37 +000010425 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010426 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010427 // TODO: Consider a target hook for valid address spaces for this xform.
10428 if (isa<UndefValue>(C) || (C->isNullValue() &&
10429 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010430 // Insert a new store to null instruction before the load to indicate that
10431 // this code is not reachable. We do this instead of inserting an
10432 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010433 new StoreInst(UndefValue::get(LI.getType()),
10434 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010435 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010436 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010437
Chris Lattnere87597f2004-10-16 18:11:37 +000010438 // Instcombine load (constant global) into the value loaded.
10439 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010440 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010441 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010442
Chris Lattnere87597f2004-10-16 18:11:37 +000010443 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010444 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010445 if (CE->getOpcode() == Instruction::GetElementPtr) {
10446 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010447 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010448 if (Constant *V =
10449 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010450 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010451 if (CE->getOperand(0)->isNullValue()) {
10452 // Insert a new store to null instruction before the load to indicate
10453 // that this code is not reachable. We do this instead of inserting
10454 // an unreachable instruction directly because we cannot modify the
10455 // CFG.
10456 new StoreInst(UndefValue::get(LI.getType()),
10457 Constant::getNullValue(Op->getType()), &LI);
10458 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10459 }
10460
Reid Spencer3da59db2006-11-27 01:05:10 +000010461 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010462 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010463 return Res;
10464 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010465 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010466 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010467
10468 // If this load comes from anywhere in a constant global, and if the global
10469 // is all undef or zero, we know what it loads.
10470 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10471 if (GV->isConstant() && GV->hasInitializer()) {
10472 if (GV->getInitializer()->isNullValue())
10473 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10474 else if (isa<UndefValue>(GV->getInitializer()))
10475 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10476 }
10477 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010478
Chris Lattner37366c12005-05-01 04:24:53 +000010479 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010480 // Change select and PHI nodes to select values instead of addresses: this
10481 // helps alias analysis out a lot, allows many others simplifications, and
10482 // exposes redundancy in the code.
10483 //
10484 // Note that we cannot do the transformation unless we know that the
10485 // introduced loads cannot trap! Something like this is valid as long as
10486 // the condition is always false: load (select bool %C, int* null, int* %G),
10487 // but it would not be valid if we transformed it to load from null
10488 // unconditionally.
10489 //
10490 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10491 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010492 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10493 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010494 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010495 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010496 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010497 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010498 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010499 }
10500
Chris Lattner684fe212004-09-23 15:46:00 +000010501 // load (select (cond, null, P)) -> load P
10502 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10503 if (C->isNullValue()) {
10504 LI.setOperand(0, SI->getOperand(2));
10505 return &LI;
10506 }
10507
10508 // load (select (cond, P, null)) -> load P
10509 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10510 if (C->isNullValue()) {
10511 LI.setOperand(0, SI->getOperand(1));
10512 return &LI;
10513 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010514 }
10515 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010516 return 0;
10517}
10518
Reid Spencer55af2b52007-01-19 21:20:31 +000010519/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010520/// when possible.
10521static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10522 User *CI = cast<User>(SI.getOperand(1));
10523 Value *CastOp = CI->getOperand(0);
10524
10525 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10526 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10527 const Type *SrcPTy = SrcTy->getElementType();
10528
Reid Spencer42230162007-01-22 05:51:25 +000010529 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010530 // If the source is an array, the code below will not succeed. Check to
10531 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10532 // constants.
10533 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10534 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10535 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010536 Value* Idxs[2];
10537 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10538 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010539 SrcTy = cast<PointerType>(CastOp->getType());
10540 SrcPTy = SrcTy->getElementType();
10541 }
10542
Reid Spencer67f827c2007-01-20 23:35:48 +000010543 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10544 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10545 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010546
10547 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010548 // the same size. Instead of casting the pointer before
10549 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010550 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010551 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010552 Instruction::CastOps opcode = Instruction::BitCast;
10553 const Type* CastSrcTy = SIOp0->getType();
10554 const Type* CastDstTy = SrcPTy;
10555 if (isa<PointerType>(CastDstTy)) {
10556 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010557 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010558 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010559 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010560 opcode = Instruction::PtrToInt;
10561 }
10562 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010563 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010564 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010565 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010566 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010567 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010568 return new StoreInst(NewCast, CastOp);
10569 }
10570 }
10571 }
10572 return 0;
10573}
10574
Chris Lattner2f503e62005-01-31 05:36:43 +000010575Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10576 Value *Val = SI.getOperand(0);
10577 Value *Ptr = SI.getOperand(1);
10578
10579 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010580 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010581 ++NumCombined;
10582 return 0;
10583 }
Chris Lattner836692d2007-01-15 06:51:56 +000010584
10585 // If the RHS is an alloca with a single use, zapify the store, making the
10586 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010587 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010588 if (isa<AllocaInst>(Ptr)) {
10589 EraseInstFromFunction(SI);
10590 ++NumCombined;
10591 return 0;
10592 }
10593
10594 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10595 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10596 GEP->getOperand(0)->hasOneUse()) {
10597 EraseInstFromFunction(SI);
10598 ++NumCombined;
10599 return 0;
10600 }
10601 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010602
Dan Gohman9941f742007-07-20 16:34:21 +000010603 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010604 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10605 if (KnownAlign >
10606 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10607 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010608 SI.setAlignment(KnownAlign);
10609
Chris Lattner9ca96412006-02-08 03:25:32 +000010610 // Do really simple DSE, to catch cases where there are several consequtive
10611 // stores to the same location, separated by a few arithmetic operations. This
10612 // situation often occurs with bitfield accesses.
10613 BasicBlock::iterator BBI = &SI;
10614 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10615 --ScanInsts) {
10616 --BBI;
10617
10618 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10619 // Prev store isn't volatile, and stores to the same location?
10620 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10621 ++NumDeadStore;
10622 ++BBI;
10623 EraseInstFromFunction(*PrevSI);
10624 continue;
10625 }
10626 break;
10627 }
10628
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010629 // If this is a load, we have to stop. However, if the loaded value is from
10630 // the pointer we're loading and is producing the pointer we're storing,
10631 // then *this* store is dead (X = load P; store X -> P).
10632 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010633 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010634 EraseInstFromFunction(SI);
10635 ++NumCombined;
10636 return 0;
10637 }
10638 // Otherwise, this is a load from some other location. Stores before it
10639 // may not be dead.
10640 break;
10641 }
10642
Chris Lattner9ca96412006-02-08 03:25:32 +000010643 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010644 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010645 break;
10646 }
10647
10648
10649 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010650
10651 // store X, null -> turns into 'unreachable' in SimplifyCFG
10652 if (isa<ConstantPointerNull>(Ptr)) {
10653 if (!isa<UndefValue>(Val)) {
10654 SI.setOperand(0, UndefValue::get(Val->getType()));
10655 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010656 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010657 ++NumCombined;
10658 }
10659 return 0; // Do not modify these!
10660 }
10661
10662 // store undef, Ptr -> noop
10663 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010664 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010665 ++NumCombined;
10666 return 0;
10667 }
10668
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010669 // If the pointer destination is a cast, see if we can fold the cast into the
10670 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010671 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010672 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10673 return Res;
10674 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010675 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010676 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10677 return Res;
10678
Chris Lattner408902b2005-09-12 23:23:25 +000010679
10680 // If this store is the last instruction in the basic block, and if the block
10681 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010682 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010683 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010684 if (BI->isUnconditional())
10685 if (SimplifyStoreAtEndOfBlock(SI))
10686 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010687
Chris Lattner2f503e62005-01-31 05:36:43 +000010688 return 0;
10689}
10690
Chris Lattner3284d1f2007-04-15 00:07:55 +000010691/// SimplifyStoreAtEndOfBlock - Turn things like:
10692/// if () { *P = v1; } else { *P = v2 }
10693/// into a phi node with a store in the successor.
10694///
Chris Lattner31755a02007-04-15 01:02:18 +000010695/// Simplify things like:
10696/// *P = v1; if () { *P = v2; }
10697/// into a phi node with a store in the successor.
10698///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010699bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10700 BasicBlock *StoreBB = SI.getParent();
10701
10702 // Check to see if the successor block has exactly two incoming edges. If
10703 // so, see if the other predecessor contains a store to the same location.
10704 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010705 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010706
10707 // Determine whether Dest has exactly two predecessors and, if so, compute
10708 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010709 pred_iterator PI = pred_begin(DestBB);
10710 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010711 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010712 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010713 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010714 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010715 return false;
10716
10717 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010718 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010719 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010720 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010721 }
Chris Lattner31755a02007-04-15 01:02:18 +000010722 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010723 return false;
10724
10725
Chris Lattner31755a02007-04-15 01:02:18 +000010726 // Verify that the other block ends in a branch and is not otherwise empty.
10727 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010728 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010729 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010730 return false;
10731
Chris Lattner31755a02007-04-15 01:02:18 +000010732 // If the other block ends in an unconditional branch, check for the 'if then
10733 // else' case. there is an instruction before the branch.
10734 StoreInst *OtherStore = 0;
10735 if (OtherBr->isUnconditional()) {
10736 // If this isn't a store, or isn't a store to the same location, bail out.
10737 --BBI;
10738 OtherStore = dyn_cast<StoreInst>(BBI);
10739 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10740 return false;
10741 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010742 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010743 // destinations is StoreBB, then we have the if/then case.
10744 if (OtherBr->getSuccessor(0) != StoreBB &&
10745 OtherBr->getSuccessor(1) != StoreBB)
10746 return false;
10747
10748 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010749 // if/then triangle. See if there is a store to the same ptr as SI that
10750 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010751 for (;; --BBI) {
10752 // Check to see if we find the matching store.
10753 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10754 if (OtherStore->getOperand(1) != SI.getOperand(1))
10755 return false;
10756 break;
10757 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010758 // If we find something that may be using the stored value, or if we run
10759 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010760 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10761 BBI == OtherBB->begin())
10762 return false;
10763 }
10764
10765 // In order to eliminate the store in OtherBr, we have to
10766 // make sure nothing reads the stored value in StoreBB.
10767 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10768 // FIXME: This should really be AA driven.
10769 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10770 return false;
10771 }
10772 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010773
Chris Lattner31755a02007-04-15 01:02:18 +000010774 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010775 Value *MergedVal = OtherStore->getOperand(0);
10776 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010777 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010778 PN->reserveOperandSpace(2);
10779 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010780 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10781 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010782 }
10783
10784 // Advance to a place where it is safe to insert the new store and
10785 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010786 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010787 while (isa<PHINode>(BBI)) ++BBI;
10788 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10789 OtherStore->isVolatile()), *BBI);
10790
10791 // Nuke the old stores.
10792 EraseInstFromFunction(SI);
10793 EraseInstFromFunction(*OtherStore);
10794 ++NumCombined;
10795 return true;
10796}
10797
Chris Lattner2f503e62005-01-31 05:36:43 +000010798
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010799Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10800 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010801 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010802 BasicBlock *TrueDest;
10803 BasicBlock *FalseDest;
10804 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10805 !isa<Constant>(X)) {
10806 // Swap Destinations and condition...
10807 BI.setCondition(X);
10808 BI.setSuccessor(0, FalseDest);
10809 BI.setSuccessor(1, TrueDest);
10810 return &BI;
10811 }
10812
Reid Spencere4d87aa2006-12-23 06:05:41 +000010813 // Cannonicalize fcmp_one -> fcmp_oeq
10814 FCmpInst::Predicate FPred; Value *Y;
10815 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10816 TrueDest, FalseDest)))
10817 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10818 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10819 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010820 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010821 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10822 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010823 // Swap Destinations and condition...
10824 BI.setCondition(NewSCC);
10825 BI.setSuccessor(0, FalseDest);
10826 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010827 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010828 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010829 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010830 return &BI;
10831 }
10832
10833 // Cannonicalize icmp_ne -> icmp_eq
10834 ICmpInst::Predicate IPred;
10835 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10836 TrueDest, FalseDest)))
10837 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10838 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10839 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10840 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010841 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010842 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10843 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010844 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010845 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010846 BI.setSuccessor(0, FalseDest);
10847 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010848 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010849 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010850 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010851 return &BI;
10852 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010853
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010854 return 0;
10855}
Chris Lattner0864acf2002-11-04 16:18:53 +000010856
Chris Lattner46238a62004-07-03 00:26:11 +000010857Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10858 Value *Cond = SI.getCondition();
10859 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10860 if (I->getOpcode() == Instruction::Add)
10861 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10862 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10863 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010864 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010865 AddRHS));
10866 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010867 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010868 return &SI;
10869 }
10870 }
10871 return 0;
10872}
10873
Chris Lattner220b0cf2006-03-05 00:22:33 +000010874/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10875/// is to leave as a vector operation.
10876static bool CheapToScalarize(Value *V, bool isConstant) {
10877 if (isa<ConstantAggregateZero>(V))
10878 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010879 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010880 if (isConstant) return true;
10881 // If all elts are the same, we can extract.
10882 Constant *Op0 = C->getOperand(0);
10883 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10884 if (C->getOperand(i) != Op0)
10885 return false;
10886 return true;
10887 }
10888 Instruction *I = dyn_cast<Instruction>(V);
10889 if (!I) return false;
10890
10891 // Insert element gets simplified to the inserted element or is deleted if
10892 // this is constant idx extract element and its a constant idx insertelt.
10893 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10894 isa<ConstantInt>(I->getOperand(2)))
10895 return true;
10896 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10897 return true;
10898 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10899 if (BO->hasOneUse() &&
10900 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10901 CheapToScalarize(BO->getOperand(1), isConstant)))
10902 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010903 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10904 if (CI->hasOneUse() &&
10905 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10906 CheapToScalarize(CI->getOperand(1), isConstant)))
10907 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010908
10909 return false;
10910}
10911
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010912/// Read and decode a shufflevector mask.
10913///
10914/// It turns undef elements into values that are larger than the number of
10915/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010916static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10917 unsigned NElts = SVI->getType()->getNumElements();
10918 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10919 return std::vector<unsigned>(NElts, 0);
10920 if (isa<UndefValue>(SVI->getOperand(2)))
10921 return std::vector<unsigned>(NElts, 2*NElts);
10922
10923 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010924 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010925 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10926 if (isa<UndefValue>(CP->getOperand(i)))
10927 Result.push_back(NElts*2); // undef -> 8
10928 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010929 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010930 return Result;
10931}
10932
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010933/// FindScalarElement - Given a vector and an element number, see if the scalar
10934/// value is already around as a register, for example if it were inserted then
10935/// extracted from the vector.
10936static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010937 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10938 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010939 unsigned Width = PTy->getNumElements();
10940 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010941 return UndefValue::get(PTy->getElementType());
10942
10943 if (isa<UndefValue>(V))
10944 return UndefValue::get(PTy->getElementType());
10945 else if (isa<ConstantAggregateZero>(V))
10946 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010947 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010948 return CP->getOperand(EltNo);
10949 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10950 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010951 if (!isa<ConstantInt>(III->getOperand(2)))
10952 return 0;
10953 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010954
10955 // If this is an insert to the element we are looking for, return the
10956 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010957 if (EltNo == IIElt)
10958 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010959
10960 // Otherwise, the insertelement doesn't modify the value, recurse on its
10961 // vector input.
10962 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010963 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010964 unsigned InEl = getShuffleMask(SVI)[EltNo];
10965 if (InEl < Width)
10966 return FindScalarElement(SVI->getOperand(0), InEl);
10967 else if (InEl < Width*2)
10968 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10969 else
10970 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010971 }
10972
10973 // Otherwise, we don't know.
10974 return 0;
10975}
10976
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010977Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010978
Dan Gohman07a96762007-07-16 14:29:03 +000010979 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010980 if (isa<UndefValue>(EI.getOperand(0)))
10981 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10982
Dan Gohman07a96762007-07-16 14:29:03 +000010983 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010984 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10985 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10986
Reid Spencer9d6565a2007-02-15 02:26:10 +000010987 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010988 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010989 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010990 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010991 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010992 if (C->getOperand(i) != op0) {
10993 op0 = 0;
10994 break;
10995 }
10996 if (op0)
10997 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010998 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010999
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011000 // If extracting a specified index from the vector, see if we can recursively
11001 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000011002 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000011003 unsigned IndexVal = IdxC->getZExtValue();
11004 unsigned VectorWidth =
11005 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11006
11007 // If this is extracting an invalid index, turn this into undef, to avoid
11008 // crashing the code below.
11009 if (IndexVal >= VectorWidth)
11010 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11011
Chris Lattner867b99f2006-10-05 06:55:50 +000011012 // This instruction only demands the single element from the input vector.
11013 // If the input vector has a single use, simplify it based on this use
11014 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011015 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011016 uint64_t UndefElts;
11017 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000011018 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000011019 UndefElts)) {
11020 EI.setOperand(0, V);
11021 return &EI;
11022 }
11023 }
11024
Reid Spencerb83eb642006-10-20 07:07:24 +000011025 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011026 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011027
11028 // If the this extractelement is directly using a bitcast from a vector of
11029 // the same number of elements, see if we can find the source element from
11030 // it. In this case, we will end up needing to bitcast the scalars.
11031 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11032 if (const VectorType *VT =
11033 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11034 if (VT->getNumElements() == VectorWidth)
11035 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11036 return new BitCastInst(Elt, EI.getType());
11037 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011038 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011039
Chris Lattner73fa49d2006-05-25 22:53:38 +000011040 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011041 if (I->hasOneUse()) {
11042 // Push extractelement into predecessor operation if legal and
11043 // profitable to do so
11044 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011045 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11046 if (CheapToScalarize(BO, isConstantElt)) {
11047 ExtractElementInst *newEI0 =
11048 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11049 EI.getName()+".lhs");
11050 ExtractElementInst *newEI1 =
11051 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11052 EI.getName()+".rhs");
11053 InsertNewInstBefore(newEI0, EI);
11054 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011055 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011056 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011057 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011058 unsigned AS =
11059 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011060 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11061 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011062 GetElementPtrInst *GEP =
11063 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011064 InsertNewInstBefore(GEP, EI);
11065 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011066 }
11067 }
11068 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11069 // Extracting the inserted element?
11070 if (IE->getOperand(2) == EI.getOperand(1))
11071 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11072 // If the inserted and extracted elements are constants, they must not
11073 // be the same value, extract from the pre-inserted value instead.
11074 if (isa<Constant>(IE->getOperand(2)) &&
11075 isa<Constant>(EI.getOperand(1))) {
11076 AddUsesToWorkList(EI);
11077 EI.setOperand(0, IE->getOperand(0));
11078 return &EI;
11079 }
11080 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11081 // If this is extracting an element from a shufflevector, figure out where
11082 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011083 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11084 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011085 Value *Src;
11086 if (SrcIdx < SVI->getType()->getNumElements())
11087 Src = SVI->getOperand(0);
11088 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11089 SrcIdx -= SVI->getType()->getNumElements();
11090 Src = SVI->getOperand(1);
11091 } else {
11092 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011093 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011094 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011095 }
11096 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011097 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011098 return 0;
11099}
11100
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011101/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11102/// elements from either LHS or RHS, return the shuffle mask and true.
11103/// Otherwise, return false.
11104static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11105 std::vector<Constant*> &Mask) {
11106 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11107 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011108 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011109
11110 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011111 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011112 return true;
11113 } else if (V == LHS) {
11114 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011115 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011116 return true;
11117 } else if (V == RHS) {
11118 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011119 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011120 return true;
11121 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11122 // If this is an insert of an extract from some other vector, include it.
11123 Value *VecOp = IEI->getOperand(0);
11124 Value *ScalarOp = IEI->getOperand(1);
11125 Value *IdxOp = IEI->getOperand(2);
11126
Chris Lattnerd929f062006-04-27 21:14:21 +000011127 if (!isa<ConstantInt>(IdxOp))
11128 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011129 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011130
11131 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11132 // Okay, we can handle this if the vector we are insertinting into is
11133 // transitively ok.
11134 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11135 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011136 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011137 return true;
11138 }
11139 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11140 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011141 EI->getOperand(0)->getType() == V->getType()) {
11142 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011143 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011144
11145 // This must be extracting from either LHS or RHS.
11146 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11147 // Okay, we can handle this if the vector we are insertinting into is
11148 // transitively ok.
11149 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11150 // If so, update the mask to reflect the inserted value.
11151 if (EI->getOperand(0) == LHS) {
11152 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011153 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011154 } else {
11155 assert(EI->getOperand(0) == RHS);
11156 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011157 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011158
11159 }
11160 return true;
11161 }
11162 }
11163 }
11164 }
11165 }
11166 // TODO: Handle shufflevector here!
11167
11168 return false;
11169}
11170
11171/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11172/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11173/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011174static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011175 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011176 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011177 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011178 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011179 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011180
11181 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011182 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011183 return V;
11184 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011185 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011186 return V;
11187 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11188 // If this is an insert of an extract from some other vector, include it.
11189 Value *VecOp = IEI->getOperand(0);
11190 Value *ScalarOp = IEI->getOperand(1);
11191 Value *IdxOp = IEI->getOperand(2);
11192
11193 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11194 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11195 EI->getOperand(0)->getType() == V->getType()) {
11196 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011197 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11198 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011199
11200 // Either the extracted from or inserted into vector must be RHSVec,
11201 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011202 if (EI->getOperand(0) == RHS || RHS == 0) {
11203 RHS = EI->getOperand(0);
11204 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011205 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011206 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011207 return V;
11208 }
11209
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011210 if (VecOp == RHS) {
11211 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011212 // Everything but the extracted element is replaced with the RHS.
11213 for (unsigned i = 0; i != NumElts; ++i) {
11214 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011215 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011216 }
11217 return V;
11218 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011219
11220 // If this insertelement is a chain that comes from exactly these two
11221 // vectors, return the vector and the effective shuffle.
11222 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11223 return EI->getOperand(0);
11224
Chris Lattnerefb47352006-04-15 01:39:45 +000011225 }
11226 }
11227 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011228 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011229
11230 // Otherwise, can't do anything fancy. Return an identity vector.
11231 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011232 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011233 return V;
11234}
11235
11236Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11237 Value *VecOp = IE.getOperand(0);
11238 Value *ScalarOp = IE.getOperand(1);
11239 Value *IdxOp = IE.getOperand(2);
11240
Chris Lattner599ded12007-04-09 01:11:16 +000011241 // Inserting an undef or into an undefined place, remove this.
11242 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11243 ReplaceInstUsesWith(IE, VecOp);
11244
Chris Lattnerefb47352006-04-15 01:39:45 +000011245 // If the inserted element was extracted from some other vector, and if the
11246 // indexes are constant, try to turn this into a shufflevector operation.
11247 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11248 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11249 EI->getOperand(0)->getType() == IE.getType()) {
11250 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011251 unsigned ExtractedIdx =
11252 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011253 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011254
11255 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11256 return ReplaceInstUsesWith(IE, VecOp);
11257
11258 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11259 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11260
11261 // If we are extracting a value from a vector, then inserting it right
11262 // back into the same place, just use the input vector.
11263 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11264 return ReplaceInstUsesWith(IE, VecOp);
11265
11266 // We could theoretically do this for ANY input. However, doing so could
11267 // turn chains of insertelement instructions into a chain of shufflevector
11268 // instructions, and right now we do not merge shufflevectors. As such,
11269 // only do this in a situation where it is clear that there is benefit.
11270 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11271 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11272 // the values of VecOp, except then one read from EIOp0.
11273 // Build a new shuffle mask.
11274 std::vector<Constant*> Mask;
11275 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011276 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011277 else {
11278 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011279 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011280 NumVectorElts));
11281 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011282 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011283 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011284 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011285 }
11286
11287 // If this insertelement isn't used by some other insertelement, turn it
11288 // (and any insertelements it points to), into one big shuffle.
11289 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11290 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011291 Value *RHS = 0;
11292 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11293 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11294 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011295 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011296 }
11297 }
11298 }
11299
11300 return 0;
11301}
11302
11303
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011304Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11305 Value *LHS = SVI.getOperand(0);
11306 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011307 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011308
11309 bool MadeChange = false;
11310
Chris Lattner867b99f2006-10-05 06:55:50 +000011311 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011312 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011313 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11314
Chris Lattnere4929dd2007-01-05 07:36:08 +000011315 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011316 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011317 if (isa<UndefValue>(SVI.getOperand(1))) {
11318 // Scan to see if there are any references to the RHS. If so, replace them
11319 // with undef element refs and set MadeChange to true.
11320 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11321 if (Mask[i] >= e && Mask[i] != 2*e) {
11322 Mask[i] = 2*e;
11323 MadeChange = true;
11324 }
11325 }
11326
11327 if (MadeChange) {
11328 // Remap any references to RHS to use LHS.
11329 std::vector<Constant*> Elts;
11330 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11331 if (Mask[i] == 2*e)
11332 Elts.push_back(UndefValue::get(Type::Int32Ty));
11333 else
11334 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11335 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011336 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011337 }
11338 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011339
Chris Lattner863bcff2006-05-25 23:48:38 +000011340 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11341 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11342 if (LHS == RHS || isa<UndefValue>(LHS)) {
11343 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011344 // shuffle(undef,undef,mask) -> undef.
11345 return ReplaceInstUsesWith(SVI, LHS);
11346 }
11347
Chris Lattner863bcff2006-05-25 23:48:38 +000011348 // Remap any references to RHS to use LHS.
11349 std::vector<Constant*> Elts;
11350 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011351 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011352 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011353 else {
11354 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11355 (Mask[i] < e && isa<UndefValue>(LHS)))
11356 Mask[i] = 2*e; // Turn into undef.
11357 else
11358 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011359 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011360 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011361 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011362 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011363 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011364 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011365 LHS = SVI.getOperand(0);
11366 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011367 MadeChange = true;
11368 }
11369
Chris Lattner7b2e27922006-05-26 00:29:06 +000011370 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011371 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011372
Chris Lattner863bcff2006-05-25 23:48:38 +000011373 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11374 if (Mask[i] >= e*2) continue; // Ignore undef values.
11375 // Is this an identity shuffle of the LHS value?
11376 isLHSID &= (Mask[i] == i);
11377
11378 // Is this an identity shuffle of the RHS value?
11379 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011380 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011381
Chris Lattner863bcff2006-05-25 23:48:38 +000011382 // Eliminate identity shuffles.
11383 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11384 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011385
Chris Lattner7b2e27922006-05-26 00:29:06 +000011386 // If the LHS is a shufflevector itself, see if we can combine it with this
11387 // one without producing an unusual shuffle. Here we are really conservative:
11388 // we are absolutely afraid of producing a shuffle mask not in the input
11389 // program, because the code gen may not be smart enough to turn a merged
11390 // shuffle into two specific shuffles: it may produce worse code. As such,
11391 // we only merge two shuffles if the result is one of the two input shuffle
11392 // masks. In this case, merging the shuffles just removes one instruction,
11393 // which we know is safe. This is good for things like turning:
11394 // (splat(splat)) -> splat.
11395 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11396 if (isa<UndefValue>(RHS)) {
11397 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11398
11399 std::vector<unsigned> NewMask;
11400 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11401 if (Mask[i] >= 2*e)
11402 NewMask.push_back(2*e);
11403 else
11404 NewMask.push_back(LHSMask[Mask[i]]);
11405
11406 // If the result mask is equal to the src shuffle or this shuffle mask, do
11407 // the replacement.
11408 if (NewMask == LHSMask || NewMask == Mask) {
11409 std::vector<Constant*> Elts;
11410 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11411 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011412 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011413 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011414 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011415 }
11416 }
11417 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11418 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011419 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011420 }
11421 }
11422 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011423
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011424 return MadeChange ? &SVI : 0;
11425}
11426
11427
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011428
Chris Lattnerea1c4542004-12-08 23:43:58 +000011429
11430/// TryToSinkInstruction - Try to move the specified instruction from its
11431/// current block into the beginning of DestBlock, which can only happen if it's
11432/// safe to move the instruction past all of the instructions between it and the
11433/// end of its block.
11434static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11435 assert(I->hasOneUse() && "Invariants didn't hold!");
11436
Chris Lattner108e9022005-10-27 17:13:11 +000011437 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011438 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11439 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011440
Chris Lattnerea1c4542004-12-08 23:43:58 +000011441 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011442 if (isa<AllocaInst>(I) && I->getParent() ==
11443 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011444 return false;
11445
Chris Lattner96a52a62004-12-09 07:14:34 +000011446 // We can only sink load instructions if there is nothing between the load and
11447 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011448 if (I->mayReadFromMemory()) {
11449 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011450 Scan != E; ++Scan)
11451 if (Scan->mayWriteToMemory())
11452 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011453 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011454
11455 BasicBlock::iterator InsertPos = DestBlock->begin();
11456 while (isa<PHINode>(InsertPos)) ++InsertPos;
11457
Chris Lattner4bc5f802005-08-08 19:11:57 +000011458 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011459 ++NumSunkInst;
11460 return true;
11461}
11462
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011463
11464/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11465/// all reachable code to the worklist.
11466///
11467/// This has a couple of tricks to make the code faster and more powerful. In
11468/// particular, we constant fold and DCE instructions as we go, to avoid adding
11469/// them to the worklist (this significantly speeds up instcombine on code where
11470/// many instructions are dead or constant). Additionally, if we find a branch
11471/// whose condition is a known constant, we only visit the reachable successors.
11472///
11473static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011474 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011475 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011476 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011477 std::vector<BasicBlock*> Worklist;
11478 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011479
Chris Lattner2c7718a2007-03-23 19:17:18 +000011480 while (!Worklist.empty()) {
11481 BB = Worklist.back();
11482 Worklist.pop_back();
11483
11484 // We have now visited this block! If we've already been here, ignore it.
11485 if (!Visited.insert(BB)) continue;
11486
11487 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11488 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011489
Chris Lattner2c7718a2007-03-23 19:17:18 +000011490 // DCE instruction if trivially dead.
11491 if (isInstructionTriviallyDead(Inst)) {
11492 ++NumDeadInst;
11493 DOUT << "IC: DCE: " << *Inst;
11494 Inst->eraseFromParent();
11495 continue;
11496 }
11497
11498 // ConstantProp instruction if trivially constant.
11499 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11500 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11501 Inst->replaceAllUsesWith(C);
11502 ++NumConstProp;
11503 Inst->eraseFromParent();
11504 continue;
11505 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011506
Chris Lattner2c7718a2007-03-23 19:17:18 +000011507 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011508 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011509
11510 // Recursively visit successors. If this is a branch or switch on a
11511 // constant, only visit the reachable successor.
11512 TerminatorInst *TI = BB->getTerminator();
11513 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11514 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11515 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011516 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011517 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011518 continue;
11519 }
11520 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11521 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11522 // See if this is an explicit destination.
11523 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11524 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011525 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011526 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011527 continue;
11528 }
11529
11530 // Otherwise it is the default destination.
11531 Worklist.push_back(SI->getSuccessor(0));
11532 continue;
11533 }
11534 }
11535
11536 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11537 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011538 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011539}
11540
Chris Lattnerec9c3582007-03-03 02:04:50 +000011541bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011542 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011543 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011544
11545 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11546 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011547
Chris Lattnerb3d59702005-07-07 20:40:38 +000011548 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011549 // Do a depth-first traversal of the function, populate the worklist with
11550 // the reachable instructions. Ignore blocks that are not reachable. Keep
11551 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011552 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011553 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011554
Chris Lattnerb3d59702005-07-07 20:40:38 +000011555 // Do a quick scan over the function. If we find any blocks that are
11556 // unreachable, remove any instructions inside of them. This prevents
11557 // the instcombine code from having to deal with some bad special cases.
11558 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11559 if (!Visited.count(BB)) {
11560 Instruction *Term = BB->getTerminator();
11561 while (Term != BB->begin()) { // Remove instrs bottom-up
11562 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011563
Bill Wendlingb7427032006-11-26 09:46:52 +000011564 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011565 ++NumDeadInst;
11566
11567 if (!I->use_empty())
11568 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11569 I->eraseFromParent();
11570 }
11571 }
11572 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011573
Chris Lattnerdbab3862007-03-02 21:28:56 +000011574 while (!Worklist.empty()) {
11575 Instruction *I = RemoveOneFromWorkList();
11576 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011577
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011578 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011579 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011580 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011581 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011582 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011583 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011584
Bill Wendlingb7427032006-11-26 09:46:52 +000011585 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011586
11587 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011588 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011589 continue;
11590 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011591
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011592 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011593 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011594 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011595
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011596 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011597 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011598 ReplaceInstUsesWith(*I, C);
11599
Chris Lattner62b14df2002-09-02 04:59:56 +000011600 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011601 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011602 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011603 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011604 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011605
Chris Lattnerea1c4542004-12-08 23:43:58 +000011606 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011607 // FIXME: Remove GetResultInst test when first class support for aggregates
11608 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011609 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011610 BasicBlock *BB = I->getParent();
11611 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11612 if (UserParent != BB) {
11613 bool UserIsSuccessor = false;
11614 // See if the user is one of our successors.
11615 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11616 if (*SI == UserParent) {
11617 UserIsSuccessor = true;
11618 break;
11619 }
11620
11621 // If the user is one of our immediate successors, and if that successor
11622 // only has us as a predecessors (we'd have to split the critical edge
11623 // otherwise), we can keep going.
11624 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11625 next(pred_begin(UserParent)) == pred_end(UserParent))
11626 // Okay, the CFG is simple enough, try to sink this instruction.
11627 Changed |= TryToSinkInstruction(I, UserParent);
11628 }
11629 }
11630
Chris Lattner8a2a3112001-12-14 16:52:21 +000011631 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011632#ifndef NDEBUG
11633 std::string OrigI;
11634#endif
11635 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011636 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011637 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011638 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011639 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011640 DOUT << "IC: Old = " << *I
11641 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011642
Chris Lattnerf523d062004-06-09 05:08:07 +000011643 // Everything uses the new instruction now.
11644 I->replaceAllUsesWith(Result);
11645
11646 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011647 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011648 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011649
Chris Lattner6934a042007-02-11 01:23:03 +000011650 // Move the name to the new instruction first.
11651 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011652
11653 // Insert the new instruction into the basic block...
11654 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011655 BasicBlock::iterator InsertPos = I;
11656
11657 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11658 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11659 ++InsertPos;
11660
11661 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011662
Chris Lattner00d51312004-05-01 23:27:23 +000011663 // Make sure that we reprocess all operands now that we reduced their
11664 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011665 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011666
Chris Lattnerf523d062004-06-09 05:08:07 +000011667 // Instructions can end up on the worklist more than once. Make sure
11668 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011669 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011670
11671 // Erase the old instruction.
11672 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011673 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011674#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011675 DOUT << "IC: Mod = " << OrigI
11676 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011677#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011678
Chris Lattner90ac28c2002-08-02 19:29:35 +000011679 // If the instruction was modified, it's possible that it is now dead.
11680 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011681 if (isInstructionTriviallyDead(I)) {
11682 // Make sure we process all operands now that we are reducing their
11683 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011684 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011685
Chris Lattner00d51312004-05-01 23:27:23 +000011686 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011687 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011688 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011689 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011690 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011691 AddToWorkList(I);
11692 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011693 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011694 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011695 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011696 }
11697 }
11698
Chris Lattnerec9c3582007-03-03 02:04:50 +000011699 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011700
11701 // Do an explicit clear, this shrinks the map if needed.
11702 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011703 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011704}
11705
Chris Lattnerec9c3582007-03-03 02:04:50 +000011706
11707bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011708 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11709
Chris Lattnerec9c3582007-03-03 02:04:50 +000011710 bool EverMadeChange = false;
11711
11712 // Iterate while there is work to do.
11713 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011714 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011715 EverMadeChange = true;
11716 return EverMadeChange;
11717}
11718
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011719FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011720 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011721}
Brian Gaeked0fde302003-11-11 22:41:34 +000011722