blob: 0c459cf143077bc0dbc1fc1830f4aef12a69a349 [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
Reid Spencer3da59db2006-11-27 01:05:10 +0000423/// getBitCastOperand - If the specified operand is a CastInst or a constant
424/// expression bitcast, return the operand value, otherwise return null.
425static Value *getBitCastOperand(Value *V) {
426 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000427 return I->getOperand(0);
428 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000429 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000430 return CE->getOperand(0);
431 return 0;
432}
433
Reid Spencer3da59db2006-11-27 01:05:10 +0000434/// This function is a wrapper around CastInst::isEliminableCastPair. It
435/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000436static Instruction::CastOps
437isEliminableCastPair(
438 const CastInst *CI, ///< The first cast instruction
439 unsigned opcode, ///< The opcode of the second cast instruction
440 const Type *DstTy, ///< The target type for the second cast instruction
441 TargetData *TD ///< The target data for pointer size
442) {
443
444 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
445 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000446
Reid Spencer3da59db2006-11-27 01:05:10 +0000447 // Get the opcodes of the two Cast instructions
448 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
449 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000450
Reid Spencer3da59db2006-11-27 01:05:10 +0000451 return Instruction::CastOps(
452 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
453 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000454}
455
456/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
457/// in any code being generated. It does not require codegen if V is simple
458/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000459static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
460 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000461 if (V->getType() == Ty || isa<Constant>(V)) return false;
462
Chris Lattner01575b72006-05-25 23:24:33 +0000463 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000464 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000465 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000466 return false;
467 return true;
468}
469
470/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
471/// InsertBefore instruction. This is specialized a bit to avoid inserting
472/// casts that are known to not do anything...
473///
Reid Spencer17212df2006-12-12 09:18:51 +0000474Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
475 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000476 Instruction *InsertBefore) {
477 if (V->getType() == DestTy) return V;
478 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000479 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000480
Reid Spencer17212df2006-12-12 09:18:51 +0000481 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000482}
483
Chris Lattner4f98c562003-03-10 21:43:22 +0000484// SimplifyCommutative - This performs a few simplifications for commutative
485// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000486//
Chris Lattner4f98c562003-03-10 21:43:22 +0000487// 1. Order operands such that they are listed from right (least complex) to
488// left (most complex). This puts constants before unary operators before
489// binary operators.
490//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000491// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
492// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000493//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000494bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000495 bool Changed = false;
496 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
497 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000498
Chris Lattner4f98c562003-03-10 21:43:22 +0000499 if (!I.isAssociative()) return Changed;
500 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000501 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
502 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
503 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000504 Constant *Folded = ConstantExpr::get(I.getOpcode(),
505 cast<Constant>(I.getOperand(1)),
506 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000507 I.setOperand(0, Op->getOperand(0));
508 I.setOperand(1, Folded);
509 return true;
510 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
511 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
512 isOnlyUse(Op) && isOnlyUse(Op1)) {
513 Constant *C1 = cast<Constant>(Op->getOperand(1));
514 Constant *C2 = cast<Constant>(Op1->getOperand(1));
515
516 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000517 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000518 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000519 Op1->getOperand(0),
520 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000521 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000522 I.setOperand(0, New);
523 I.setOperand(1, Folded);
524 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000525 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000526 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000527 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000528}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000529
Reid Spencere4d87aa2006-12-23 06:05:41 +0000530/// SimplifyCompare - For a CmpInst this function just orders the operands
531/// so that theyare listed from right (least complex) to left (most complex).
532/// This puts constants before unary operators before binary operators.
533bool InstCombiner::SimplifyCompare(CmpInst &I) {
534 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
535 return false;
536 I.swapOperands();
537 // Compare instructions are not associative so there's nothing else we can do.
538 return true;
539}
540
Chris Lattner8d969642003-03-10 23:06:50 +0000541// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
542// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000543//
Chris Lattner8d969642003-03-10 23:06:50 +0000544static inline Value *dyn_castNegVal(Value *V) {
545 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000546 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000547
Chris Lattner0ce85802004-12-14 20:08:06 +0000548 // Constants can be considered to be negated values if they can be folded.
549 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
550 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000551 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000552}
553
Chris Lattner8d969642003-03-10 23:06:50 +0000554static inline Value *dyn_castNotVal(Value *V) {
555 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000556 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000557
558 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000559 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000560 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000561 return 0;
562}
563
Chris Lattnerc8802d22003-03-11 00:12:48 +0000564// dyn_castFoldableMul - If this value is a multiply that can be folded into
565// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000566// non-constant operand of the multiply, and set CST to point to the multiplier.
567// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000568//
Chris Lattner50af16a2004-11-13 19:50:12 +0000569static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000570 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000571 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000572 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000573 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000574 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000575 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000576 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000577 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000578 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000579 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000580 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000581 return I->getOperand(0);
582 }
583 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000584 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000585}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000586
Chris Lattner574da9b2005-01-13 20:14:25 +0000587/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
588/// expression, return it.
589static User *dyn_castGetElementPtr(Value *V) {
590 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
591 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
592 if (CE->getOpcode() == Instruction::GetElementPtr)
593 return cast<User>(V);
594 return false;
595}
596
Dan Gohmaneee962e2008-04-10 18:43:06 +0000597/// getOpcode - If this is an Instruction or a ConstantExpr, return the
598/// opcode value. Otherwise return UserOp1.
599static unsigned getOpcode(User *U) {
600 if (Instruction *I = dyn_cast<Instruction>(U))
601 return I->getOpcode();
602 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U))
603 return CE->getOpcode();
604 // Use UserOp1 to mean there's no opcode.
605 return Instruction::UserOp1;
606}
607
Reid Spencer7177c3a2007-03-25 05:33:51 +0000608/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000609static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000610 APInt Val(C->getValue());
611 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000612}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000613/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000614static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000615 APInt Val(C->getValue());
616 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000617}
618/// Add - Add two ConstantInts together
619static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
620 return ConstantInt::get(C1->getValue() + C2->getValue());
621}
622/// And - Bitwise AND two ConstantInts together
623static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
624 return ConstantInt::get(C1->getValue() & C2->getValue());
625}
626/// Subtract - Subtract one ConstantInt from another
627static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
628 return ConstantInt::get(C1->getValue() - C2->getValue());
629}
630/// Multiply - Multiply two ConstantInts together
631static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
632 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000633}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000634/// MultiplyOverflows - True if the multiply can not be expressed in an int
635/// this size.
636static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
637 uint32_t W = C1->getBitWidth();
638 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
639 if (sign) {
640 LHSExt.sext(W * 2);
641 RHSExt.sext(W * 2);
642 } else {
643 LHSExt.zext(W * 2);
644 RHSExt.zext(W * 2);
645 }
646
647 APInt MulExt = LHSExt * RHSExt;
648
649 if (sign) {
650 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
651 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
652 return MulExt.slt(Min) || MulExt.sgt(Max);
653 } else
654 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
655}
Chris Lattner955f3312004-09-28 21:48:02 +0000656
Chris Lattner68d5ff22006-02-09 07:38:58 +0000657/// ComputeMaskedBits - Determine which of the bits specified in Mask are
658/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000659/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
660/// processing.
661/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
662/// we cannot optimize based on the assumption that it is zero without changing
663/// it to be an explicit zero. If we don't change it to zero, other code could
664/// optimized based on the contradictory assumption that it is non-zero.
665/// Because instcombine aggressively folds operations with undef args anyway,
666/// this won't lose us code quality.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000667void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
668 APInt& KnownZero, APInt& KnownOne,
669 unsigned Depth) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000670 assert(V && "No Value?");
671 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000672 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000673 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
674 "Not integer or pointer type!");
675 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
676 (!isa<IntegerType>(V->getType()) ||
677 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000678 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000679 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000680 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000681 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
682 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000683 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000684 KnownZero = ~KnownOne & Mask;
685 return;
686 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000687 // Null is all-zeros.
688 if (isa<ConstantPointerNull>(V)) {
689 KnownOne.clear();
690 KnownZero = Mask;
691 return;
692 }
693 // The address of an aligned GlobalValue has trailing zeros.
694 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
695 unsigned Align = GV->getAlignment();
696 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
697 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
698 if (Align > 0)
699 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
700 CountTrailingZeros_32(Align));
701 else
702 KnownZero.clear();
703 KnownOne.clear();
704 return;
705 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000706
Dan Gohman23e8b712008-04-28 17:02:21 +0000707 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
708
Reid Spencer3e7594f2007-03-08 01:46:38 +0000709 if (Depth == 6 || Mask == 0)
710 return; // Limit search depth.
711
Dan Gohmaneee962e2008-04-10 18:43:06 +0000712 User *I = dyn_cast<User>(V);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000713 if (!I) return;
714
715 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000716 switch (getOpcode(I)) {
717 default: break;
Reid Spencer2b812072007-03-25 02:03:12 +0000718 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000719 // If either the LHS or the RHS are Zero, the result is zero.
720 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000721 APInt Mask2(Mask & ~KnownZero);
722 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000723 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
724 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
725
726 // Output known-1 bits are only known if set in both the LHS & RHS.
727 KnownOne &= KnownOne2;
728 // Output known-0 are known to be clear if zero in either the LHS | RHS.
729 KnownZero |= KnownZero2;
730 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000731 }
732 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000733 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000734 APInt Mask2(Mask & ~KnownOne);
735 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000736 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
737 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
738
739 // Output known-0 bits are only known if clear in both the LHS & RHS.
740 KnownZero &= KnownZero2;
741 // Output known-1 are known to be set if set in either the LHS | RHS.
742 KnownOne |= KnownOne2;
743 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000744 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000745 case Instruction::Xor: {
746 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
747 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
748 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 known if clear or set in both the LHS & RHS.
752 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
753 // Output known-1 are known to be set if set in only one of the LHS, RHS.
754 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
755 KnownZero = KnownZeroOut;
756 return;
757 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000758 case Instruction::Mul: {
759 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
760 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
761 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
762 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
763 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
764
765 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohman23e8b712008-04-28 17:02:21 +0000766 // Also compute a conserative estimate for high known-0 bits.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000767 // More trickiness is possible, but this is sufficient for the
768 // interesting case of alignment computation.
769 KnownOne.clear();
770 unsigned TrailZ = KnownZero.countTrailingOnes() +
771 KnownZero2.countTrailingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +0000772 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
Dan Gohman42ac9292008-05-07 00:35:55 +0000773 KnownZero2.countLeadingOnes(),
774 BitWidth) - BitWidth;
Dan Gohman23e8b712008-04-28 17:02:21 +0000775
Dan Gohmaneee962e2008-04-10 18:43:06 +0000776 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000777 LeadZ = std::min(LeadZ, BitWidth);
778 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
779 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000780 KnownZero &= Mask;
781 return;
782 }
Dan Gohman23e8b712008-04-28 17:02:21 +0000783 case Instruction::UDiv: {
784 // For the purposes of computing leading zeros we can conservatively
785 // treat a udiv as a logical right shift by the power of 2 known to
Dan Gohman1d9cd502008-05-02 21:30:02 +0000786 // be less than the denominator.
Dan Gohman23e8b712008-04-28 17:02:21 +0000787 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
788 ComputeMaskedBits(I->getOperand(0),
789 AllOnes, KnownZero2, KnownOne2, Depth+1);
790 unsigned LeadZ = KnownZero2.countLeadingOnes();
791
792 KnownOne2.clear();
793 KnownZero2.clear();
794 ComputeMaskedBits(I->getOperand(1),
795 AllOnes, KnownZero2, KnownOne2, Depth+1);
Dan Gohman1d9cd502008-05-02 21:30:02 +0000796 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
797 if (RHSUnknownLeadingOnes != BitWidth)
798 LeadZ = std::min(BitWidth,
799 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000800
801 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
802 return;
803 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000804 case Instruction::Select:
805 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
806 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
807 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
808 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
809
810 // Only known if known in both the LHS and RHS.
811 KnownOne &= KnownOne2;
812 KnownZero &= KnownZero2;
813 return;
814 case Instruction::FPTrunc:
815 case Instruction::FPExt:
816 case Instruction::FPToUI:
817 case Instruction::FPToSI:
818 case Instruction::SIToFP:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000819 case Instruction::UIToFP:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000820 return; // Can't work with floating point.
821 case Instruction::PtrToInt:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000822 case Instruction::IntToPtr:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000823 // We can't handle these if we don't know the pointer size.
824 if (!TD) return;
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000825 // FALL THROUGH and handle them the same as zext/trunc.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000826 case Instruction::ZExt:
Zhou Sheng771dbf72007-03-13 02:23:10 +0000827 case Instruction::Trunc: {
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000828 // Note that we handle pointer operands here because of inttoptr/ptrtoint
829 // which fall through here.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000830 const Type *SrcTy = I->getOperand(0)->getType();
831 uint32_t SrcBitWidth = TD ?
832 TD->getTypeSizeInBits(SrcTy) :
833 SrcTy->getPrimitiveSizeInBits();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000834 APInt MaskIn(Mask);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000835 MaskIn.zextOrTrunc(SrcBitWidth);
836 KnownZero.zextOrTrunc(SrcBitWidth);
837 KnownOne.zextOrTrunc(SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000838 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000839 KnownZero.zextOrTrunc(BitWidth);
840 KnownOne.zextOrTrunc(BitWidth);
841 // Any top bits are known to be zero.
842 if (BitWidth > SrcBitWidth)
843 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000844 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000845 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000846 case Instruction::BitCast: {
847 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000848 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000849 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
850 return;
851 }
852 break;
853 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000854 case Instruction::SExt: {
855 // Compute the bits in the result that are not present in the input.
856 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000857 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000858
Zhou Shengaa305ab2007-03-28 02:19:03 +0000859 APInt MaskIn(Mask);
860 MaskIn.trunc(SrcBitWidth);
861 KnownZero.trunc(SrcBitWidth);
862 KnownOne.trunc(SrcBitWidth);
863 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000864 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000865 KnownZero.zext(BitWidth);
866 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000867
868 // If the sign bit of the input is known set or clear, then we know the
869 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000870 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000871 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000872 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000873 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000874 return;
875 }
876 case Instruction::Shl:
877 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
878 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000879 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000880 APInt Mask2(Mask.lshr(ShiftAmt));
881 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000882 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000883 KnownZero <<= ShiftAmt;
884 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000885 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000886 return;
887 }
888 break;
889 case Instruction::LShr:
890 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
891 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
892 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000893 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000894
895 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000896 APInt Mask2(Mask.shl(ShiftAmt));
897 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000898 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
899 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
900 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000901 // high bits known zero.
902 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000903 return;
904 }
905 break;
906 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000907 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000908 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
909 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000910 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000911
912 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000913 APInt Mask2(Mask.shl(ShiftAmt));
914 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000915 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
916 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
917 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
918
Zhou Shengaa305ab2007-03-28 02:19:03 +0000919 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
920 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000921 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000922 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000923 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000924 return;
925 }
926 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000927 case Instruction::Sub: {
928 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
929 // We know that the top bits of C-X are clear if X contains less bits
930 // than C (i.e. no wrap-around can happen). For example, 20-X is
931 // positive if we can prove that X is >= 0 and < 16.
932 if (!CLHS->getValue().isNegative()) {
933 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
934 // NLZ can't be BitWidth with no sign bit
935 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000936 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
937 Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000938
Dan Gohman23e8b712008-04-28 17:02:21 +0000939 // If all of the MaskV bits are known to be zero, then we know the
940 // output top bits are zero, because we now know that the output is
941 // from [0-C].
942 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohmaneee962e2008-04-10 18:43:06 +0000943 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
944 // Top bits known zero.
945 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000946 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000947 }
948 }
949 }
950 // fall through
Duncan Sands1d57a752008-03-21 08:32:17 +0000951 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000952 // Output known-0 bits are known if clear or set in both the low clear bits
953 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
954 // low 3 bits clear.
Dan Gohman23e8b712008-04-28 17:02:21 +0000955 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
956 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
957 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
958 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
959
960 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
961 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
962 KnownZeroOut = std::min(KnownZeroOut,
963 KnownZero2.countTrailingOnes());
964
965 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000966 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000967 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000968 case Instruction::SRem:
969 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
970 APInt RA = Rem->getValue();
971 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +0000972 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000973 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
974 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
975
976 // The sign of a remainder is equal to the sign of the first
977 // operand (zero being positive).
978 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
979 KnownZero2 |= ~LowBits;
980 else if (KnownOne2[BitWidth-1])
981 KnownOne2 |= ~LowBits;
982
983 KnownZero |= KnownZero2 & Mask;
984 KnownOne |= KnownOne2 & Mask;
985
986 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
987 }
988 }
989 break;
Dan Gohman23e8b712008-04-28 17:02:21 +0000990 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000991 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
992 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +0000993 if (RA.isPowerOf2()) {
994 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000995 APInt Mask2 = LowBits & Mask;
996 KnownZero |= ~LowBits & Mask;
997 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
998 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +0000999 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001000 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001001 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001002
1003 // Since the result is less than or equal to either operand, any leading
1004 // zero bits in either operand must also exist in the result.
1005 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1006 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1007 Depth+1);
1008 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1009 Depth+1);
1010
1011 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1012 KnownZero2.countLeadingOnes());
1013 KnownOne.clear();
1014 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001015 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001016 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00001017
1018 case Instruction::Alloca:
1019 case Instruction::Malloc: {
1020 AllocationInst *AI = cast<AllocationInst>(V);
1021 unsigned Align = AI->getAlignment();
1022 if (Align == 0 && TD) {
1023 if (isa<AllocaInst>(AI))
1024 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1025 else if (isa<MallocInst>(AI)) {
1026 // Malloc returns maximally aligned memory.
1027 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1028 Align =
1029 std::max(Align,
1030 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1031 Align =
1032 std::max(Align,
1033 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1034 }
1035 }
1036
1037 if (Align > 0)
1038 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1039 CountTrailingZeros_32(Align));
1040 break;
1041 }
1042 case Instruction::GetElementPtr: {
1043 // Analyze all of the subscripts of this getelementptr instruction
1044 // to determine if we can prove known low zero bits.
1045 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1046 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1047 ComputeMaskedBits(I->getOperand(0), LocalMask,
1048 LocalKnownZero, LocalKnownOne, Depth+1);
1049 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1050
1051 gep_type_iterator GTI = gep_type_begin(I);
1052 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1053 Value *Index = I->getOperand(i);
1054 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1055 // Handle struct member offset arithmetic.
1056 if (!TD) return;
1057 const StructLayout *SL = TD->getStructLayout(STy);
1058 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1059 uint64_t Offset = SL->getElementOffset(Idx);
1060 TrailZ = std::min(TrailZ,
1061 CountTrailingZeros_64(Offset));
1062 } else {
1063 // Handle array index arithmetic.
1064 const Type *IndexedTy = GTI.getIndexedType();
1065 if (!IndexedTy->isSized()) return;
1066 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1067 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1068 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1069 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1070 ComputeMaskedBits(Index, LocalMask,
1071 LocalKnownZero, LocalKnownOne, Depth+1);
1072 TrailZ = std::min(TrailZ,
1073 CountTrailingZeros_64(TypeSize) +
1074 LocalKnownZero.countTrailingOnes());
1075 }
1076 }
1077
1078 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1079 break;
1080 }
1081 case Instruction::PHI: {
1082 PHINode *P = cast<PHINode>(I);
1083 // Handle the case of a simple two-predecessor recurrence PHI.
1084 // There's a lot more that could theoretically be done here, but
1085 // this is sufficient to catch some interesting cases.
1086 if (P->getNumIncomingValues() == 2) {
1087 for (unsigned i = 0; i != 2; ++i) {
1088 Value *L = P->getIncomingValue(i);
1089 Value *R = P->getIncomingValue(!i);
1090 User *LU = dyn_cast<User>(L);
1091 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1092 // Check for operations that have the property that if
1093 // both their operands have low zero bits, the result
1094 // will have low zero bits.
1095 if (Opcode == Instruction::Add ||
1096 Opcode == Instruction::Sub ||
1097 Opcode == Instruction::And ||
1098 Opcode == Instruction::Or ||
1099 Opcode == Instruction::Mul) {
1100 Value *LL = LU->getOperand(0);
1101 Value *LR = LU->getOperand(1);
1102 // Find a recurrence.
1103 if (LL == I)
1104 L = LR;
1105 else if (LR == I)
1106 L = LL;
1107 else
1108 break;
1109 // Ok, we have a PHI of the form L op= R. Check for low
1110 // zero bits.
1111 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1112 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1113 Mask2 = APInt::getLowBitsSet(BitWidth,
1114 KnownZero2.countTrailingOnes());
1115 KnownOne2.clear();
1116 KnownZero2.clear();
1117 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1118 KnownZero = Mask &
1119 APInt::getLowBitsSet(BitWidth,
1120 KnownZero2.countTrailingOnes());
1121 break;
1122 }
1123 }
1124 }
1125 break;
1126 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001127 case Instruction::Call:
1128 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1129 switch (II->getIntrinsicID()) {
1130 default: break;
1131 case Intrinsic::ctpop:
1132 case Intrinsic::ctlz:
1133 case Intrinsic::cttz: {
1134 unsigned LowBits = Log2_32(BitWidth)+1;
1135 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1136 break;
1137 }
1138 }
1139 }
1140 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +00001141 }
1142}
1143
Reid Spencere7816b52007-03-08 01:52:58 +00001144/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1145/// this predicate to simplify operations downstream. Mask is known to be zero
1146/// for bits that V cannot have.
Dan Gohmaneee962e2008-04-10 18:43:06 +00001147bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1148 unsigned Depth) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001149 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001150 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1151 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1152 return (KnownZero & Mask) == Mask;
1153}
1154
Chris Lattner255d8912006-02-11 09:31:47 +00001155/// ShrinkDemandedConstant - Check to see if the specified operand of the
1156/// specified instruction is a constant integer. If so, check to see if there
1157/// are any bits set in the constant that are not demanded. If so, shrink the
1158/// constant and return true.
1159static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001160 APInt Demanded) {
1161 assert(I && "No instruction?");
1162 assert(OpNo < I->getNumOperands() && "Operand index too large");
1163
1164 // If the operand is not a constant integer, nothing to do.
1165 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1166 if (!OpC) return false;
1167
1168 // If there are no bits set that aren't demanded, nothing to do.
1169 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1170 if ((~Demanded & OpC->getValue()) == 0)
1171 return false;
1172
1173 // This instruction is producing bits that are not demanded. Shrink the RHS.
1174 Demanded &= OpC->getValue();
1175 I->setOperand(OpNo, ConstantInt::get(Demanded));
1176 return true;
1177}
1178
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001179// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1180// set of known zero and one bits, compute the maximum and minimum values that
1181// could have the specified known zero and known one bits, returning them in
1182// min/max.
1183static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +00001184 const APInt& KnownZero,
1185 const APInt& KnownOne,
1186 APInt& Min, APInt& Max) {
1187 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1188 assert(KnownZero.getBitWidth() == BitWidth &&
1189 KnownOne.getBitWidth() == BitWidth &&
1190 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1191 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001192 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001193
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001194 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1195 // bit if it is unknown.
1196 Min = KnownOne;
1197 Max = KnownOne|UnknownBits;
1198
Zhou Sheng4acf1552007-03-28 05:15:57 +00001199 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001200 Min.set(BitWidth-1);
1201 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001202 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001203}
1204
1205// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1206// a set of known zero and one bits, compute the maximum and minimum values that
1207// could have the specified known zero and known one bits, returning them in
1208// min/max.
1209static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001210 const APInt &KnownZero,
1211 const APInt &KnownOne,
1212 APInt &Min, APInt &Max) {
1213 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +00001214 assert(KnownZero.getBitWidth() == BitWidth &&
1215 KnownOne.getBitWidth() == BitWidth &&
1216 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1217 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001218 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001219
1220 // The minimum value is when the unknown bits are all zeros.
1221 Min = KnownOne;
1222 // The maximum value is when the unknown bits are all ones.
1223 Max = KnownOne|UnknownBits;
1224}
Chris Lattner255d8912006-02-11 09:31:47 +00001225
Reid Spencer8cb68342007-03-12 17:25:59 +00001226/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1227/// value based on the demanded bits. When this function is called, it is known
1228/// that only the bits set in DemandedMask of the result of V are ever used
1229/// downstream. Consequently, depending on the mask and V, it may be possible
1230/// to replace V with a constant or one of its operands. In such cases, this
1231/// function does the replacement and returns true. In all other cases, it
1232/// returns false after analyzing the expression and setting KnownOne and known
1233/// to be one in the expression. KnownZero contains all the bits that are known
1234/// to be zero in the expression. These are provided to potentially allow the
1235/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1236/// the expression. KnownOne and KnownZero always follow the invariant that
1237/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1238/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1239/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1240/// and KnownOne must all be the same.
1241bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1242 APInt& KnownZero, APInt& KnownOne,
1243 unsigned Depth) {
1244 assert(V != 0 && "Null pointer of Value???");
1245 assert(Depth <= 6 && "Limit Search Depth");
1246 uint32_t BitWidth = DemandedMask.getBitWidth();
1247 const IntegerType *VTy = cast<IntegerType>(V->getType());
1248 assert(VTy->getBitWidth() == BitWidth &&
1249 KnownZero.getBitWidth() == BitWidth &&
1250 KnownOne.getBitWidth() == BitWidth &&
1251 "Value *V, DemandedMask, KnownZero and KnownOne \
1252 must have same BitWidth");
1253 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1254 // We know all of the bits for a constant!
1255 KnownOne = CI->getValue() & DemandedMask;
1256 KnownZero = ~KnownOne & DemandedMask;
1257 return false;
1258 }
1259
Zhou Sheng96704452007-03-14 03:21:24 +00001260 KnownZero.clear();
1261 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001262 if (!V->hasOneUse()) { // Other users may use these bits.
1263 if (Depth != 0) { // Not at the root.
1264 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1265 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1266 return false;
1267 }
1268 // If this is the root being simplified, allow it to have multiple uses,
1269 // just set the DemandedMask to all bits.
1270 DemandedMask = APInt::getAllOnesValue(BitWidth);
1271 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1272 if (V != UndefValue::get(VTy))
1273 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1274 return false;
1275 } else if (Depth == 6) { // Limit search depth.
1276 return false;
1277 }
1278
1279 Instruction *I = dyn_cast<Instruction>(V);
1280 if (!I) return false; // Only analyze instructions.
1281
Reid Spencer8cb68342007-03-12 17:25:59 +00001282 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1283 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1284 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001285 default:
1286 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1287 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001288 case Instruction::And:
1289 // If either the LHS or the RHS are Zero, the result is zero.
1290 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1291 RHSKnownZero, RHSKnownOne, Depth+1))
1292 return true;
1293 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1294 "Bits known to be one AND zero?");
1295
1296 // If something is known zero on the RHS, the bits aren't demanded on the
1297 // LHS.
1298 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1299 LHSKnownZero, LHSKnownOne, Depth+1))
1300 return true;
1301 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1302 "Bits known to be one AND zero?");
1303
1304 // If all of the demanded bits are known 1 on one side, return the other.
1305 // These bits cannot contribute to the result of the 'and'.
1306 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1307 (DemandedMask & ~LHSKnownZero))
1308 return UpdateValueUsesWith(I, I->getOperand(0));
1309 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1310 (DemandedMask & ~RHSKnownZero))
1311 return UpdateValueUsesWith(I, I->getOperand(1));
1312
1313 // If all of the demanded bits in the inputs are known zeros, return zero.
1314 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1315 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1316
1317 // If the RHS is a constant, see if we can simplify it.
1318 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1319 return UpdateValueUsesWith(I, I);
1320
1321 // Output known-1 bits are only known if set in both the LHS & RHS.
1322 RHSKnownOne &= LHSKnownOne;
1323 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1324 RHSKnownZero |= LHSKnownZero;
1325 break;
1326 case Instruction::Or:
1327 // If either the LHS or the RHS are One, the result is One.
1328 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1329 RHSKnownZero, RHSKnownOne, Depth+1))
1330 return true;
1331 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1332 "Bits known to be one AND zero?");
1333 // If something is known one on the RHS, the bits aren't demanded on the
1334 // LHS.
1335 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1336 LHSKnownZero, LHSKnownOne, Depth+1))
1337 return true;
1338 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1339 "Bits known to be one AND zero?");
1340
1341 // If all of the demanded bits are known zero on one side, return the other.
1342 // These bits cannot contribute to the result of the 'or'.
1343 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1344 (DemandedMask & ~LHSKnownOne))
1345 return UpdateValueUsesWith(I, I->getOperand(0));
1346 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1347 (DemandedMask & ~RHSKnownOne))
1348 return UpdateValueUsesWith(I, I->getOperand(1));
1349
1350 // If all of the potentially set bits on one side are known to be set on
1351 // the other side, just use the 'other' side.
1352 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1353 (DemandedMask & (~RHSKnownZero)))
1354 return UpdateValueUsesWith(I, I->getOperand(0));
1355 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1356 (DemandedMask & (~LHSKnownZero)))
1357 return UpdateValueUsesWith(I, I->getOperand(1));
1358
1359 // If the RHS is a constant, see if we can simplify it.
1360 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1361 return UpdateValueUsesWith(I, I);
1362
1363 // Output known-0 bits are only known if clear in both the LHS & RHS.
1364 RHSKnownZero &= LHSKnownZero;
1365 // Output known-1 are known to be set if set in either the LHS | RHS.
1366 RHSKnownOne |= LHSKnownOne;
1367 break;
1368 case Instruction::Xor: {
1369 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1370 RHSKnownZero, RHSKnownOne, Depth+1))
1371 return true;
1372 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1373 "Bits known to be one AND zero?");
1374 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1375 LHSKnownZero, LHSKnownOne, Depth+1))
1376 return true;
1377 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1378 "Bits known to be one AND zero?");
1379
1380 // If all of the demanded bits are known zero on one side, return the other.
1381 // These bits cannot contribute to the result of the 'xor'.
1382 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1383 return UpdateValueUsesWith(I, I->getOperand(0));
1384 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1385 return UpdateValueUsesWith(I, I->getOperand(1));
1386
1387 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1388 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1389 (RHSKnownOne & LHSKnownOne);
1390 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1391 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1392 (RHSKnownOne & LHSKnownZero);
1393
1394 // If all of the demanded bits are known to be zero on one side or the
1395 // other, turn this into an *inclusive* or.
1396 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1397 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1398 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001399 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001400 I->getName());
1401 InsertNewInstBefore(Or, *I);
1402 return UpdateValueUsesWith(I, Or);
1403 }
1404
1405 // If all of the demanded bits on one side are known, and all of the set
1406 // bits on that side are also known to be set on the other side, turn this
1407 // into an AND, as we know the bits will be cleared.
1408 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1409 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1410 // all known
1411 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1412 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1413 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001414 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +00001415 InsertNewInstBefore(And, *I);
1416 return UpdateValueUsesWith(I, And);
1417 }
1418 }
1419
1420 // If the RHS is a constant, see if we can simplify it.
1421 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1422 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1423 return UpdateValueUsesWith(I, I);
1424
1425 RHSKnownZero = KnownZeroOut;
1426 RHSKnownOne = KnownOneOut;
1427 break;
1428 }
1429 case Instruction::Select:
1430 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1431 RHSKnownZero, RHSKnownOne, Depth+1))
1432 return true;
1433 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1434 LHSKnownZero, LHSKnownOne, Depth+1))
1435 return true;
1436 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1437 "Bits known to be one AND zero?");
1438 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1439 "Bits known to be one AND zero?");
1440
1441 // If the operands are constants, see if we can simplify them.
1442 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1443 return UpdateValueUsesWith(I, I);
1444 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1445 return UpdateValueUsesWith(I, I);
1446
1447 // Only known if known in both the LHS and RHS.
1448 RHSKnownOne &= LHSKnownOne;
1449 RHSKnownZero &= LHSKnownZero;
1450 break;
1451 case Instruction::Trunc: {
1452 uint32_t truncBf =
1453 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001454 DemandedMask.zext(truncBf);
1455 RHSKnownZero.zext(truncBf);
1456 RHSKnownOne.zext(truncBf);
1457 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1458 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001459 return true;
1460 DemandedMask.trunc(BitWidth);
1461 RHSKnownZero.trunc(BitWidth);
1462 RHSKnownOne.trunc(BitWidth);
1463 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1464 "Bits known to be one AND zero?");
1465 break;
1466 }
1467 case Instruction::BitCast:
1468 if (!I->getOperand(0)->getType()->isInteger())
1469 return false;
1470
1471 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1472 RHSKnownZero, RHSKnownOne, Depth+1))
1473 return true;
1474 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1475 "Bits known to be one AND zero?");
1476 break;
1477 case Instruction::ZExt: {
1478 // Compute the bits in the result that are not present in the input.
1479 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001480 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001481
Zhou Shengd48653a2007-03-29 04:45:55 +00001482 DemandedMask.trunc(SrcBitWidth);
1483 RHSKnownZero.trunc(SrcBitWidth);
1484 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001485 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1486 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001487 return true;
1488 DemandedMask.zext(BitWidth);
1489 RHSKnownZero.zext(BitWidth);
1490 RHSKnownOne.zext(BitWidth);
1491 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1492 "Bits known to be one AND zero?");
1493 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001494 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001495 break;
1496 }
1497 case Instruction::SExt: {
1498 // Compute the bits in the result that are not present in the input.
1499 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001500 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001501
Reid Spencer8cb68342007-03-12 17:25:59 +00001502 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001503 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001504
Zhou Sheng01542f32007-03-29 02:26:30 +00001505 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001506 // If any of the sign extended bits are demanded, we know that the sign
1507 // bit is demanded.
1508 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001509 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001510
Zhou Shengd48653a2007-03-29 04:45:55 +00001511 InputDemandedBits.trunc(SrcBitWidth);
1512 RHSKnownZero.trunc(SrcBitWidth);
1513 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001514 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1515 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001516 return true;
1517 InputDemandedBits.zext(BitWidth);
1518 RHSKnownZero.zext(BitWidth);
1519 RHSKnownOne.zext(BitWidth);
1520 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1521 "Bits known to be one AND zero?");
1522
1523 // If the sign bit of the input is known set or clear, then we know the
1524 // top bits of the result.
1525
1526 // If the input sign bit is known zero, or if the NewBits are not demanded
1527 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001528 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001529 {
1530 // Convert to ZExt cast
1531 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1532 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001533 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001534 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001535 }
1536 break;
1537 }
1538 case Instruction::Add: {
1539 // Figure out what the input bits are. If the top bits of the and result
1540 // are not demanded, then the add doesn't demand them from its input
1541 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001542 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001543
1544 // If there is a constant on the RHS, there are a variety of xformations
1545 // we can do.
1546 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1547 // If null, this should be simplified elsewhere. Some of the xforms here
1548 // won't work if the RHS is zero.
1549 if (RHS->isZero())
1550 break;
1551
1552 // If the top bit of the output is demanded, demand everything from the
1553 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001554 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001555
1556 // Find information about known zero/one bits in the input.
1557 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1558 LHSKnownZero, LHSKnownOne, Depth+1))
1559 return true;
1560
1561 // If the RHS of the add has bits set that can't affect the input, reduce
1562 // the constant.
1563 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1564 return UpdateValueUsesWith(I, I);
1565
1566 // Avoid excess work.
1567 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1568 break;
1569
1570 // Turn it into OR if input bits are zero.
1571 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1572 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001573 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001574 I->getName());
1575 InsertNewInstBefore(Or, *I);
1576 return UpdateValueUsesWith(I, Or);
1577 }
1578
1579 // We can say something about the output known-zero and known-one bits,
1580 // depending on potential carries from the input constant and the
1581 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1582 // bits set and the RHS constant is 0x01001, then we know we have a known
1583 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1584
1585 // To compute this, we first compute the potential carry bits. These are
1586 // the bits which may be modified. I'm not aware of a better way to do
1587 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001588 const APInt& RHSVal = RHS->getValue();
1589 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001590
1591 // Now that we know which bits have carries, compute the known-1/0 sets.
1592
1593 // Bits are known one if they are known zero in one operand and one in the
1594 // other, and there is no input carry.
1595 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1596 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1597
1598 // Bits are known zero if they are known zero in both operands and there
1599 // is no input carry.
1600 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1601 } else {
1602 // If the high-bits of this ADD are not demanded, then it does not demand
1603 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001604 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001605 // Right fill the mask of bits for this ADD to demand the most
1606 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001607 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001608 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1609 LHSKnownZero, LHSKnownOne, Depth+1))
1610 return true;
1611 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1612 LHSKnownZero, LHSKnownOne, Depth+1))
1613 return true;
1614 }
1615 }
1616 break;
1617 }
1618 case Instruction::Sub:
1619 // If the high-bits of this SUB are not demanded, then it does not demand
1620 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001621 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001622 // Right fill the mask of bits for this SUB to demand the most
1623 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001624 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001625 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001626 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1627 LHSKnownZero, LHSKnownOne, Depth+1))
1628 return true;
1629 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1630 LHSKnownZero, LHSKnownOne, Depth+1))
1631 return true;
1632 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001633 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1634 // the known zeros and ones.
1635 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001636 break;
1637 case Instruction::Shl:
1638 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001639 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001640 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1641 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001642 RHSKnownZero, RHSKnownOne, Depth+1))
1643 return true;
1644 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1645 "Bits known to be one AND zero?");
1646 RHSKnownZero <<= ShiftAmt;
1647 RHSKnownOne <<= ShiftAmt;
1648 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001649 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001650 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001651 }
1652 break;
1653 case Instruction::LShr:
1654 // For a logical shift right
1655 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001656 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001657
Reid Spencer8cb68342007-03-12 17:25:59 +00001658 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001659 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1660 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001661 RHSKnownZero, RHSKnownOne, Depth+1))
1662 return true;
1663 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1664 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001665 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1666 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001667 if (ShiftAmt) {
1668 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001669 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001670 RHSKnownZero |= HighBits; // high bits known zero.
1671 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001672 }
1673 break;
1674 case Instruction::AShr:
1675 // If this is an arithmetic shift right and only the low-bit is set, we can
1676 // always convert this into a logical shr, even if the shift amount is
1677 // variable. The low bit of the shift cannot be an input sign bit unless
1678 // the shift amount is >= the size of the datatype, which is undefined.
1679 if (DemandedMask == 1) {
1680 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001681 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001682 I->getOperand(0), I->getOperand(1), I->getName());
1683 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1684 return UpdateValueUsesWith(I, NewVal);
1685 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001686
1687 // If the sign bit is the only bit demanded by this ashr, then there is no
1688 // need to do it, the shift doesn't change the high bit.
1689 if (DemandedMask.isSignBit())
1690 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001691
1692 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001693 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001694
Reid Spencer8cb68342007-03-12 17:25:59 +00001695 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001696 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001697 // If any of the "high bits" are demanded, we should set the sign bit as
1698 // demanded.
1699 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1700 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001701 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001702 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001703 RHSKnownZero, RHSKnownOne, Depth+1))
1704 return true;
1705 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1706 "Bits known to be one AND zero?");
1707 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001708 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001709 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1710 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1711
1712 // Handle the sign bits.
1713 APInt SignBit(APInt::getSignBit(BitWidth));
1714 // Adjust to where it is now in the mask.
1715 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1716
1717 // If the input sign bit is known to be zero, or if none of the top bits
1718 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001719 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001720 (HighBits & ~DemandedMask) == HighBits) {
1721 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001722 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001723 I->getOperand(0), SA, I->getName());
1724 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1725 return UpdateValueUsesWith(I, NewVal);
1726 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1727 RHSKnownOne |= HighBits;
1728 }
1729 }
1730 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001731 case Instruction::SRem:
1732 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1733 APInt RA = Rem->getValue();
1734 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001735 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001736 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1737 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1738 LHSKnownZero, LHSKnownOne, Depth+1))
1739 return true;
1740
1741 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1742 LHSKnownZero |= ~LowBits;
1743 else if (LHSKnownOne[BitWidth-1])
1744 LHSKnownOne |= ~LowBits;
1745
1746 KnownZero |= LHSKnownZero & DemandedMask;
1747 KnownOne |= LHSKnownOne & DemandedMask;
1748
1749 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1750 }
1751 }
1752 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001753 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001754 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1755 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001756 if (RA.isPowerOf2()) {
1757 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001758 APInt Mask2 = LowBits & DemandedMask;
1759 KnownZero |= ~LowBits & DemandedMask;
1760 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1761 KnownZero, KnownOne, Depth+1))
1762 return true;
1763
1764 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001765 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001766 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001767 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001768
1769 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1770 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001771 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1772 KnownZero2, KnownOne2, Depth+1))
1773 return true;
1774
Dan Gohman23e8b712008-04-28 17:02:21 +00001775 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001776 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001777 KnownZero2, KnownOne2, Depth+1))
1778 return true;
1779
1780 Leaders = std::max(Leaders,
1781 KnownZero2.countLeadingOnes());
1782 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001783 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001784 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001785 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001786
1787 // If the client is only demanding bits that we know, return the known
1788 // constant.
1789 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1790 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1791 return false;
1792}
1793
Chris Lattner867b99f2006-10-05 06:55:50 +00001794
1795/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1796/// 64 or fewer elements. DemandedElts contains the set of elements that are
1797/// actually used by the caller. This method analyzes which elements of the
1798/// operand are undef and returns that information in UndefElts.
1799///
1800/// If the information about demanded elements can be used to simplify the
1801/// operation, the operation is simplified, then the resultant value is
1802/// returned. This returns null if no change was made.
1803Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1804 uint64_t &UndefElts,
1805 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001806 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001807 assert(VWidth <= 64 && "Vector too wide to analyze!");
1808 uint64_t EltMask = ~0ULL >> (64-VWidth);
1809 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1810 "Invalid DemandedElts!");
1811
1812 if (isa<UndefValue>(V)) {
1813 // If the entire vector is undefined, just return this info.
1814 UndefElts = EltMask;
1815 return 0;
1816 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1817 UndefElts = EltMask;
1818 return UndefValue::get(V->getType());
1819 }
1820
1821 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001822 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1823 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001824 Constant *Undef = UndefValue::get(EltTy);
1825
1826 std::vector<Constant*> Elts;
1827 for (unsigned i = 0; i != VWidth; ++i)
1828 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1829 Elts.push_back(Undef);
1830 UndefElts |= (1ULL << i);
1831 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1832 Elts.push_back(Undef);
1833 UndefElts |= (1ULL << i);
1834 } else { // Otherwise, defined.
1835 Elts.push_back(CP->getOperand(i));
1836 }
1837
1838 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001839 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001840 return NewCP != CP ? NewCP : 0;
1841 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001842 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001843 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001844 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001845 Constant *Zero = Constant::getNullValue(EltTy);
1846 Constant *Undef = UndefValue::get(EltTy);
1847 std::vector<Constant*> Elts;
1848 for (unsigned i = 0; i != VWidth; ++i)
1849 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1850 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001851 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001852 }
1853
1854 if (!V->hasOneUse()) { // Other users may use these bits.
1855 if (Depth != 0) { // Not at the root.
1856 // TODO: Just compute the UndefElts information recursively.
1857 return false;
1858 }
1859 return false;
1860 } else if (Depth == 10) { // Limit search depth.
1861 return false;
1862 }
1863
1864 Instruction *I = dyn_cast<Instruction>(V);
1865 if (!I) return false; // Only analyze instructions.
1866
1867 bool MadeChange = false;
1868 uint64_t UndefElts2;
1869 Value *TmpV;
1870 switch (I->getOpcode()) {
1871 default: break;
1872
1873 case Instruction::InsertElement: {
1874 // If this is a variable index, we don't know which element it overwrites.
1875 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001876 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001877 if (Idx == 0) {
1878 // Note that we can't propagate undef elt info, because we don't know
1879 // which elt is getting updated.
1880 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1881 UndefElts2, Depth+1);
1882 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1883 break;
1884 }
1885
1886 // If this is inserting an element that isn't demanded, remove this
1887 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001888 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001889 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1890 return AddSoonDeadInstToWorklist(*I, 0);
1891
1892 // Otherwise, the element inserted overwrites whatever was there, so the
1893 // input demanded set is simpler than the output set.
1894 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1895 DemandedElts & ~(1ULL << IdxNo),
1896 UndefElts, Depth+1);
1897 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1898
1899 // The inserted element is defined.
1900 UndefElts |= 1ULL << IdxNo;
1901 break;
1902 }
Chris Lattner69878332007-04-14 22:29:23 +00001903 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001904 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001905 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1906 if (!VTy) break;
1907 unsigned InVWidth = VTy->getNumElements();
1908 uint64_t InputDemandedElts = 0;
1909 unsigned Ratio;
1910
1911 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001912 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001913 // elements as are demanded of us.
1914 Ratio = 1;
1915 InputDemandedElts = DemandedElts;
1916 } else if (VWidth > InVWidth) {
1917 // Untested so far.
1918 break;
1919
1920 // If there are more elements in the result than there are in the source,
1921 // then an input element is live if any of the corresponding output
1922 // elements are live.
1923 Ratio = VWidth/InVWidth;
1924 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1925 if (DemandedElts & (1ULL << OutIdx))
1926 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1927 }
1928 } else {
1929 // Untested so far.
1930 break;
1931
1932 // If there are more elements in the source than there are in the result,
1933 // then an input element is live if the corresponding output element is
1934 // live.
1935 Ratio = InVWidth/VWidth;
1936 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1937 if (DemandedElts & (1ULL << InIdx/Ratio))
1938 InputDemandedElts |= 1ULL << InIdx;
1939 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001940
Chris Lattner69878332007-04-14 22:29:23 +00001941 // div/rem demand all inputs, because they don't want divide by zero.
1942 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1943 UndefElts2, Depth+1);
1944 if (TmpV) {
1945 I->setOperand(0, TmpV);
1946 MadeChange = true;
1947 }
1948
1949 UndefElts = UndefElts2;
1950 if (VWidth > InVWidth) {
1951 assert(0 && "Unimp");
1952 // If there are more elements in the result than there are in the source,
1953 // then an output element is undef if the corresponding input element is
1954 // undef.
1955 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1956 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1957 UndefElts |= 1ULL << OutIdx;
1958 } else if (VWidth < InVWidth) {
1959 assert(0 && "Unimp");
1960 // If there are more elements in the source than there are in the result,
1961 // then a result element is undef if all of the corresponding input
1962 // elements are undef.
1963 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1964 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1965 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1966 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1967 }
1968 break;
1969 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001970 case Instruction::And:
1971 case Instruction::Or:
1972 case Instruction::Xor:
1973 case Instruction::Add:
1974 case Instruction::Sub:
1975 case Instruction::Mul:
1976 // div/rem demand all inputs, because they don't want divide by zero.
1977 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1978 UndefElts, Depth+1);
1979 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1980 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1981 UndefElts2, Depth+1);
1982 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1983
1984 // Output elements are undefined if both are undefined. Consider things
1985 // like undef&0. The result is known zero, not undef.
1986 UndefElts &= UndefElts2;
1987 break;
1988
1989 case Instruction::Call: {
1990 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1991 if (!II) break;
1992 switch (II->getIntrinsicID()) {
1993 default: break;
1994
1995 // Binary vector operations that work column-wise. A dest element is a
1996 // function of the corresponding input elements from the two inputs.
1997 case Intrinsic::x86_sse_sub_ss:
1998 case Intrinsic::x86_sse_mul_ss:
1999 case Intrinsic::x86_sse_min_ss:
2000 case Intrinsic::x86_sse_max_ss:
2001 case Intrinsic::x86_sse2_sub_sd:
2002 case Intrinsic::x86_sse2_mul_sd:
2003 case Intrinsic::x86_sse2_min_sd:
2004 case Intrinsic::x86_sse2_max_sd:
2005 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2006 UndefElts, Depth+1);
2007 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2008 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2009 UndefElts2, Depth+1);
2010 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2011
2012 // If only the low elt is demanded and this is a scalarizable intrinsic,
2013 // scalarize it now.
2014 if (DemandedElts == 1) {
2015 switch (II->getIntrinsicID()) {
2016 default: break;
2017 case Intrinsic::x86_sse_sub_ss:
2018 case Intrinsic::x86_sse_mul_ss:
2019 case Intrinsic::x86_sse2_sub_sd:
2020 case Intrinsic::x86_sse2_mul_sd:
2021 // TODO: Lower MIN/MAX/ABS/etc
2022 Value *LHS = II->getOperand(1);
2023 Value *RHS = II->getOperand(2);
2024 // Extract the element as scalars.
2025 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2026 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2027
2028 switch (II->getIntrinsicID()) {
2029 default: assert(0 && "Case stmts out of sync!");
2030 case Intrinsic::x86_sse_sub_ss:
2031 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002032 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002033 II->getName()), *II);
2034 break;
2035 case Intrinsic::x86_sse_mul_ss:
2036 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002037 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002038 II->getName()), *II);
2039 break;
2040 }
2041
2042 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00002043 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2044 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00002045 InsertNewInstBefore(New, *II);
2046 AddSoonDeadInstToWorklist(*II, 0);
2047 return New;
2048 }
2049 }
2050
2051 // Output elements are undefined if both are undefined. Consider things
2052 // like undef&0. The result is known zero, not undef.
2053 UndefElts &= UndefElts2;
2054 break;
2055 }
2056 break;
2057 }
2058 }
2059 return MadeChange ? I : 0;
2060}
2061
Chris Lattner564a7272003-08-13 19:01:45 +00002062/// AssociativeOpt - Perform an optimization on an associative operator. This
2063/// function is designed to check a chain of associative operators for a
2064/// potential to apply a certain optimization. Since the optimization may be
2065/// applicable if the expression was reassociated, this checks the chain, then
2066/// reassociates the expression as necessary to expose the optimization
2067/// opportunity. This makes use of a special Functor, which must define
2068/// 'shouldApply' and 'apply' methods.
2069///
2070template<typename Functor>
2071Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2072 unsigned Opcode = Root.getOpcode();
2073 Value *LHS = Root.getOperand(0);
2074
2075 // Quick check, see if the immediate LHS matches...
2076 if (F.shouldApply(LHS))
2077 return F.apply(Root);
2078
2079 // Otherwise, if the LHS is not of the same opcode as the root, return.
2080 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002081 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002082 // Should we apply this transform to the RHS?
2083 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2084
2085 // If not to the RHS, check to see if we should apply to the LHS...
2086 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2087 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2088 ShouldApply = true;
2089 }
2090
2091 // If the functor wants to apply the optimization to the RHS of LHSI,
2092 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2093 if (ShouldApply) {
2094 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002095
Chris Lattner564a7272003-08-13 19:01:45 +00002096 // Now all of the instructions are in the current basic block, go ahead
2097 // and perform the reassociation.
2098 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2099
2100 // First move the selected RHS to the LHS of the root...
2101 Root.setOperand(0, LHSI->getOperand(1));
2102
2103 // Make what used to be the LHS of the root be the user of the root...
2104 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002105 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002106 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2107 return 0;
2108 }
Chris Lattner65725312004-04-16 18:08:07 +00002109 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002110 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002111 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2112 BasicBlock::iterator ARI = &Root; ++ARI;
2113 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2114 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002115
2116 // Now propagate the ExtraOperand down the chain of instructions until we
2117 // get to LHSI.
2118 while (TmpLHSI != LHSI) {
2119 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002120 // Move the instruction to immediately before the chain we are
2121 // constructing to avoid breaking dominance properties.
2122 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2123 BB->getInstList().insert(ARI, NextLHSI);
2124 ARI = NextLHSI;
2125
Chris Lattner564a7272003-08-13 19:01:45 +00002126 Value *NextOp = NextLHSI->getOperand(1);
2127 NextLHSI->setOperand(1, ExtraOperand);
2128 TmpLHSI = NextLHSI;
2129 ExtraOperand = NextOp;
2130 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002131
Chris Lattner564a7272003-08-13 19:01:45 +00002132 // Now that the instructions are reassociated, have the functor perform
2133 // the transformation...
2134 return F.apply(Root);
2135 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002136
Chris Lattner564a7272003-08-13 19:01:45 +00002137 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2138 }
2139 return 0;
2140}
2141
Dan Gohman844731a2008-05-13 00:00:25 +00002142namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002143
2144// AddRHS - Implements: X + X --> X << 1
2145struct AddRHS {
2146 Value *RHS;
2147 AddRHS(Value *rhs) : RHS(rhs) {}
2148 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2149 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002150 return BinaryOperator::CreateShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00002151 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002152 }
2153};
2154
2155// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2156// iff C1&C2 == 0
2157struct AddMaskingAnd {
2158 Constant *C2;
2159 AddMaskingAnd(Constant *c) : C2(c) {}
2160 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002161 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002162 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002163 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002164 }
2165 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002166 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002167 }
2168};
2169
Dan Gohman844731a2008-05-13 00:00:25 +00002170}
2171
Chris Lattner6e7ba452005-01-01 16:22:27 +00002172static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002173 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002174 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002175 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002176 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002177
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002178 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00002179 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002180 }
2181
Chris Lattner2eefe512004-04-09 19:05:30 +00002182 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002183 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2184 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002185
Chris Lattner2eefe512004-04-09 19:05:30 +00002186 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2187 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002188 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2189 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002190 }
2191
2192 Value *Op0 = SO, *Op1 = ConstOperand;
2193 if (!ConstIsRHS)
2194 std::swap(Op0, Op1);
2195 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002196 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002197 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002198 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002199 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002200 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002201 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002202 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002203 abort();
2204 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002205 return IC->InsertNewInstBefore(New, I);
2206}
2207
2208// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2209// constant as the other operand, try to fold the binary operator into the
2210// select arguments. This also works for Cast instructions, which obviously do
2211// not have a second operand.
2212static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2213 InstCombiner *IC) {
2214 // Don't modify shared select instructions
2215 if (!SI->hasOneUse()) return 0;
2216 Value *TV = SI->getOperand(1);
2217 Value *FV = SI->getOperand(2);
2218
2219 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002220 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002221 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002222
Chris Lattner6e7ba452005-01-01 16:22:27 +00002223 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2224 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2225
Gabor Greif051a9502008-04-06 20:25:17 +00002226 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2227 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002228 }
2229 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002230}
2231
Chris Lattner4e998b22004-09-29 05:07:12 +00002232
2233/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2234/// node as operand #0, see if we can fold the instruction into the PHI (which
2235/// is only possible if all operands to the PHI are constants).
2236Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2237 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002238 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002239 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002240
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002241 // Check to see if all of the operands of the PHI are constants. If there is
2242 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002243 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002244 BasicBlock *NonConstBB = 0;
2245 for (unsigned i = 0; i != NumPHIValues; ++i)
2246 if (!isa<Constant>(PN->getIncomingValue(i))) {
2247 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002248 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002249 NonConstBB = PN->getIncomingBlock(i);
2250
2251 // If the incoming non-constant value is in I's block, we have an infinite
2252 // loop.
2253 if (NonConstBB == I.getParent())
2254 return 0;
2255 }
2256
2257 // If there is exactly one non-constant value, we can insert a copy of the
2258 // operation in that block. However, if this is a critical edge, we would be
2259 // inserting the computation one some other paths (e.g. inside a loop). Only
2260 // do this if the pred block is unconditionally branching into the phi block.
2261 if (NonConstBB) {
2262 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2263 if (!BI || !BI->isUnconditional()) return 0;
2264 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002265
2266 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002267 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002268 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002269 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002270 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002271
2272 // Next, add all of the operands to the PHI.
2273 if (I.getNumOperands() == 2) {
2274 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002275 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002276 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002277 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002278 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2279 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2280 else
2281 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002282 } else {
2283 assert(PN->getIncomingBlock(i) == NonConstBB);
2284 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002285 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002286 PN->getIncomingValue(i), C, "phitmp",
2287 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002288 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002289 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002290 CI->getPredicate(),
2291 PN->getIncomingValue(i), C, "phitmp",
2292 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002293 else
2294 assert(0 && "Unknown binop!");
2295
Chris Lattnerdbab3862007-03-02 21:28:56 +00002296 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002297 }
2298 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002299 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002300 } else {
2301 CastInst *CI = cast<CastInst>(&I);
2302 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002303 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002304 Value *InV;
2305 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002306 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002307 } else {
2308 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002309 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002310 I.getType(), "phitmp",
2311 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002312 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002313 }
2314 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002315 }
2316 }
2317 return ReplaceInstUsesWith(I, NewPN);
2318}
2319
Chris Lattner2454a2e2008-01-29 06:52:45 +00002320
2321/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2322/// value is never equal to -0.0.
2323///
2324/// Note that this function will need to be revisited when we support nondefault
2325/// rounding modes!
2326///
2327static bool CannotBeNegativeZero(const Value *V) {
2328 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2329 return !CFP->getValueAPF().isNegZero();
2330
Chris Lattner2454a2e2008-01-29 06:52:45 +00002331 if (const Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002332 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Chris Lattner2454a2e2008-01-29 06:52:45 +00002333 if (I->getOpcode() == Instruction::Add &&
2334 isa<ConstantFP>(I->getOperand(1)) &&
2335 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2336 return true;
2337
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002338 // sitofp and uitofp turn into +0.0 for zero.
2339 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2340 return true;
2341
Chris Lattner2454a2e2008-01-29 06:52:45 +00002342 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2343 if (II->getIntrinsicID() == Intrinsic::sqrt)
2344 return CannotBeNegativeZero(II->getOperand(1));
2345
2346 if (const CallInst *CI = dyn_cast<CallInst>(I))
2347 if (const Function *F = CI->getCalledFunction()) {
2348 if (F->isDeclaration()) {
2349 switch (F->getNameLen()) {
2350 case 3: // abs(x) != -0.0
2351 if (!strcmp(F->getNameStart(), "abs")) return true;
2352 break;
2353 case 4: // abs[lf](x) != -0.0
2354 if (!strcmp(F->getNameStart(), "absf")) return true;
2355 if (!strcmp(F->getNameStart(), "absl")) return true;
2356 break;
2357 }
2358 }
2359 }
2360 }
2361
2362 return false;
2363}
2364
2365
Chris Lattner7e708292002-06-25 16:13:24 +00002366Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002367 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002368 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002369
Chris Lattner66331a42004-04-10 22:01:55 +00002370 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002371 // X + undef -> undef
2372 if (isa<UndefValue>(RHS))
2373 return ReplaceInstUsesWith(I, RHS);
2374
Chris Lattner66331a42004-04-10 22:01:55 +00002375 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002376 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002377 if (RHSC->isNullValue())
2378 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002379 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002380 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2381 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002382 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002383 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002384
Chris Lattner66331a42004-04-10 22:01:55 +00002385 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002386 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002387 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002388 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002389 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002390 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002391
2392 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2393 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002394 if (!isa<VectorType>(I.getType())) {
2395 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2396 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2397 KnownZero, KnownOne))
2398 return &I;
2399 }
Chris Lattner66331a42004-04-10 22:01:55 +00002400 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002401
2402 if (isa<PHINode>(LHS))
2403 if (Instruction *NV = FoldOpIntoPhi(I))
2404 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002405
Chris Lattner4f637d42006-01-06 17:59:59 +00002406 ConstantInt *XorRHS = 0;
2407 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002408 if (isa<ConstantInt>(RHSC) &&
2409 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002410 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002411 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002412
Zhou Sheng4351c642007-04-02 08:20:41 +00002413 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002414 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2415 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002416 do {
2417 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002418 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2419 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002420 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2421 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002422 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002423 if (!MaskedValueIsZero(XorLHS,
2424 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002425 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002426 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002427 }
2428 }
2429 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002430 C0080Val = APIntOps::lshr(C0080Val, Size);
2431 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2432 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002433
Reid Spencer35c38852007-03-28 01:36:16 +00002434 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002435 // with funny bit widths then this switch statement should be removed. It
2436 // is just here to get the size of the "middle" type back up to something
2437 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002438 const Type *MiddleType = 0;
2439 switch (Size) {
2440 default: break;
2441 case 32: MiddleType = Type::Int32Ty; break;
2442 case 16: MiddleType = Type::Int16Ty; break;
2443 case 8: MiddleType = Type::Int8Ty; break;
2444 }
2445 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002446 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002447 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002448 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002449 }
2450 }
Chris Lattner66331a42004-04-10 22:01:55 +00002451 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002452
Chris Lattner564a7272003-08-13 19:01:45 +00002453 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002454 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002455 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002456
2457 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2458 if (RHSI->getOpcode() == Instruction::Sub)
2459 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2460 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2461 }
2462 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2463 if (LHSI->getOpcode() == Instruction::Sub)
2464 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2465 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2466 }
Robert Bocchino71698282004-07-27 21:02:21 +00002467 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002468
Chris Lattner5c4afb92002-05-08 22:46:53 +00002469 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002470 // -A + -B --> -(A + B)
2471 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002472 if (LHS->getType()->isIntOrIntVector()) {
2473 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002474 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002475 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002476 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002477 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002478 }
2479
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002480 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002481 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002482
2483 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002484 if (!isa<Constant>(RHS))
2485 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002486 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002487
Misha Brukmanfd939082005-04-21 23:48:37 +00002488
Chris Lattner50af16a2004-11-13 19:50:12 +00002489 ConstantInt *C2;
2490 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2491 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002492 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002493
2494 // X*C1 + X*C2 --> X * (C1+C2)
2495 ConstantInt *C1;
2496 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002497 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002498 }
2499
2500 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002501 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002502 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002503
Chris Lattnere617c9e2007-01-05 02:17:46 +00002504 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002505 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2506 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002507
Chris Lattnerad3448c2003-02-18 19:57:07 +00002508
Chris Lattner564a7272003-08-13 19:01:45 +00002509 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002510 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002511 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2512 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002513
2514 // A+B --> A|B iff A and B have no bits set in common.
2515 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2516 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2517 APInt LHSKnownOne(IT->getBitWidth(), 0);
2518 APInt LHSKnownZero(IT->getBitWidth(), 0);
2519 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2520 if (LHSKnownZero != 0) {
2521 APInt RHSKnownOne(IT->getBitWidth(), 0);
2522 APInt RHSKnownZero(IT->getBitWidth(), 0);
2523 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2524
2525 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002526 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002527 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002528 }
2529 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002530
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002531 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002532 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002533 Value *W, *X, *Y, *Z;
2534 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2535 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2536 if (W != Y) {
2537 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002538 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002539 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002540 std::swap(W, X);
2541 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002542 std::swap(Y, Z);
2543 std::swap(W, X);
2544 }
2545 }
2546
2547 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002548 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002549 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002550 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002551 }
2552 }
2553 }
2554
Chris Lattner6b032052003-10-02 15:11:26 +00002555 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002556 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002557 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002558 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002559
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002560 // (X & FF00) + xx00 -> (X+xx00) & FF00
2561 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002562 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002563 if (Anded == CRHS) {
2564 // See if all bits from the first bit set in the Add RHS up are included
2565 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002566 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002567
2568 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002569 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002570
2571 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002572 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002573
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002574 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2575 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002576 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002577 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002578 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002579 }
2580 }
2581 }
2582
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002583 // Try to fold constant add into select arguments.
2584 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002585 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002586 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002587 }
2588
Reid Spencer1628cec2006-10-26 06:15:43 +00002589 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002590 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002591 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002592 CastInst *CI = dyn_cast<CastInst>(LHS);
2593 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002594 if (!CI) {
2595 CI = dyn_cast<CastInst>(RHS);
2596 Other = LHS;
2597 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002598 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002599 (CI->getType()->getPrimitiveSizeInBits() ==
2600 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002601 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002602 unsigned AS =
2603 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002604 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2605 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002606 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002607 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002608 }
2609 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002610
Chris Lattner42790482007-12-20 01:56:58 +00002611 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002612 {
2613 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2614 Value *Other = RHS;
2615 if (!SI) {
2616 SI = dyn_cast<SelectInst>(RHS);
2617 Other = LHS;
2618 }
Chris Lattner42790482007-12-20 01:56:58 +00002619 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002620 Value *TV = SI->getTrueValue();
2621 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002622 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002623
2624 // Can we fold the add into the argument of the select?
2625 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002626 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2627 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002628 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002629 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2630 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002631 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002632 }
2633 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002634
2635 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2636 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2637 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2638 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002639
Chris Lattner7e708292002-06-25 16:13:24 +00002640 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002641}
2642
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002643// isSignBit - Return true if the value represented by the constant only has the
2644// highest order bit set.
2645static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002646 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002647 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002648}
2649
Chris Lattner7e708292002-06-25 16:13:24 +00002650Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002651 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002652
Chris Lattner233f7dc2002-08-12 21:17:25 +00002653 if (Op0 == Op1) // sub X, X -> 0
2654 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002655
Chris Lattner233f7dc2002-08-12 21:17:25 +00002656 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002657 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002658 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002659
Chris Lattnere87597f2004-10-16 18:11:37 +00002660 if (isa<UndefValue>(Op0))
2661 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2662 if (isa<UndefValue>(Op1))
2663 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2664
Chris Lattnerd65460f2003-11-05 01:06:05 +00002665 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2666 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002667 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002668 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002669
Chris Lattnerd65460f2003-11-05 01:06:05 +00002670 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002671 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002672 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002673 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002674
Chris Lattner76b7a062007-01-15 07:02:54 +00002675 // -(X >>u 31) -> (X >>s 31)
2676 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002677 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002678 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002679 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002680 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002681 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002682 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002683 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002684 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002685 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002686 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002687 }
2688 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002689 }
2690 else if (SI->getOpcode() == Instruction::AShr) {
2691 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2692 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002693 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002694 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002695 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002696 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002697 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002698 }
2699 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002700 }
2701 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002702 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002703
2704 // Try to fold constant sub into select arguments.
2705 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002706 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002707 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002708
2709 if (isa<PHINode>(Op0))
2710 if (Instruction *NV = FoldOpIntoPhi(I))
2711 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002712 }
2713
Chris Lattner43d84d62005-04-07 16:15:25 +00002714 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2715 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002716 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002717 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002718 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002719 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002720 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002721 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2722 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2723 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002724 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002725 Op1I->getOperand(0));
2726 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002727 }
2728
Chris Lattnerfd059242003-10-15 16:48:29 +00002729 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002730 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2731 // is not used by anyone else...
2732 //
Chris Lattner0517e722004-02-02 20:09:56 +00002733 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002734 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002735 // Swap the two operands of the subexpr...
2736 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2737 Op1I->setOperand(0, IIOp1);
2738 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002739
Chris Lattnera2881962003-02-18 19:28:33 +00002740 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002741 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002742 }
2743
2744 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2745 //
2746 if (Op1I->getOpcode() == Instruction::And &&
2747 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2748 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2749
Chris Lattnerf523d062004-06-09 05:08:07 +00002750 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002751 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2752 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002753 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002754
Reid Spencerac5209e2006-10-16 23:08:08 +00002755 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002756 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002757 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002758 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002759 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002760 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002761 ConstantExpr::getNeg(DivRHS));
2762
Chris Lattnerad3448c2003-02-18 19:57:07 +00002763 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002764 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002765 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002766 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002767 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002768 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002769
2770 // X - ((X / Y) * Y) --> X % Y
2771 if (Op1I->getOpcode() == Instruction::Mul)
2772 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2773 if (Op0 == I->getOperand(0) &&
2774 Op1I->getOperand(1) == I->getOperand(1)) {
2775 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002776 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002777 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002778 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002779 }
Chris Lattner40371712002-05-09 01:29:19 +00002780 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002781 }
Chris Lattnera2881962003-02-18 19:28:33 +00002782
Chris Lattner9919e3d2006-12-02 00:13:08 +00002783 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002784 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002785 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002786 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2787 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2788 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2789 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002790 } else if (Op0I->getOpcode() == Instruction::Sub) {
2791 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002792 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002793 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002794 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002795
Chris Lattner50af16a2004-11-13 19:50:12 +00002796 ConstantInt *C1;
2797 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002798 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002799 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002800
Chris Lattner50af16a2004-11-13 19:50:12 +00002801 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2802 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002803 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002804 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002805 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002806}
2807
Chris Lattnera0141b92007-07-15 20:42:37 +00002808/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2809/// comparison only checks the sign bit. If it only checks the sign bit, set
2810/// TrueIfSigned if the result of the comparison is true when the input value is
2811/// signed.
2812static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2813 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002814 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002815 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2816 TrueIfSigned = true;
2817 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002818 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2819 TrueIfSigned = true;
2820 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002821 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2822 TrueIfSigned = false;
2823 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002824 case ICmpInst::ICMP_UGT:
2825 // True if LHS u> RHS and RHS == high-bit-mask - 1
2826 TrueIfSigned = true;
2827 return RHS->getValue() ==
2828 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2829 case ICmpInst::ICMP_UGE:
2830 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2831 TrueIfSigned = true;
2832 return RHS->getValue() ==
2833 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002834 default:
2835 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002836 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002837}
2838
Chris Lattner7e708292002-06-25 16:13:24 +00002839Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002840 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002841 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002842
Chris Lattnere87597f2004-10-16 18:11:37 +00002843 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2844 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2845
Chris Lattner233f7dc2002-08-12 21:17:25 +00002846 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002847 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2848 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002849
2850 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002851 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002852 if (SI->getOpcode() == Instruction::Shl)
2853 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002854 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002855 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002856
Zhou Sheng843f07672007-04-19 05:39:12 +00002857 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002858 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2859 if (CI->equalsInt(1)) // X * 1 == X
2860 return ReplaceInstUsesWith(I, Op0);
2861 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002862 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002863
Zhou Sheng97b52c22007-03-29 01:57:21 +00002864 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002865 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002866 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002867 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002868 }
Robert Bocchino71698282004-07-27 21:02:21 +00002869 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002870 if (Op1F->isNullValue())
2871 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002872
Chris Lattnera2881962003-02-18 19:28:33 +00002873 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2874 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002875 // We need a better interface for long double here.
2876 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2877 if (Op1F->isExactlyValue(1.0))
2878 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002879 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002880
2881 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2882 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002883 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002884 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002885 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002886 Op1, "tmp");
2887 InsertNewInstBefore(Add, I);
2888 Value *C1C2 = ConstantExpr::getMul(Op1,
2889 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002890 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002891
2892 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002893
2894 // Try to fold constant mul into select arguments.
2895 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002896 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002897 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002898
2899 if (isa<PHINode>(Op0))
2900 if (Instruction *NV = FoldOpIntoPhi(I))
2901 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002902 }
2903
Chris Lattnera4f445b2003-03-10 23:23:04 +00002904 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2905 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002906 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002907
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002908 // If one of the operands of the multiply is a cast from a boolean value, then
2909 // we know the bool is either zero or one, so this is a 'masking' multiply.
2910 // See if we can simplify things based on how the boolean was originally
2911 // formed.
2912 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002913 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002914 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002915 BoolCast = CI;
2916 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002917 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002918 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002919 BoolCast = CI;
2920 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002921 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002922 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2923 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002924 bool TIS = false;
2925
Reid Spencere4d87aa2006-12-23 06:05:41 +00002926 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002927 // multiply into a shift/and combination.
2928 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002929 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2930 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002931 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002932 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002933 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002934 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002935 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002936 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002937 BoolCast->getOperand(0)->getName()+
2938 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002939
2940 // If the multiply type is not the same as the source type, sign extend
2941 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002942 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002943 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2944 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002945 Instruction::CastOps opcode =
2946 (SrcBits == DstBits ? Instruction::BitCast :
2947 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2948 V = InsertCastBefore(opcode, V, I.getType(), I);
2949 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002950
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002951 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002952 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002953 }
2954 }
2955 }
2956
Chris Lattner7e708292002-06-25 16:13:24 +00002957 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002958}
2959
Reid Spencer1628cec2006-10-26 06:15:43 +00002960/// This function implements the transforms on div instructions that work
2961/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2962/// used by the visitors to those instructions.
2963/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002964Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002965 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002966
Chris Lattner50b2ca42008-02-19 06:12:18 +00002967 // undef / X -> 0 for integer.
2968 // undef / X -> undef for FP (the undef could be a snan).
2969 if (isa<UndefValue>(Op0)) {
2970 if (Op0->getType()->isFPOrFPVector())
2971 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002972 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002973 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002974
2975 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002976 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002977 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002978
Chris Lattner25feae52008-01-28 00:58:18 +00002979 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2980 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002981 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002982 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2983 // the same basic block, then we replace the select with Y, and the
2984 // condition of the select with false (if the cond value is in the same BB).
2985 // If the select has uses other than the div, this allows them to be
2986 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2987 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002988 if (ST->isNullValue()) {
2989 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2990 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002991 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002992 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2993 I.setOperand(1, SI->getOperand(2));
2994 else
2995 UpdateValueUsesWith(SI, SI->getOperand(2));
2996 return &I;
2997 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002998
Chris Lattner25feae52008-01-28 00:58:18 +00002999 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3000 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003001 if (ST->isNullValue()) {
3002 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3003 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003004 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00003005 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3006 I.setOperand(1, SI->getOperand(1));
3007 else
3008 UpdateValueUsesWith(SI, SI->getOperand(1));
3009 return &I;
3010 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003011 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003012
Reid Spencer1628cec2006-10-26 06:15:43 +00003013 return 0;
3014}
Misha Brukmanfd939082005-04-21 23:48:37 +00003015
Reid Spencer1628cec2006-10-26 06:15:43 +00003016/// This function implements the transforms common to both integer division
3017/// instructions (udiv and sdiv). It is called by the visitors to those integer
3018/// division instructions.
3019/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003020Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003021 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3022
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003023 // (sdiv X, X) --> 1 (udiv X, X) --> 1
3024 if (Op0 == Op1)
3025 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
3026
Reid Spencer1628cec2006-10-26 06:15:43 +00003027 if (Instruction *Common = commonDivTransforms(I))
3028 return Common;
3029
3030 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3031 // div X, 1 == X
3032 if (RHS->equalsInt(1))
3033 return ReplaceInstUsesWith(I, Op0);
3034
3035 // (X / C1) / C2 -> X / (C1*C2)
3036 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3037 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3038 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003039 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3040 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3041 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003042 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003043 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003044 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003045
Reid Spencerbca0e382007-03-23 20:05:17 +00003046 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003047 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3048 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3049 return R;
3050 if (isa<PHINode>(Op0))
3051 if (Instruction *NV = FoldOpIntoPhi(I))
3052 return NV;
3053 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003054 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003055
Chris Lattnera2881962003-02-18 19:28:33 +00003056 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003057 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003058 if (LHS->equalsInt(0))
3059 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3060
Reid Spencer1628cec2006-10-26 06:15:43 +00003061 return 0;
3062}
3063
3064Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3065 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3066
3067 // Handle the integer div common cases
3068 if (Instruction *Common = commonIDivTransforms(I))
3069 return Common;
3070
3071 // X udiv C^2 -> X >> C
3072 // Check to see if this is an unsigned division with an exact power of 2,
3073 // if so, convert to a right shift.
3074 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00003075 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003076 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003077 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003078 }
3079
3080 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003081 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003082 if (RHSI->getOpcode() == Instruction::Shl &&
3083 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003084 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003085 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003086 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003087 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003088 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003089 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003090 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003091 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003092 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003093 }
3094 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003095 }
3096
Reid Spencer1628cec2006-10-26 06:15:43 +00003097 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3098 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003099 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003100 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003101 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003102 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003103 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003104 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003105 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003106 // Construct the "on true" case of the select
3107 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003108 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003109 Op0, TC, SI->getName()+".t");
3110 TSI = InsertNewInstBefore(TSI, I);
3111
3112 // Construct the "on false" case of the select
3113 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003114 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003115 Op0, FC, SI->getName()+".f");
3116 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003117
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003118 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003119 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003120 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003121 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003122 return 0;
3123}
3124
Reid Spencer1628cec2006-10-26 06:15:43 +00003125Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3126 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3127
3128 // Handle the integer div common cases
3129 if (Instruction *Common = commonIDivTransforms(I))
3130 return Common;
3131
3132 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3133 // sdiv X, -1 == -X
3134 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003135 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003136
3137 // -X/C -> X/-C
3138 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003139 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003140 }
3141
3142 // If the sign bits of both operands are zero (i.e. we can prove they are
3143 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003144 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003145 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003146 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003147 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003148 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003149 }
3150 }
3151
3152 return 0;
3153}
3154
3155Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3156 return commonDivTransforms(I);
3157}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003158
Reid Spencer0a783f72006-11-02 01:53:59 +00003159/// This function implements the transforms on rem instructions that work
3160/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3161/// is used by the visitors to those instructions.
3162/// @brief Transforms common to all three rem instructions
3163Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003164 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003165
Chris Lattner50b2ca42008-02-19 06:12:18 +00003166 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003167 if (Constant *LHS = dyn_cast<Constant>(Op0))
3168 if (LHS->isNullValue())
3169 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3170
Chris Lattner50b2ca42008-02-19 06:12:18 +00003171 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3172 if (I.getType()->isFPOrFPVector())
3173 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003174 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003175 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003176 if (isa<UndefValue>(Op1))
3177 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003178
3179 // Handle cases involving: rem X, (select Cond, Y, Z)
3180 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3181 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3182 // the same basic block, then we replace the select with Y, and the
3183 // condition of the select with false (if the cond value is in the same
3184 // BB). If the select has uses other than the div, this allows them to be
3185 // simplified also.
3186 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3187 if (ST->isNullValue()) {
3188 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3189 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003190 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003191 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3192 I.setOperand(1, SI->getOperand(2));
3193 else
3194 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003195 return &I;
3196 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003197 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3198 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
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::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003203 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3204 I.setOperand(1, SI->getOperand(1));
3205 else
3206 UpdateValueUsesWith(SI, SI->getOperand(1));
3207 return &I;
3208 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003209 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003210
Reid Spencer0a783f72006-11-02 01:53:59 +00003211 return 0;
3212}
3213
3214/// This function implements the transforms common to both integer remainder
3215/// instructions (urem and srem). It is called by the visitors to those integer
3216/// remainder instructions.
3217/// @brief Common integer remainder transforms
3218Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3219 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3220
3221 if (Instruction *common = commonRemTransforms(I))
3222 return common;
3223
Chris Lattner857e8cd2004-12-12 21:48:58 +00003224 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003225 // X % 0 == undef, we don't need to preserve faults!
3226 if (RHS->equalsInt(0))
3227 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3228
Chris Lattnera2881962003-02-18 19:28:33 +00003229 if (RHS->equalsInt(1)) // X % 1 == 0
3230 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3231
Chris Lattner97943922006-02-28 05:49:21 +00003232 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3233 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3234 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3235 return R;
3236 } else if (isa<PHINode>(Op0I)) {
3237 if (Instruction *NV = FoldOpIntoPhi(I))
3238 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003239 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003240
3241 // See if we can fold away this rem instruction.
3242 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3243 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3244 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3245 KnownZero, KnownOne))
3246 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003247 }
Chris Lattnera2881962003-02-18 19:28:33 +00003248 }
3249
Reid Spencer0a783f72006-11-02 01:53:59 +00003250 return 0;
3251}
3252
3253Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3254 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3255
3256 if (Instruction *common = commonIRemTransforms(I))
3257 return common;
3258
3259 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3260 // X urem C^2 -> X and C
3261 // Check to see if this is an unsigned remainder with an exact power of 2,
3262 // if so, convert to a bitwise and.
3263 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003264 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003265 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003266 }
3267
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003268 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003269 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3270 if (RHSI->getOpcode() == Instruction::Shl &&
3271 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003272 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003273 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003274 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003275 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003276 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003277 }
3278 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003279 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003280
Reid Spencer0a783f72006-11-02 01:53:59 +00003281 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3282 // where C1&C2 are powers of two.
3283 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3284 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3285 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3286 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003287 if ((STO->getValue().isPowerOf2()) &&
3288 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003289 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003290 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003291 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003292 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003293 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003294 }
3295 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003296 }
3297
Chris Lattner3f5b8772002-05-06 16:14:14 +00003298 return 0;
3299}
3300
Reid Spencer0a783f72006-11-02 01:53:59 +00003301Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3302 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3303
Dan Gohmancff55092007-11-05 23:16:33 +00003304 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003305 if (Instruction *common = commonIRemTransforms(I))
3306 return common;
3307
3308 if (Value *RHSNeg = dyn_castNegVal(Op1))
3309 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003310 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003311 // X % -Y -> X % Y
3312 AddUsesToWorkList(I);
3313 I.setOperand(1, RHSNeg);
3314 return &I;
3315 }
3316
Dan Gohmancff55092007-11-05 23:16:33 +00003317 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003318 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003319 if (I.getType()->isInteger()) {
3320 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3321 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3322 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003323 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003324 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003325 }
3326
3327 return 0;
3328}
3329
3330Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003331 return commonRemTransforms(I);
3332}
3333
Chris Lattner8b170942002-08-09 23:47:40 +00003334// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003335static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003336 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003337 if (!isSigned)
3338 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3339 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003340}
3341
3342// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003343static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003344 if (!isSigned)
3345 return C->getValue() == 1; // unsigned
3346
3347 // Calculate 1111111111000000000000
3348 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3349 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003350}
3351
Chris Lattner457dd822004-06-09 07:59:58 +00003352// isOneBitSet - Return true if there is exactly one bit set in the specified
3353// constant.
3354static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003355 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003356}
3357
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003358// isHighOnes - Return true if the constant is of the form 1+0+.
3359// This is the same as lowones(~X).
3360static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003361 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003362}
3363
Reid Spencere4d87aa2006-12-23 06:05:41 +00003364/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003365/// are carefully arranged to allow folding of expressions such as:
3366///
3367/// (A < B) | (A > B) --> (A != B)
3368///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003369/// Note that this is only valid if the first and second predicates have the
3370/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003371///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003372/// Three bits are used to represent the condition, as follows:
3373/// 0 A > B
3374/// 1 A == B
3375/// 2 A < B
3376///
3377/// <=> Value Definition
3378/// 000 0 Always false
3379/// 001 1 A > B
3380/// 010 2 A == B
3381/// 011 3 A >= B
3382/// 100 4 A < B
3383/// 101 5 A != B
3384/// 110 6 A <= B
3385/// 111 7 Always true
3386///
3387static unsigned getICmpCode(const ICmpInst *ICI) {
3388 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003389 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003390 case ICmpInst::ICMP_UGT: return 1; // 001
3391 case ICmpInst::ICMP_SGT: return 1; // 001
3392 case ICmpInst::ICMP_EQ: return 2; // 010
3393 case ICmpInst::ICMP_UGE: return 3; // 011
3394 case ICmpInst::ICMP_SGE: return 3; // 011
3395 case ICmpInst::ICMP_ULT: return 4; // 100
3396 case ICmpInst::ICMP_SLT: return 4; // 100
3397 case ICmpInst::ICMP_NE: return 5; // 101
3398 case ICmpInst::ICMP_ULE: return 6; // 110
3399 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003400 // True -> 7
3401 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003402 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003403 return 0;
3404 }
3405}
3406
Reid Spencere4d87aa2006-12-23 06:05:41 +00003407/// getICmpValue - This is the complement of getICmpCode, which turns an
3408/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003409/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003410/// of predicate to use in new icmp instructions.
3411static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3412 switch (code) {
3413 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003414 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003415 case 1:
3416 if (sign)
3417 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3418 else
3419 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3420 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3421 case 3:
3422 if (sign)
3423 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3424 else
3425 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3426 case 4:
3427 if (sign)
3428 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3429 else
3430 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3431 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3432 case 6:
3433 if (sign)
3434 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3435 else
3436 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003437 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003438 }
3439}
3440
Reid Spencere4d87aa2006-12-23 06:05:41 +00003441static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3442 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3443 (ICmpInst::isSignedPredicate(p1) &&
3444 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3445 (ICmpInst::isSignedPredicate(p2) &&
3446 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3447}
3448
3449namespace {
3450// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3451struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003452 InstCombiner &IC;
3453 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003454 ICmpInst::Predicate pred;
3455 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3456 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3457 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003458 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003459 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3460 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003461 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3462 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003463 return false;
3464 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003465 Instruction *apply(Instruction &Log) const {
3466 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3467 if (ICI->getOperand(0) != LHS) {
3468 assert(ICI->getOperand(1) == LHS);
3469 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003470 }
3471
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003472 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003473 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003474 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003475 unsigned Code;
3476 switch (Log.getOpcode()) {
3477 case Instruction::And: Code = LHSCode & RHSCode; break;
3478 case Instruction::Or: Code = LHSCode | RHSCode; break;
3479 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003480 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003481 }
3482
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003483 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3484 ICmpInst::isSignedPredicate(ICI->getPredicate());
3485
3486 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003487 if (Instruction *I = dyn_cast<Instruction>(RV))
3488 return I;
3489 // Otherwise, it's a constant boolean value...
3490 return IC.ReplaceInstUsesWith(Log, RV);
3491 }
3492};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003493} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003494
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003495// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3496// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003497// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003498Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003499 ConstantInt *OpRHS,
3500 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003501 BinaryOperator &TheAnd) {
3502 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003503 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003504 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003505 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003506
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003507 switch (Op->getOpcode()) {
3508 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003509 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003510 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003511 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003512 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003513 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003514 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003515 }
3516 break;
3517 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003518 if (Together == AndRHS) // (X | C) & C --> C
3519 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003520
Chris Lattner6e7ba452005-01-01 16:22:27 +00003521 if (Op->hasOneUse() && Together != OpRHS) {
3522 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003523 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003524 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003525 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003526 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003527 }
3528 break;
3529 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003530 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003531 // Adding a one to a single bit bit-field should be turned into an XOR
3532 // of the bit. First thing to check is to see if this AND is with a
3533 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003534 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003535
3536 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003537 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003538 // Ok, at this point, we know that we are masking the result of the
3539 // ADD down to exactly one bit. If the constant we are adding has
3540 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003541 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003542
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003543 // Check to see if any bits below the one bit set in AndRHSV are set.
3544 if ((AddRHS & (AndRHSV-1)) == 0) {
3545 // If not, the only thing that can effect the output of the AND is
3546 // the bit specified by AndRHSV. If that bit is set, the effect of
3547 // the XOR is to toggle the bit. If it is clear, then the ADD has
3548 // no effect.
3549 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3550 TheAnd.setOperand(0, X);
3551 return &TheAnd;
3552 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003553 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003554 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003555 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003556 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003557 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003558 }
3559 }
3560 }
3561 }
3562 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003563
3564 case Instruction::Shl: {
3565 // We know that the AND will not produce any of the bits shifted in, so if
3566 // the anded constant includes them, clear them now!
3567 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003568 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003569 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003570 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3571 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003572
Zhou Sheng290bec52007-03-29 08:15:12 +00003573 if (CI->getValue() == ShlMask) {
3574 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003575 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3576 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003577 TheAnd.setOperand(1, CI);
3578 return &TheAnd;
3579 }
3580 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003581 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003582 case Instruction::LShr:
3583 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003584 // We know that the AND will not produce any of the bits shifted in, so if
3585 // the anded constant includes them, clear them now! This only applies to
3586 // unsigned shifts, because a signed shr may bring in set bits!
3587 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003588 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003589 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003590 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3591 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003592
Zhou Sheng290bec52007-03-29 08:15:12 +00003593 if (CI->getValue() == ShrMask) {
3594 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003595 return ReplaceInstUsesWith(TheAnd, Op);
3596 } else if (CI != AndRHS) {
3597 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3598 return &TheAnd;
3599 }
3600 break;
3601 }
3602 case Instruction::AShr:
3603 // Signed shr.
3604 // See if this is shifting in some sign extension, then masking it out
3605 // with an and.
3606 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003607 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003608 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003609 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3610 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003611 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003612 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003613 // Make the argument unsigned.
3614 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003615 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003616 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003617 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003618 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003619 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003620 }
3621 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003622 }
3623 return 0;
3624}
3625
Chris Lattner8b170942002-08-09 23:47:40 +00003626
Chris Lattnera96879a2004-09-29 17:40:11 +00003627/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3628/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003629/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3630/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003631/// insert new instructions.
3632Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003633 bool isSigned, bool Inside,
3634 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003635 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003636 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003637 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003638
Chris Lattnera96879a2004-09-29 17:40:11 +00003639 if (Inside) {
3640 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003641 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003642
Reid Spencere4d87aa2006-12-23 06:05:41 +00003643 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003644 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003645 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003646 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3647 return new ICmpInst(pred, V, Hi);
3648 }
3649
3650 // Emit V-Lo <u Hi-Lo
3651 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003652 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003653 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003654 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3655 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003656 }
3657
3658 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003659 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003660
Reid Spencere4e40032007-03-21 23:19:50 +00003661 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003662 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003663 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003664 ICmpInst::Predicate pred = (isSigned ?
3665 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3666 return new ICmpInst(pred, V, Hi);
3667 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003668
Reid Spencere4e40032007-03-21 23:19:50 +00003669 // Emit V-Lo >u Hi-1-Lo
3670 // Note that Hi has already had one subtracted from it, above.
3671 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003672 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003673 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003674 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3675 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003676}
3677
Chris Lattner7203e152005-09-18 07:22:02 +00003678// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3679// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3680// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3681// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003682static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003683 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003684 uint32_t BitWidth = Val->getType()->getBitWidth();
3685 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003686
3687 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003688 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003689 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003690 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003691 return true;
3692}
3693
Chris Lattner7203e152005-09-18 07:22:02 +00003694/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3695/// where isSub determines whether the operator is a sub. If we can fold one of
3696/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003697///
3698/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3699/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3700/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3701///
3702/// return (A +/- B).
3703///
3704Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003705 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003706 Instruction &I) {
3707 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3708 if (!LHSI || LHSI->getNumOperands() != 2 ||
3709 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3710
3711 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3712
3713 switch (LHSI->getOpcode()) {
3714 default: return 0;
3715 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003716 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003717 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003718 if ((Mask->getValue().countLeadingZeros() +
3719 Mask->getValue().countPopulation()) ==
3720 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003721 break;
3722
3723 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3724 // part, we don't need any explicit masks to take them out of A. If that
3725 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003726 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003727 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003728 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003729 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003730 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003731 break;
3732 }
3733 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003734 return 0;
3735 case Instruction::Or:
3736 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003737 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003738 if ((Mask->getValue().countLeadingZeros() +
3739 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003740 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003741 break;
3742 return 0;
3743 }
3744
3745 Instruction *New;
3746 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003747 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003748 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003749 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003750 return InsertNewInstBefore(New, I);
3751}
3752
Chris Lattner7e708292002-06-25 16:13:24 +00003753Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003754 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003755 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003756
Chris Lattnere87597f2004-10-16 18:11:37 +00003757 if (isa<UndefValue>(Op1)) // X & undef -> 0
3758 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3759
Chris Lattner6e7ba452005-01-01 16:22:27 +00003760 // and X, X = X
3761 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003762 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003763
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003764 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003765 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003766 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003767 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3768 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3769 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003770 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003771 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003772 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003773 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003774 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003775 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003776 } else if (isa<ConstantAggregateZero>(Op1)) {
3777 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003778 }
3779 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003780
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003781 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003782 const APInt& AndRHSMask = AndRHS->getValue();
3783 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003784
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003785 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003786 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003787 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003788 Value *Op0LHS = Op0I->getOperand(0);
3789 Value *Op0RHS = Op0I->getOperand(1);
3790 switch (Op0I->getOpcode()) {
3791 case Instruction::Xor:
3792 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003793 // If the mask is only needed on one incoming arm, push it up.
3794 if (Op0I->hasOneUse()) {
3795 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3796 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003797 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003798 Op0RHS->getName()+".masked");
3799 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003800 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003801 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003802 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003803 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003804 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3805 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003806 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003807 Op0LHS->getName()+".masked");
3808 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003809 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003810 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3811 }
3812 }
3813
Chris Lattner6e7ba452005-01-01 16:22:27 +00003814 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003815 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003816 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3817 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3818 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3819 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003820 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003821 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003822 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003823 break;
3824
3825 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003826 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3827 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3828 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3829 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003830 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003831 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003832 }
3833
Chris Lattner58403262003-07-23 19:25:52 +00003834 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003835 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003836 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003837 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003838 // If this is an integer truncation or change from signed-to-unsigned, and
3839 // if the source is an and/or with immediate, transform it. This
3840 // frequently occurs for bitfield accesses.
3841 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003842 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003843 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003844 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003845 if (CastOp->getOpcode() == Instruction::And) {
3846 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003847 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3848 // This will fold the two constants together, which may allow
3849 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003850 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003851 CastOp->getOperand(0), I.getType(),
3852 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003853 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003854 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003855 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003856 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003857 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003858 } else if (CastOp->getOpcode() == Instruction::Or) {
3859 // Change: and (cast (or X, C1) to T), C2
3860 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003861 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003862 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3863 return ReplaceInstUsesWith(I, AndRHS);
3864 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003865 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003866 }
Chris Lattner06782f82003-07-23 19:36:21 +00003867 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003868
3869 // Try to fold constant and into select arguments.
3870 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003871 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003872 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003873 if (isa<PHINode>(Op0))
3874 if (Instruction *NV = FoldOpIntoPhi(I))
3875 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003876 }
3877
Chris Lattner8d969642003-03-10 23:06:50 +00003878 Value *Op0NotVal = dyn_castNotVal(Op0);
3879 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003880
Chris Lattner5b62aa72004-06-18 06:07:51 +00003881 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3882 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3883
Misha Brukmancb6267b2004-07-30 12:50:08 +00003884 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003885 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003886 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003887 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003888 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003889 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003890 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003891
3892 {
Chris Lattner003b6202007-06-15 05:58:24 +00003893 Value *A = 0, *B = 0, *C = 0, *D = 0;
3894 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003895 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3896 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003897
3898 // (A|B) & ~(A&B) -> A^B
3899 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3900 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003901 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003902 }
3903 }
3904
3905 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003906 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3907 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003908
3909 // ~(A&B) & (A|B) -> A^B
3910 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3911 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003912 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003913 }
3914 }
Chris Lattner64daab52006-04-01 08:03:55 +00003915
3916 if (Op0->hasOneUse() &&
3917 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3918 if (A == Op1) { // (A^B)&A -> A&(A^B)
3919 I.swapOperands(); // Simplify below
3920 std::swap(Op0, Op1);
3921 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3922 cast<BinaryOperator>(Op0)->swapOperands();
3923 I.swapOperands(); // Simplify below
3924 std::swap(Op0, Op1);
3925 }
3926 }
3927 if (Op1->hasOneUse() &&
3928 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3929 if (B == Op0) { // B&(A^B) -> B&(B^A)
3930 cast<BinaryOperator>(Op1)->swapOperands();
3931 std::swap(A, B);
3932 }
3933 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003934 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00003935 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003936 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00003937 }
3938 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003939 }
3940
Reid Spencere4d87aa2006-12-23 06:05:41 +00003941 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3942 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3943 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003944 return R;
3945
Chris Lattner955f3312004-09-28 21:48:02 +00003946 Value *LHSVal, *RHSVal;
3947 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003948 ICmpInst::Predicate LHSCC, RHSCC;
3949 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3950 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3951 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3952 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3953 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3954 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3955 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003956 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3957
3958 // Don't try to fold ICMP_SLT + ICMP_ULT.
3959 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3960 ICmpInst::isSignedPredicate(LHSCC) ==
3961 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003962 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003963 ICmpInst::Predicate GT;
3964 if (ICmpInst::isSignedPredicate(LHSCC) ||
3965 (ICmpInst::isEquality(LHSCC) &&
3966 ICmpInst::isSignedPredicate(RHSCC)))
3967 GT = ICmpInst::ICMP_SGT;
3968 else
3969 GT = ICmpInst::ICMP_UGT;
3970
Reid Spencere4d87aa2006-12-23 06:05:41 +00003971 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3972 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003973 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003974 std::swap(LHS, RHS);
3975 std::swap(LHSCst, RHSCst);
3976 std::swap(LHSCC, RHSCC);
3977 }
3978
Reid Spencere4d87aa2006-12-23 06:05:41 +00003979 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003980 // comparing a value against two constants and and'ing the result
3981 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003982 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3983 // (from the FoldICmpLogical check above), that the two constants
3984 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003985 assert(LHSCst != RHSCst && "Compares not folded above?");
3986
3987 switch (LHSCC) {
3988 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003989 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003990 switch (RHSCC) {
3991 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003992 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3993 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3994 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003995 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003996 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3997 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3998 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003999 return ReplaceInstUsesWith(I, LHS);
4000 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004001 case ICmpInst::ICMP_NE:
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_ULT:
4005 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4006 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4007 break; // (X != 13 & X u< 15) -> no change
4008 case ICmpInst::ICMP_SLT:
4009 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4010 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4011 break; // (X != 13 & X s< 15) -> no change
4012 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4013 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4014 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00004015 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004016 case ICmpInst::ICMP_NE:
4017 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00004018 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004019 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00004020 LHSVal->getName()+".off");
4021 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00004022 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4023 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00004024 }
4025 break; // (X != 13 & X != 15) -> no change
4026 }
4027 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004028 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00004029 switch (RHSCC) {
4030 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004031 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4032 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004033 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004034 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4035 break;
4036 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4037 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00004038 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004039 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4040 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004041 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004042 break;
4043 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00004044 switch (RHSCC) {
4045 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004046 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4047 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004048 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004049 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4050 break;
4051 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4052 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00004053 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004054 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4055 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004056 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004057 break;
4058 case ICmpInst::ICMP_UGT:
4059 switch (RHSCC) {
4060 default: assert(0 && "Unknown integer condition code!");
4061 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4062 return ReplaceInstUsesWith(I, LHS);
4063 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4064 return ReplaceInstUsesWith(I, RHS);
4065 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4066 break;
4067 case ICmpInst::ICMP_NE:
4068 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4069 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4070 break; // (X u> 13 & X != 15) -> no change
4071 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4072 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4073 true, I);
4074 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4075 break;
4076 }
4077 break;
4078 case ICmpInst::ICMP_SGT:
4079 switch (RHSCC) {
4080 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004081 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004082 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4083 return ReplaceInstUsesWith(I, RHS);
4084 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4085 break;
4086 case ICmpInst::ICMP_NE:
4087 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4088 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4089 break; // (X s> 13 & X != 15) -> no change
4090 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4091 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4092 true, I);
4093 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4094 break;
4095 }
4096 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004097 }
4098 }
4099 }
4100
Chris Lattner6fc205f2006-05-05 06:39:07 +00004101 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004102 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4103 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4104 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4105 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004106 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004107 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004108 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4109 I.getType(), TD) &&
4110 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4111 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004112 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004113 Op1C->getOperand(0),
4114 I.getName());
4115 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004116 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004117 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004118 }
Chris Lattnere511b742006-11-14 07:46:50 +00004119
4120 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004121 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4122 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4123 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004124 SI0->getOperand(1) == SI1->getOperand(1) &&
4125 (SI0->hasOneUse() || SI1->hasOneUse())) {
4126 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004127 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004128 SI1->getOperand(0),
4129 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004130 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004131 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004132 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004133 }
4134
Chris Lattner99c65742007-10-24 05:38:08 +00004135 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4136 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4137 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4138 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4139 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4140 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4141 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4142 // If either of the constants are nans, then the whole thing returns
4143 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004144 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004145 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4146 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4147 RHS->getOperand(0));
4148 }
4149 }
4150 }
4151
Chris Lattner7e708292002-06-25 16:13:24 +00004152 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004153}
4154
Chris Lattnerafe91a52006-06-15 19:07:26 +00004155/// CollectBSwapParts - Look to see if the specified value defines a single byte
4156/// in the result. If it does, and if the specified byte hasn't been filled in
4157/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004158static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004159 Instruction *I = dyn_cast<Instruction>(V);
4160 if (I == 0) return true;
4161
4162 // If this is an or instruction, it is an inner node of the bswap.
4163 if (I->getOpcode() == Instruction::Or)
4164 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4165 CollectBSwapParts(I->getOperand(1), ByteValues);
4166
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004167 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004168 // If this is a shift by a constant int, and it is "24", then its operand
4169 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004170 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004171 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004172 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004173 8*(ByteValues.size()-1))
4174 return true;
4175
4176 unsigned DestNo;
4177 if (I->getOpcode() == Instruction::Shl) {
4178 // X << 24 defines the top byte with the lowest of the input bytes.
4179 DestNo = ByteValues.size()-1;
4180 } else {
4181 // X >>u 24 defines the low byte with the highest of the input bytes.
4182 DestNo = 0;
4183 }
4184
4185 // If the destination byte value is already defined, the values are or'd
4186 // together, which isn't a bswap (unless it's an or of the same bits).
4187 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4188 return true;
4189 ByteValues[DestNo] = I->getOperand(0);
4190 return false;
4191 }
4192
4193 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4194 // don't have this.
4195 Value *Shift = 0, *ShiftLHS = 0;
4196 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4197 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4198 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4199 return true;
4200 Instruction *SI = cast<Instruction>(Shift);
4201
4202 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004203 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4204 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004205 return true;
4206
4207 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4208 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004209 if (AndAmt->getValue().getActiveBits() > 64)
4210 return true;
4211 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004212 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004213 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004214 break;
4215 // Unknown mask for bswap.
4216 if (DestByte == ByteValues.size()) return true;
4217
Reid Spencerb83eb642006-10-20 07:07:24 +00004218 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004219 unsigned SrcByte;
4220 if (SI->getOpcode() == Instruction::Shl)
4221 SrcByte = DestByte - ShiftBytes;
4222 else
4223 SrcByte = DestByte + ShiftBytes;
4224
4225 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4226 if (SrcByte != ByteValues.size()-DestByte-1)
4227 return true;
4228
4229 // If the destination byte value is already defined, the values are or'd
4230 // together, which isn't a bswap (unless it's an or of the same bits).
4231 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4232 return true;
4233 ByteValues[DestByte] = SI->getOperand(0);
4234 return false;
4235}
4236
4237/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4238/// If so, insert the new bswap intrinsic and return it.
4239Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004240 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4241 if (!ITy || ITy->getBitWidth() % 16)
4242 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004243
4244 /// ByteValues - For each byte of the result, we keep track of which value
4245 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004246 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004247 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004248
4249 // Try to find all the pieces corresponding to the bswap.
4250 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4251 CollectBSwapParts(I.getOperand(1), ByteValues))
4252 return 0;
4253
4254 // Check to see if all of the bytes come from the same value.
4255 Value *V = ByteValues[0];
4256 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4257
4258 // Check to make sure that all of the bytes come from the same value.
4259 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4260 if (ByteValues[i] != V)
4261 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004262 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004263 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004264 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004265 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004266}
4267
4268
Chris Lattner7e708292002-06-25 16:13:24 +00004269Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004270 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004271 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004272
Chris Lattner42593e62007-03-24 23:56:43 +00004273 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004274 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004275
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004276 // or X, X = X
4277 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004278 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004279
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004280 // See if we can simplify any instructions used by the instruction whose sole
4281 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004282 if (!isa<VectorType>(I.getType())) {
4283 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4284 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4285 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4286 KnownZero, KnownOne))
4287 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004288 } else if (isa<ConstantAggregateZero>(Op1)) {
4289 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4290 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4291 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4292 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004293 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004294
4295
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004296
Chris Lattner3f5b8772002-05-06 16:14:14 +00004297 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004298 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004299 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004300 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4301 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004302 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004303 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004304 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004305 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004306 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004307 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004308
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004309 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4310 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004311 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004312 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004313 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004314 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004315 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004316 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004317
4318 // Try to fold constant and into select arguments.
4319 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004320 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004321 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004322 if (isa<PHINode>(Op0))
4323 if (Instruction *NV = FoldOpIntoPhi(I))
4324 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004325 }
4326
Chris Lattner4f637d42006-01-06 17:59:59 +00004327 Value *A = 0, *B = 0;
4328 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004329
4330 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4331 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4332 return ReplaceInstUsesWith(I, Op1);
4333 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4334 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4335 return ReplaceInstUsesWith(I, Op0);
4336
Chris Lattner6423d4c2006-07-10 20:25:24 +00004337 // (A | B) | C and A | (B | C) -> bswap if possible.
4338 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004339 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004340 match(Op1, m_Or(m_Value(), m_Value())) ||
4341 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4342 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004343 if (Instruction *BSwap = MatchBSwap(I))
4344 return BSwap;
4345 }
4346
Chris Lattner6e4c6492005-05-09 04:58:36 +00004347 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4348 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004349 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004350 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004351 InsertNewInstBefore(NOr, I);
4352 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004353 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004354 }
4355
4356 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4357 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004358 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004359 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004360 InsertNewInstBefore(NOr, I);
4361 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004362 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004363 }
4364
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004365 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004366 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004367 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4368 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004369 Value *V1 = 0, *V2 = 0, *V3 = 0;
4370 C1 = dyn_cast<ConstantInt>(C);
4371 C2 = dyn_cast<ConstantInt>(D);
4372 if (C1 && C2) { // (A & C1)|(B & C2)
4373 // If we have: ((V + N) & C1) | (V & C2)
4374 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4375 // replace with V+N.
4376 if (C1->getValue() == ~C2->getValue()) {
4377 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4378 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4379 // Add commutes, try both ways.
4380 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4381 return ReplaceInstUsesWith(I, A);
4382 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4383 return ReplaceInstUsesWith(I, A);
4384 }
4385 // Or commutes, try both ways.
4386 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4387 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4388 // Add commutes, try both ways.
4389 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4390 return ReplaceInstUsesWith(I, B);
4391 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4392 return ReplaceInstUsesWith(I, B);
4393 }
4394 }
Chris Lattner044e5332007-04-08 08:01:49 +00004395 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004396 }
4397
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004398 // Check to see if we have any common things being and'ed. If so, find the
4399 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004400 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4401 if (A == B) // (A & C)|(A & D) == A & (C|D)
4402 V1 = A, V2 = C, V3 = D;
4403 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4404 V1 = A, V2 = B, V3 = C;
4405 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4406 V1 = C, V2 = A, V3 = D;
4407 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4408 V1 = C, V2 = A, V3 = B;
4409
4410 if (V1) {
4411 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004412 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4413 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004414 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004415 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004416 }
Chris Lattnere511b742006-11-14 07:46:50 +00004417
4418 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004419 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4420 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4421 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004422 SI0->getOperand(1) == SI1->getOperand(1) &&
4423 (SI0->hasOneUse() || SI1->hasOneUse())) {
4424 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004425 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004426 SI1->getOperand(0),
4427 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004428 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004429 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004430 }
4431 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004432
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004433 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4434 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004435 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004436 } else {
4437 A = 0;
4438 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004439 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004440 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4441 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004442 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004443
Misha Brukmancb6267b2004-07-30 12:50:08 +00004444 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004445 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004446 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004447 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004448 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004449 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004450 }
Chris Lattnera2881962003-02-18 19:28:33 +00004451
Reid Spencere4d87aa2006-12-23 06:05:41 +00004452 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4453 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4454 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004455 return R;
4456
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004457 Value *LHSVal, *RHSVal;
4458 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004459 ICmpInst::Predicate LHSCC, RHSCC;
4460 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4461 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4462 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4463 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4464 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4465 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4466 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004467 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4468 // We can't fold (ugt x, C) | (sgt x, C2).
4469 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004470 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004471 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004472 bool NeedsSwap;
4473 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004474 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004475 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004476 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004477
4478 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004479 std::swap(LHS, RHS);
4480 std::swap(LHSCst, RHSCst);
4481 std::swap(LHSCC, RHSCC);
4482 }
4483
Reid Spencere4d87aa2006-12-23 06:05:41 +00004484 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004485 // comparing a value against two constants and or'ing the result
4486 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004487 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4488 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004489 // equal.
4490 assert(LHSCst != RHSCst && "Compares not folded above?");
4491
4492 switch (LHSCC) {
4493 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004494 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004495 switch (RHSCC) {
4496 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004497 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004498 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4499 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004500 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004501 LHSVal->getName()+".off");
4502 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004503 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004504 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004505 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004506 break; // (X == 13 | X == 15) -> no change
4507 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4508 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004509 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004510 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4511 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4512 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004513 return ReplaceInstUsesWith(I, RHS);
4514 }
4515 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004516 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004517 switch (RHSCC) {
4518 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004519 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4520 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4521 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004522 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004523 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4524 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4525 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004526 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004527 }
4528 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004529 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004530 switch (RHSCC) {
4531 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004532 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004533 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004534 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004535 // If RHSCst is [us]MAXINT, it is always false. Not handling
4536 // this can cause overflow.
4537 if (RHSCst->isMaxValue(false))
4538 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004539 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4540 false, I);
4541 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4542 break;
4543 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4544 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004545 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004546 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4547 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004548 }
4549 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004550 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004551 switch (RHSCC) {
4552 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004553 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4554 break;
4555 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004556 // If RHSCst is [us]MAXINT, it is always false. Not handling
4557 // this can cause overflow.
4558 if (RHSCst->isMaxValue(true))
4559 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004560 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4561 false, I);
4562 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4563 break;
4564 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4565 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4566 return ReplaceInstUsesWith(I, RHS);
4567 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4568 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004569 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004570 break;
4571 case ICmpInst::ICMP_UGT:
4572 switch (RHSCC) {
4573 default: assert(0 && "Unknown integer condition code!");
4574 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4575 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4576 return ReplaceInstUsesWith(I, LHS);
4577 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4578 break;
4579 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4580 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004581 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004582 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4583 break;
4584 }
4585 break;
4586 case ICmpInst::ICMP_SGT:
4587 switch (RHSCC) {
4588 default: assert(0 && "Unknown integer condition code!");
4589 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4590 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4591 return ReplaceInstUsesWith(I, LHS);
4592 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4593 break;
4594 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4595 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004596 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004597 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4598 break;
4599 }
4600 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004601 }
4602 }
4603 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004604
4605 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004606 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004607 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004608 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004609 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4610 !isa<ICmpInst>(Op1C->getOperand(0))) {
4611 const Type *SrcTy = Op0C->getOperand(0)->getType();
4612 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4613 // Only do this if the casts both really cause code to be
4614 // generated.
4615 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4616 I.getType(), TD) &&
4617 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4618 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004619 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004620 Op1C->getOperand(0),
4621 I.getName());
4622 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004623 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004624 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004625 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004626 }
Chris Lattner99c65742007-10-24 05:38:08 +00004627 }
4628
4629
4630 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4631 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4632 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4633 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004634 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4635 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004636 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4637 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4638 // If either of the constants are nans, then the whole thing returns
4639 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004640 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004641 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4642
4643 // Otherwise, no need to compare the two constants, compare the
4644 // rest.
4645 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4646 RHS->getOperand(0));
4647 }
4648 }
4649 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004650
Chris Lattner7e708292002-06-25 16:13:24 +00004651 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004652}
4653
Dan Gohman844731a2008-05-13 00:00:25 +00004654namespace {
4655
Chris Lattnerc317d392004-02-16 01:20:27 +00004656// XorSelf - Implements: X ^ X --> 0
4657struct XorSelf {
4658 Value *RHS;
4659 XorSelf(Value *rhs) : RHS(rhs) {}
4660 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4661 Instruction *apply(BinaryOperator &Xor) const {
4662 return &Xor;
4663 }
4664};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004665
Dan Gohman844731a2008-05-13 00:00:25 +00004666}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004667
Chris Lattner7e708292002-06-25 16:13:24 +00004668Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004669 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004670 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004671
Evan Chengd34af782008-03-25 20:07:13 +00004672 if (isa<UndefValue>(Op1)) {
4673 if (isa<UndefValue>(Op0))
4674 // Handle undef ^ undef -> 0 special case. This is a common
4675 // idiom (misuse).
4676 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004677 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004678 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004679
Chris Lattnerc317d392004-02-16 01:20:27 +00004680 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4681 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004682 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004683 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004684 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004685
4686 // See if we can simplify any instructions used by the instruction whose sole
4687 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004688 if (!isa<VectorType>(I.getType())) {
4689 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4690 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4691 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4692 KnownZero, KnownOne))
4693 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004694 } else if (isa<ConstantAggregateZero>(Op1)) {
4695 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004696 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004697
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004698 // Is this a ~ operation?
4699 if (Value *NotOp = dyn_castNotVal(&I)) {
4700 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4701 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4702 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4703 if (Op0I->getOpcode() == Instruction::And ||
4704 Op0I->getOpcode() == Instruction::Or) {
4705 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4706 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4707 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004708 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004709 Op0I->getOperand(1)->getName()+".not");
4710 InsertNewInstBefore(NotY, I);
4711 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004712 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004713 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004714 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004715 }
4716 }
4717 }
4718 }
4719
4720
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004721 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004722 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4723 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4724 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004725 return new ICmpInst(ICI->getInversePredicate(),
4726 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004727
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004728 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4729 return new FCmpInst(FCI->getInversePredicate(),
4730 FCI->getOperand(0), FCI->getOperand(1));
4731 }
4732
Reid Spencere4d87aa2006-12-23 06:05:41 +00004733 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004734 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004735 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4736 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004737 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4738 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004739 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004740 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004741 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004742
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004743 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004744 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004745 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004746 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004747 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004748 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004749 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004750 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004751 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004752 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004753 // (X + C) ^ signbit -> (X + C + signbit)
4754 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004755 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004756
Chris Lattner7c4049c2004-01-12 19:35:11 +00004757 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004758 } else if (Op0I->getOpcode() == Instruction::Or) {
4759 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004760 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004761 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4762 // Anything in both C1 and C2 is known to be zero, remove it from
4763 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004764 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004765 NewRHS = ConstantExpr::getAnd(NewRHS,
4766 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004767 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004768 I.setOperand(0, Op0I->getOperand(0));
4769 I.setOperand(1, NewRHS);
4770 return &I;
4771 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004772 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004773 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004774 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004775
4776 // Try to fold constant and into select arguments.
4777 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004778 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004779 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004780 if (isa<PHINode>(Op0))
4781 if (Instruction *NV = FoldOpIntoPhi(I))
4782 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004783 }
4784
Chris Lattner8d969642003-03-10 23:06:50 +00004785 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004786 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004787 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004788
Chris Lattner8d969642003-03-10 23:06:50 +00004789 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004790 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004791 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004792
Chris Lattner318bf792007-03-18 22:51:34 +00004793
4794 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4795 if (Op1I) {
4796 Value *A, *B;
4797 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4798 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004799 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004800 I.swapOperands();
4801 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004802 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004803 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004804 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004805 }
Chris Lattner318bf792007-03-18 22:51:34 +00004806 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4807 if (Op0 == A) // A^(A^B) == B
4808 return ReplaceInstUsesWith(I, B);
4809 else if (Op0 == B) // A^(B^A) == B
4810 return ReplaceInstUsesWith(I, A);
4811 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004812 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004813 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004814 std::swap(A, B);
4815 }
Chris Lattner318bf792007-03-18 22:51:34 +00004816 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004817 I.swapOperands(); // Simplified below.
4818 std::swap(Op0, Op1);
4819 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004820 }
Chris Lattner318bf792007-03-18 22:51:34 +00004821 }
4822
4823 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4824 if (Op0I) {
4825 Value *A, *B;
4826 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4827 if (A == Op1) // (B|A)^B == (A|B)^B
4828 std::swap(A, B);
4829 if (B == Op1) { // (A|B)^B == A & ~B
4830 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004831 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4832 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004833 }
Chris Lattner318bf792007-03-18 22:51:34 +00004834 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4835 if (Op1 == A) // (A^B)^A == B
4836 return ReplaceInstUsesWith(I, B);
4837 else if (Op1 == B) // (B^A)^A == B
4838 return ReplaceInstUsesWith(I, A);
4839 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4840 if (A == Op1) // (A&B)^A -> (B&A)^A
4841 std::swap(A, B);
4842 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004843 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004844 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004845 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4846 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004847 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004848 }
Chris Lattner318bf792007-03-18 22:51:34 +00004849 }
4850
4851 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4852 if (Op0I && Op1I && Op0I->isShift() &&
4853 Op0I->getOpcode() == Op1I->getOpcode() &&
4854 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4855 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4856 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004857 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00004858 Op1I->getOperand(0),
4859 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004860 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00004861 Op1I->getOperand(1));
4862 }
4863
4864 if (Op0I && Op1I) {
4865 Value *A, *B, *C, *D;
4866 // (A & B)^(A | B) -> A ^ B
4867 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4868 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4869 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004870 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004871 }
4872 // (A | B)^(A & B) -> A ^ B
4873 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4874 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4875 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004876 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004877 }
4878
4879 // (A & B)^(C & D)
4880 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4881 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4882 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4883 // (X & Y)^(X & Y) -> (Y^Z) & X
4884 Value *X = 0, *Y = 0, *Z = 0;
4885 if (A == C)
4886 X = A, Y = B, Z = D;
4887 else if (A == D)
4888 X = A, Y = B, Z = C;
4889 else if (B == C)
4890 X = B, Y = A, Z = D;
4891 else if (B == D)
4892 X = B, Y = A, Z = C;
4893
4894 if (X) {
4895 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004896 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4897 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00004898 }
4899 }
4900 }
4901
Reid Spencere4d87aa2006-12-23 06:05:41 +00004902 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4903 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4904 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004905 return R;
4906
Chris Lattner6fc205f2006-05-05 06:39:07 +00004907 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004908 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004909 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004910 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4911 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004912 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004913 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004914 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4915 I.getType(), TD) &&
4916 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4917 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004918 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004919 Op1C->getOperand(0),
4920 I.getName());
4921 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004922 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004923 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004924 }
Chris Lattner99c65742007-10-24 05:38:08 +00004925 }
Chris Lattner7e708292002-06-25 16:13:24 +00004926 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004927}
4928
Chris Lattnera96879a2004-09-29 17:40:11 +00004929/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4930/// overflowed for this type.
4931static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004932 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004933 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004934
Reid Spencere4e40032007-03-21 23:19:50 +00004935 if (IsSigned)
4936 if (In2->getValue().isNegative())
4937 return Result->getValue().sgt(In1->getValue());
4938 else
4939 return Result->getValue().slt(In1->getValue());
4940 else
4941 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004942}
4943
Chris Lattner574da9b2005-01-13 20:14:25 +00004944/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4945/// code necessary to compute the offset from the base pointer (without adding
4946/// in the base pointer). Return the result as a signed integer of intptr size.
4947static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4948 TargetData &TD = IC.getTargetData();
4949 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004950 const Type *IntPtrTy = TD.getIntPtrType();
4951 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004952
4953 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00004954 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00004955 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004956
Chris Lattner574da9b2005-01-13 20:14:25 +00004957 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4958 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004959 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004960 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4961 if (OpC->isZero()) continue;
4962
4963 // Handle a struct index, which adds its field offset to the pointer.
4964 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4965 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4966
4967 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4968 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004969 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004970 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004971 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004972 ConstantInt::get(IntPtrTy, Size),
4973 GEP->getName()+".offs"), I);
4974 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004975 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004976
4977 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4978 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4979 Scale = ConstantExpr::getMul(OC, Scale);
4980 if (Constant *RC = dyn_cast<Constant>(Result))
4981 Result = ConstantExpr::getAdd(RC, Scale);
4982 else {
4983 // Emit an add instruction.
4984 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004985 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004986 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004987 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004988 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004989 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004990 // Convert to correct type.
4991 if (Op->getType() != IntPtrTy) {
4992 if (Constant *OpC = dyn_cast<Constant>(Op))
4993 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4994 else
4995 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4996 Op->getName()+".c"), I);
4997 }
4998 if (Size != 1) {
4999 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5000 if (Constant *OpC = dyn_cast<Constant>(Op))
5001 Op = ConstantExpr::getMul(OpC, Scale);
5002 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005003 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005004 GEP->getName()+".idx"), I);
5005 }
5006
5007 // Emit an add instruction.
5008 if (isa<Constant>(Op) && isa<Constant>(Result))
5009 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5010 cast<Constant>(Result));
5011 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005012 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005013 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005014 }
5015 return Result;
5016}
5017
Chris Lattner10c0d912008-04-22 02:53:33 +00005018
5019/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5020/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5021/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5022/// complex, and scales are involved. The above expression would also be legal
5023/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5024/// later form is less amenable to optimization though, and we are allowed to
5025/// generate the first by knowing that pointer arithmetic doesn't overflow.
5026///
5027/// If we can't emit an optimized form for this expression, this returns null.
5028///
5029static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5030 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005031 TargetData &TD = IC.getTargetData();
5032 gep_type_iterator GTI = gep_type_begin(GEP);
5033
5034 // Check to see if this gep only has a single variable index. If so, and if
5035 // any constant indices are a multiple of its scale, then we can compute this
5036 // in terms of the scale of the variable index. For example, if the GEP
5037 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5038 // because the expression will cross zero at the same point.
5039 unsigned i, e = GEP->getNumOperands();
5040 int64_t Offset = 0;
5041 for (i = 1; i != e; ++i, ++GTI) {
5042 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5043 // Compute the aggregate offset of constant indices.
5044 if (CI->isZero()) continue;
5045
5046 // Handle a struct index, which adds its field offset to the pointer.
5047 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5048 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5049 } else {
5050 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5051 Offset += Size*CI->getSExtValue();
5052 }
5053 } else {
5054 // Found our variable index.
5055 break;
5056 }
5057 }
5058
5059 // If there are no variable indices, we must have a constant offset, just
5060 // evaluate it the general way.
5061 if (i == e) return 0;
5062
5063 Value *VariableIdx = GEP->getOperand(i);
5064 // Determine the scale factor of the variable element. For example, this is
5065 // 4 if the variable index is into an array of i32.
5066 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5067
5068 // Verify that there are no other variable indices. If so, emit the hard way.
5069 for (++i, ++GTI; i != e; ++i, ++GTI) {
5070 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5071 if (!CI) return 0;
5072
5073 // Compute the aggregate offset of constant indices.
5074 if (CI->isZero()) continue;
5075
5076 // Handle a struct index, which adds its field offset to the pointer.
5077 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5078 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5079 } else {
5080 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5081 Offset += Size*CI->getSExtValue();
5082 }
5083 }
5084
5085 // Okay, we know we have a single variable index, which must be a
5086 // pointer/array/vector index. If there is no offset, life is simple, return
5087 // the index.
5088 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5089 if (Offset == 0) {
5090 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5091 // we don't need to bother extending: the extension won't affect where the
5092 // computation crosses zero.
5093 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5094 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5095 VariableIdx->getNameStart(), &I);
5096 return VariableIdx;
5097 }
5098
5099 // Otherwise, there is an index. The computation we will do will be modulo
5100 // the pointer size, so get it.
5101 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5102
5103 Offset &= PtrSizeMask;
5104 VariableScale &= PtrSizeMask;
5105
5106 // To do this transformation, any constant index must be a multiple of the
5107 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5108 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5109 // multiple of the variable scale.
5110 int64_t NewOffs = Offset / (int64_t)VariableScale;
5111 if (Offset != NewOffs*(int64_t)VariableScale)
5112 return 0;
5113
5114 // Okay, we can do this evaluation. Start by converting the index to intptr.
5115 const Type *IntPtrTy = TD.getIntPtrType();
5116 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005117 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005118 true /*SExt*/,
5119 VariableIdx->getNameStart(), &I);
5120 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005121 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005122}
5123
5124
Reid Spencere4d87aa2006-12-23 06:05:41 +00005125/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005126/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005127Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5128 ICmpInst::Predicate Cond,
5129 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005130 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005131
Chris Lattner10c0d912008-04-22 02:53:33 +00005132 // Look through bitcasts.
5133 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5134 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005135
Chris Lattner574da9b2005-01-13 20:14:25 +00005136 Value *PtrBase = GEPLHS->getOperand(0);
5137 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005138 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005139 // This transformation (ignoring the base and scales) is valid because we
5140 // know pointers can't overflow. See if we can output an optimized form.
5141 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5142
5143 // If not, synthesize the offset the hard way.
5144 if (Offset == 0)
5145 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005146 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5147 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005148 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005149 // If the base pointers are different, but the indices are the same, just
5150 // compare the base pointer.
5151 if (PtrBase != GEPRHS->getOperand(0)) {
5152 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005153 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005154 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005155 if (IndicesTheSame)
5156 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5157 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5158 IndicesTheSame = false;
5159 break;
5160 }
5161
5162 // If all indices are the same, just compare the base pointers.
5163 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005164 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5165 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005166
5167 // Otherwise, the base pointers are different and the indices are
5168 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005169 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005170 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005171
Chris Lattnere9d782b2005-01-13 22:25:21 +00005172 // If one of the GEPs has all zero indices, recurse.
5173 bool AllZeros = true;
5174 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5175 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5176 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5177 AllZeros = false;
5178 break;
5179 }
5180 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005181 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5182 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005183
5184 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005185 AllZeros = true;
5186 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5187 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5188 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5189 AllZeros = false;
5190 break;
5191 }
5192 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005193 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005194
Chris Lattner4401c9c2005-01-14 00:20:05 +00005195 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5196 // If the GEPs only differ by one index, compare it.
5197 unsigned NumDifferences = 0; // Keep track of # differences.
5198 unsigned DiffOperand = 0; // The operand that differs.
5199 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5200 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005201 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5202 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005203 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005204 NumDifferences = 2;
5205 break;
5206 } else {
5207 if (NumDifferences++) break;
5208 DiffOperand = i;
5209 }
5210 }
5211
5212 if (NumDifferences == 0) // SAME GEP?
5213 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005214 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005215 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005216
Chris Lattner4401c9c2005-01-14 00:20:05 +00005217 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005218 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5219 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005220 // Make sure we do a signed comparison here.
5221 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005222 }
5223 }
5224
Reid Spencere4d87aa2006-12-23 06:05:41 +00005225 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005226 // the result to fold to a constant!
5227 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5228 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5229 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5230 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5231 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005232 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005233 }
5234 }
5235 return 0;
5236}
5237
Chris Lattnera5406232008-05-19 20:18:56 +00005238/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5239///
5240Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5241 Instruction *LHSI,
5242 Constant *RHSC) {
5243 if (!isa<ConstantFP>(RHSC)) return 0;
5244 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5245
5246 // Get the width of the mantissa. We don't want to hack on conversions that
5247 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005248 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005249 if (MantissaWidth == -1) return 0; // Unknown.
5250
5251 // Check to see that the input is converted from an integer type that is small
5252 // enough that preserves all bits. TODO: check here for "known" sign bits.
5253 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5254 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5255
5256 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5257 if (isa<UIToFPInst>(LHSI))
5258 ++InputSize;
5259
5260 // If the conversion would lose info, don't hack on this.
5261 if ((int)InputSize > MantissaWidth)
5262 return 0;
5263
5264 // Otherwise, we can potentially simplify the comparison. We know that it
5265 // will always come through as an integer value and we know the constant is
5266 // not a NAN (it would have been previously simplified).
5267 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5268
5269 ICmpInst::Predicate Pred;
5270 switch (I.getPredicate()) {
5271 default: assert(0 && "Unexpected predicate!");
5272 case FCmpInst::FCMP_UEQ:
5273 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5274 case FCmpInst::FCMP_UGT:
5275 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5276 case FCmpInst::FCMP_UGE:
5277 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5278 case FCmpInst::FCMP_ULT:
5279 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5280 case FCmpInst::FCMP_ULE:
5281 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5282 case FCmpInst::FCMP_UNE:
5283 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5284 case FCmpInst::FCMP_ORD:
5285 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5286 case FCmpInst::FCMP_UNO:
5287 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5288 }
5289
5290 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5291
5292 // Now we know that the APFloat is a normal number, zero or inf.
5293
5294 // See if the FP constant is top large for the integer. For example,
5295 // comparing an i8 to 300.0.
5296 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5297
5298 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5299 // and large values.
5300 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5301 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5302 APFloat::rmNearestTiesToEven);
5303 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5304 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5305 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5306 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5307 }
5308
5309 // See if the RHS value is < SignedMin.
5310 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5311 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5312 APFloat::rmNearestTiesToEven);
5313 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5314 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5315 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5316 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5317 }
5318
5319 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5320 // it may still be fractional. See if it is fractional by casting the FP
5321 // value to the integer value and back, checking for equality. Don't do this
5322 // for zero, because -0.0 is not fractional.
5323 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5324 if (!RHS.isZero() &&
5325 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5326 // If we had a comparison against a fractional value, we have to adjust
5327 // the compare predicate and sometimes the value. RHSC is rounded towards
5328 // zero at this point.
5329 switch (Pred) {
5330 default: assert(0 && "Unexpected integer comparison!");
5331 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5332 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5333 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5334 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5335 case ICmpInst::ICMP_SLE:
5336 // (float)int <= 4.4 --> int <= 4
5337 // (float)int <= -4.4 --> int < -4
5338 if (RHS.isNegative())
5339 Pred = ICmpInst::ICMP_SLT;
5340 break;
5341 case ICmpInst::ICMP_SLT:
5342 // (float)int < -4.4 --> int < -4
5343 // (float)int < 4.4 --> int <= 4
5344 if (!RHS.isNegative())
5345 Pred = ICmpInst::ICMP_SLE;
5346 break;
5347 case ICmpInst::ICMP_SGT:
5348 // (float)int > 4.4 --> int > 4
5349 // (float)int > -4.4 --> int >= -4
5350 if (RHS.isNegative())
5351 Pred = ICmpInst::ICMP_SGE;
5352 break;
5353 case ICmpInst::ICMP_SGE:
5354 // (float)int >= -4.4 --> int >= -4
5355 // (float)int >= 4.4 --> int > 4
5356 if (!RHS.isNegative())
5357 Pred = ICmpInst::ICMP_SGT;
5358 break;
5359 }
5360 }
5361
5362 // Lower this FP comparison into an appropriate integer version of the
5363 // comparison.
5364 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5365}
5366
Reid Spencere4d87aa2006-12-23 06:05:41 +00005367Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5368 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005369 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005370
Chris Lattner58e97462007-01-14 19:42:17 +00005371 // Fold trivial predicates.
5372 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5373 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5374 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5375 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5376
5377 // Simplify 'fcmp pred X, X'
5378 if (Op0 == Op1) {
5379 switch (I.getPredicate()) {
5380 default: assert(0 && "Unknown predicate!");
5381 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5382 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5383 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5384 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5385 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5386 case FCmpInst::FCMP_OLT: // True if ordered and less than
5387 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5388 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5389
5390 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5391 case FCmpInst::FCMP_ULT: // True if unordered or less than
5392 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5393 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5394 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5395 I.setPredicate(FCmpInst::FCMP_UNO);
5396 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5397 return &I;
5398
5399 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5400 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5401 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5402 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5403 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5404 I.setPredicate(FCmpInst::FCMP_ORD);
5405 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5406 return &I;
5407 }
5408 }
5409
Reid Spencere4d87aa2006-12-23 06:05:41 +00005410 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005411 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005412
Reid Spencere4d87aa2006-12-23 06:05:41 +00005413 // Handle fcmp with constant RHS
5414 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005415 // If the constant is a nan, see if we can fold the comparison based on it.
5416 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5417 if (CFP->getValueAPF().isNaN()) {
5418 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5419 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5420 if (FCmpInst::isUnordered(I.getPredicate())) // True if unordered or...
5421 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5422 if (FCmpInst::isUnordered(I.getPredicate())) // Undef on unordered.
5423 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5424 }
5425 }
5426
Reid Spencere4d87aa2006-12-23 06:05:41 +00005427 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5428 switch (LHSI->getOpcode()) {
5429 case Instruction::PHI:
5430 if (Instruction *NV = FoldOpIntoPhi(I))
5431 return NV;
5432 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005433 case Instruction::SIToFP:
5434 case Instruction::UIToFP:
5435 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5436 return NV;
5437 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005438 case Instruction::Select:
5439 // If either operand of the select is a constant, we can fold the
5440 // comparison into the select arms, which will cause one to be
5441 // constant folded and the select turned into a bitwise or.
5442 Value *Op1 = 0, *Op2 = 0;
5443 if (LHSI->hasOneUse()) {
5444 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5445 // Fold the known value into the constant operand.
5446 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5447 // Insert a new FCmp of the other select operand.
5448 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5449 LHSI->getOperand(2), RHSC,
5450 I.getName()), I);
5451 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5452 // Fold the known value into the constant operand.
5453 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5454 // Insert a new FCmp of the other select operand.
5455 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5456 LHSI->getOperand(1), RHSC,
5457 I.getName()), I);
5458 }
5459 }
5460
5461 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005462 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005463 break;
5464 }
5465 }
5466
5467 return Changed ? &I : 0;
5468}
5469
5470Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5471 bool Changed = SimplifyCompare(I);
5472 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5473 const Type *Ty = Op0->getType();
5474
5475 // icmp X, X
5476 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005477 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005478 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005479
5480 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005481 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005482
Reid Spencere4d87aa2006-12-23 06:05:41 +00005483 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005484 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005485 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5486 isa<ConstantPointerNull>(Op0)) &&
5487 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005488 isa<ConstantPointerNull>(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()));
Chris Lattner8b170942002-08-09 23:47:40 +00005491
Reid Spencere4d87aa2006-12-23 06:05:41 +00005492 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005493 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005494 switch (I.getPredicate()) {
5495 default: assert(0 && "Invalid icmp instruction!");
5496 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005497 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005498 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005499 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005500 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005501 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005502 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005503
Reid Spencere4d87aa2006-12-23 06:05:41 +00005504 case ICmpInst::ICMP_UGT:
5505 case ICmpInst::ICMP_SGT:
5506 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005507 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005508 case ICmpInst::ICMP_ULT:
5509 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005510 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005511 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005512 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005513 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005514 case ICmpInst::ICMP_UGE:
5515 case ICmpInst::ICMP_SGE:
5516 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005517 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005518 case ICmpInst::ICMP_ULE:
5519 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005520 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005521 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005522 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005523 }
5524 }
Chris Lattner8b170942002-08-09 23:47:40 +00005525 }
5526
Chris Lattner2be51ae2004-06-09 04:24:29 +00005527 // See if we are doing a comparison between a constant and an instruction that
5528 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005529 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005530 Value *A, *B;
5531
Chris Lattnerb6566012008-01-05 01:18:20 +00005532 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5533 if (I.isEquality() && CI->isNullValue() &&
5534 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5535 // (icmp cond A B) if cond is equality
5536 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005537 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005538
Reid Spencere4d87aa2006-12-23 06:05:41 +00005539 switch (I.getPredicate()) {
5540 default: break;
5541 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5542 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005543 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005544 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5545 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5546 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5547 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005548 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5549 if (CI->isMinValue(true))
5550 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5551 ConstantInt::getAllOnesValue(Op0->getType()));
5552
Reid Spencere4d87aa2006-12-23 06:05:41 +00005553 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005554
Reid Spencere4d87aa2006-12-23 06:05:41 +00005555 case ICmpInst::ICMP_SLT:
5556 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005557 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005558 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5559 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5560 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5561 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5562 break;
5563
5564 case ICmpInst::ICMP_UGT:
5565 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005566 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005567 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5568 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5569 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5570 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005571
5572 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5573 if (CI->isMaxValue(true))
5574 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5575 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005576 break;
5577
5578 case ICmpInst::ICMP_SGT:
5579 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005580 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005581 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5582 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5583 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5584 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5585 break;
5586
5587 case ICmpInst::ICMP_ULE:
5588 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005589 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005590 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5591 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5592 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5593 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5594 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005595
Reid Spencere4d87aa2006-12-23 06:05:41 +00005596 case ICmpInst::ICMP_SLE:
5597 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005598 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005599 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5600 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5601 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5602 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5603 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005604
Reid Spencere4d87aa2006-12-23 06:05:41 +00005605 case ICmpInst::ICMP_UGE:
5606 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005607 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005608 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5609 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5610 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5611 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5612 break;
5613
5614 case ICmpInst::ICMP_SGE:
5615 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005616 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005617 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5618 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5619 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5620 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5621 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005622 }
5623
Reid Spencere4d87aa2006-12-23 06:05:41 +00005624 // If we still have a icmp le or icmp ge instruction, turn it into the
5625 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005626 // already been handled above, this requires little checking.
5627 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005628 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005629 default: break;
5630 case ICmpInst::ICMP_ULE:
5631 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5632 case ICmpInst::ICMP_SLE:
5633 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5634 case ICmpInst::ICMP_UGE:
5635 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5636 case ICmpInst::ICMP_SGE:
5637 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005638 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005639
5640 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005641 // in the input. If this comparison is a normal comparison, it demands all
5642 // bits, if it is a sign bit comparison, it only demands the sign bit.
5643
5644 bool UnusedBit;
5645 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5646
Reid Spencer0460fb32007-03-22 20:36:03 +00005647 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5648 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005649 if (SimplifyDemandedBits(Op0,
5650 isSignBit ? APInt::getSignBit(BitWidth)
5651 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005652 KnownZero, KnownOne, 0))
5653 return &I;
5654
5655 // Given the known and unknown bits, compute a range that the LHS could be
5656 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005657 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005658 // Compute the Min, Max and RHS values based on the known bits. For the
5659 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005660 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5661 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005662 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005663 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5664 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005665 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005666 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5667 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005668 }
5669 switch (I.getPredicate()) { // LE/GE have been folded already.
5670 default: assert(0 && "Unknown icmp opcode!");
5671 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005672 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005673 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005674 break;
5675 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005676 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005677 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005678 break;
5679 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005680 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005681 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005682 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005683 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005684 break;
5685 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005686 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005687 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005688 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005689 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005690 break;
5691 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005692 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005693 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005694 if (Min.sgt(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_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005698 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005699 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005700 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005701 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005702 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005703 }
5704 }
5705
Reid Spencere4d87aa2006-12-23 06:05:41 +00005706 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005707 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005708 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005709 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005710 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5711 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005712 }
5713
Chris Lattner01deb9d2007-04-03 17:43:25 +00005714 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005715 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5716 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5717 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005718 case Instruction::GetElementPtr:
5719 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005720 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005721 bool isAllZeros = true;
5722 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5723 if (!isa<Constant>(LHSI->getOperand(i)) ||
5724 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5725 isAllZeros = false;
5726 break;
5727 }
5728 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005729 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005730 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5731 }
5732 break;
5733
Chris Lattner6970b662005-04-23 15:31:55 +00005734 case Instruction::PHI:
5735 if (Instruction *NV = FoldOpIntoPhi(I))
5736 return NV;
5737 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005738 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005739 // If either operand of the select is a constant, we can fold the
5740 // comparison into the select arms, which will cause one to be
5741 // constant folded and the select turned into a bitwise or.
5742 Value *Op1 = 0, *Op2 = 0;
5743 if (LHSI->hasOneUse()) {
5744 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5745 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005746 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5747 // Insert a new ICmp of the other select operand.
5748 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5749 LHSI->getOperand(2), RHSC,
5750 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005751 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5752 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005753 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5754 // Insert a new ICmp of the other select operand.
5755 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5756 LHSI->getOperand(1), RHSC,
5757 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005758 }
5759 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005760
Chris Lattner6970b662005-04-23 15:31:55 +00005761 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005762 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005763 break;
5764 }
Chris Lattner4802d902007-04-06 18:57:34 +00005765 case Instruction::Malloc:
5766 // If we have (malloc != null), and if the malloc has a single use, we
5767 // can assume it is successful and remove the malloc.
5768 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5769 AddToWorkList(LHSI);
5770 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005771 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00005772 }
5773 break;
5774 }
Chris Lattner6970b662005-04-23 15:31:55 +00005775 }
5776
Reid Spencere4d87aa2006-12-23 06:05:41 +00005777 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005778 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005779 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005780 return NI;
5781 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005782 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5783 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005784 return NI;
5785
Reid Spencere4d87aa2006-12-23 06:05:41 +00005786 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005787 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5788 // now.
5789 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5790 if (isa<PointerType>(Op0->getType()) &&
5791 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005792 // We keep moving the cast from the left operand over to the right
5793 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005794 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005795
Chris Lattner57d86372007-01-06 01:45:59 +00005796 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5797 // so eliminate it as well.
5798 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5799 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005800
Chris Lattnerde90b762003-11-03 04:25:02 +00005801 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005802 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005803 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005804 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005805 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005806 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005807 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005808 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005809 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005810 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005811 }
Chris Lattner57d86372007-01-06 01:45:59 +00005812 }
5813
5814 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005815 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005816 // This comes up when you have code like
5817 // int X = A < B;
5818 // if (X) ...
5819 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005820 // with a constant or another cast from the same type.
5821 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005822 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005823 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005824 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005825
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005826 // ~x < ~y --> y < x
5827 { Value *A, *B;
5828 if (match(Op0, m_Not(m_Value(A))) &&
5829 match(Op1, m_Not(m_Value(B))))
5830 return new ICmpInst(I.getPredicate(), B, A);
5831 }
5832
Chris Lattner65b72ba2006-09-18 04:22:48 +00005833 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005834 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005835
5836 // -x == -y --> x == y
5837 if (match(Op0, m_Neg(m_Value(A))) &&
5838 match(Op1, m_Neg(m_Value(B))))
5839 return new ICmpInst(I.getPredicate(), A, B);
5840
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005841 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5842 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5843 Value *OtherVal = A == Op1 ? B : A;
5844 return new ICmpInst(I.getPredicate(), OtherVal,
5845 Constant::getNullValue(A->getType()));
5846 }
5847
5848 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5849 // A^c1 == C^c2 --> A == C^(c1^c2)
5850 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5851 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5852 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005853 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005854 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005855 return new ICmpInst(I.getPredicate(), A,
5856 InsertNewInstBefore(Xor, I));
5857 }
5858
5859 // A^B == A^D -> B == D
5860 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5861 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5862 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5863 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5864 }
5865 }
5866
5867 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5868 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005869 // A == (A^B) -> B == 0
5870 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005871 return new ICmpInst(I.getPredicate(), OtherVal,
5872 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005873 }
5874 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005875 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005876 return new ICmpInst(I.getPredicate(), B,
5877 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005878 }
5879 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005880 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005881 return new ICmpInst(I.getPredicate(), B,
5882 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005883 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005884
Chris Lattner9c2328e2006-11-14 06:06:06 +00005885 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5886 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5887 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5888 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5889 Value *X = 0, *Y = 0, *Z = 0;
5890
5891 if (A == C) {
5892 X = B; Y = D; Z = A;
5893 } else if (A == D) {
5894 X = B; Y = C; Z = A;
5895 } else if (B == C) {
5896 X = A; Y = D; Z = B;
5897 } else if (B == D) {
5898 X = A; Y = C; Z = B;
5899 }
5900
5901 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005902 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5903 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00005904 I.setOperand(0, Op1);
5905 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5906 return &I;
5907 }
5908 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005909 }
Chris Lattner7e708292002-06-25 16:13:24 +00005910 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005911}
5912
Chris Lattner562ef782007-06-20 23:46:26 +00005913
5914/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5915/// and CmpRHS are both known to be integer constants.
5916Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5917 ConstantInt *DivRHS) {
5918 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5919 const APInt &CmpRHSV = CmpRHS->getValue();
5920
5921 // FIXME: If the operand types don't match the type of the divide
5922 // then don't attempt this transform. The code below doesn't have the
5923 // logic to deal with a signed divide and an unsigned compare (and
5924 // vice versa). This is because (x /s C1) <s C2 produces different
5925 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5926 // (x /u C1) <u C2. Simply casting the operands and result won't
5927 // work. :( The if statement below tests that condition and bails
5928 // if it finds it.
5929 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5930 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5931 return 0;
5932 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005933 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005934
5935 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5936 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5937 // C2 (CI). By solving for X we can turn this into a range check
5938 // instead of computing a divide.
5939 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5940
5941 // Determine if the product overflows by seeing if the product is
5942 // not equal to the divide. Make sure we do the same kind of divide
5943 // as in the LHS instruction that we're folding.
5944 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5945 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5946
5947 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005948 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005949
Chris Lattner1dbfd482007-06-21 18:11:19 +00005950 // Figure out the interval that is being checked. For example, a comparison
5951 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5952 // Compute this interval based on the constants involved and the signedness of
5953 // the compare/divide. This computes a half-open interval, keeping track of
5954 // whether either value in the interval overflows. After analysis each
5955 // overflow variable is set to 0 if it's corresponding bound variable is valid
5956 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5957 int LoOverflow = 0, HiOverflow = 0;
5958 ConstantInt *LoBound = 0, *HiBound = 0;
5959
5960
Chris Lattner562ef782007-06-20 23:46:26 +00005961 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005962 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005963 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005964 HiOverflow = LoOverflow = ProdOV;
5965 if (!HiOverflow)
5966 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005967 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005968 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005969 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005970 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5971 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005972 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005973 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5974 HiOverflow = LoOverflow = ProdOV;
5975 if (!HiOverflow)
5976 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005977 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005978 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005979 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5980 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005981 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005982 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005983 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005984 }
Dan Gohman76491272008-02-13 22:09:18 +00005985 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005986 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005987 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005988 LoBound = AddOne(DivRHS);
5989 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005990 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5991 HiOverflow = 1; // [INTMIN+1, overflow)
5992 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5993 }
Dan Gohman76491272008-02-13 22:09:18 +00005994 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005995 // e.g. X/-5 op 3 --> [-19, -14)
5996 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005997 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005998 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005999 HiBound = AddOne(Prod);
6000 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006001 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006002 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006003 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006004 HiBound = Subtract(Prod, DivRHS);
6005 }
6006
Chris Lattner1dbfd482007-06-21 18:11:19 +00006007 // Dividing by a negative swaps the condition. LT <-> GT
6008 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006009 }
6010
6011 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006012 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006013 default: assert(0 && "Unhandled icmp opcode!");
6014 case ICmpInst::ICMP_EQ:
6015 if (LoOverflow && HiOverflow)
6016 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6017 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006018 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006019 ICmpInst::ICMP_UGE, X, LoBound);
6020 else if (LoOverflow)
6021 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6022 ICmpInst::ICMP_ULT, X, HiBound);
6023 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006024 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006025 case ICmpInst::ICMP_NE:
6026 if (LoOverflow && HiOverflow)
6027 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6028 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006029 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006030 ICmpInst::ICMP_ULT, X, LoBound);
6031 else if (LoOverflow)
6032 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6033 ICmpInst::ICMP_UGE, X, HiBound);
6034 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006035 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006036 case ICmpInst::ICMP_ULT:
6037 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006038 if (LoOverflow == +1) // Low bound is greater than input range.
6039 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6040 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006041 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006042 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006043 case ICmpInst::ICMP_UGT:
6044 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006045 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006046 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006047 else if (HiOverflow == -1) // High bound less than input range.
6048 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6049 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006050 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6051 else
6052 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6053 }
6054}
6055
6056
Chris Lattner01deb9d2007-04-03 17:43:25 +00006057/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6058///
6059Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6060 Instruction *LHSI,
6061 ConstantInt *RHS) {
6062 const APInt &RHSV = RHS->getValue();
6063
6064 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00006065 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006066 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6067 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6068 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006069 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6070 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006071 Value *CompareVal = LHSI->getOperand(0);
6072
6073 // If the sign bit of the XorCST is not set, there is no change to
6074 // the operation, just stop using the Xor.
6075 if (!XorCST->getValue().isNegative()) {
6076 ICI.setOperand(0, CompareVal);
6077 AddToWorkList(LHSI);
6078 return &ICI;
6079 }
6080
6081 // Was the old condition true if the operand is positive?
6082 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6083
6084 // If so, the new one isn't.
6085 isTrueIfPositive ^= true;
6086
6087 if (isTrueIfPositive)
6088 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6089 else
6090 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6091 }
6092 }
6093 break;
6094 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6095 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6096 LHSI->getOperand(0)->hasOneUse()) {
6097 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6098
6099 // If the LHS is an AND of a truncating cast, we can widen the
6100 // and/compare to be the input width without changing the value
6101 // produced, eliminating a cast.
6102 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6103 // We can do this transformation if either the AND constant does not
6104 // have its sign bit set or if it is an equality comparison.
6105 // Extending a relational comparison when we're checking the sign
6106 // bit would not work.
6107 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006108 (ICI.isEquality() ||
6109 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006110 uint32_t BitWidth =
6111 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6112 APInt NewCST = AndCST->getValue();
6113 NewCST.zext(BitWidth);
6114 APInt NewCI = RHSV;
6115 NewCI.zext(BitWidth);
6116 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006117 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006118 ConstantInt::get(NewCST),LHSI->getName());
6119 InsertNewInstBefore(NewAnd, ICI);
6120 return new ICmpInst(ICI.getPredicate(), NewAnd,
6121 ConstantInt::get(NewCI));
6122 }
6123 }
6124
6125 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6126 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6127 // happens a LOT in code produced by the C front-end, for bitfield
6128 // access.
6129 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6130 if (Shift && !Shift->isShift())
6131 Shift = 0;
6132
6133 ConstantInt *ShAmt;
6134 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6135 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6136 const Type *AndTy = AndCST->getType(); // Type of the and.
6137
6138 // We can fold this as long as we can't shift unknown bits
6139 // into the mask. This can only happen with signed shift
6140 // rights, as they sign-extend.
6141 if (ShAmt) {
6142 bool CanFold = Shift->isLogicalShift();
6143 if (!CanFold) {
6144 // To test for the bad case of the signed shr, see if any
6145 // of the bits shifted in could be tested after the mask.
6146 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6147 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6148
6149 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6150 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6151 AndCST->getValue()) == 0)
6152 CanFold = true;
6153 }
6154
6155 if (CanFold) {
6156 Constant *NewCst;
6157 if (Shift->getOpcode() == Instruction::Shl)
6158 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6159 else
6160 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6161
6162 // Check to see if we are shifting out any of the bits being
6163 // compared.
6164 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6165 // If we shifted bits out, the fold is not going to work out.
6166 // As a special case, check to see if this means that the
6167 // result is always true or false now.
6168 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6169 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6170 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6171 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6172 } else {
6173 ICI.setOperand(1, NewCst);
6174 Constant *NewAndCST;
6175 if (Shift->getOpcode() == Instruction::Shl)
6176 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6177 else
6178 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6179 LHSI->setOperand(1, NewAndCST);
6180 LHSI->setOperand(0, Shift->getOperand(0));
6181 AddToWorkList(Shift); // Shift is dead.
6182 AddUsesToWorkList(ICI);
6183 return &ICI;
6184 }
6185 }
6186 }
6187
6188 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6189 // preferable because it allows the C<<Y expression to be hoisted out
6190 // of a loop if Y is invariant and X is not.
6191 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6192 ICI.isEquality() && !Shift->isArithmeticShift() &&
6193 isa<Instruction>(Shift->getOperand(0))) {
6194 // Compute C << Y.
6195 Value *NS;
6196 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006197 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006198 Shift->getOperand(1), "tmp");
6199 } else {
6200 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006201 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006202 Shift->getOperand(1), "tmp");
6203 }
6204 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6205
6206 // Compute X & (C << Y).
6207 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006208 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006209 InsertNewInstBefore(NewAnd, ICI);
6210
6211 ICI.setOperand(0, NewAnd);
6212 return &ICI;
6213 }
6214 }
6215 break;
6216
Chris Lattnera0141b92007-07-15 20:42:37 +00006217 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6218 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6219 if (!ShAmt) break;
6220
6221 uint32_t TypeBits = RHSV.getBitWidth();
6222
6223 // Check that the shift amount is in range. If not, don't perform
6224 // undefined shifts. When the shift is visited it will be
6225 // simplified.
6226 if (ShAmt->uge(TypeBits))
6227 break;
6228
6229 if (ICI.isEquality()) {
6230 // If we are comparing against bits always shifted out, the
6231 // comparison cannot succeed.
6232 Constant *Comp =
6233 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6234 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6235 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6236 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6237 return ReplaceInstUsesWith(ICI, Cst);
6238 }
6239
6240 if (LHSI->hasOneUse()) {
6241 // Otherwise strength reduce the shift into an and.
6242 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6243 Constant *Mask =
6244 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006245
Chris Lattnera0141b92007-07-15 20:42:37 +00006246 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006247 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006248 Mask, LHSI->getName()+".mask");
6249 Value *And = InsertNewInstBefore(AndI, ICI);
6250 return new ICmpInst(ICI.getPredicate(), And,
6251 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006252 }
6253 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006254
6255 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6256 bool TrueIfSigned = false;
6257 if (LHSI->hasOneUse() &&
6258 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6259 // (X << 31) <s 0 --> (X&1) != 0
6260 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6261 (TypeBits-ShAmt->getZExtValue()-1));
6262 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006263 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006264 Mask, LHSI->getName()+".mask");
6265 Value *And = InsertNewInstBefore(AndI, ICI);
6266
6267 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6268 And, Constant::getNullValue(And->getType()));
6269 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006270 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006271 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006272
6273 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006274 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006275 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006276 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006277 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006278
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006279 // Check that the shift amount is in range. If not, don't perform
6280 // undefined shifts. When the shift is visited it will be
6281 // simplified.
6282 uint32_t TypeBits = RHSV.getBitWidth();
6283 if (ShAmt->uge(TypeBits))
6284 break;
6285
6286 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006287
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006288 // If we are comparing against bits always shifted out, the
6289 // comparison cannot succeed.
6290 APInt Comp = RHSV << ShAmtVal;
6291 if (LHSI->getOpcode() == Instruction::LShr)
6292 Comp = Comp.lshr(ShAmtVal);
6293 else
6294 Comp = Comp.ashr(ShAmtVal);
6295
6296 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6297 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6298 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6299 return ReplaceInstUsesWith(ICI, Cst);
6300 }
6301
6302 // Otherwise, check to see if the bits shifted out are known to be zero.
6303 // If so, we can compare against the unshifted value:
6304 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006305 if (LHSI->hasOneUse() &&
6306 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006307 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6308 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6309 ConstantExpr::getShl(RHS, ShAmt));
6310 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006311
Evan Chengf30752c2008-04-23 00:38:06 +00006312 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006313 // Otherwise strength reduce the shift into an and.
6314 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6315 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006316
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006317 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006318 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006319 Mask, LHSI->getName()+".mask");
6320 Value *And = InsertNewInstBefore(AndI, ICI);
6321 return new ICmpInst(ICI.getPredicate(), And,
6322 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006323 }
6324 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006325 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006326
6327 case Instruction::SDiv:
6328 case Instruction::UDiv:
6329 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6330 // Fold this div into the comparison, producing a range check.
6331 // Determine, based on the divide type, what the range is being
6332 // checked. If there is an overflow on the low or high side, remember
6333 // it, otherwise compute the range [low, hi) bounding the new value.
6334 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006335 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6336 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6337 DivRHS))
6338 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006339 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006340
6341 case Instruction::Add:
6342 // Fold: icmp pred (add, X, C1), C2
6343
6344 if (!ICI.isEquality()) {
6345 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6346 if (!LHSC) break;
6347 const APInt &LHSV = LHSC->getValue();
6348
6349 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6350 .subtract(LHSV);
6351
6352 if (ICI.isSignedPredicate()) {
6353 if (CR.getLower().isSignBit()) {
6354 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6355 ConstantInt::get(CR.getUpper()));
6356 } else if (CR.getUpper().isSignBit()) {
6357 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6358 ConstantInt::get(CR.getLower()));
6359 }
6360 } else {
6361 if (CR.getLower().isMinValue()) {
6362 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6363 ConstantInt::get(CR.getUpper()));
6364 } else if (CR.getUpper().isMinValue()) {
6365 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6366 ConstantInt::get(CR.getLower()));
6367 }
6368 }
6369 }
6370 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006371 }
6372
6373 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6374 if (ICI.isEquality()) {
6375 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6376
6377 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6378 // the second operand is a constant, simplify a bit.
6379 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6380 switch (BO->getOpcode()) {
6381 case Instruction::SRem:
6382 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6383 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6384 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6385 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6386 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006387 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006388 BO->getName());
6389 InsertNewInstBefore(NewRem, ICI);
6390 return new ICmpInst(ICI.getPredicate(), NewRem,
6391 Constant::getNullValue(BO->getType()));
6392 }
6393 }
6394 break;
6395 case Instruction::Add:
6396 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6397 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6398 if (BO->hasOneUse())
6399 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6400 Subtract(RHS, BOp1C));
6401 } else if (RHSV == 0) {
6402 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6403 // efficiently invertible, or if the add has just this one use.
6404 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6405
6406 if (Value *NegVal = dyn_castNegVal(BOp1))
6407 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6408 else if (Value *NegVal = dyn_castNegVal(BOp0))
6409 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6410 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006411 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006412 InsertNewInstBefore(Neg, ICI);
6413 Neg->takeName(BO);
6414 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6415 }
6416 }
6417 break;
6418 case Instruction::Xor:
6419 // For the xor case, we can xor two constants together, eliminating
6420 // the explicit xor.
6421 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6422 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6423 ConstantExpr::getXor(RHS, BOC));
6424
6425 // FALLTHROUGH
6426 case Instruction::Sub:
6427 // Replace (([sub|xor] A, B) != 0) with (A != B)
6428 if (RHSV == 0)
6429 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6430 BO->getOperand(1));
6431 break;
6432
6433 case Instruction::Or:
6434 // If bits are being or'd in that are not present in the constant we
6435 // are comparing against, then the comparison could never succeed!
6436 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6437 Constant *NotCI = ConstantExpr::getNot(RHS);
6438 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6439 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6440 isICMP_NE));
6441 }
6442 break;
6443
6444 case Instruction::And:
6445 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6446 // If bits are being compared against that are and'd out, then the
6447 // comparison can never succeed!
6448 if ((RHSV & ~BOC->getValue()) != 0)
6449 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6450 isICMP_NE));
6451
6452 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6453 if (RHS == BOC && RHSV.isPowerOf2())
6454 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6455 ICmpInst::ICMP_NE, LHSI,
6456 Constant::getNullValue(RHS->getType()));
6457
6458 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6459 if (isSignBit(BOC)) {
6460 Value *X = BO->getOperand(0);
6461 Constant *Zero = Constant::getNullValue(X->getType());
6462 ICmpInst::Predicate pred = isICMP_NE ?
6463 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6464 return new ICmpInst(pred, X, Zero);
6465 }
6466
6467 // ((X & ~7) == 0) --> X < 8
6468 if (RHSV == 0 && isHighOnes(BOC)) {
6469 Value *X = BO->getOperand(0);
6470 Constant *NegX = ConstantExpr::getNeg(BOC);
6471 ICmpInst::Predicate pred = isICMP_NE ?
6472 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6473 return new ICmpInst(pred, X, NegX);
6474 }
6475 }
6476 default: break;
6477 }
6478 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6479 // Handle icmp {eq|ne} <intrinsic>, intcst.
6480 if (II->getIntrinsicID() == Intrinsic::bswap) {
6481 AddToWorkList(II);
6482 ICI.setOperand(0, II->getOperand(1));
6483 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6484 return &ICI;
6485 }
6486 }
6487 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006488 // If the LHS is a cast from an integral value of the same size,
6489 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006490 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6491 Value *CastOp = Cast->getOperand(0);
6492 const Type *SrcTy = CastOp->getType();
6493 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6494 if (SrcTy->isInteger() &&
6495 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6496 // If this is an unsigned comparison, try to make the comparison use
6497 // smaller constant values.
6498 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6499 // X u< 128 => X s> -1
6500 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6501 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6502 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6503 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6504 // X u> 127 => X s< 0
6505 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6506 Constant::getNullValue(SrcTy));
6507 }
6508 }
6509 }
6510 }
6511 return 0;
6512}
6513
6514/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6515/// We only handle extending casts so far.
6516///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006517Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6518 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006519 Value *LHSCIOp = LHSCI->getOperand(0);
6520 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006521 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006522 Value *RHSCIOp;
6523
Chris Lattner8c756c12007-05-05 22:41:33 +00006524 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6525 // integer type is the same size as the pointer type.
6526 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6527 getTargetData().getPointerSizeInBits() ==
6528 cast<IntegerType>(DestTy)->getBitWidth()) {
6529 Value *RHSOp = 0;
6530 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006531 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006532 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6533 RHSOp = RHSC->getOperand(0);
6534 // If the pointer types don't match, insert a bitcast.
6535 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006536 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006537 }
6538
6539 if (RHSOp)
6540 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6541 }
6542
6543 // The code below only handles extension cast instructions, so far.
6544 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006545 if (LHSCI->getOpcode() != Instruction::ZExt &&
6546 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006547 return 0;
6548
Reid Spencere4d87aa2006-12-23 06:05:41 +00006549 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6550 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006551
Reid Spencere4d87aa2006-12-23 06:05:41 +00006552 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006553 // Not an extension from the same type?
6554 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006555 if (RHSCIOp->getType() != LHSCIOp->getType())
6556 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006557
Nick Lewycky4189a532008-01-28 03:48:02 +00006558 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006559 // and the other is a zext), then we can't handle this.
6560 if (CI->getOpcode() != LHSCI->getOpcode())
6561 return 0;
6562
Nick Lewycky4189a532008-01-28 03:48:02 +00006563 // Deal with equality cases early.
6564 if (ICI.isEquality())
6565 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6566
6567 // A signed comparison of sign extended values simplifies into a
6568 // signed comparison.
6569 if (isSignedCmp && isSignedExt)
6570 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6571
6572 // The other three cases all fold into an unsigned comparison.
6573 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006574 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006575
Reid Spencere4d87aa2006-12-23 06:05:41 +00006576 // If we aren't dealing with a constant on the RHS, exit early
6577 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6578 if (!CI)
6579 return 0;
6580
6581 // Compute the constant that would happen if we truncated to SrcTy then
6582 // reextended to DestTy.
6583 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6584 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6585
6586 // If the re-extended constant didn't change...
6587 if (Res2 == CI) {
6588 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6589 // For example, we might have:
6590 // %A = sext short %X to uint
6591 // %B = icmp ugt uint %A, 1330
6592 // It is incorrect to transform this into
6593 // %B = icmp ugt short %X, 1330
6594 // because %A may have negative value.
6595 //
6596 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6597 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006598 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006599 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6600 else
6601 return 0;
6602 }
6603
6604 // The re-extended constant changed so the constant cannot be represented
6605 // in the shorter type. Consequently, we cannot emit a simple comparison.
6606
6607 // First, handle some easy cases. We know the result cannot be equal at this
6608 // point so handle the ICI.isEquality() cases
6609 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006610 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006611 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006612 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006613
6614 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6615 // should have been folded away previously and not enter in here.
6616 Value *Result;
6617 if (isSignedCmp) {
6618 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006619 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006620 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006621 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006622 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006623 } else {
6624 // We're performing an unsigned comparison.
6625 if (isSignedExt) {
6626 // We're performing an unsigned comp with a sign extended value.
6627 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006628 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006629 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6630 NegOne, ICI.getName()), ICI);
6631 } else {
6632 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006633 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006634 }
6635 }
6636
6637 // Finally, return the value computed.
6638 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6639 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6640 return ReplaceInstUsesWith(ICI, Result);
6641 } else {
6642 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6643 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6644 "ICmp should be folded!");
6645 if (Constant *CI = dyn_cast<Constant>(Result))
6646 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6647 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006648 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006649 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006650}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006651
Reid Spencer832254e2007-02-02 02:16:23 +00006652Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6653 return commonShiftTransforms(I);
6654}
6655
6656Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6657 return commonShiftTransforms(I);
6658}
6659
6660Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006661 if (Instruction *R = commonShiftTransforms(I))
6662 return R;
6663
6664 Value *Op0 = I.getOperand(0);
6665
6666 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6667 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6668 if (CSI->isAllOnesValue())
6669 return ReplaceInstUsesWith(I, CSI);
6670
6671 // See if we can turn a signed shr into an unsigned shr.
6672 if (MaskedValueIsZero(Op0,
6673 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006674 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006675
6676 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006677}
6678
6679Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6680 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006681 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006682
6683 // shl X, 0 == X and shr X, 0 == X
6684 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006685 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006686 Op0 == Constant::getNullValue(Op0->getType()))
6687 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006688
Reid Spencere4d87aa2006-12-23 06:05:41 +00006689 if (isa<UndefValue>(Op0)) {
6690 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006691 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006692 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006693 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6694 }
6695 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006696 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6697 return ReplaceInstUsesWith(I, Op0);
6698 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006699 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006700 }
6701
Chris Lattner2eefe512004-04-09 19:05:30 +00006702 // Try to fold constant and into select arguments.
6703 if (isa<Constant>(Op0))
6704 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006705 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006706 return R;
6707
Reid Spencerb83eb642006-10-20 07:07:24 +00006708 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006709 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6710 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006711 return 0;
6712}
6713
Reid Spencerb83eb642006-10-20 07:07:24 +00006714Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006715 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006716 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006717
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006718 // See if we can simplify any instructions used by the instruction whose sole
6719 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006720 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6721 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6722 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006723 KnownZero, KnownOne))
6724 return &I;
6725
Chris Lattner4d5542c2006-01-06 07:12:35 +00006726 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6727 // of a signed value.
6728 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006729 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006730 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006731 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6732 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006733 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006734 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006735 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006736 }
6737
6738 // ((X*C1) << C2) == (X * (C1 << C2))
6739 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6740 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6741 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006742 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006743 ConstantExpr::getShl(BOOp, Op1));
6744
6745 // Try to fold constant and into select arguments.
6746 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6747 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6748 return R;
6749 if (isa<PHINode>(Op0))
6750 if (Instruction *NV = FoldOpIntoPhi(I))
6751 return NV;
6752
Chris Lattner8999dd32007-12-22 09:07:47 +00006753 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6754 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6755 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6756 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6757 // place. Don't try to do this transformation in this case. Also, we
6758 // require that the input operand is a shift-by-constant so that we have
6759 // confidence that the shifts will get folded together. We could do this
6760 // xform in more cases, but it is unlikely to be profitable.
6761 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6762 isa<ConstantInt>(TrOp->getOperand(1))) {
6763 // Okay, we'll do this xform. Make the shift of shift.
6764 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006765 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00006766 I.getName());
6767 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6768
6769 // For logical shifts, the truncation has the effect of making the high
6770 // part of the register be zeros. Emulate this by inserting an AND to
6771 // clear the top bits as needed. This 'and' will usually be zapped by
6772 // other xforms later if dead.
6773 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6774 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6775 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6776
6777 // The mask we constructed says what the trunc would do if occurring
6778 // between the shifts. We want to know the effect *after* the second
6779 // shift. We know that it is a logical shift by a constant, so adjust the
6780 // mask as appropriate.
6781 if (I.getOpcode() == Instruction::Shl)
6782 MaskV <<= Op1->getZExtValue();
6783 else {
6784 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6785 MaskV = MaskV.lshr(Op1->getZExtValue());
6786 }
6787
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006788 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00006789 TI->getName());
6790 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6791
6792 // Return the value truncated to the interesting size.
6793 return new TruncInst(And, I.getType());
6794 }
6795 }
6796
Chris Lattner4d5542c2006-01-06 07:12:35 +00006797 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006798 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6799 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6800 Value *V1, *V2;
6801 ConstantInt *CC;
6802 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006803 default: break;
6804 case Instruction::Add:
6805 case Instruction::And:
6806 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006807 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006808 // These operators commute.
6809 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006810 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6811 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006812 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006813 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006814 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006815 Op0BO->getName());
6816 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006817 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006818 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006819 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006820 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006821 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006822 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006823 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006824 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006825
Chris Lattner150f12a2005-09-18 06:30:59 +00006826 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006827 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006828 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006829 match(Op0BOOp1,
6830 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006831 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6832 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006833 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006834 Op0BO->getOperand(0), Op1,
6835 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006836 InsertNewInstBefore(YS, I); // (Y << C)
6837 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006838 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006839 V1->getName()+".mask");
6840 InsertNewInstBefore(XM, I); // X & (CC << C)
6841
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006842 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00006843 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006844 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006845
Reid Spencera07cb7d2007-02-02 14:41:37 +00006846 // FALL THROUGH.
6847 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006848 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006849 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6850 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006851 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006852 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006853 Op0BO->getOperand(1), Op1,
6854 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006855 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006856 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006857 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006858 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006859 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006860 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006861 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006862 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006863 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006864
Chris Lattner13d4ab42006-05-31 21:14:00 +00006865 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006866 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6867 match(Op0BO->getOperand(0),
6868 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006869 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006870 cast<BinaryOperator>(Op0BO->getOperand(0))
6871 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006872 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006873 Op0BO->getOperand(1), Op1,
6874 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006875 InsertNewInstBefore(YS, I); // (Y << C)
6876 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006877 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006878 V1->getName()+".mask");
6879 InsertNewInstBefore(XM, I); // X & (CC << C)
6880
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006881 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006882 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006883
Chris Lattner11021cb2005-09-18 05:12:10 +00006884 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006885 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006886 }
6887
6888
6889 // If the operand is an bitwise operator with a constant RHS, and the
6890 // shift is the only use, we can pull it out of the shift.
6891 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6892 bool isValid = true; // Valid only for And, Or, Xor
6893 bool highBitSet = false; // Transform if high bit of constant set?
6894
6895 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006896 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006897 case Instruction::Add:
6898 isValid = isLeftShift;
6899 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006900 case Instruction::Or:
6901 case Instruction::Xor:
6902 highBitSet = false;
6903 break;
6904 case Instruction::And:
6905 highBitSet = true;
6906 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006907 }
6908
6909 // If this is a signed shift right, and the high bit is modified
6910 // by the logical operation, do not perform the transformation.
6911 // The highBitSet boolean indicates the value of the high bit of
6912 // the constant which would cause it to be modified for this
6913 // operation.
6914 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006915 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006916 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006917
6918 if (isValid) {
6919 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6920
6921 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006922 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006923 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006924 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006925
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006926 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00006927 NewRHS);
6928 }
6929 }
6930 }
6931 }
6932
Chris Lattnerad0124c2006-01-06 07:52:12 +00006933 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006934 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6935 if (ShiftOp && !ShiftOp->isShift())
6936 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006937
Reid Spencerb83eb642006-10-20 07:07:24 +00006938 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006939 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006940 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6941 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006942 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6943 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6944 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006945
Zhou Sheng4351c642007-04-02 08:20:41 +00006946 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006947 if (AmtSum > TypeBits)
6948 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006949
6950 const IntegerType *Ty = cast<IntegerType>(I.getType());
6951
6952 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006953 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006954 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006955 ConstantInt::get(Ty, AmtSum));
6956 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6957 I.getOpcode() == Instruction::AShr) {
6958 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006959 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006960 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6961 I.getOpcode() == Instruction::LShr) {
6962 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6963 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006964 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006965 InsertNewInstBefore(Shift, I);
6966
Zhou Shenge9e03f62007-03-28 15:02:20 +00006967 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006968 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006969 }
6970
Chris Lattnerb87056f2007-02-05 00:57:54 +00006971 // Okay, if we get here, one shift must be left, and the other shift must be
6972 // right. See if the amounts are equal.
6973 if (ShiftAmt1 == ShiftAmt2) {
6974 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6975 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006976 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006977 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006978 }
6979 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6980 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006981 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006982 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006983 }
6984 // We can simplify ((X << C) >>s C) into a trunc + sext.
6985 // NOTE: we could do this for any C, but that would make 'unusual' integer
6986 // types. For now, just stick to ones well-supported by the code
6987 // generators.
6988 const Type *SExtType = 0;
6989 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006990 case 1 :
6991 case 8 :
6992 case 16 :
6993 case 32 :
6994 case 64 :
6995 case 128:
6996 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6997 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006998 default: break;
6999 }
7000 if (SExtType) {
7001 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7002 InsertNewInstBefore(NewTrunc, I);
7003 return new SExtInst(NewTrunc, Ty);
7004 }
7005 // Otherwise, we can't handle it yet.
7006 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007007 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007008
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007009 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007010 if (I.getOpcode() == Instruction::Shl) {
7011 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7012 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007013 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007014 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007015 InsertNewInstBefore(Shift, I);
7016
Reid Spencer55702aa2007-03-25 21:11:44 +00007017 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007018 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007019 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007020
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007021 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007022 if (I.getOpcode() == Instruction::LShr) {
7023 assert(ShiftOp->getOpcode() == Instruction::Shl);
7024 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007025 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007026 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007027
Reid Spencerd5e30f02007-03-26 17:18:58 +00007028 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007029 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007030 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007031
7032 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7033 } else {
7034 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007035 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007036
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007037 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007038 if (I.getOpcode() == Instruction::Shl) {
7039 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7040 ShiftOp->getOpcode() == Instruction::AShr);
7041 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007042 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007043 ConstantInt::get(Ty, ShiftDiff));
7044 InsertNewInstBefore(Shift, I);
7045
Reid Spencer55702aa2007-03-25 21:11:44 +00007046 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007047 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007048 }
7049
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007050 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007051 if (I.getOpcode() == Instruction::LShr) {
7052 assert(ShiftOp->getOpcode() == Instruction::Shl);
7053 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007054 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007055 InsertNewInstBefore(Shift, I);
7056
Reid Spencer68d27cf2007-03-26 23:45:51 +00007057 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007058 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007059 }
7060
7061 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007062 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007063 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007064 return 0;
7065}
7066
Chris Lattnera1be5662002-05-02 17:06:02 +00007067
Chris Lattnercfd65102005-10-29 04:36:15 +00007068/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7069/// expression. If so, decompose it, returning some value X, such that Val is
7070/// X*Scale+Offset.
7071///
7072static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007073 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007074 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007075 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007076 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007077 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007078 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007079 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7080 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7081 if (I->getOpcode() == Instruction::Shl) {
7082 // This is a value scaled by '1 << the shift amt'.
7083 Scale = 1U << RHS->getZExtValue();
7084 Offset = 0;
7085 return I->getOperand(0);
7086 } else if (I->getOpcode() == Instruction::Mul) {
7087 // This value is scaled by 'RHS'.
7088 Scale = RHS->getZExtValue();
7089 Offset = 0;
7090 return I->getOperand(0);
7091 } else if (I->getOpcode() == Instruction::Add) {
7092 // We have X+C. Check to see if we really have (X*C2)+C1,
7093 // where C1 is divisible by C2.
7094 unsigned SubScale;
7095 Value *SubVal =
7096 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7097 Offset += RHS->getZExtValue();
7098 Scale = SubScale;
7099 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007100 }
7101 }
7102 }
7103
7104 // Otherwise, we can't look past this.
7105 Scale = 1;
7106 Offset = 0;
7107 return Val;
7108}
7109
7110
Chris Lattnerb3f83972005-10-24 06:03:58 +00007111/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7112/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007113Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007114 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007115 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007116
Chris Lattnerb53c2382005-10-24 06:22:12 +00007117 // Remove any uses of AI that are dead.
7118 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007119
Chris Lattnerb53c2382005-10-24 06:22:12 +00007120 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7121 Instruction *User = cast<Instruction>(*UI++);
7122 if (isInstructionTriviallyDead(User)) {
7123 while (UI != E && *UI == User)
7124 ++UI; // If this instruction uses AI more than once, don't break UI.
7125
Chris Lattnerb53c2382005-10-24 06:22:12 +00007126 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007127 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007128 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007129 }
7130 }
7131
Chris Lattnerb3f83972005-10-24 06:03:58 +00007132 // Get the type really allocated and the type casted to.
7133 const Type *AllocElTy = AI.getAllocatedType();
7134 const Type *CastElTy = PTy->getElementType();
7135 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007136
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007137 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7138 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007139 if (CastElTyAlign < AllocElTyAlign) return 0;
7140
Chris Lattner39387a52005-10-24 06:35:18 +00007141 // If the allocation has multiple uses, only promote it if we are strictly
7142 // increasing the alignment of the resultant allocation. If we keep it the
7143 // same, we open the door to infinite loops of various kinds.
7144 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7145
Duncan Sands514ab342007-11-01 20:53:16 +00007146 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7147 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007148 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007149
Chris Lattner455fcc82005-10-29 03:19:53 +00007150 // See if we can satisfy the modulus by pulling a scale out of the array
7151 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007152 unsigned ArraySizeScale;
7153 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007154 Value *NumElements = // See if the array size is a decomposable linear expr.
7155 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7156
Chris Lattner455fcc82005-10-29 03:19:53 +00007157 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7158 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007159 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7160 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007161
Chris Lattner455fcc82005-10-29 03:19:53 +00007162 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7163 Value *Amt = 0;
7164 if (Scale == 1) {
7165 Amt = NumElements;
7166 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007167 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007168 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7169 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007170 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007171 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007172 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007173 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007174 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007175 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007176 }
7177
Jeff Cohen86796be2007-04-04 16:58:57 +00007178 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7179 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007180 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007181 Amt = InsertNewInstBefore(Tmp, AI);
7182 }
7183
Chris Lattnerb3f83972005-10-24 06:03:58 +00007184 AllocationInst *New;
7185 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007186 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007187 else
Chris Lattner6934a042007-02-11 01:23:03 +00007188 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007189 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007190 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007191
7192 // If the allocation has multiple uses, insert a cast and change all things
7193 // that used it to use the new cast. This will also hack on CI, but it will
7194 // die soon.
7195 if (!AI.hasOneUse()) {
7196 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007197 // New is the allocation instruction, pointer typed. AI is the original
7198 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7199 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007200 InsertNewInstBefore(NewCast, AI);
7201 AI.replaceAllUsesWith(NewCast);
7202 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007203 return ReplaceInstUsesWith(CI, New);
7204}
7205
Chris Lattner70074e02006-05-13 02:06:03 +00007206/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007207/// and return it as type Ty without inserting any new casts and without
7208/// changing the computed value. This is used by code that tries to decide
7209/// whether promoting or shrinking integer operations to wider or smaller types
7210/// will allow us to eliminate a truncate or extend.
7211///
7212/// This is a truncation operation if Ty is smaller than V->getType(), or an
7213/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00007214bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7215 unsigned CastOpc,
7216 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007217 // We can always evaluate constants in another type.
7218 if (isa<ConstantInt>(V))
7219 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007220
7221 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007222 if (!I) return false;
7223
7224 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007225
Chris Lattner951626b2007-08-02 06:11:14 +00007226 // If this is an extension or truncate, we can often eliminate it.
7227 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7228 // If this is a cast from the destination type, we can trivially eliminate
7229 // it, and this will remove a cast overall.
7230 if (I->getOperand(0)->getType() == Ty) {
7231 // If the first operand is itself a cast, and is eliminable, do not count
7232 // this as an eliminable cast. We would prefer to eliminate those two
7233 // casts first.
7234 if (!isa<CastInst>(I->getOperand(0)))
7235 ++NumCastsRemoved;
7236 return true;
7237 }
7238 }
7239
7240 // We can't extend or shrink something that has multiple uses: doing so would
7241 // require duplicating the instruction in general, which isn't profitable.
7242 if (!I->hasOneUse()) return false;
7243
Chris Lattner70074e02006-05-13 02:06:03 +00007244 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007245 case Instruction::Add:
7246 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00007247 case Instruction::And:
7248 case Instruction::Or:
7249 case Instruction::Xor:
7250 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007251 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7252 NumCastsRemoved) &&
7253 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7254 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007255
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007256 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007257 // A multiply can be truncated by truncating its operands.
7258 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7259 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7260 NumCastsRemoved) &&
7261 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7262 NumCastsRemoved);
7263
Chris Lattner46b96052006-11-29 07:18:39 +00007264 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007265 // If we are truncating the result of this SHL, and if it's a shift of a
7266 // constant amount, we can always perform a SHL in a smaller type.
7267 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007268 uint32_t BitWidth = Ty->getBitWidth();
7269 if (BitWidth < OrigTy->getBitWidth() &&
7270 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007271 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7272 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007273 }
7274 break;
7275 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007276 // If this is a truncate of a logical shr, we can truncate it to a smaller
7277 // lshr iff we know that the bits we would otherwise be shifting in are
7278 // already zeros.
7279 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007280 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7281 uint32_t BitWidth = Ty->getBitWidth();
7282 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007283 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007284 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7285 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007286 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7287 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007288 }
7289 }
Chris Lattner46b96052006-11-29 07:18:39 +00007290 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007291 case Instruction::ZExt:
7292 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007293 case Instruction::Trunc:
7294 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007295 // can safely replace it. Note that replacing it does not reduce the number
7296 // of casts in the input.
7297 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007298 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00007299
Reid Spencer3da59db2006-11-27 01:05:10 +00007300 break;
7301 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007302 // TODO: Can handle more cases here.
7303 break;
7304 }
7305
7306 return false;
7307}
7308
7309/// EvaluateInDifferentType - Given an expression that
7310/// CanEvaluateInDifferentType returns true for, actually insert the code to
7311/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007312Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007313 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007314 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007315 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007316
7317 // Otherwise, it must be an instruction.
7318 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007319 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007320 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007321 case Instruction::Add:
7322 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007323 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007324 case Instruction::And:
7325 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007326 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007327 case Instruction::AShr:
7328 case Instruction::LShr:
7329 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007330 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007331 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007332 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00007333 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00007334 break;
7335 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007336 case Instruction::Trunc:
7337 case Instruction::ZExt:
7338 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007339 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007340 // just return the source. There's no need to insert it because it is not
7341 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007342 if (I->getOperand(0)->getType() == Ty)
7343 return I->getOperand(0);
7344
Chris Lattner951626b2007-08-02 06:11:14 +00007345 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007346 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00007347 Ty, I->getName());
7348 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007349 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007350 // TODO: Can handle more cases here.
7351 assert(0 && "Unreachable!");
7352 break;
7353 }
7354
7355 return InsertNewInstBefore(Res, *I);
7356}
7357
Reid Spencer3da59db2006-11-27 01:05:10 +00007358/// @brief Implement the transforms common to all CastInst visitors.
7359Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007360 Value *Src = CI.getOperand(0);
7361
Dan Gohman23d9d272007-05-11 21:10:54 +00007362 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007363 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007364 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007365 if (Instruction::CastOps opc =
7366 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7367 // The first cast (CSrc) is eliminable so we need to fix up or replace
7368 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007369 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007370 }
7371 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007372
Reid Spencer3da59db2006-11-27 01:05:10 +00007373 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007374 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7375 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7376 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007377
7378 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007379 if (isa<PHINode>(Src))
7380 if (Instruction *NV = FoldOpIntoPhi(CI))
7381 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007382
Reid Spencer3da59db2006-11-27 01:05:10 +00007383 return 0;
7384}
7385
Chris Lattnerd3e28342007-04-27 17:44:50 +00007386/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7387Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7388 Value *Src = CI.getOperand(0);
7389
Chris Lattnerd3e28342007-04-27 17:44:50 +00007390 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007391 // If casting the result of a getelementptr instruction with no offset, turn
7392 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007393 if (GEP->hasAllZeroIndices()) {
7394 // Changing the cast operand is usually not a good idea but it is safe
7395 // here because the pointer operand is being replaced with another
7396 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007397 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007398 CI.setOperand(0, GEP->getOperand(0));
7399 return &CI;
7400 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007401
7402 // If the GEP has a single use, and the base pointer is a bitcast, and the
7403 // GEP computes a constant offset, see if we can convert these three
7404 // instructions into fewer. This typically happens with unions and other
7405 // non-type-safe code.
7406 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7407 if (GEP->hasAllConstantIndices()) {
7408 // We are guaranteed to get a constant from EmitGEPOffset.
7409 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7410 int64_t Offset = OffsetV->getSExtValue();
7411
7412 // Get the base pointer input of the bitcast, and the type it points to.
7413 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7414 const Type *GEPIdxTy =
7415 cast<PointerType>(OrigBase->getType())->getElementType();
7416 if (GEPIdxTy->isSized()) {
7417 SmallVector<Value*, 8> NewIndices;
7418
Chris Lattnerc42e2262007-05-05 01:59:31 +00007419 // Start with the index over the outer type. Note that the type size
7420 // might be zero (even if the offset isn't zero) if the indexed type
7421 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007422 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007423 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007424 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007425 FirstIdx = Offset/TySize;
7426 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007427
Chris Lattnerc42e2262007-05-05 01:59:31 +00007428 // Handle silly modulus not returning values values [0..TySize).
7429 if (Offset < 0) {
7430 --FirstIdx;
7431 Offset += TySize;
7432 assert(Offset >= 0);
7433 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007434 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007435 }
7436
7437 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007438
7439 // Index into the types. If we fail, set OrigBase to null.
7440 while (Offset) {
7441 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7442 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007443 if (Offset < (int64_t)SL->getSizeInBytes()) {
7444 unsigned Elt = SL->getElementContainingOffset(Offset);
7445 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007446
Chris Lattner6b6aef82007-05-15 00:16:00 +00007447 Offset -= SL->getElementOffset(Elt);
7448 GEPIdxTy = STy->getElementType(Elt);
7449 } else {
7450 // Otherwise, we can't index into this, bail out.
7451 Offset = 0;
7452 OrigBase = 0;
7453 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007454 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7455 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007456 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007457 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7458 Offset %= EltSize;
7459 } else {
7460 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7461 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007462 GEPIdxTy = STy->getElementType();
7463 } else {
7464 // Otherwise, we can't index into this, bail out.
7465 Offset = 0;
7466 OrigBase = 0;
7467 }
7468 }
7469 if (OrigBase) {
7470 // If we were able to index down into an element, create the GEP
7471 // and bitcast the result. This eliminates one bitcast, potentially
7472 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007473 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7474 NewIndices.begin(),
7475 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007476 InsertNewInstBefore(NGEP, CI);
7477 NGEP->takeName(GEP);
7478
Chris Lattner9bc14642007-04-28 00:57:34 +00007479 if (isa<BitCastInst>(CI))
7480 return new BitCastInst(NGEP, CI.getType());
7481 assert(isa<PtrToIntInst>(CI));
7482 return new PtrToIntInst(NGEP, CI.getType());
7483 }
7484 }
7485 }
7486 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007487 }
7488
7489 return commonCastTransforms(CI);
7490}
7491
7492
7493
Chris Lattnerc739cd62007-03-03 05:27:34 +00007494/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7495/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007496/// cases.
7497/// @brief Implement the transforms common to CastInst with integer operands
7498Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7499 if (Instruction *Result = commonCastTransforms(CI))
7500 return Result;
7501
7502 Value *Src = CI.getOperand(0);
7503 const Type *SrcTy = Src->getType();
7504 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007505 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7506 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007507
Reid Spencer3da59db2006-11-27 01:05:10 +00007508 // See if we can simplify any instructions used by the LHS whose sole
7509 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007510 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7511 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007512 KnownZero, KnownOne))
7513 return &CI;
7514
7515 // If the source isn't an instruction or has more than one use then we
7516 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007517 Instruction *SrcI = dyn_cast<Instruction>(Src);
7518 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007519 return 0;
7520
Chris Lattnerc739cd62007-03-03 05:27:34 +00007521 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007522 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007523 if (!isa<BitCastInst>(CI) &&
7524 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007525 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007526 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007527 // eliminates the cast, so it is always a win. If this is a zero-extension,
7528 // we need to do an AND to maintain the clear top-part of the computation,
7529 // so we require that the input have eliminated at least one cast. If this
7530 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007531 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007532 bool DoXForm;
7533 switch (CI.getOpcode()) {
7534 default:
7535 // All the others use floating point so we shouldn't actually
7536 // get here because of the check above.
7537 assert(0 && "Unknown cast type");
7538 case Instruction::Trunc:
7539 DoXForm = true;
7540 break;
7541 case Instruction::ZExt:
7542 DoXForm = NumCastsRemoved >= 1;
7543 break;
7544 case Instruction::SExt:
7545 DoXForm = NumCastsRemoved >= 2;
7546 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007547 }
7548
7549 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007550 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7551 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007552 assert(Res->getType() == DestTy);
7553 switch (CI.getOpcode()) {
7554 default: assert(0 && "Unknown cast type!");
7555 case Instruction::Trunc:
7556 case Instruction::BitCast:
7557 // Just replace this cast with the result.
7558 return ReplaceInstUsesWith(CI, Res);
7559 case Instruction::ZExt: {
7560 // We need to emit an AND to clear the high bits.
7561 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007562 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7563 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007564 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007565 }
7566 case Instruction::SExt:
7567 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007568 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007569 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7570 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007571 }
7572 }
7573 }
7574
7575 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7576 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7577
7578 switch (SrcI->getOpcode()) {
7579 case Instruction::Add:
7580 case Instruction::Mul:
7581 case Instruction::And:
7582 case Instruction::Or:
7583 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007584 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007585 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7586 // Don't insert two casts if they cannot be eliminated. We allow
7587 // two casts to be inserted if the sizes are the same. This could
7588 // only be converting signedness, which is a noop.
7589 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007590 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7591 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007592 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007593 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7594 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007595 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007596 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007597 }
7598 }
7599
7600 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7601 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7602 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007603 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007604 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007605 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007606 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007607 }
7608 break;
7609 case Instruction::SDiv:
7610 case Instruction::UDiv:
7611 case Instruction::SRem:
7612 case Instruction::URem:
7613 // If we are just changing the sign, rewrite.
7614 if (DestBitSize == SrcBitSize) {
7615 // Don't insert two casts if they cannot be eliminated. We allow
7616 // two casts to be inserted if the sizes are the same. This could
7617 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007618 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7619 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007620 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7621 Op0, DestTy, SrcI);
7622 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7623 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007624 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007625 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7626 }
7627 }
7628 break;
7629
7630 case Instruction::Shl:
7631 // Allow changing the sign of the source operand. Do not allow
7632 // changing the size of the shift, UNLESS the shift amount is a
7633 // constant. We must not change variable sized shifts to a smaller
7634 // size, because it is undefined to shift more bits out than exist
7635 // in the value.
7636 if (DestBitSize == SrcBitSize ||
7637 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007638 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7639 Instruction::BitCast : Instruction::Trunc);
7640 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007641 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007642 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007643 }
7644 break;
7645 case Instruction::AShr:
7646 // If this is a signed shr, and if all bits shifted in are about to be
7647 // truncated off, turn it into an unsigned shr to allow greater
7648 // simplifications.
7649 if (DestBitSize < SrcBitSize &&
7650 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007651 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007652 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7653 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007654 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007655 }
7656 }
7657 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007658 }
7659 return 0;
7660}
7661
Chris Lattner8a9f5712007-04-11 06:57:46 +00007662Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007663 if (Instruction *Result = commonIntCastTransforms(CI))
7664 return Result;
7665
7666 Value *Src = CI.getOperand(0);
7667 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007668 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7669 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007670
7671 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7672 switch (SrcI->getOpcode()) {
7673 default: break;
7674 case Instruction::LShr:
7675 // We can shrink lshr to something smaller if we know the bits shifted in
7676 // are already zeros.
7677 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007678 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007679
7680 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007681 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007682 Value* SrcIOp0 = SrcI->getOperand(0);
7683 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007684 if (ShAmt >= DestBitWidth) // All zeros.
7685 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7686
7687 // Okay, we can shrink this. Truncate the input, then return a new
7688 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007689 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7690 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7691 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007692 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007693 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007694 } else { // This is a variable shr.
7695
7696 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7697 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7698 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007699 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007700 Value *One = ConstantInt::get(SrcI->getType(), 1);
7701
Reid Spencer832254e2007-02-02 02:16:23 +00007702 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007703 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007704 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007705 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007706 SrcI->getOperand(0),
7707 "tmp"), CI);
7708 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007709 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007710 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007711 }
7712 break;
7713 }
7714 }
7715
7716 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007717}
7718
Evan Chengb98a10e2008-03-24 00:21:34 +00007719/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7720/// in order to eliminate the icmp.
7721Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7722 bool DoXform) {
7723 // If we are just checking for a icmp eq of a single bit and zext'ing it
7724 // to an integer, then shift the bit to the appropriate place and then
7725 // cast to integer to avoid the comparison.
7726 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7727 const APInt &Op1CV = Op1C->getValue();
7728
7729 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7730 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7731 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7732 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7733 if (!DoXform) return ICI;
7734
7735 Value *In = ICI->getOperand(0);
7736 Value *Sh = ConstantInt::get(In->getType(),
7737 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007738 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00007739 In->getName()+".lobit"),
7740 CI);
7741 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007742 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00007743 false/*ZExt*/, "tmp", &CI);
7744
7745 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7746 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007747 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00007748 In->getName()+".not"),
7749 CI);
7750 }
7751
7752 return ReplaceInstUsesWith(CI, In);
7753 }
7754
7755
7756
7757 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7758 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7759 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7760 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7761 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7762 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7763 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7764 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7765 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7766 // This only works for EQ and NE
7767 ICI->isEquality()) {
7768 // If Op1C some other power of two, convert:
7769 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7770 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7771 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7772 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7773
7774 APInt KnownZeroMask(~KnownZero);
7775 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7776 if (!DoXform) return ICI;
7777
7778 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7779 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7780 // (X&4) == 2 --> false
7781 // (X&4) != 2 --> true
7782 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7783 Res = ConstantExpr::getZExt(Res, CI.getType());
7784 return ReplaceInstUsesWith(CI, Res);
7785 }
7786
7787 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7788 Value *In = ICI->getOperand(0);
7789 if (ShiftAmt) {
7790 // Perform a logical shr by shiftamt.
7791 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007792 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00007793 ConstantInt::get(In->getType(), ShiftAmt),
7794 In->getName()+".lobit"), CI);
7795 }
7796
7797 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7798 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007799 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007800 InsertNewInstBefore(cast<Instruction>(In), CI);
7801 }
7802
7803 if (CI.getType() == In->getType())
7804 return ReplaceInstUsesWith(CI, In);
7805 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007806 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00007807 }
7808 }
7809 }
7810
7811 return 0;
7812}
7813
Chris Lattner8a9f5712007-04-11 06:57:46 +00007814Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007815 // If one of the common conversion will work ..
7816 if (Instruction *Result = commonIntCastTransforms(CI))
7817 return Result;
7818
7819 Value *Src = CI.getOperand(0);
7820
7821 // If this is a cast of a cast
7822 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007823 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7824 // types and if the sizes are just right we can convert this into a logical
7825 // 'and' which will be much cheaper than the pair of casts.
7826 if (isa<TruncInst>(CSrc)) {
7827 // Get the sizes of the types involved
7828 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007829 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7830 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7831 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007832 // If we're actually extending zero bits and the trunc is a no-op
7833 if (MidSize < DstSize && SrcSize == DstSize) {
7834 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007835 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007836 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007837 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007838 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00007839 // Unfortunately, if the type changed, we need to cast it back.
7840 if (And->getType() != CI.getType()) {
7841 And->setName(CSrc->getName()+".mask");
7842 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007843 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007844 }
7845 return And;
7846 }
7847 }
7848 }
7849
Evan Chengb98a10e2008-03-24 00:21:34 +00007850 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7851 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007852
Evan Chengb98a10e2008-03-24 00:21:34 +00007853 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7854 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7855 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7856 // of the (zext icmp) will be transformed.
7857 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7858 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7859 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7860 (transformZExtICmp(LHS, CI, false) ||
7861 transformZExtICmp(RHS, CI, false))) {
7862 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7863 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007864 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007865 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007866 }
7867
Reid Spencer3da59db2006-11-27 01:05:10 +00007868 return 0;
7869}
7870
Chris Lattner8a9f5712007-04-11 06:57:46 +00007871Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007872 if (Instruction *I = commonIntCastTransforms(CI))
7873 return I;
7874
Chris Lattner8a9f5712007-04-11 06:57:46 +00007875 Value *Src = CI.getOperand(0);
7876
7877 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7878 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7879 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7880 // If we are just checking for a icmp eq of a single bit and zext'ing it
7881 // to an integer, then shift the bit to the appropriate place and then
7882 // cast to integer to avoid the comparison.
7883 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7884 const APInt &Op1CV = Op1C->getValue();
7885
7886 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7887 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7888 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7889 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7890 Value *In = ICI->getOperand(0);
7891 Value *Sh = ConstantInt::get(In->getType(),
7892 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007893 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007894 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007895 CI);
7896 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007897 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007898 true/*SExt*/, "tmp", &CI);
7899
7900 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007901 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00007902 In->getName()+".not"), CI);
7903
7904 return ReplaceInstUsesWith(CI, In);
7905 }
7906 }
7907 }
7908
Chris Lattnerba417832007-04-11 06:12:58 +00007909 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007910}
7911
Chris Lattnerb7530652008-01-27 05:29:54 +00007912/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7913/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007914static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007915 APFloat F = CFP->getValueAPF();
7916 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007917 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007918 return 0;
7919}
7920
7921/// LookThroughFPExtensions - If this is an fp extension instruction, look
7922/// through it until we get the source value.
7923static Value *LookThroughFPExtensions(Value *V) {
7924 if (Instruction *I = dyn_cast<Instruction>(V))
7925 if (I->getOpcode() == Instruction::FPExt)
7926 return LookThroughFPExtensions(I->getOperand(0));
7927
7928 // If this value is a constant, return the constant in the smallest FP type
7929 // that can accurately represent it. This allows us to turn
7930 // (float)((double)X+2.0) into x+2.0f.
7931 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7932 if (CFP->getType() == Type::PPC_FP128Ty)
7933 return V; // No constant folding of this.
7934 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007935 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007936 return V;
7937 if (CFP->getType() == Type::DoubleTy)
7938 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007939 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007940 return V;
7941 // Don't try to shrink to various long double types.
7942 }
7943
7944 return V;
7945}
7946
7947Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7948 if (Instruction *I = commonCastTransforms(CI))
7949 return I;
7950
7951 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7952 // smaller than the destination type, we can eliminate the truncate by doing
7953 // the add as the smaller type. This applies to add/sub/mul/div as well as
7954 // many builtins (sqrt, etc).
7955 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7956 if (OpI && OpI->hasOneUse()) {
7957 switch (OpI->getOpcode()) {
7958 default: break;
7959 case Instruction::Add:
7960 case Instruction::Sub:
7961 case Instruction::Mul:
7962 case Instruction::FDiv:
7963 case Instruction::FRem:
7964 const Type *SrcTy = OpI->getType();
7965 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7966 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7967 if (LHSTrunc->getType() != SrcTy &&
7968 RHSTrunc->getType() != SrcTy) {
7969 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7970 // If the source types were both smaller than the destination type of
7971 // the cast, do this xform.
7972 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7973 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7974 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7975 CI.getType(), CI);
7976 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7977 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007978 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00007979 }
7980 }
7981 break;
7982 }
7983 }
7984 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007985}
7986
7987Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7988 return commonCastTransforms(CI);
7989}
7990
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007991Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7992 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
7993 // mantissa to accurately represent all values of X. For example, do not
7994 // do this with i64->float->i64.
7995 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7996 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7997 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00007998 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00007999 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8000
8001 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008002}
8003
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008004Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8005 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
8006 // mantissa to accurately represent all values of X. For example, do not
8007 // do this with i64->float->i64.
8008 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8009 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8010 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00008011 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008012 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8013
8014 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008015}
8016
8017Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8018 return commonCastTransforms(CI);
8019}
8020
8021Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8022 return commonCastTransforms(CI);
8023}
8024
8025Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008026 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008027}
8028
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008029Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8030 if (Instruction *I = commonCastTransforms(CI))
8031 return I;
8032
8033 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8034 if (!DestPointee->isSized()) return 0;
8035
8036 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8037 ConstantInt *Cst;
8038 Value *X;
8039 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8040 m_ConstantInt(Cst)))) {
8041 // If the source and destination operands have the same type, see if this
8042 // is a single-index GEP.
8043 if (X->getType() == CI.getType()) {
8044 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00008045 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008046
8047 // Convert the constant to intptr type.
8048 APInt Offset = Cst->getValue();
8049 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8050
8051 // If Offset is evenly divisible by Size, we can do this xform.
8052 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8053 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008054 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008055 }
8056 }
8057 // TODO: Could handle other cases, e.g. where add is indexing into field of
8058 // struct etc.
8059 } else if (CI.getOperand(0)->hasOneUse() &&
8060 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8061 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8062 // "inttoptr+GEP" instead of "add+intptr".
8063
8064 // Get the size of the pointee type.
8065 uint64_t Size = TD->getABITypeSize(DestPointee);
8066
8067 // Convert the constant to intptr type.
8068 APInt Offset = Cst->getValue();
8069 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8070
8071 // If Offset is evenly divisible by Size, we can do this xform.
8072 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8073 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8074
8075 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8076 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008077 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008078 }
8079 }
8080 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008081}
8082
Chris Lattnerd3e28342007-04-27 17:44:50 +00008083Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008084 // If the operands are integer typed then apply the integer transforms,
8085 // otherwise just apply the common ones.
8086 Value *Src = CI.getOperand(0);
8087 const Type *SrcTy = Src->getType();
8088 const Type *DestTy = CI.getType();
8089
Chris Lattner42a75512007-01-15 02:27:26 +00008090 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008091 if (Instruction *Result = commonIntCastTransforms(CI))
8092 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008093 } else if (isa<PointerType>(SrcTy)) {
8094 if (Instruction *I = commonPointerCastTransforms(CI))
8095 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008096 } else {
8097 if (Instruction *Result = commonCastTransforms(CI))
8098 return Result;
8099 }
8100
8101
8102 // Get rid of casts from one type to the same type. These are useless and can
8103 // be replaced by the operand.
8104 if (DestTy == Src->getType())
8105 return ReplaceInstUsesWith(CI, Src);
8106
Reid Spencer3da59db2006-11-27 01:05:10 +00008107 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008108 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8109 const Type *DstElTy = DstPTy->getElementType();
8110 const Type *SrcElTy = SrcPTy->getElementType();
8111
Nate Begeman83ad90a2008-03-31 00:22:16 +00008112 // If the address spaces don't match, don't eliminate the bitcast, which is
8113 // required for changing types.
8114 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8115 return 0;
8116
Chris Lattnerd3e28342007-04-27 17:44:50 +00008117 // If we are casting a malloc or alloca to a pointer to a type of the same
8118 // size, rewrite the allocation instruction to allocate the "right" type.
8119 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8120 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8121 return V;
8122
Chris Lattnerd717c182007-05-05 22:32:24 +00008123 // If the source and destination are pointers, and this cast is equivalent
8124 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008125 // This can enhance SROA and other transforms that want type-safe pointers.
8126 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8127 unsigned NumZeros = 0;
8128 while (SrcElTy != DstElTy &&
8129 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8130 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8131 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8132 ++NumZeros;
8133 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008134
Chris Lattnerd3e28342007-04-27 17:44:50 +00008135 // If we found a path from the src to dest, create the getelementptr now.
8136 if (SrcElTy == DstElTy) {
8137 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008138 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8139 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008140 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008141 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008142
Reid Spencer3da59db2006-11-27 01:05:10 +00008143 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8144 if (SVI->hasOneUse()) {
8145 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8146 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008147 if (isa<VectorType>(DestTy) &&
8148 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00008149 SVI->getType()->getNumElements()) {
8150 CastInst *Tmp;
8151 // If either of the operands is a cast from CI.getType(), then
8152 // evaluating the shuffle in the casted destination's type will allow
8153 // us to eliminate at least one cast.
8154 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8155 Tmp->getOperand(0)->getType() == DestTy) ||
8156 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8157 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008158 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8159 SVI->getOperand(0), DestTy, &CI);
8160 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8161 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008162 // Return a new shuffle vector. Use the same element ID's, as we
8163 // know the vector types match #elts.
8164 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008165 }
8166 }
8167 }
8168 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008169 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008170}
8171
Chris Lattnere576b912004-04-09 23:46:01 +00008172/// GetSelectFoldableOperands - We want to turn code that looks like this:
8173/// %C = or %A, %B
8174/// %D = select %cond, %C, %A
8175/// into:
8176/// %C = select %cond, %B, 0
8177/// %D = or %A, %C
8178///
8179/// Assuming that the specified instruction is an operand to the select, return
8180/// a bitmask indicating which operands of this instruction are foldable if they
8181/// equal the other incoming value of the select.
8182///
8183static unsigned GetSelectFoldableOperands(Instruction *I) {
8184 switch (I->getOpcode()) {
8185 case Instruction::Add:
8186 case Instruction::Mul:
8187 case Instruction::And:
8188 case Instruction::Or:
8189 case Instruction::Xor:
8190 return 3; // Can fold through either operand.
8191 case Instruction::Sub: // Can only fold on the amount subtracted.
8192 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008193 case Instruction::LShr:
8194 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008195 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008196 default:
8197 return 0; // Cannot fold
8198 }
8199}
8200
8201/// GetSelectFoldableConstant - For the same transformation as the previous
8202/// function, return the identity constant that goes into the select.
8203static Constant *GetSelectFoldableConstant(Instruction *I) {
8204 switch (I->getOpcode()) {
8205 default: assert(0 && "This cannot happen!"); abort();
8206 case Instruction::Add:
8207 case Instruction::Sub:
8208 case Instruction::Or:
8209 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008210 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008211 case Instruction::LShr:
8212 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008213 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008214 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008215 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008216 case Instruction::Mul:
8217 return ConstantInt::get(I->getType(), 1);
8218 }
8219}
8220
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008221/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8222/// have the same opcode and only one use each. Try to simplify this.
8223Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8224 Instruction *FI) {
8225 if (TI->getNumOperands() == 1) {
8226 // If this is a non-volatile load or a cast from the same type,
8227 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008228 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008229 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8230 return 0;
8231 } else {
8232 return 0; // unknown unary op.
8233 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008234
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008235 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008236 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8237 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008238 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008239 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008240 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008241 }
8242
Reid Spencer832254e2007-02-02 02:16:23 +00008243 // Only handle binary operators here.
8244 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008245 return 0;
8246
8247 // Figure out if the operations have any operands in common.
8248 Value *MatchOp, *OtherOpT, *OtherOpF;
8249 bool MatchIsOpZero;
8250 if (TI->getOperand(0) == FI->getOperand(0)) {
8251 MatchOp = TI->getOperand(0);
8252 OtherOpT = TI->getOperand(1);
8253 OtherOpF = FI->getOperand(1);
8254 MatchIsOpZero = true;
8255 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8256 MatchOp = TI->getOperand(1);
8257 OtherOpT = TI->getOperand(0);
8258 OtherOpF = FI->getOperand(0);
8259 MatchIsOpZero = false;
8260 } else if (!TI->isCommutative()) {
8261 return 0;
8262 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8263 MatchOp = TI->getOperand(0);
8264 OtherOpT = TI->getOperand(1);
8265 OtherOpF = FI->getOperand(0);
8266 MatchIsOpZero = true;
8267 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8268 MatchOp = TI->getOperand(1);
8269 OtherOpT = TI->getOperand(0);
8270 OtherOpF = FI->getOperand(1);
8271 MatchIsOpZero = true;
8272 } else {
8273 return 0;
8274 }
8275
8276 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008277 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8278 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008279 InsertNewInstBefore(NewSI, SI);
8280
8281 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8282 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008283 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008284 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008285 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008286 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008287 assert(0 && "Shouldn't get here");
8288 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008289}
8290
Chris Lattner3d69f462004-03-12 05:52:32 +00008291Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008292 Value *CondVal = SI.getCondition();
8293 Value *TrueVal = SI.getTrueValue();
8294 Value *FalseVal = SI.getFalseValue();
8295
8296 // select true, X, Y -> X
8297 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008298 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008299 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008300
8301 // select C, X, X -> X
8302 if (TrueVal == FalseVal)
8303 return ReplaceInstUsesWith(SI, TrueVal);
8304
Chris Lattnere87597f2004-10-16 18:11:37 +00008305 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8306 return ReplaceInstUsesWith(SI, FalseVal);
8307 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8308 return ReplaceInstUsesWith(SI, TrueVal);
8309 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8310 if (isa<Constant>(TrueVal))
8311 return ReplaceInstUsesWith(SI, TrueVal);
8312 else
8313 return ReplaceInstUsesWith(SI, FalseVal);
8314 }
8315
Reid Spencer4fe16d62007-01-11 18:21:29 +00008316 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008317 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008318 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008319 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008320 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008321 } else {
8322 // Change: A = select B, false, C --> A = and !B, C
8323 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008324 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008325 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008326 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008327 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008328 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008329 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008330 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008331 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008332 } else {
8333 // Change: A = select B, C, true --> A = or !B, C
8334 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008335 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008336 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008337 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008338 }
8339 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008340
8341 // select a, b, a -> a&b
8342 // select a, a, b -> a|b
8343 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008344 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008345 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008346 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008347 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008348
Chris Lattner2eefe512004-04-09 19:05:30 +00008349 // Selecting between two integer constants?
8350 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8351 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008352 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008353 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008354 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008355 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008356 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008357 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008358 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008359 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008360 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008361 }
Chris Lattnerba417832007-04-11 06:12:58 +00008362
8363 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008364
Reid Spencere4d87aa2006-12-23 06:05:41 +00008365 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008366
Reid Spencere4d87aa2006-12-23 06:05:41 +00008367 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008368 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008369 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008370 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008371 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008372 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008373 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008374 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008375 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008376 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008377 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008378 InsertNewInstBefore(SRA, SI);
8379
Reid Spencer3da59db2006-11-27 01:05:10 +00008380 // Finally, convert to the type of the select RHS. We figure out
8381 // if this requires a SExt, Trunc or BitCast based on the sizes.
8382 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008383 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8384 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008385 if (SRASize < SISize)
8386 opc = Instruction::SExt;
8387 else if (SRASize > SISize)
8388 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008389 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008390 }
8391 }
8392
8393
8394 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008395 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008396 // non-constant value, eliminate this whole mess. This corresponds to
8397 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008398 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008399 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008400 cast<Constant>(IC->getOperand(1))->isNullValue())
8401 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8402 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008403 isa<ConstantInt>(ICA->getOperand(1)) &&
8404 (ICA->getOperand(1) == TrueValC ||
8405 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008406 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8407 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008408 // know whether we have a icmp_ne or icmp_eq and whether the
8409 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008410 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008411 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008412 Value *V = ICA;
8413 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008414 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008415 Instruction::Xor, V, ICA->getOperand(1)), SI);
8416 return ReplaceInstUsesWith(SI, V);
8417 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008418 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008419 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008420
8421 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008422 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8423 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008424 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008425 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8426 // This is not safe in general for floating point:
8427 // consider X== -0, Y== +0.
8428 // It becomes safe if either operand is a nonzero constant.
8429 ConstantFP *CFPt, *CFPf;
8430 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8431 !CFPt->getValueAPF().isZero()) ||
8432 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8433 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008434 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008435 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008436 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008437 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008438 return ReplaceInstUsesWith(SI, TrueVal);
8439 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8440
Reid Spencere4d87aa2006-12-23 06:05:41 +00008441 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008442 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008443 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8444 // This is not safe in general for floating point:
8445 // consider X== -0, Y== +0.
8446 // It becomes safe if either operand is a nonzero constant.
8447 ConstantFP *CFPt, *CFPf;
8448 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8449 !CFPt->getValueAPF().isZero()) ||
8450 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8451 !CFPf->getValueAPF().isZero()))
8452 return ReplaceInstUsesWith(SI, FalseVal);
8453 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008454 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008455 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8456 return ReplaceInstUsesWith(SI, TrueVal);
8457 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8458 }
8459 }
8460
8461 // See if we are selecting two values based on a comparison of the two values.
8462 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8463 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8464 // Transform (X == Y) ? X : Y -> Y
8465 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8466 return ReplaceInstUsesWith(SI, FalseVal);
8467 // Transform (X != Y) ? X : Y -> X
8468 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8469 return ReplaceInstUsesWith(SI, TrueVal);
8470 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8471
8472 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8473 // Transform (X == Y) ? Y : X -> X
8474 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8475 return ReplaceInstUsesWith(SI, FalseVal);
8476 // Transform (X != Y) ? Y : X -> Y
8477 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008478 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008479 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8480 }
8481 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008482
Chris Lattner87875da2005-01-13 22:52:24 +00008483 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8484 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8485 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008486 Instruction *AddOp = 0, *SubOp = 0;
8487
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008488 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8489 if (TI->getOpcode() == FI->getOpcode())
8490 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8491 return IV;
8492
8493 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8494 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008495 if (TI->getOpcode() == Instruction::Sub &&
8496 FI->getOpcode() == Instruction::Add) {
8497 AddOp = FI; SubOp = TI;
8498 } else if (FI->getOpcode() == Instruction::Sub &&
8499 TI->getOpcode() == Instruction::Add) {
8500 AddOp = TI; SubOp = FI;
8501 }
8502
8503 if (AddOp) {
8504 Value *OtherAddOp = 0;
8505 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8506 OtherAddOp = AddOp->getOperand(1);
8507 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8508 OtherAddOp = AddOp->getOperand(0);
8509 }
8510
8511 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008512 // So at this point we know we have (Y -> OtherAddOp):
8513 // select C, (add X, Y), (sub X, Z)
8514 Value *NegVal; // Compute -Z
8515 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8516 NegVal = ConstantExpr::getNeg(C);
8517 } else {
8518 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008519 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008520 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008521
8522 Value *NewTrueOp = OtherAddOp;
8523 Value *NewFalseOp = NegVal;
8524 if (AddOp != TI)
8525 std::swap(NewTrueOp, NewFalseOp);
8526 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008527 SelectInst::Create(CondVal, NewTrueOp,
8528 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008529
8530 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008531 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008532 }
8533 }
8534 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008535
Chris Lattnere576b912004-04-09 23:46:01 +00008536 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008537 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008538 // See the comment above GetSelectFoldableOperands for a description of the
8539 // transformation we are doing here.
8540 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8541 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8542 !isa<Constant>(FalseVal))
8543 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8544 unsigned OpToFold = 0;
8545 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8546 OpToFold = 1;
8547 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8548 OpToFold = 2;
8549 }
8550
8551 if (OpToFold) {
8552 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008553 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008554 SelectInst::Create(SI.getCondition(),
8555 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008556 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008557 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008558 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008559 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008560 else {
8561 assert(0 && "Unknown instruction!!");
8562 }
8563 }
8564 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008565
Chris Lattnere576b912004-04-09 23:46:01 +00008566 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8567 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8568 !isa<Constant>(TrueVal))
8569 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8570 unsigned OpToFold = 0;
8571 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8572 OpToFold = 1;
8573 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8574 OpToFold = 2;
8575 }
8576
8577 if (OpToFold) {
8578 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008579 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008580 SelectInst::Create(SI.getCondition(), C,
8581 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008582 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008583 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008584 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008585 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008586 else
Chris Lattnere576b912004-04-09 23:46:01 +00008587 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008588 }
8589 }
8590 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008591
8592 if (BinaryOperator::isNot(CondVal)) {
8593 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8594 SI.setOperand(1, FalseVal);
8595 SI.setOperand(2, TrueVal);
8596 return &SI;
8597 }
8598
Chris Lattner3d69f462004-03-12 05:52:32 +00008599 return 0;
8600}
8601
Dan Gohmaneee962e2008-04-10 18:43:06 +00008602/// EnforceKnownAlignment - If the specified pointer points to an object that
8603/// we control, modify the object's alignment to PrefAlign. This isn't
8604/// often possible though. If alignment is important, a more reliable approach
8605/// is to simply align all global variables and allocation instructions to
8606/// their preferred alignment from the beginning.
8607///
8608static unsigned EnforceKnownAlignment(Value *V,
8609 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008610
Dan Gohmaneee962e2008-04-10 18:43:06 +00008611 User *U = dyn_cast<User>(V);
8612 if (!U) return Align;
8613
8614 switch (getOpcode(U)) {
8615 default: break;
8616 case Instruction::BitCast:
8617 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8618 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008619 // If all indexes are zero, it is just the alignment of the base pointer.
8620 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008621 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8622 if (!isa<Constant>(U->getOperand(i)) ||
8623 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008624 AllZeroOperands = false;
8625 break;
8626 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008627
8628 if (AllZeroOperands) {
8629 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008630 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008631 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008632 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008633 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008634 }
8635
8636 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8637 // If there is a large requested alignment and we can, bump up the alignment
8638 // of the global.
8639 if (!GV->isDeclaration()) {
8640 GV->setAlignment(PrefAlign);
8641 Align = PrefAlign;
8642 }
8643 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8644 // If there is a requested alignment and if this is an alloca, round up. We
8645 // don't do this for malloc, because some systems can't respect the request.
8646 if (isa<AllocaInst>(AI)) {
8647 AI->setAlignment(PrefAlign);
8648 Align = PrefAlign;
8649 }
8650 }
8651
8652 return Align;
8653}
8654
8655/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8656/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8657/// and it is more than the alignment of the ultimate object, see if we can
8658/// increase the alignment of the ultimate object, making this check succeed.
8659unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8660 unsigned PrefAlign) {
8661 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8662 sizeof(PrefAlign) * CHAR_BIT;
8663 APInt Mask = APInt::getAllOnesValue(BitWidth);
8664 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8665 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8666 unsigned TrailZ = KnownZero.countTrailingOnes();
8667 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8668
8669 if (PrefAlign > Align)
8670 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8671
8672 // We don't need to make any adjustment.
8673 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008674}
8675
Chris Lattnerf497b022008-01-13 23:50:23 +00008676Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008677 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8678 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008679 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8680 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8681
8682 if (CopyAlign < MinAlign) {
8683 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8684 return MI;
8685 }
8686
8687 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8688 // load/store.
8689 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8690 if (MemOpLength == 0) return 0;
8691
Chris Lattner37ac6082008-01-14 00:28:35 +00008692 // Source and destination pointer types are always "i8*" for intrinsic. See
8693 // if the size is something we can handle with a single primitive load/store.
8694 // A single load+store correctly handles overlapping memory in the memmove
8695 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008696 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008697 if (Size == 0) return MI; // Delete this mem transfer.
8698
8699 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008700 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008701
Chris Lattner37ac6082008-01-14 00:28:35 +00008702 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008703 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008704
8705 // Memcpy forces the use of i8* for the source and destination. That means
8706 // that if you're using memcpy to move one double around, you'll get a cast
8707 // from double* to i8*. We'd much rather use a double load+store rather than
8708 // an i64 load+store, here because this improves the odds that the source or
8709 // dest address will be promotable. See if we can find a better type than the
8710 // integer datatype.
8711 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8712 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8713 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8714 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8715 // down through these levels if so.
8716 while (!SrcETy->isFirstClassType()) {
8717 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8718 if (STy->getNumElements() == 1)
8719 SrcETy = STy->getElementType(0);
8720 else
8721 break;
8722 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8723 if (ATy->getNumElements() == 1)
8724 SrcETy = ATy->getElementType();
8725 else
8726 break;
8727 } else
8728 break;
8729 }
8730
8731 if (SrcETy->isFirstClassType())
8732 NewPtrTy = PointerType::getUnqual(SrcETy);
8733 }
8734 }
8735
8736
Chris Lattnerf497b022008-01-13 23:50:23 +00008737 // If the memcpy/memmove provides better alignment info than we can
8738 // infer, use it.
8739 SrcAlign = std::max(SrcAlign, CopyAlign);
8740 DstAlign = std::max(DstAlign, CopyAlign);
8741
8742 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8743 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008744 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8745 InsertNewInstBefore(L, *MI);
8746 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8747
8748 // Set the size of the copy to 0, it will be deleted on the next iteration.
8749 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8750 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008751}
Chris Lattner3d69f462004-03-12 05:52:32 +00008752
Chris Lattner69ea9d22008-04-30 06:39:11 +00008753Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8754 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8755 if (MI->getAlignment()->getZExtValue() < Alignment) {
8756 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8757 return MI;
8758 }
8759
8760 // Extract the length and alignment and fill if they are constant.
8761 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8762 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8763 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8764 return 0;
8765 uint64_t Len = LenC->getZExtValue();
8766 Alignment = MI->getAlignment()->getZExtValue();
8767
8768 // If the length is zero, this is a no-op
8769 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8770
8771 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8772 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8773 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8774
8775 Value *Dest = MI->getDest();
8776 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8777
8778 // Alignment 0 is identity for alignment 1 for memset, but not store.
8779 if (Alignment == 0) Alignment = 1;
8780
8781 // Extract the fill value and store.
8782 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8783 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8784 Alignment), *MI);
8785
8786 // Set the size of the copy to 0, it will be deleted on the next iteration.
8787 MI->setLength(Constant::getNullValue(LenC->getType()));
8788 return MI;
8789 }
8790
8791 return 0;
8792}
8793
8794
Chris Lattner8b0ea312006-01-13 20:11:04 +00008795/// visitCallInst - CallInst simplification. This mostly only handles folding
8796/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8797/// the heavy lifting.
8798///
Chris Lattner9fe38862003-06-19 17:00:31 +00008799Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008800 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8801 if (!II) return visitCallSite(&CI);
8802
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008803 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8804 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008805 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008806 bool Changed = false;
8807
8808 // memmove/cpy/set of zero bytes is a noop.
8809 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8810 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8811
Chris Lattner35b9e482004-10-12 04:52:52 +00008812 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008813 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008814 // Replace the instruction with just byte operations. We would
8815 // transform other cases to loads/stores, but we don't know if
8816 // alignment is sufficient.
8817 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008818 }
8819
Chris Lattner35b9e482004-10-12 04:52:52 +00008820 // If we have a memmove and the source operation is a constant global,
8821 // then the source and dest pointers can't alias, so we can change this
8822 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008823 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008824 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8825 if (GVSrc->isConstant()) {
8826 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008827 Intrinsic::ID MemCpyID;
8828 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8829 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008830 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008831 MemCpyID = Intrinsic::memcpy_i64;
8832 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008833 Changed = true;
8834 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008835 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008836
Chris Lattner95a959d2006-03-06 20:18:44 +00008837 // If we can determine a pointer alignment that is bigger than currently
8838 // set, update the alignment.
8839 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008840 if (Instruction *I = SimplifyMemTransfer(MI))
8841 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008842 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8843 if (Instruction *I = SimplifyMemSet(MSI))
8844 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008845 }
8846
Chris Lattner8b0ea312006-01-13 20:11:04 +00008847 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008848 } else {
8849 switch (II->getIntrinsicID()) {
8850 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008851 case Intrinsic::ppc_altivec_lvx:
8852 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008853 case Intrinsic::x86_sse_loadu_ps:
8854 case Intrinsic::x86_sse2_loadu_pd:
8855 case Intrinsic::x86_sse2_loadu_dq:
8856 // Turn PPC lvx -> load if the pointer is known aligned.
8857 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008858 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008859 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8860 PointerType::getUnqual(II->getType()),
8861 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008862 return new LoadInst(Ptr);
8863 }
8864 break;
8865 case Intrinsic::ppc_altivec_stvx:
8866 case Intrinsic::ppc_altivec_stvxl:
8867 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008868 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008869 const Type *OpPtrTy =
8870 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008871 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008872 return new StoreInst(II->getOperand(1), Ptr);
8873 }
8874 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008875 case Intrinsic::x86_sse_storeu_ps:
8876 case Intrinsic::x86_sse2_storeu_pd:
8877 case Intrinsic::x86_sse2_storeu_dq:
8878 case Intrinsic::x86_sse2_storel_dq:
8879 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008880 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008881 const Type *OpPtrTy =
8882 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008883 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008884 return new StoreInst(II->getOperand(2), Ptr);
8885 }
8886 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008887
8888 case Intrinsic::x86_sse_cvttss2si: {
8889 // These intrinsics only demands the 0th element of its input vector. If
8890 // we can simplify the input based on that, do so now.
8891 uint64_t UndefElts;
8892 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8893 UndefElts)) {
8894 II->setOperand(1, V);
8895 return II;
8896 }
8897 break;
8898 }
8899
Chris Lattnere2ed0572006-04-06 19:19:17 +00008900 case Intrinsic::ppc_altivec_vperm:
8901 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008902 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008903 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8904
8905 // Check that all of the elements are integer constants or undefs.
8906 bool AllEltsOk = true;
8907 for (unsigned i = 0; i != 16; ++i) {
8908 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8909 !isa<UndefValue>(Mask->getOperand(i))) {
8910 AllEltsOk = false;
8911 break;
8912 }
8913 }
8914
8915 if (AllEltsOk) {
8916 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008917 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8918 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008919 Value *Result = UndefValue::get(Op0->getType());
8920
8921 // Only extract each element once.
8922 Value *ExtractedElts[32];
8923 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8924
8925 for (unsigned i = 0; i != 16; ++i) {
8926 if (isa<UndefValue>(Mask->getOperand(i)))
8927 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008928 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008929 Idx &= 31; // Match the hardware behavior.
8930
8931 if (ExtractedElts[Idx] == 0) {
8932 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008933 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008934 InsertNewInstBefore(Elt, CI);
8935 ExtractedElts[Idx] = Elt;
8936 }
8937
8938 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008939 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8940 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008941 InsertNewInstBefore(cast<Instruction>(Result), CI);
8942 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008943 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008944 }
8945 }
8946 break;
8947
Chris Lattnera728ddc2006-01-13 21:28:09 +00008948 case Intrinsic::stackrestore: {
8949 // If the save is right next to the restore, remove the restore. This can
8950 // happen when variable allocas are DCE'd.
8951 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8952 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8953 BasicBlock::iterator BI = SS;
8954 if (&*++BI == II)
8955 return EraseInstFromFunction(CI);
8956 }
8957 }
8958
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008959 // Scan down this block to see if there is another stack restore in the
8960 // same block without an intervening call/alloca.
8961 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008962 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008963 bool CannotRemove = false;
8964 for (++BI; &*BI != TI; ++BI) {
8965 if (isa<AllocaInst>(BI)) {
8966 CannotRemove = true;
8967 break;
8968 }
8969 if (isa<CallInst>(BI)) {
8970 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008971 CannotRemove = true;
8972 break;
8973 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008974 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008975 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008976 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008977 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008978
8979 // If the stack restore is in a return/unwind block and if there are no
8980 // allocas or calls between the restore and the return, nuke the restore.
8981 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8982 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008983 break;
8984 }
8985 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008986 }
8987
Chris Lattner8b0ea312006-01-13 20:11:04 +00008988 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008989}
8990
8991// InvokeInst simplification
8992//
8993Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008994 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008995}
8996
Dale Johannesenda30ccb2008-04-25 21:16:07 +00008997/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8998/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00008999static bool isSafeToEliminateVarargsCast(const CallSite CS,
9000 const CastInst * const CI,
9001 const TargetData * const TD,
9002 const int ix) {
9003 if (!CI->isLosslessCast())
9004 return false;
9005
9006 // The size of ByVal arguments is derived from the type, so we
9007 // can't change to a type with a different size. If the size were
9008 // passed explicitly we could avoid this check.
9009 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9010 return true;
9011
9012 const Type* SrcTy =
9013 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9014 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9015 if (!SrcTy->isSized() || !DstTy->isSized())
9016 return false;
9017 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9018 return false;
9019 return true;
9020}
9021
Chris Lattnera44d8a22003-10-07 22:32:43 +00009022// visitCallSite - Improvements for call and invoke instructions.
9023//
9024Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009025 bool Changed = false;
9026
9027 // If the callee is a constexpr cast of a function, attempt to move the cast
9028 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009029 if (transformConstExprCastCall(CS)) return 0;
9030
Chris Lattner6c266db2003-10-07 22:54:13 +00009031 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009032
Chris Lattner08b22ec2005-05-13 07:09:09 +00009033 if (Function *CalleeF = dyn_cast<Function>(Callee))
9034 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9035 Instruction *OldCall = CS.getInstruction();
9036 // If the call and callee calling conventions don't match, this call must
9037 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009038 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009039 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9040 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009041 if (!OldCall->use_empty())
9042 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9043 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9044 return EraseInstFromFunction(*OldCall);
9045 return 0;
9046 }
9047
Chris Lattner17be6352004-10-18 02:59:09 +00009048 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9049 // This instruction is not reachable, just remove it. We insert a store to
9050 // undef so that we know that this code is not reachable, despite the fact
9051 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009052 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009053 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009054 CS.getInstruction());
9055
9056 if (!CS.getInstruction()->use_empty())
9057 CS.getInstruction()->
9058 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9059
9060 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9061 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009062 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9063 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009064 }
Chris Lattner17be6352004-10-18 02:59:09 +00009065 return EraseInstFromFunction(*CS.getInstruction());
9066 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009067
Duncan Sandscdb6d922007-09-17 10:26:40 +00009068 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9069 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9070 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9071 return transformCallThroughTrampoline(CS);
9072
Chris Lattner6c266db2003-10-07 22:54:13 +00009073 const PointerType *PTy = cast<PointerType>(Callee->getType());
9074 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9075 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009076 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009077 // See if we can optimize any arguments passed through the varargs area of
9078 // the call.
9079 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009080 E = CS.arg_end(); I != E; ++I, ++ix) {
9081 CastInst *CI = dyn_cast<CastInst>(*I);
9082 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9083 *I = CI->getOperand(0);
9084 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009085 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009086 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009087 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009088
Duncan Sandsf0c33542007-12-19 21:13:37 +00009089 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009090 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009091 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009092 Changed = true;
9093 }
9094
Chris Lattner6c266db2003-10-07 22:54:13 +00009095 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009096}
9097
Chris Lattner9fe38862003-06-19 17:00:31 +00009098// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9099// attempt to move the cast to the arguments of the call/invoke.
9100//
9101bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9102 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9103 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009104 if (CE->getOpcode() != Instruction::BitCast ||
9105 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009106 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009107 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009108 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00009109 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00009110
9111 // Okay, this is a cast from a function to a different type. Unless doing so
9112 // would cause a type conversion of one of our arguments, change this call to
9113 // be a direct call with arguments casted to the appropriate types.
9114 //
9115 const FunctionType *FT = Callee->getFunctionType();
9116 const Type *OldRetTy = Caller->getType();
9117
Devang Patel75e6f022008-03-11 18:04:06 +00009118 if (isa<StructType>(FT->getReturnType()))
9119 return false; // TODO: Handle multiple return values.
9120
Chris Lattnerf78616b2004-01-14 06:06:08 +00009121 // Check to see if we are changing the return type...
9122 if (OldRetTy != FT->getReturnType()) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009123 if (Callee->isDeclaration() &&
Chris Lattner46013f42007-01-06 19:53:32 +00009124 // Conversion is ok if changing from pointer to int of same size.
9125 !(isa<PointerType>(FT->getReturnType()) &&
9126 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00009127 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009128
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009129 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009130 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00009131 FT->getReturnType() != Type::VoidTy &&
9132 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009133 return false; // Cannot transform this return value.
9134
Chris Lattner58d74912008-03-12 17:45:29 +00009135 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9136 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00009137 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9138 return false; // Attribute not compatible with transformed value.
9139 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009140
Chris Lattnerf78616b2004-01-14 06:06:08 +00009141 // If the callsite is an invoke instruction, and the return value is used by
9142 // a PHI node in a successor, we cannot change the return type of the call
9143 // because there is no place to put the cast instruction (without breaking
9144 // the critical edge). Bail out in this case.
9145 if (!Caller->use_empty())
9146 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9147 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9148 UI != E; ++UI)
9149 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9150 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009151 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009152 return false;
9153 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009154
9155 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9156 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009157
Chris Lattner9fe38862003-06-19 17:00:31 +00009158 CallSite::arg_iterator AI = CS.arg_begin();
9159 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9160 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009161 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009162
9163 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009164 return false; // Cannot transform this parameter value.
9165
Chris Lattner58d74912008-03-12 17:45:29 +00009166 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9167 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009168
Reid Spencer3da59db2006-11-27 01:05:10 +00009169 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009170 // Some conversions are safe even if we do not have a body.
9171 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00009172 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00009173 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00009174 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009175 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9176 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00009177 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00009178 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009179 }
9180
9181 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009182 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009183 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009184
Chris Lattner58d74912008-03-12 17:45:29 +00009185 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9186 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009187 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009188 // won't be dropping them. Check that these extra arguments have attributes
9189 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009190 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9191 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009192 break;
Chris Lattner58d74912008-03-12 17:45:29 +00009193 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00009194 if (PAttrs & ParamAttr::VarArgsIncompatible)
9195 return false;
9196 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009197
Chris Lattner9fe38862003-06-19 17:00:31 +00009198 // Okay, we decided that this is a safe thing to do: go ahead and start
9199 // inserting cast instructions as necessary...
9200 std::vector<Value*> Args;
9201 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00009202 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009203 attrVec.reserve(NumCommonArgs);
9204
9205 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009206 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009207
9208 // If the return value is not being used, the type may not be compatible
9209 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00009210 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009211
9212 // Add the new return attributes.
9213 if (RAttrs)
9214 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009215
9216 AI = CS.arg_begin();
9217 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9218 const Type *ParamTy = FT->getParamType(i);
9219 if ((*AI)->getType() == ParamTy) {
9220 Args.push_back(*AI);
9221 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009222 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009223 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009224 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009225 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009226 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009227
9228 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009229 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009230 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009231 }
9232
9233 // If the function takes more arguments than the call was taking, add them
9234 // now...
9235 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9236 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9237
9238 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009239 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009240 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009241 cerr << "WARNING: While resolving call to function '"
9242 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009243 } else {
9244 // Add all of the arguments in their promoted form to the arg list...
9245 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9246 const Type *PTy = getPromotedType((*AI)->getType());
9247 if (PTy != (*AI)->getType()) {
9248 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009249 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9250 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009251 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009252 InsertNewInstBefore(Cast, *Caller);
9253 Args.push_back(Cast);
9254 } else {
9255 Args.push_back(*AI);
9256 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009257
Duncan Sandse1e520f2008-01-13 08:02:44 +00009258 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009259 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009260 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9261 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009262 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009263 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009264
9265 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009266 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009267
Chris Lattner58d74912008-03-12 17:45:29 +00009268 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009269
Chris Lattner9fe38862003-06-19 17:00:31 +00009270 Instruction *NC;
9271 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009272 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009273 Args.begin(), Args.end(),
9274 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009275 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009276 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009277 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009278 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9279 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009280 CallInst *CI = cast<CallInst>(Caller);
9281 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009282 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009283 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009284 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009285 }
9286
Chris Lattner6934a042007-02-11 01:23:03 +00009287 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009288 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009289 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009290 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009291 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009292 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009293 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009294
9295 // If this is an invoke instruction, we should insert it after the first
9296 // non-phi, instruction in the normal successor block.
9297 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9298 BasicBlock::iterator I = II->getNormalDest()->begin();
9299 while (isa<PHINode>(I)) ++I;
9300 InsertNewInstBefore(NC, *I);
9301 } else {
9302 // Otherwise, it's a call, just insert cast right after the call instr
9303 InsertNewInstBefore(NC, *Caller);
9304 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009305 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009306 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009307 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009308 }
9309 }
9310
9311 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9312 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009313 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009314 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009315 return true;
9316}
9317
Duncan Sandscdb6d922007-09-17 10:26:40 +00009318// transformCallThroughTrampoline - Turn a call to a function created by the
9319// init_trampoline intrinsic into a direct call to the underlying function.
9320//
9321Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9322 Value *Callee = CS.getCalledValue();
9323 const PointerType *PTy = cast<PointerType>(Callee->getType());
9324 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009325 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009326
9327 // If the call already has the 'nest' attribute somewhere then give up -
9328 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009329 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009330 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009331
9332 IntrinsicInst *Tramp =
9333 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9334
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009335 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009336 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9337 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9338
Chris Lattner58d74912008-03-12 17:45:29 +00009339 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9340 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009341 unsigned NestIdx = 1;
9342 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009343 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009344
9345 // Look for a parameter marked with the 'nest' attribute.
9346 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9347 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009348 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009349 // Record the parameter type and any other attributes.
9350 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009351 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009352 break;
9353 }
9354
9355 if (NestTy) {
9356 Instruction *Caller = CS.getInstruction();
9357 std::vector<Value*> NewArgs;
9358 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9359
Chris Lattner58d74912008-03-12 17:45:29 +00009360 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9361 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009362
Duncan Sandscdb6d922007-09-17 10:26:40 +00009363 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009364 // mean appending it. Likewise for attributes.
9365
9366 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009367 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9368 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009369
Duncan Sandscdb6d922007-09-17 10:26:40 +00009370 {
9371 unsigned Idx = 1;
9372 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9373 do {
9374 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009375 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009376 Value *NestVal = Tramp->getOperand(3);
9377 if (NestVal->getType() != NestTy)
9378 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9379 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009380 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009381 }
9382
9383 if (I == E)
9384 break;
9385
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009386 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009387 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009388 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009389 NewAttrs.push_back
9390 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009391
9392 ++Idx, ++I;
9393 } while (1);
9394 }
9395
9396 // The trampoline may have been bitcast to a bogus type (FTy).
9397 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009398 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009399
Duncan Sandscdb6d922007-09-17 10:26:40 +00009400 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009401 NewTypes.reserve(FTy->getNumParams()+1);
9402
Duncan Sandscdb6d922007-09-17 10:26:40 +00009403 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009404 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009405 {
9406 unsigned Idx = 1;
9407 FunctionType::param_iterator I = FTy->param_begin(),
9408 E = FTy->param_end();
9409
9410 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009411 if (Idx == NestIdx)
9412 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009413 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009414
9415 if (I == E)
9416 break;
9417
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009418 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009419 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009420
9421 ++Idx, ++I;
9422 } while (1);
9423 }
9424
9425 // Replace the trampoline call with a direct call. Let the generic
9426 // code sort out any function type mismatches.
9427 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009428 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009429 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9430 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009431 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009432
9433 Instruction *NewCaller;
9434 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009435 NewCaller = InvokeInst::Create(NewCallee,
9436 II->getNormalDest(), II->getUnwindDest(),
9437 NewArgs.begin(), NewArgs.end(),
9438 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009439 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009440 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009441 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009442 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9443 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009444 if (cast<CallInst>(Caller)->isTailCall())
9445 cast<CallInst>(NewCaller)->setTailCall();
9446 cast<CallInst>(NewCaller)->
9447 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009448 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009449 }
9450 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9451 Caller->replaceAllUsesWith(NewCaller);
9452 Caller->eraseFromParent();
9453 RemoveFromWorkList(Caller);
9454 return 0;
9455 }
9456 }
9457
9458 // Replace the trampoline call with a direct call. Since there is no 'nest'
9459 // parameter, there is no need to adjust the argument list. Let the generic
9460 // code sort out any function type mismatches.
9461 Constant *NewCallee =
9462 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9463 CS.setCalledFunction(NewCallee);
9464 return CS.getInstruction();
9465}
9466
Chris Lattner7da52b22006-11-01 04:51:18 +00009467/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9468/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9469/// and a single binop.
9470Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9471 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009472 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9473 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009474 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009475 Value *LHSVal = FirstInst->getOperand(0);
9476 Value *RHSVal = FirstInst->getOperand(1);
9477
9478 const Type *LHSType = LHSVal->getType();
9479 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009480
9481 // Scan to see if all operands are the same opcode, all have one use, and all
9482 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009483 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009484 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009485 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009486 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009487 // types or GEP's with different index types.
9488 I->getOperand(0)->getType() != LHSType ||
9489 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009490 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009491
9492 // If they are CmpInst instructions, check their predicates
9493 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9494 if (cast<CmpInst>(I)->getPredicate() !=
9495 cast<CmpInst>(FirstInst)->getPredicate())
9496 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009497
9498 // Keep track of which operand needs a phi node.
9499 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9500 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009501 }
9502
Chris Lattner53738a42006-11-08 19:42:28 +00009503 // Otherwise, this is safe to transform, determine if it is profitable.
9504
9505 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9506 // Indexes are often folded into load/store instructions, so we don't want to
9507 // hide them behind a phi.
9508 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9509 return 0;
9510
Chris Lattner7da52b22006-11-01 04:51:18 +00009511 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009512 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009513 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009514 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009515 NewLHS = PHINode::Create(LHSType,
9516 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009517 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9518 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009519 InsertNewInstBefore(NewLHS, PN);
9520 LHSVal = NewLHS;
9521 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009522
9523 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009524 NewRHS = PHINode::Create(RHSType,
9525 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009526 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9527 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009528 InsertNewInstBefore(NewRHS, PN);
9529 RHSVal = NewRHS;
9530 }
9531
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009532 // Add all operands to the new PHIs.
9533 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9534 if (NewLHS) {
9535 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9536 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9537 }
9538 if (NewRHS) {
9539 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9540 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9541 }
9542 }
9543
Chris Lattner7da52b22006-11-01 04:51:18 +00009544 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009545 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009546 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009547 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009548 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009549 else {
9550 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009551 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009552 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009553}
9554
Chris Lattner76c73142006-11-01 07:13:54 +00009555/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9556/// of the block that defines it. This means that it must be obvious the value
9557/// of the load is not changed from the point of the load to the end of the
9558/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009559///
9560/// Finally, it is safe, but not profitable, to sink a load targetting a
9561/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9562/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009563static bool isSafeToSinkLoad(LoadInst *L) {
9564 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9565
9566 for (++BBI; BBI != E; ++BBI)
9567 if (BBI->mayWriteToMemory())
9568 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009569
9570 // Check for non-address taken alloca. If not address-taken already, it isn't
9571 // profitable to do this xform.
9572 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9573 bool isAddressTaken = false;
9574 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9575 UI != E; ++UI) {
9576 if (isa<LoadInst>(UI)) continue;
9577 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9578 // If storing TO the alloca, then the address isn't taken.
9579 if (SI->getOperand(1) == AI) continue;
9580 }
9581 isAddressTaken = true;
9582 break;
9583 }
9584
9585 if (!isAddressTaken)
9586 return false;
9587 }
9588
Chris Lattner76c73142006-11-01 07:13:54 +00009589 return true;
9590}
9591
Chris Lattner9fe38862003-06-19 17:00:31 +00009592
Chris Lattnerbac32862004-11-14 19:13:23 +00009593// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9594// operator and they all are only used by the PHI, PHI together their
9595// inputs, and do the operation once, to the result of the PHI.
9596Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9597 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9598
9599 // Scan the instruction, looking for input operations that can be folded away.
9600 // If all input operands to the phi are the same instruction (e.g. a cast from
9601 // the same type or "+42") we can pull the operation through the PHI, reducing
9602 // code size and simplifying code.
9603 Constant *ConstantOp = 0;
9604 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009605 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009606 if (isa<CastInst>(FirstInst)) {
9607 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009608 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009609 // Can fold binop, compare or shift here if the RHS is a constant,
9610 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009611 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009612 if (ConstantOp == 0)
9613 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009614 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9615 isVolatile = LI->isVolatile();
9616 // We can't sink the load if the loaded value could be modified between the
9617 // load and the PHI.
9618 if (LI->getParent() != PN.getIncomingBlock(0) ||
9619 !isSafeToSinkLoad(LI))
9620 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009621 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009622 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009623 return FoldPHIArgBinOpIntoPHI(PN);
9624 // Can't handle general GEPs yet.
9625 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009626 } else {
9627 return 0; // Cannot fold this operation.
9628 }
9629
9630 // Check to see if all arguments are the same operation.
9631 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9632 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9633 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009634 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009635 return 0;
9636 if (CastSrcTy) {
9637 if (I->getOperand(0)->getType() != CastSrcTy)
9638 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009639 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009640 // We can't sink the load if the loaded value could be modified between
9641 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009642 if (LI->isVolatile() != isVolatile ||
9643 LI->getParent() != PN.getIncomingBlock(i) ||
9644 !isSafeToSinkLoad(LI))
9645 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009646
9647 // If the PHI is volatile and its block has multiple successors, sinking
9648 // it would remove a load of the volatile value from the path through the
9649 // other successor.
9650 if (isVolatile &&
9651 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9652 return 0;
9653
9654
Chris Lattnerbac32862004-11-14 19:13:23 +00009655 } else if (I->getOperand(1) != ConstantOp) {
9656 return 0;
9657 }
9658 }
9659
9660 // Okay, they are all the same operation. Create a new PHI node of the
9661 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009662 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9663 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009664 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009665
9666 Value *InVal = FirstInst->getOperand(0);
9667 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009668
9669 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009670 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9671 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9672 if (NewInVal != InVal)
9673 InVal = 0;
9674 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9675 }
9676
9677 Value *PhiVal;
9678 if (InVal) {
9679 // The new PHI unions all of the same values together. This is really
9680 // common, so we handle it intelligently here for compile-time speed.
9681 PhiVal = InVal;
9682 delete NewPN;
9683 } else {
9684 InsertNewInstBefore(NewPN, PN);
9685 PhiVal = NewPN;
9686 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009687
Chris Lattnerbac32862004-11-14 19:13:23 +00009688 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009689 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009690 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009691 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009692 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009693 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009694 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009695 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009696 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9697
9698 // If this was a volatile load that we are merging, make sure to loop through
9699 // and mark all the input loads as non-volatile. If we don't do this, we will
9700 // insert a new volatile load and the old ones will not be deletable.
9701 if (isVolatile)
9702 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9703 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9704
9705 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009706}
Chris Lattnera1be5662002-05-02 17:06:02 +00009707
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009708/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9709/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009710static bool DeadPHICycle(PHINode *PN,
9711 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009712 if (PN->use_empty()) return true;
9713 if (!PN->hasOneUse()) return false;
9714
9715 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009716 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009717 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009718
9719 // Don't scan crazily complex things.
9720 if (PotentiallyDeadPHIs.size() == 16)
9721 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009722
9723 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9724 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009725
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009726 return false;
9727}
9728
Chris Lattnercf5008a2007-11-06 21:52:06 +00009729/// PHIsEqualValue - Return true if this phi node is always equal to
9730/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9731/// z = some value; x = phi (y, z); y = phi (x, z)
9732static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9733 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9734 // See if we already saw this PHI node.
9735 if (!ValueEqualPHIs.insert(PN))
9736 return true;
9737
9738 // Don't scan crazily complex things.
9739 if (ValueEqualPHIs.size() == 16)
9740 return false;
9741
9742 // Scan the operands to see if they are either phi nodes or are equal to
9743 // the value.
9744 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9745 Value *Op = PN->getIncomingValue(i);
9746 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9747 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9748 return false;
9749 } else if (Op != NonPhiInVal)
9750 return false;
9751 }
9752
9753 return true;
9754}
9755
9756
Chris Lattner473945d2002-05-06 18:06:38 +00009757// PHINode simplification
9758//
Chris Lattner7e708292002-06-25 16:13:24 +00009759Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009760 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009761 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009762
Owen Anderson7e057142006-07-10 22:03:18 +00009763 if (Value *V = PN.hasConstantValue())
9764 return ReplaceInstUsesWith(PN, V);
9765
Owen Anderson7e057142006-07-10 22:03:18 +00009766 // If all PHI operands are the same operation, pull them through the PHI,
9767 // reducing code size.
9768 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9769 PN.getIncomingValue(0)->hasOneUse())
9770 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9771 return Result;
9772
9773 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9774 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9775 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009776 if (PN.hasOneUse()) {
9777 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9778 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009779 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009780 PotentiallyDeadPHIs.insert(&PN);
9781 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9782 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9783 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009784
9785 // If this phi has a single use, and if that use just computes a value for
9786 // the next iteration of a loop, delete the phi. This occurs with unused
9787 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9788 // common case here is good because the only other things that catch this
9789 // are induction variable analysis (sometimes) and ADCE, which is only run
9790 // late.
9791 if (PHIUser->hasOneUse() &&
9792 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9793 PHIUser->use_back() == &PN) {
9794 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9795 }
9796 }
Owen Anderson7e057142006-07-10 22:03:18 +00009797
Chris Lattnercf5008a2007-11-06 21:52:06 +00009798 // We sometimes end up with phi cycles that non-obviously end up being the
9799 // same value, for example:
9800 // z = some value; x = phi (y, z); y = phi (x, z)
9801 // where the phi nodes don't necessarily need to be in the same block. Do a
9802 // quick check to see if the PHI node only contains a single non-phi value, if
9803 // so, scan to see if the phi cycle is actually equal to that value.
9804 {
9805 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9806 // Scan for the first non-phi operand.
9807 while (InValNo != NumOperandVals &&
9808 isa<PHINode>(PN.getIncomingValue(InValNo)))
9809 ++InValNo;
9810
9811 if (InValNo != NumOperandVals) {
9812 Value *NonPhiInVal = PN.getOperand(InValNo);
9813
9814 // Scan the rest of the operands to see if there are any conflicts, if so
9815 // there is no need to recursively scan other phis.
9816 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9817 Value *OpVal = PN.getIncomingValue(InValNo);
9818 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9819 break;
9820 }
9821
9822 // If we scanned over all operands, then we have one unique value plus
9823 // phi values. Scan PHI nodes to see if they all merge in each other or
9824 // the value.
9825 if (InValNo == NumOperandVals) {
9826 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9827 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9828 return ReplaceInstUsesWith(PN, NonPhiInVal);
9829 }
9830 }
9831 }
Chris Lattner60921c92003-12-19 05:58:40 +00009832 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009833}
9834
Reid Spencer17212df2006-12-12 09:18:51 +00009835static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9836 Instruction *InsertPoint,
9837 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009838 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9839 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009840 // We must cast correctly to the pointer type. Ensure that we
9841 // sign extend the integer value if it is smaller as this is
9842 // used for address computation.
9843 Instruction::CastOps opcode =
9844 (VTySize < PtrSize ? Instruction::SExt :
9845 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9846 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009847}
9848
Chris Lattnera1be5662002-05-02 17:06:02 +00009849
Chris Lattner7e708292002-06-25 16:13:24 +00009850Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009851 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009852 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009853 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009854 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009855 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009856
Chris Lattnere87597f2004-10-16 18:11:37 +00009857 if (isa<UndefValue>(GEP.getOperand(0)))
9858 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9859
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009860 bool HasZeroPointerIndex = false;
9861 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9862 HasZeroPointerIndex = C->isNullValue();
9863
9864 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009865 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009866
Chris Lattner28977af2004-04-05 01:30:19 +00009867 // Eliminate unneeded casts for indices.
9868 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009869
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009870 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009871 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009872 if (isa<SequentialType>(*GTI)) {
9873 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009874 if (CI->getOpcode() == Instruction::ZExt ||
9875 CI->getOpcode() == Instruction::SExt) {
9876 const Type *SrcTy = CI->getOperand(0)->getType();
9877 // We can eliminate a cast from i32 to i64 iff the target
9878 // is a 32-bit pointer target.
9879 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9880 MadeChange = true;
9881 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009882 }
9883 }
9884 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009885 // If we are using a wider index than needed for this platform, shrink it
9886 // to what we need. If the incoming value needs a cast instruction,
9887 // insert it. This explicit cast can make subsequent optimizations more
9888 // obvious.
9889 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009890 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009891 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009892 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009893 MadeChange = true;
9894 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009895 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9896 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009897 GEP.setOperand(i, Op);
9898 MadeChange = true;
9899 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009900 }
Chris Lattner28977af2004-04-05 01:30:19 +00009901 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009902 }
Chris Lattner28977af2004-04-05 01:30:19 +00009903 if (MadeChange) return &GEP;
9904
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009905 // If this GEP instruction doesn't move the pointer, and if the input operand
9906 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9907 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009908 if (GEP.hasAllZeroIndices()) {
9909 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9910 // If the bitcast is of an allocation, and the allocation will be
9911 // converted to match the type of the cast, don't touch this.
9912 if (isa<AllocationInst>(BCI->getOperand(0))) {
9913 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009914 if (Instruction *I = visitBitCast(*BCI)) {
9915 if (I != BCI) {
9916 I->takeName(BCI);
9917 BCI->getParent()->getInstList().insert(BCI, I);
9918 ReplaceInstUsesWith(*BCI, I);
9919 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009920 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009921 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009922 }
9923 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9924 }
9925 }
9926
Chris Lattner90ac28c2002-08-02 19:29:35 +00009927 // Combine Indices - If the source pointer to this getelementptr instruction
9928 // is a getelementptr instruction, combine the indices of the two
9929 // getelementptr instructions into a single instruction.
9930 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009931 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009932 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009933 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009934
9935 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009936 // Note that if our source is a gep chain itself that we wait for that
9937 // chain to be resolved before we perform this transformation. This
9938 // avoids us creating a TON of code in some cases.
9939 //
9940 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9941 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9942 return 0; // Wait until our source is folded to completion.
9943
Chris Lattner72588fc2007-02-15 22:48:32 +00009944 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009945
9946 // Find out whether the last index in the source GEP is a sequential idx.
9947 bool EndsWithSequential = false;
9948 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9949 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009950 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009951
Chris Lattner90ac28c2002-08-02 19:29:35 +00009952 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009953 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009954 // Replace: gep (gep %P, long B), long A, ...
9955 // With: T = long A+B; gep %P, T, ...
9956 //
Chris Lattner620ce142004-05-07 22:09:22 +00009957 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009958 if (SO1 == Constant::getNullValue(SO1->getType())) {
9959 Sum = GO1;
9960 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9961 Sum = SO1;
9962 } else {
9963 // If they aren't the same type, convert both to an integer of the
9964 // target's pointer size.
9965 if (SO1->getType() != GO1->getType()) {
9966 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009967 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009968 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009969 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009970 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009971 unsigned PS = TD->getPointerSizeInBits();
9972 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009973 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009974 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009975
Duncan Sands514ab342007-11-01 20:53:16 +00009976 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009977 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009978 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009979 } else {
9980 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009981 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9982 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009983 }
9984 }
9985 }
Chris Lattner620ce142004-05-07 22:09:22 +00009986 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9987 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9988 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009989 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +00009990 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009991 }
Chris Lattner28977af2004-04-05 01:30:19 +00009992 }
Chris Lattner620ce142004-05-07 22:09:22 +00009993
9994 // Recycle the GEP we already have if possible.
9995 if (SrcGEPOperands.size() == 2) {
9996 GEP.setOperand(0, SrcGEPOperands[0]);
9997 GEP.setOperand(1, Sum);
9998 return &GEP;
9999 } else {
10000 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10001 SrcGEPOperands.end()-1);
10002 Indices.push_back(Sum);
10003 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10004 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010005 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010006 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010007 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010008 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010009 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10010 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010011 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10012 }
10013
10014 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010015 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10016 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010017
Chris Lattner620ce142004-05-07 22:09:22 +000010018 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010019 // GEP of global variable. If all of the indices for this GEP are
10020 // constants, we can promote this to a constexpr instead of an instruction.
10021
10022 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010023 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010024 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10025 for (; I != E && isa<Constant>(*I); ++I)
10026 Indices.push_back(cast<Constant>(*I));
10027
10028 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010029 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10030 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010031
10032 // Replace all uses of the GEP with the new constexpr...
10033 return ReplaceInstUsesWith(GEP, CE);
10034 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010035 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010036 if (!isa<PointerType>(X->getType())) {
10037 // Not interesting. Source pointer must be a cast from pointer.
10038 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010039 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10040 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010041 //
10042 // This occurs when the program declares an array extern like "int X[];"
10043 //
10044 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10045 const PointerType *XTy = cast<PointerType>(X->getType());
10046 if (const ArrayType *XATy =
10047 dyn_cast<ArrayType>(XTy->getElementType()))
10048 if (const ArrayType *CATy =
10049 dyn_cast<ArrayType>(CPTy->getElementType()))
10050 if (CATy->getElementType() == XATy->getElementType()) {
10051 // At this point, we know that the cast source type is a pointer
10052 // to an array of the same type as the destination pointer
10053 // array. Because the array type is never stepped over (there
10054 // is a leading zero) we can fold the cast into this GEP.
10055 GEP.setOperand(0, X);
10056 return &GEP;
10057 }
10058 } else if (GEP.getNumOperands() == 2) {
10059 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010060 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10061 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010062 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10063 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10064 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +000010065 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10066 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010067 Value *Idx[2];
10068 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10069 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010070 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010071 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010072 // V and GEP are both pointer types --> BitCast
10073 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010074 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010075
10076 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010077 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010078 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010079 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010080
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010081 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010082 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +000010083 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010084
10085 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10086 // allow either a mul, shift, or constant here.
10087 Value *NewIdx = 0;
10088 ConstantInt *Scale = 0;
10089 if (ArrayEltSize == 1) {
10090 NewIdx = GEP.getOperand(1);
10091 Scale = ConstantInt::get(NewIdx->getType(), 1);
10092 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010093 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010094 Scale = CI;
10095 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10096 if (Inst->getOpcode() == Instruction::Shl &&
10097 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010098 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10099 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10100 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010101 NewIdx = Inst->getOperand(0);
10102 } else if (Inst->getOpcode() == Instruction::Mul &&
10103 isa<ConstantInt>(Inst->getOperand(1))) {
10104 Scale = cast<ConstantInt>(Inst->getOperand(1));
10105 NewIdx = Inst->getOperand(0);
10106 }
10107 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010108
Chris Lattner7835cdd2005-09-13 18:36:04 +000010109 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010110 // out, perform the transformation. Note, we don't know whether Scale is
10111 // signed or not. We'll use unsigned version of division/modulo
10112 // operation after making sure Scale doesn't have the sign bit set.
10113 if (Scale && Scale->getSExtValue() >= 0LL &&
10114 Scale->getZExtValue() % ArrayEltSize == 0) {
10115 Scale = ConstantInt::get(Scale->getType(),
10116 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010117 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010118 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010119 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010120 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010121 NewIdx = InsertNewInstBefore(Sc, GEP);
10122 }
10123
10124 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010125 Value *Idx[2];
10126 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10127 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010128 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010129 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010130 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10131 // The NewGEP must be pointer typed, so must the old one -> BitCast
10132 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010133 }
10134 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010135 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010136 }
10137
Chris Lattner8a2a3112001-12-14 16:52:21 +000010138 return 0;
10139}
10140
Chris Lattner0864acf2002-11-04 16:18:53 +000010141Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10142 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010143 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010144 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10145 const Type *NewTy =
10146 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010147 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010148
10149 // Create and insert the replacement instruction...
10150 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010151 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010152 else {
10153 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010154 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010155 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010156
10157 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010158
Chris Lattner0864acf2002-11-04 16:18:53 +000010159 // Scan to the end of the allocation instructions, to skip over a block of
10160 // allocas if possible...
10161 //
10162 BasicBlock::iterator It = New;
10163 while (isa<AllocationInst>(*It)) ++It;
10164
10165 // Now that I is pointing to the first non-allocation-inst in the block,
10166 // insert our getelementptr instruction...
10167 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010168 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010169 Value *Idx[2];
10170 Idx[0] = NullIdx;
10171 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010172 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10173 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010174
10175 // Now make everything use the getelementptr instead of the original
10176 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010177 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010178 } else if (isa<UndefValue>(AI.getArraySize())) {
10179 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010180 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010181 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010182
10183 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10184 // Note that we only do this for alloca's, because malloc should allocate and
10185 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +000010186 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +000010187 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +000010188 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10189
Chris Lattner0864acf2002-11-04 16:18:53 +000010190 return 0;
10191}
10192
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010193Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10194 Value *Op = FI.getOperand(0);
10195
Chris Lattner17be6352004-10-18 02:59:09 +000010196 // free undef -> unreachable.
10197 if (isa<UndefValue>(Op)) {
10198 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010199 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010200 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010201 return EraseInstFromFunction(FI);
10202 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010203
Chris Lattner6160e852004-02-28 04:57:37 +000010204 // If we have 'free null' delete the instruction. This can happen in stl code
10205 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010206 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010207 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010208
10209 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10210 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10211 FI.setOperand(0, CI->getOperand(0));
10212 return &FI;
10213 }
10214
10215 // Change free (gep X, 0,0,0,0) into free(X)
10216 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10217 if (GEPI->hasAllZeroIndices()) {
10218 AddToWorkList(GEPI);
10219 FI.setOperand(0, GEPI->getOperand(0));
10220 return &FI;
10221 }
10222 }
10223
10224 // Change free(malloc) into nothing, if the malloc has a single use.
10225 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10226 if (MI->hasOneUse()) {
10227 EraseInstFromFunction(FI);
10228 return EraseInstFromFunction(*MI);
10229 }
Chris Lattner6160e852004-02-28 04:57:37 +000010230
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010231 return 0;
10232}
10233
10234
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010235/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010236static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010237 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010238 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010239 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010240
Devang Patel99db6ad2007-10-18 19:52:32 +000010241 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10242 // Instead of loading constant c string, use corresponding integer value
10243 // directly if string length is small enough.
10244 const std::string &Str = CE->getOperand(0)->getStringValue();
10245 if (!Str.empty()) {
10246 unsigned len = Str.length();
10247 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10248 unsigned numBits = Ty->getPrimitiveSizeInBits();
10249 // Replace LI with immediate integer store.
10250 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010251 APInt StrVal(numBits, 0);
10252 APInt SingleChar(numBits, 0);
10253 if (TD->isLittleEndian()) {
10254 for (signed i = len-1; i >= 0; i--) {
10255 SingleChar = (uint64_t) Str[i];
10256 StrVal = (StrVal << 8) | SingleChar;
10257 }
10258 } else {
10259 for (unsigned i = 0; i < len; i++) {
10260 SingleChar = (uint64_t) Str[i];
10261 StrVal = (StrVal << 8) | SingleChar;
10262 }
10263 // Append NULL at the end.
10264 SingleChar = 0;
10265 StrVal = (StrVal << 8) | SingleChar;
10266 }
10267 Value *NL = ConstantInt::get(StrVal);
10268 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010269 }
10270 }
10271 }
10272
Chris Lattnerb89e0712004-07-13 01:49:43 +000010273 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010274 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010275 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010276
Reid Spencer42230162007-01-22 05:51:25 +000010277 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010278 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010279 // If the source is an array, the code below will not succeed. Check to
10280 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10281 // constants.
10282 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10283 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10284 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010285 Value *Idxs[2];
10286 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10287 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010288 SrcTy = cast<PointerType>(CastOp->getType());
10289 SrcPTy = SrcTy->getElementType();
10290 }
10291
Reid Spencer42230162007-01-22 05:51:25 +000010292 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010293 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010294 // Do not allow turning this into a load of an integer, which is then
10295 // casted to a pointer, this pessimizes pointer analysis a lot.
10296 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010297 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10298 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010299
Chris Lattnerf9527852005-01-31 04:50:46 +000010300 // Okay, we are casting from one integer or pointer type to another of
10301 // the same size. Instead of casting the pointer before the load, cast
10302 // the result of the loaded value.
10303 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10304 CI->getName(),
10305 LI.isVolatile()),LI);
10306 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010307 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010308 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010309 }
10310 }
10311 return 0;
10312}
10313
Chris Lattnerc10aced2004-09-19 18:43:46 +000010314/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010315/// from this value cannot trap. If it is not obviously safe to load from the
10316/// specified pointer, we do a quick local scan of the basic block containing
10317/// ScanFrom, to determine if the address is already accessed.
10318static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010319 // If it is an alloca it is always safe to load from.
10320 if (isa<AllocaInst>(V)) return true;
10321
Duncan Sands46318cd2007-09-19 10:25:38 +000010322 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010323 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010324 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010325 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010326
10327 // Otherwise, be a little bit agressive by scanning the local block where we
10328 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010329 // from/to. If so, the previous load or store would have already trapped,
10330 // so there is no harm doing an extra load (also, CSE will later eliminate
10331 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010332 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10333
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010334 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010335 --BBI;
10336
10337 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10338 if (LI->getOperand(0) == V) return true;
10339 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10340 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010341
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010342 }
Chris Lattner8a375202004-09-19 19:18:10 +000010343 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010344}
10345
Chris Lattner8d2e8882007-08-11 18:48:48 +000010346/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10347/// until we find the underlying object a pointer is referring to or something
10348/// we don't understand. Note that the returned pointer may be offset from the
10349/// input, because we ignore GEP indices.
10350static Value *GetUnderlyingObject(Value *Ptr) {
10351 while (1) {
10352 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10353 if (CE->getOpcode() == Instruction::BitCast ||
10354 CE->getOpcode() == Instruction::GetElementPtr)
10355 Ptr = CE->getOperand(0);
10356 else
10357 return Ptr;
10358 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10359 Ptr = BCI->getOperand(0);
10360 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10361 Ptr = GEP->getOperand(0);
10362 } else {
10363 return Ptr;
10364 }
10365 }
10366}
10367
Chris Lattner833b8a42003-06-26 05:06:25 +000010368Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10369 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010370
Dan Gohman9941f742007-07-20 16:34:21 +000010371 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010372 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10373 if (KnownAlign >
10374 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10375 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010376 LI.setAlignment(KnownAlign);
10377
Chris Lattner37366c12005-05-01 04:24:53 +000010378 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010379 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010380 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010381 return Res;
10382
10383 // None of the following transforms are legal for volatile loads.
10384 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010385
Chris Lattner62f254d2005-09-12 22:00:15 +000010386 if (&LI.getParent()->front() != &LI) {
10387 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010388 // If the instruction immediately before this is a store to the same
10389 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010390 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10391 if (SI->getOperand(1) == LI.getOperand(0))
10392 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010393 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10394 if (LIB->getOperand(0) == LI.getOperand(0))
10395 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010396 }
Chris Lattner37366c12005-05-01 04:24:53 +000010397
Christopher Lambb15147e2007-12-29 07:56:53 +000010398 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10399 const Value *GEPI0 = GEPI->getOperand(0);
10400 // TODO: Consider a target hook for valid address spaces for this xform.
10401 if (isa<ConstantPointerNull>(GEPI0) &&
10402 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010403 // Insert a new store to null instruction before the load to indicate
10404 // that this code is not reachable. We do this instead of inserting
10405 // an unreachable instruction directly because we cannot modify the
10406 // CFG.
10407 new StoreInst(UndefValue::get(LI.getType()),
10408 Constant::getNullValue(Op->getType()), &LI);
10409 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10410 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010411 }
Chris Lattner37366c12005-05-01 04:24:53 +000010412
Chris Lattnere87597f2004-10-16 18:11:37 +000010413 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010414 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010415 // TODO: Consider a target hook for valid address spaces for this xform.
10416 if (isa<UndefValue>(C) || (C->isNullValue() &&
10417 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010418 // Insert a new store to null instruction before the load to indicate that
10419 // this code is not reachable. We do this instead of inserting an
10420 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010421 new StoreInst(UndefValue::get(LI.getType()),
10422 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010423 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010424 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010425
Chris Lattnere87597f2004-10-16 18:11:37 +000010426 // Instcombine load (constant global) into the value loaded.
10427 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010428 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010429 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010430
Chris Lattnere87597f2004-10-16 18:11:37 +000010431 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010432 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010433 if (CE->getOpcode() == Instruction::GetElementPtr) {
10434 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010435 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010436 if (Constant *V =
10437 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010438 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010439 if (CE->getOperand(0)->isNullValue()) {
10440 // Insert a new store to null instruction before the load to indicate
10441 // that this code is not reachable. We do this instead of inserting
10442 // an unreachable instruction directly because we cannot modify the
10443 // CFG.
10444 new StoreInst(UndefValue::get(LI.getType()),
10445 Constant::getNullValue(Op->getType()), &LI);
10446 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10447 }
10448
Reid Spencer3da59db2006-11-27 01:05:10 +000010449 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010450 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010451 return Res;
10452 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010453 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010454 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010455
10456 // If this load comes from anywhere in a constant global, and if the global
10457 // is all undef or zero, we know what it loads.
10458 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10459 if (GV->isConstant() && GV->hasInitializer()) {
10460 if (GV->getInitializer()->isNullValue())
10461 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10462 else if (isa<UndefValue>(GV->getInitializer()))
10463 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10464 }
10465 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010466
Chris Lattner37366c12005-05-01 04:24:53 +000010467 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010468 // Change select and PHI nodes to select values instead of addresses: this
10469 // helps alias analysis out a lot, allows many others simplifications, and
10470 // exposes redundancy in the code.
10471 //
10472 // Note that we cannot do the transformation unless we know that the
10473 // introduced loads cannot trap! Something like this is valid as long as
10474 // the condition is always false: load (select bool %C, int* null, int* %G),
10475 // but it would not be valid if we transformed it to load from null
10476 // unconditionally.
10477 //
10478 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10479 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010480 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10481 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010482 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010483 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010484 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010485 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010486 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010487 }
10488
Chris Lattner684fe212004-09-23 15:46:00 +000010489 // load (select (cond, null, P)) -> load P
10490 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10491 if (C->isNullValue()) {
10492 LI.setOperand(0, SI->getOperand(2));
10493 return &LI;
10494 }
10495
10496 // load (select (cond, P, null)) -> load P
10497 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10498 if (C->isNullValue()) {
10499 LI.setOperand(0, SI->getOperand(1));
10500 return &LI;
10501 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010502 }
10503 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010504 return 0;
10505}
10506
Reid Spencer55af2b52007-01-19 21:20:31 +000010507/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010508/// when possible.
10509static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10510 User *CI = cast<User>(SI.getOperand(1));
10511 Value *CastOp = CI->getOperand(0);
10512
10513 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10514 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10515 const Type *SrcPTy = SrcTy->getElementType();
10516
Reid Spencer42230162007-01-22 05:51:25 +000010517 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010518 // If the source is an array, the code below will not succeed. Check to
10519 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10520 // constants.
10521 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10522 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10523 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010524 Value* Idxs[2];
10525 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10526 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010527 SrcTy = cast<PointerType>(CastOp->getType());
10528 SrcPTy = SrcTy->getElementType();
10529 }
10530
Reid Spencer67f827c2007-01-20 23:35:48 +000010531 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10532 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10533 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010534
10535 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010536 // the same size. Instead of casting the pointer before
10537 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010538 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010539 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010540 Instruction::CastOps opcode = Instruction::BitCast;
10541 const Type* CastSrcTy = SIOp0->getType();
10542 const Type* CastDstTy = SrcPTy;
10543 if (isa<PointerType>(CastDstTy)) {
10544 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010545 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010546 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010547 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010548 opcode = Instruction::PtrToInt;
10549 }
10550 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010551 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010552 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010553 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010554 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010555 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010556 return new StoreInst(NewCast, CastOp);
10557 }
10558 }
10559 }
10560 return 0;
10561}
10562
Chris Lattner2f503e62005-01-31 05:36:43 +000010563Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10564 Value *Val = SI.getOperand(0);
10565 Value *Ptr = SI.getOperand(1);
10566
10567 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010568 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010569 ++NumCombined;
10570 return 0;
10571 }
Chris Lattner836692d2007-01-15 06:51:56 +000010572
10573 // If the RHS is an alloca with a single use, zapify the store, making the
10574 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010575 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010576 if (isa<AllocaInst>(Ptr)) {
10577 EraseInstFromFunction(SI);
10578 ++NumCombined;
10579 return 0;
10580 }
10581
10582 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10583 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10584 GEP->getOperand(0)->hasOneUse()) {
10585 EraseInstFromFunction(SI);
10586 ++NumCombined;
10587 return 0;
10588 }
10589 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010590
Dan Gohman9941f742007-07-20 16:34:21 +000010591 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010592 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10593 if (KnownAlign >
10594 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10595 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010596 SI.setAlignment(KnownAlign);
10597
Chris Lattner9ca96412006-02-08 03:25:32 +000010598 // Do really simple DSE, to catch cases where there are several consequtive
10599 // stores to the same location, separated by a few arithmetic operations. This
10600 // situation often occurs with bitfield accesses.
10601 BasicBlock::iterator BBI = &SI;
10602 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10603 --ScanInsts) {
10604 --BBI;
10605
10606 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10607 // Prev store isn't volatile, and stores to the same location?
10608 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10609 ++NumDeadStore;
10610 ++BBI;
10611 EraseInstFromFunction(*PrevSI);
10612 continue;
10613 }
10614 break;
10615 }
10616
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010617 // If this is a load, we have to stop. However, if the loaded value is from
10618 // the pointer we're loading and is producing the pointer we're storing,
10619 // then *this* store is dead (X = load P; store X -> P).
10620 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010621 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010622 EraseInstFromFunction(SI);
10623 ++NumCombined;
10624 return 0;
10625 }
10626 // Otherwise, this is a load from some other location. Stores before it
10627 // may not be dead.
10628 break;
10629 }
10630
Chris Lattner9ca96412006-02-08 03:25:32 +000010631 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010632 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010633 break;
10634 }
10635
10636
10637 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010638
10639 // store X, null -> turns into 'unreachable' in SimplifyCFG
10640 if (isa<ConstantPointerNull>(Ptr)) {
10641 if (!isa<UndefValue>(Val)) {
10642 SI.setOperand(0, UndefValue::get(Val->getType()));
10643 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010644 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010645 ++NumCombined;
10646 }
10647 return 0; // Do not modify these!
10648 }
10649
10650 // store undef, Ptr -> noop
10651 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010652 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010653 ++NumCombined;
10654 return 0;
10655 }
10656
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010657 // If the pointer destination is a cast, see if we can fold the cast into the
10658 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010659 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010660 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10661 return Res;
10662 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010663 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010664 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10665 return Res;
10666
Chris Lattner408902b2005-09-12 23:23:25 +000010667
10668 // If this store is the last instruction in the basic block, and if the block
10669 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010670 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010671 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010672 if (BI->isUnconditional())
10673 if (SimplifyStoreAtEndOfBlock(SI))
10674 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010675
Chris Lattner2f503e62005-01-31 05:36:43 +000010676 return 0;
10677}
10678
Chris Lattner3284d1f2007-04-15 00:07:55 +000010679/// SimplifyStoreAtEndOfBlock - Turn things like:
10680/// if () { *P = v1; } else { *P = v2 }
10681/// into a phi node with a store in the successor.
10682///
Chris Lattner31755a02007-04-15 01:02:18 +000010683/// Simplify things like:
10684/// *P = v1; if () { *P = v2; }
10685/// into a phi node with a store in the successor.
10686///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010687bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10688 BasicBlock *StoreBB = SI.getParent();
10689
10690 // Check to see if the successor block has exactly two incoming edges. If
10691 // so, see if the other predecessor contains a store to the same location.
10692 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010693 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010694
10695 // Determine whether Dest has exactly two predecessors and, if so, compute
10696 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010697 pred_iterator PI = pred_begin(DestBB);
10698 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010699 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010700 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010701 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010702 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010703 return false;
10704
10705 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010706 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010707 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010708 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010709 }
Chris Lattner31755a02007-04-15 01:02:18 +000010710 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010711 return false;
10712
10713
Chris Lattner31755a02007-04-15 01:02:18 +000010714 // Verify that the other block ends in a branch and is not otherwise empty.
10715 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010716 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010717 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010718 return false;
10719
Chris Lattner31755a02007-04-15 01:02:18 +000010720 // If the other block ends in an unconditional branch, check for the 'if then
10721 // else' case. there is an instruction before the branch.
10722 StoreInst *OtherStore = 0;
10723 if (OtherBr->isUnconditional()) {
10724 // If this isn't a store, or isn't a store to the same location, bail out.
10725 --BBI;
10726 OtherStore = dyn_cast<StoreInst>(BBI);
10727 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10728 return false;
10729 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010730 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010731 // destinations is StoreBB, then we have the if/then case.
10732 if (OtherBr->getSuccessor(0) != StoreBB &&
10733 OtherBr->getSuccessor(1) != StoreBB)
10734 return false;
10735
10736 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010737 // if/then triangle. See if there is a store to the same ptr as SI that
10738 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010739 for (;; --BBI) {
10740 // Check to see if we find the matching store.
10741 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10742 if (OtherStore->getOperand(1) != SI.getOperand(1))
10743 return false;
10744 break;
10745 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010746 // If we find something that may be using the stored value, or if we run
10747 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010748 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10749 BBI == OtherBB->begin())
10750 return false;
10751 }
10752
10753 // In order to eliminate the store in OtherBr, we have to
10754 // make sure nothing reads the stored value in StoreBB.
10755 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10756 // FIXME: This should really be AA driven.
10757 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10758 return false;
10759 }
10760 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010761
Chris Lattner31755a02007-04-15 01:02:18 +000010762 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010763 Value *MergedVal = OtherStore->getOperand(0);
10764 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010765 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010766 PN->reserveOperandSpace(2);
10767 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010768 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10769 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010770 }
10771
10772 // Advance to a place where it is safe to insert the new store and
10773 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010774 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010775 while (isa<PHINode>(BBI)) ++BBI;
10776 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10777 OtherStore->isVolatile()), *BBI);
10778
10779 // Nuke the old stores.
10780 EraseInstFromFunction(SI);
10781 EraseInstFromFunction(*OtherStore);
10782 ++NumCombined;
10783 return true;
10784}
10785
Chris Lattner2f503e62005-01-31 05:36:43 +000010786
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010787Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10788 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010789 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010790 BasicBlock *TrueDest;
10791 BasicBlock *FalseDest;
10792 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10793 !isa<Constant>(X)) {
10794 // Swap Destinations and condition...
10795 BI.setCondition(X);
10796 BI.setSuccessor(0, FalseDest);
10797 BI.setSuccessor(1, TrueDest);
10798 return &BI;
10799 }
10800
Reid Spencere4d87aa2006-12-23 06:05:41 +000010801 // Cannonicalize fcmp_one -> fcmp_oeq
10802 FCmpInst::Predicate FPred; Value *Y;
10803 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10804 TrueDest, FalseDest)))
10805 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10806 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10807 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010808 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010809 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10810 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010811 // Swap Destinations and condition...
10812 BI.setCondition(NewSCC);
10813 BI.setSuccessor(0, FalseDest);
10814 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010815 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010816 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010817 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010818 return &BI;
10819 }
10820
10821 // Cannonicalize icmp_ne -> icmp_eq
10822 ICmpInst::Predicate IPred;
10823 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10824 TrueDest, FalseDest)))
10825 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10826 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10827 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10828 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010829 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010830 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10831 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010832 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010833 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010834 BI.setSuccessor(0, FalseDest);
10835 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010836 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010837 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010838 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010839 return &BI;
10840 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010841
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010842 return 0;
10843}
Chris Lattner0864acf2002-11-04 16:18:53 +000010844
Chris Lattner46238a62004-07-03 00:26:11 +000010845Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10846 Value *Cond = SI.getCondition();
10847 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10848 if (I->getOpcode() == Instruction::Add)
10849 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10850 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10851 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010852 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010853 AddRHS));
10854 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010855 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010856 return &SI;
10857 }
10858 }
10859 return 0;
10860}
10861
Chris Lattner220b0cf2006-03-05 00:22:33 +000010862/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10863/// is to leave as a vector operation.
10864static bool CheapToScalarize(Value *V, bool isConstant) {
10865 if (isa<ConstantAggregateZero>(V))
10866 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010867 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010868 if (isConstant) return true;
10869 // If all elts are the same, we can extract.
10870 Constant *Op0 = C->getOperand(0);
10871 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10872 if (C->getOperand(i) != Op0)
10873 return false;
10874 return true;
10875 }
10876 Instruction *I = dyn_cast<Instruction>(V);
10877 if (!I) return false;
10878
10879 // Insert element gets simplified to the inserted element or is deleted if
10880 // this is constant idx extract element and its a constant idx insertelt.
10881 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10882 isa<ConstantInt>(I->getOperand(2)))
10883 return true;
10884 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10885 return true;
10886 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10887 if (BO->hasOneUse() &&
10888 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10889 CheapToScalarize(BO->getOperand(1), isConstant)))
10890 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010891 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10892 if (CI->hasOneUse() &&
10893 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10894 CheapToScalarize(CI->getOperand(1), isConstant)))
10895 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010896
10897 return false;
10898}
10899
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010900/// Read and decode a shufflevector mask.
10901///
10902/// It turns undef elements into values that are larger than the number of
10903/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010904static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10905 unsigned NElts = SVI->getType()->getNumElements();
10906 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10907 return std::vector<unsigned>(NElts, 0);
10908 if (isa<UndefValue>(SVI->getOperand(2)))
10909 return std::vector<unsigned>(NElts, 2*NElts);
10910
10911 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010912 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010913 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10914 if (isa<UndefValue>(CP->getOperand(i)))
10915 Result.push_back(NElts*2); // undef -> 8
10916 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010917 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010918 return Result;
10919}
10920
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010921/// FindScalarElement - Given a vector and an element number, see if the scalar
10922/// value is already around as a register, for example if it were inserted then
10923/// extracted from the vector.
10924static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010925 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10926 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010927 unsigned Width = PTy->getNumElements();
10928 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010929 return UndefValue::get(PTy->getElementType());
10930
10931 if (isa<UndefValue>(V))
10932 return UndefValue::get(PTy->getElementType());
10933 else if (isa<ConstantAggregateZero>(V))
10934 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010935 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010936 return CP->getOperand(EltNo);
10937 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10938 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010939 if (!isa<ConstantInt>(III->getOperand(2)))
10940 return 0;
10941 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010942
10943 // If this is an insert to the element we are looking for, return the
10944 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010945 if (EltNo == IIElt)
10946 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010947
10948 // Otherwise, the insertelement doesn't modify the value, recurse on its
10949 // vector input.
10950 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010951 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010952 unsigned InEl = getShuffleMask(SVI)[EltNo];
10953 if (InEl < Width)
10954 return FindScalarElement(SVI->getOperand(0), InEl);
10955 else if (InEl < Width*2)
10956 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10957 else
10958 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010959 }
10960
10961 // Otherwise, we don't know.
10962 return 0;
10963}
10964
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010965Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010966
Dan Gohman07a96762007-07-16 14:29:03 +000010967 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010968 if (isa<UndefValue>(EI.getOperand(0)))
10969 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10970
Dan Gohman07a96762007-07-16 14:29:03 +000010971 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010972 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10973 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10974
Reid Spencer9d6565a2007-02-15 02:26:10 +000010975 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010976 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010977 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010978 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010979 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010980 if (C->getOperand(i) != op0) {
10981 op0 = 0;
10982 break;
10983 }
10984 if (op0)
10985 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010986 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010987
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010988 // If extracting a specified index from the vector, see if we can recursively
10989 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010990 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010991 unsigned IndexVal = IdxC->getZExtValue();
10992 unsigned VectorWidth =
10993 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10994
10995 // If this is extracting an invalid index, turn this into undef, to avoid
10996 // crashing the code below.
10997 if (IndexVal >= VectorWidth)
10998 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10999
Chris Lattner867b99f2006-10-05 06:55:50 +000011000 // This instruction only demands the single element from the input vector.
11001 // If the input vector has a single use, simplify it based on this use
11002 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011003 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011004 uint64_t UndefElts;
11005 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000011006 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000011007 UndefElts)) {
11008 EI.setOperand(0, V);
11009 return &EI;
11010 }
11011 }
11012
Reid Spencerb83eb642006-10-20 07:07:24 +000011013 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011014 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011015
11016 // If the this extractelement is directly using a bitcast from a vector of
11017 // the same number of elements, see if we can find the source element from
11018 // it. In this case, we will end up needing to bitcast the scalars.
11019 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11020 if (const VectorType *VT =
11021 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11022 if (VT->getNumElements() == VectorWidth)
11023 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11024 return new BitCastInst(Elt, EI.getType());
11025 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011026 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011027
Chris Lattner73fa49d2006-05-25 22:53:38 +000011028 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011029 if (I->hasOneUse()) {
11030 // Push extractelement into predecessor operation if legal and
11031 // profitable to do so
11032 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011033 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11034 if (CheapToScalarize(BO, isConstantElt)) {
11035 ExtractElementInst *newEI0 =
11036 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11037 EI.getName()+".lhs");
11038 ExtractElementInst *newEI1 =
11039 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11040 EI.getName()+".rhs");
11041 InsertNewInstBefore(newEI0, EI);
11042 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011043 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011044 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011045 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011046 unsigned AS =
11047 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011048 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11049 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011050 GetElementPtrInst *GEP =
11051 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011052 InsertNewInstBefore(GEP, EI);
11053 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011054 }
11055 }
11056 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11057 // Extracting the inserted element?
11058 if (IE->getOperand(2) == EI.getOperand(1))
11059 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11060 // If the inserted and extracted elements are constants, they must not
11061 // be the same value, extract from the pre-inserted value instead.
11062 if (isa<Constant>(IE->getOperand(2)) &&
11063 isa<Constant>(EI.getOperand(1))) {
11064 AddUsesToWorkList(EI);
11065 EI.setOperand(0, IE->getOperand(0));
11066 return &EI;
11067 }
11068 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11069 // If this is extracting an element from a shufflevector, figure out where
11070 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011071 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11072 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011073 Value *Src;
11074 if (SrcIdx < SVI->getType()->getNumElements())
11075 Src = SVI->getOperand(0);
11076 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11077 SrcIdx -= SVI->getType()->getNumElements();
11078 Src = SVI->getOperand(1);
11079 } else {
11080 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011081 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011082 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011083 }
11084 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011085 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011086 return 0;
11087}
11088
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011089/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11090/// elements from either LHS or RHS, return the shuffle mask and true.
11091/// Otherwise, return false.
11092static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11093 std::vector<Constant*> &Mask) {
11094 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11095 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011096 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011097
11098 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011099 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011100 return true;
11101 } else if (V == LHS) {
11102 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011103 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011104 return true;
11105 } else if (V == RHS) {
11106 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011107 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011108 return true;
11109 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11110 // If this is an insert of an extract from some other vector, include it.
11111 Value *VecOp = IEI->getOperand(0);
11112 Value *ScalarOp = IEI->getOperand(1);
11113 Value *IdxOp = IEI->getOperand(2);
11114
Chris Lattnerd929f062006-04-27 21:14:21 +000011115 if (!isa<ConstantInt>(IdxOp))
11116 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011117 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011118
11119 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11120 // Okay, we can handle this if the vector we are insertinting into is
11121 // transitively ok.
11122 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11123 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011124 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011125 return true;
11126 }
11127 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11128 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011129 EI->getOperand(0)->getType() == V->getType()) {
11130 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011131 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011132
11133 // This must be extracting from either LHS or RHS.
11134 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11135 // Okay, we can handle this if the vector we are insertinting into is
11136 // transitively ok.
11137 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11138 // If so, update the mask to reflect the inserted value.
11139 if (EI->getOperand(0) == LHS) {
11140 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011141 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011142 } else {
11143 assert(EI->getOperand(0) == RHS);
11144 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011145 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011146
11147 }
11148 return true;
11149 }
11150 }
11151 }
11152 }
11153 }
11154 // TODO: Handle shufflevector here!
11155
11156 return false;
11157}
11158
11159/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11160/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11161/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011162static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011163 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011164 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011165 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011166 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011167 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011168
11169 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011170 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011171 return V;
11172 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011173 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011174 return V;
11175 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11176 // If this is an insert of an extract from some other vector, include it.
11177 Value *VecOp = IEI->getOperand(0);
11178 Value *ScalarOp = IEI->getOperand(1);
11179 Value *IdxOp = IEI->getOperand(2);
11180
11181 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11182 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11183 EI->getOperand(0)->getType() == V->getType()) {
11184 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011185 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11186 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011187
11188 // Either the extracted from or inserted into vector must be RHSVec,
11189 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011190 if (EI->getOperand(0) == RHS || RHS == 0) {
11191 RHS = EI->getOperand(0);
11192 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011193 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011194 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011195 return V;
11196 }
11197
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011198 if (VecOp == RHS) {
11199 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011200 // Everything but the extracted element is replaced with the RHS.
11201 for (unsigned i = 0; i != NumElts; ++i) {
11202 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011203 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011204 }
11205 return V;
11206 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011207
11208 // If this insertelement is a chain that comes from exactly these two
11209 // vectors, return the vector and the effective shuffle.
11210 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11211 return EI->getOperand(0);
11212
Chris Lattnerefb47352006-04-15 01:39:45 +000011213 }
11214 }
11215 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011216 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011217
11218 // Otherwise, can't do anything fancy. Return an identity vector.
11219 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011220 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011221 return V;
11222}
11223
11224Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11225 Value *VecOp = IE.getOperand(0);
11226 Value *ScalarOp = IE.getOperand(1);
11227 Value *IdxOp = IE.getOperand(2);
11228
Chris Lattner599ded12007-04-09 01:11:16 +000011229 // Inserting an undef or into an undefined place, remove this.
11230 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11231 ReplaceInstUsesWith(IE, VecOp);
11232
Chris Lattnerefb47352006-04-15 01:39:45 +000011233 // If the inserted element was extracted from some other vector, and if the
11234 // indexes are constant, try to turn this into a shufflevector operation.
11235 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11236 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11237 EI->getOperand(0)->getType() == IE.getType()) {
11238 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011239 unsigned ExtractedIdx =
11240 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011241 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011242
11243 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11244 return ReplaceInstUsesWith(IE, VecOp);
11245
11246 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11247 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11248
11249 // If we are extracting a value from a vector, then inserting it right
11250 // back into the same place, just use the input vector.
11251 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11252 return ReplaceInstUsesWith(IE, VecOp);
11253
11254 // We could theoretically do this for ANY input. However, doing so could
11255 // turn chains of insertelement instructions into a chain of shufflevector
11256 // instructions, and right now we do not merge shufflevectors. As such,
11257 // only do this in a situation where it is clear that there is benefit.
11258 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11259 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11260 // the values of VecOp, except then one read from EIOp0.
11261 // Build a new shuffle mask.
11262 std::vector<Constant*> Mask;
11263 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011264 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011265 else {
11266 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011267 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011268 NumVectorElts));
11269 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011270 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011271 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011272 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011273 }
11274
11275 // If this insertelement isn't used by some other insertelement, turn it
11276 // (and any insertelements it points to), into one big shuffle.
11277 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11278 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011279 Value *RHS = 0;
11280 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11281 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11282 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011283 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011284 }
11285 }
11286 }
11287
11288 return 0;
11289}
11290
11291
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011292Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11293 Value *LHS = SVI.getOperand(0);
11294 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011295 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011296
11297 bool MadeChange = false;
11298
Chris Lattner867b99f2006-10-05 06:55:50 +000011299 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011300 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011301 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11302
Chris Lattnere4929dd2007-01-05 07:36:08 +000011303 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011304 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011305 if (isa<UndefValue>(SVI.getOperand(1))) {
11306 // Scan to see if there are any references to the RHS. If so, replace them
11307 // with undef element refs and set MadeChange to true.
11308 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11309 if (Mask[i] >= e && Mask[i] != 2*e) {
11310 Mask[i] = 2*e;
11311 MadeChange = true;
11312 }
11313 }
11314
11315 if (MadeChange) {
11316 // Remap any references to RHS to use LHS.
11317 std::vector<Constant*> Elts;
11318 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11319 if (Mask[i] == 2*e)
11320 Elts.push_back(UndefValue::get(Type::Int32Ty));
11321 else
11322 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11323 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011324 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011325 }
11326 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011327
Chris Lattner863bcff2006-05-25 23:48:38 +000011328 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11329 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11330 if (LHS == RHS || isa<UndefValue>(LHS)) {
11331 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011332 // shuffle(undef,undef,mask) -> undef.
11333 return ReplaceInstUsesWith(SVI, LHS);
11334 }
11335
Chris Lattner863bcff2006-05-25 23:48:38 +000011336 // Remap any references to RHS to use LHS.
11337 std::vector<Constant*> Elts;
11338 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011339 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011340 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011341 else {
11342 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11343 (Mask[i] < e && isa<UndefValue>(LHS)))
11344 Mask[i] = 2*e; // Turn into undef.
11345 else
11346 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011347 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011348 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011349 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011350 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011351 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011352 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011353 LHS = SVI.getOperand(0);
11354 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011355 MadeChange = true;
11356 }
11357
Chris Lattner7b2e27922006-05-26 00:29:06 +000011358 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011359 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011360
Chris Lattner863bcff2006-05-25 23:48:38 +000011361 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11362 if (Mask[i] >= e*2) continue; // Ignore undef values.
11363 // Is this an identity shuffle of the LHS value?
11364 isLHSID &= (Mask[i] == i);
11365
11366 // Is this an identity shuffle of the RHS value?
11367 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011368 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011369
Chris Lattner863bcff2006-05-25 23:48:38 +000011370 // Eliminate identity shuffles.
11371 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11372 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011373
Chris Lattner7b2e27922006-05-26 00:29:06 +000011374 // If the LHS is a shufflevector itself, see if we can combine it with this
11375 // one without producing an unusual shuffle. Here we are really conservative:
11376 // we are absolutely afraid of producing a shuffle mask not in the input
11377 // program, because the code gen may not be smart enough to turn a merged
11378 // shuffle into two specific shuffles: it may produce worse code. As such,
11379 // we only merge two shuffles if the result is one of the two input shuffle
11380 // masks. In this case, merging the shuffles just removes one instruction,
11381 // which we know is safe. This is good for things like turning:
11382 // (splat(splat)) -> splat.
11383 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11384 if (isa<UndefValue>(RHS)) {
11385 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11386
11387 std::vector<unsigned> NewMask;
11388 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11389 if (Mask[i] >= 2*e)
11390 NewMask.push_back(2*e);
11391 else
11392 NewMask.push_back(LHSMask[Mask[i]]);
11393
11394 // If the result mask is equal to the src shuffle or this shuffle mask, do
11395 // the replacement.
11396 if (NewMask == LHSMask || NewMask == Mask) {
11397 std::vector<Constant*> Elts;
11398 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11399 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011400 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011401 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011402 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011403 }
11404 }
11405 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11406 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011407 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011408 }
11409 }
11410 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011411
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011412 return MadeChange ? &SVI : 0;
11413}
11414
11415
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011416
Chris Lattnerea1c4542004-12-08 23:43:58 +000011417
11418/// TryToSinkInstruction - Try to move the specified instruction from its
11419/// current block into the beginning of DestBlock, which can only happen if it's
11420/// safe to move the instruction past all of the instructions between it and the
11421/// end of its block.
11422static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11423 assert(I->hasOneUse() && "Invariants didn't hold!");
11424
Chris Lattner108e9022005-10-27 17:13:11 +000011425 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011426 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11427 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011428
Chris Lattnerea1c4542004-12-08 23:43:58 +000011429 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011430 if (isa<AllocaInst>(I) && I->getParent() ==
11431 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011432 return false;
11433
Chris Lattner96a52a62004-12-09 07:14:34 +000011434 // We can only sink load instructions if there is nothing between the load and
11435 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011436 if (I->mayReadFromMemory()) {
11437 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011438 Scan != E; ++Scan)
11439 if (Scan->mayWriteToMemory())
11440 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011441 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011442
11443 BasicBlock::iterator InsertPos = DestBlock->begin();
11444 while (isa<PHINode>(InsertPos)) ++InsertPos;
11445
Chris Lattner4bc5f802005-08-08 19:11:57 +000011446 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011447 ++NumSunkInst;
11448 return true;
11449}
11450
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011451
11452/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11453/// all reachable code to the worklist.
11454///
11455/// This has a couple of tricks to make the code faster and more powerful. In
11456/// particular, we constant fold and DCE instructions as we go, to avoid adding
11457/// them to the worklist (this significantly speeds up instcombine on code where
11458/// many instructions are dead or constant). Additionally, if we find a branch
11459/// whose condition is a known constant, we only visit the reachable successors.
11460///
11461static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011462 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011463 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011464 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011465 std::vector<BasicBlock*> Worklist;
11466 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011467
Chris Lattner2c7718a2007-03-23 19:17:18 +000011468 while (!Worklist.empty()) {
11469 BB = Worklist.back();
11470 Worklist.pop_back();
11471
11472 // We have now visited this block! If we've already been here, ignore it.
11473 if (!Visited.insert(BB)) continue;
11474
11475 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11476 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011477
Chris Lattner2c7718a2007-03-23 19:17:18 +000011478 // DCE instruction if trivially dead.
11479 if (isInstructionTriviallyDead(Inst)) {
11480 ++NumDeadInst;
11481 DOUT << "IC: DCE: " << *Inst;
11482 Inst->eraseFromParent();
11483 continue;
11484 }
11485
11486 // ConstantProp instruction if trivially constant.
11487 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11488 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11489 Inst->replaceAllUsesWith(C);
11490 ++NumConstProp;
11491 Inst->eraseFromParent();
11492 continue;
11493 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011494
Chris Lattner2c7718a2007-03-23 19:17:18 +000011495 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011496 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011497
11498 // Recursively visit successors. If this is a branch or switch on a
11499 // constant, only visit the reachable successor.
11500 TerminatorInst *TI = BB->getTerminator();
11501 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11502 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11503 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011504 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011505 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011506 continue;
11507 }
11508 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11509 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11510 // See if this is an explicit destination.
11511 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11512 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011513 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011514 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011515 continue;
11516 }
11517
11518 // Otherwise it is the default destination.
11519 Worklist.push_back(SI->getSuccessor(0));
11520 continue;
11521 }
11522 }
11523
11524 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11525 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011526 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011527}
11528
Chris Lattnerec9c3582007-03-03 02:04:50 +000011529bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011530 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011531 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011532
11533 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11534 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011535
Chris Lattnerb3d59702005-07-07 20:40:38 +000011536 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011537 // Do a depth-first traversal of the function, populate the worklist with
11538 // the reachable instructions. Ignore blocks that are not reachable. Keep
11539 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011540 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011541 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011542
Chris Lattnerb3d59702005-07-07 20:40:38 +000011543 // Do a quick scan over the function. If we find any blocks that are
11544 // unreachable, remove any instructions inside of them. This prevents
11545 // the instcombine code from having to deal with some bad special cases.
11546 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11547 if (!Visited.count(BB)) {
11548 Instruction *Term = BB->getTerminator();
11549 while (Term != BB->begin()) { // Remove instrs bottom-up
11550 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011551
Bill Wendlingb7427032006-11-26 09:46:52 +000011552 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011553 ++NumDeadInst;
11554
11555 if (!I->use_empty())
11556 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11557 I->eraseFromParent();
11558 }
11559 }
11560 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011561
Chris Lattnerdbab3862007-03-02 21:28:56 +000011562 while (!Worklist.empty()) {
11563 Instruction *I = RemoveOneFromWorkList();
11564 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011565
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011566 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011567 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011568 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011569 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011570 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011571 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011572
Bill Wendlingb7427032006-11-26 09:46:52 +000011573 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011574
11575 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011576 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011577 continue;
11578 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011579
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011580 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011581 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011582 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011583
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011584 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011585 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011586 ReplaceInstUsesWith(*I, C);
11587
Chris Lattner62b14df2002-09-02 04:59:56 +000011588 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011589 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011590 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011591 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011592 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011593
Chris Lattnerea1c4542004-12-08 23:43:58 +000011594 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011595 // FIXME: Remove GetResultInst test when first class support for aggregates
11596 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011597 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011598 BasicBlock *BB = I->getParent();
11599 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11600 if (UserParent != BB) {
11601 bool UserIsSuccessor = false;
11602 // See if the user is one of our successors.
11603 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11604 if (*SI == UserParent) {
11605 UserIsSuccessor = true;
11606 break;
11607 }
11608
11609 // If the user is one of our immediate successors, and if that successor
11610 // only has us as a predecessors (we'd have to split the critical edge
11611 // otherwise), we can keep going.
11612 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11613 next(pred_begin(UserParent)) == pred_end(UserParent))
11614 // Okay, the CFG is simple enough, try to sink this instruction.
11615 Changed |= TryToSinkInstruction(I, UserParent);
11616 }
11617 }
11618
Chris Lattner8a2a3112001-12-14 16:52:21 +000011619 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011620#ifndef NDEBUG
11621 std::string OrigI;
11622#endif
11623 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011624 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011625 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011626 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011627 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011628 DOUT << "IC: Old = " << *I
11629 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011630
Chris Lattnerf523d062004-06-09 05:08:07 +000011631 // Everything uses the new instruction now.
11632 I->replaceAllUsesWith(Result);
11633
11634 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011635 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011636 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011637
Chris Lattner6934a042007-02-11 01:23:03 +000011638 // Move the name to the new instruction first.
11639 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011640
11641 // Insert the new instruction into the basic block...
11642 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011643 BasicBlock::iterator InsertPos = I;
11644
11645 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11646 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11647 ++InsertPos;
11648
11649 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011650
Chris Lattner00d51312004-05-01 23:27:23 +000011651 // Make sure that we reprocess all operands now that we reduced their
11652 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011653 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011654
Chris Lattnerf523d062004-06-09 05:08:07 +000011655 // Instructions can end up on the worklist more than once. Make sure
11656 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011657 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011658
11659 // Erase the old instruction.
11660 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011661 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011662#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011663 DOUT << "IC: Mod = " << OrigI
11664 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011665#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011666
Chris Lattner90ac28c2002-08-02 19:29:35 +000011667 // If the instruction was modified, it's possible that it is now dead.
11668 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011669 if (isInstructionTriviallyDead(I)) {
11670 // Make sure we process all operands now that we are reducing their
11671 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011672 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011673
Chris Lattner00d51312004-05-01 23:27:23 +000011674 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011675 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011676 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011677 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011678 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011679 AddToWorkList(I);
11680 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011681 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011682 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011683 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011684 }
11685 }
11686
Chris Lattnerec9c3582007-03-03 02:04:50 +000011687 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011688
11689 // Do an explicit clear, this shrinks the map if needed.
11690 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011691 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011692}
11693
Chris Lattnerec9c3582007-03-03 02:04:50 +000011694
11695bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011696 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11697
Chris Lattnerec9c3582007-03-03 02:04:50 +000011698 bool EverMadeChange = false;
11699
11700 // Iterate while there is work to do.
11701 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011702 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011703 EverMadeChange = true;
11704 return EverMadeChange;
11705}
11706
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011707FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011708 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011709}
Brian Gaeked0fde302003-11-11 22:41:34 +000011710