blob: 41282f2650e4d3a592c0a9e727bac3caa1491149 [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);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000188 Instruction *visitFCmpInst(FCmpInst &I);
189 Instruction *visitICmpInst(ICmpInst &I);
190 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000191 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
192 Instruction *LHS,
193 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000194 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
195 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000196
Reid Spencere4d87aa2006-12-23 06:05:41 +0000197 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
198 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000199 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000200 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000201 Instruction *commonCastTransforms(CastInst &CI);
202 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000203 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000204 Instruction *visitTrunc(TruncInst &CI);
205 Instruction *visitZExt(ZExtInst &CI);
206 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000207 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000208 Instruction *visitFPExt(CastInst &CI);
209 Instruction *visitFPToUI(CastInst &CI);
210 Instruction *visitFPToSI(CastInst &CI);
211 Instruction *visitUIToFP(CastInst &CI);
212 Instruction *visitSIToFP(CastInst &CI);
213 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000214 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000215 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000216 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
217 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000218 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000219 Instruction *visitCallInst(CallInst &CI);
220 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000221 Instruction *visitPHINode(PHINode &PN);
222 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000223 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000224 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000225 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000226 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000227 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000228 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000229 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000230 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000231 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000232
233 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000234 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000235
Chris Lattner9fe38862003-06-19 17:00:31 +0000236 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000237 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000238 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000239 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000240 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
241 bool DoXform = true);
Chris Lattner9fe38862003-06-19 17:00:31 +0000242
Chris Lattner28977af2004-04-05 01:30:19 +0000243 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000244 // InsertNewInstBefore - insert an instruction New before instruction Old
245 // in the program. Add the new instruction to the worklist.
246 //
Chris Lattner955f3312004-09-28 21:48:02 +0000247 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000248 assert(New && New->getParent() == 0 &&
249 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000250 BasicBlock *BB = Old.getParent();
251 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000252 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000253 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000254 }
255
Chris Lattner0c967662004-09-24 15:21:34 +0000256 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
257 /// This also adds the cast to the worklist. Finally, this returns the
258 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000259 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
260 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000261 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000262
Chris Lattnere2ed0572006-04-06 19:19:17 +0000263 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000264 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000265
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000266 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000267 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000268 return C;
269 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000270
271 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
272 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
273 }
274
Chris Lattner0c967662004-09-24 15:21:34 +0000275
Chris Lattner8b170942002-08-09 23:47:40 +0000276 // ReplaceInstUsesWith - This method is to be used when an instruction is
277 // found to be dead, replacable with another preexisting expression. Here
278 // we add all uses of I to the worklist, replace all uses of I with the new
279 // value, then return I, so that the inst combiner will know that I was
280 // modified.
281 //
282 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000283 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000284 if (&I != V) {
285 I.replaceAllUsesWith(V);
286 return &I;
287 } else {
288 // If we are replacing the instruction with itself, this must be in a
289 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000290 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000291 return &I;
292 }
Chris Lattner8b170942002-08-09 23:47:40 +0000293 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000294
Chris Lattner6dce1a72006-02-07 06:56:34 +0000295 // UpdateValueUsesWith - This method is to be used when an value is
296 // found to be replacable with another preexisting expression or was
297 // updated. Here we add all uses of I to the worklist, replace all uses of
298 // I with the new value (unless the instruction was just updated), then
299 // return true, so that the inst combiner will know that I was modified.
300 //
301 bool UpdateValueUsesWith(Value *Old, Value *New) {
302 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
303 if (Old != New)
304 Old->replaceAllUsesWith(New);
305 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000306 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000307 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000308 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000309 return true;
310 }
311
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000312 // EraseInstFromFunction - When dealing with an instruction that has side
313 // effects or produces a void value, we can't rely on DCE to delete the
314 // instruction. Instead, visit methods should return the value returned by
315 // this function.
316 Instruction *EraseInstFromFunction(Instruction &I) {
317 assert(I.use_empty() && "Cannot erase instruction that is used!");
318 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000319 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000320 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000321 return 0; // Don't do anything with FI
322 }
323
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000324 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000325 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
326 /// InsertBefore instruction. This is specialized a bit to avoid inserting
327 /// casts that are known to not do anything...
328 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000329 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
330 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000331 Instruction *InsertBefore);
332
Reid Spencere4d87aa2006-12-23 06:05:41 +0000333 /// SimplifyCommutative - This performs a few simplifications for
334 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000335 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000336
Reid Spencere4d87aa2006-12-23 06:05:41 +0000337 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
338 /// most-complex to least-complex order.
339 bool SimplifyCompare(CmpInst &I);
340
Reid Spencer2ec619a2007-03-23 21:24:59 +0000341 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
342 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000343 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
344 APInt& KnownZero, APInt& KnownOne,
345 unsigned Depth = 0);
346
Chris Lattner867b99f2006-10-05 06:55:50 +0000347 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
348 uint64_t &UndefElts, unsigned Depth = 0);
349
Chris Lattner4e998b22004-09-29 05:07:12 +0000350 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
351 // PHI node as operand #0, see if we can fold the instruction into the PHI
352 // (which is only possible if all operands to the PHI are constants).
353 Instruction *FoldOpIntoPhi(Instruction &I);
354
Chris Lattnerbac32862004-11-14 19:13:23 +0000355 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
356 // operator and they all are only used by the PHI, PHI together their
357 // inputs, and do the operation once, to the result of the PHI.
358 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000359 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
360
361
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000362 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
363 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000364
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000365 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000366 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000367 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000368 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000369 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000370 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000371 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000372 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000373 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000374
Chris Lattnerafe91a52006-06-15 19:07:26 +0000375
Reid Spencerc55b2432006-12-13 18:21:21 +0000376 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000377
378 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
379 APInt& KnownOne, unsigned Depth = 0);
380 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
381 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
382 unsigned CastOpc,
383 int &NumCastsRemoved);
384 unsigned GetOrEnforceKnownAlignment(Value *V,
385 unsigned PrefAlign = 0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000386 };
387}
388
Dan Gohman844731a2008-05-13 00:00:25 +0000389char InstCombiner::ID = 0;
390static RegisterPass<InstCombiner>
391X("instcombine", "Combine redundant instructions");
392
Chris Lattner4f98c562003-03-10 21:43:22 +0000393// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000394// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000395static unsigned getComplexity(Value *V) {
396 if (isa<Instruction>(V)) {
397 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000398 return 3;
399 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000400 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000401 if (isa<Argument>(V)) return 3;
402 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000403}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000404
Chris Lattnerc8802d22003-03-11 00:12:48 +0000405// isOnlyUse - Return true if this instruction will be deleted if we stop using
406// it.
407static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000408 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000409}
410
Chris Lattner4cb170c2004-02-23 06:38:22 +0000411// getPromotedType - Return the specified type promoted as it would be to pass
412// though a va_arg area...
413static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000414 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
415 if (ITy->getBitWidth() < 32)
416 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000417 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000418 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000419}
420
Reid Spencer3da59db2006-11-27 01:05:10 +0000421/// getBitCastOperand - If the specified operand is a CastInst or a constant
422/// expression bitcast, return the operand value, otherwise return null.
423static Value *getBitCastOperand(Value *V) {
424 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000425 return I->getOperand(0);
426 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000427 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000428 return CE->getOperand(0);
429 return 0;
430}
431
Reid Spencer3da59db2006-11-27 01:05:10 +0000432/// This function is a wrapper around CastInst::isEliminableCastPair. It
433/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000434static Instruction::CastOps
435isEliminableCastPair(
436 const CastInst *CI, ///< The first cast instruction
437 unsigned opcode, ///< The opcode of the second cast instruction
438 const Type *DstTy, ///< The target type for the second cast instruction
439 TargetData *TD ///< The target data for pointer size
440) {
441
442 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
443 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000444
Reid Spencer3da59db2006-11-27 01:05:10 +0000445 // Get the opcodes of the two Cast instructions
446 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
447 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000448
Reid Spencer3da59db2006-11-27 01:05:10 +0000449 return Instruction::CastOps(
450 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
451 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000452}
453
454/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
455/// in any code being generated. It does not require codegen if V is simple
456/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000457static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
458 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000459 if (V->getType() == Ty || isa<Constant>(V)) return false;
460
Chris Lattner01575b72006-05-25 23:24:33 +0000461 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000462 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000463 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000464 return false;
465 return true;
466}
467
468/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
469/// InsertBefore instruction. This is specialized a bit to avoid inserting
470/// casts that are known to not do anything...
471///
Reid Spencer17212df2006-12-12 09:18:51 +0000472Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
473 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000474 Instruction *InsertBefore) {
475 if (V->getType() == DestTy) return V;
476 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000477 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000478
Reid Spencer17212df2006-12-12 09:18:51 +0000479 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000480}
481
Chris Lattner4f98c562003-03-10 21:43:22 +0000482// SimplifyCommutative - This performs a few simplifications for commutative
483// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000484//
Chris Lattner4f98c562003-03-10 21:43:22 +0000485// 1. Order operands such that they are listed from right (least complex) to
486// left (most complex). This puts constants before unary operators before
487// binary operators.
488//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000489// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
490// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000491//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000492bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000493 bool Changed = false;
494 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
495 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000496
Chris Lattner4f98c562003-03-10 21:43:22 +0000497 if (!I.isAssociative()) return Changed;
498 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000499 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
500 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
501 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000502 Constant *Folded = ConstantExpr::get(I.getOpcode(),
503 cast<Constant>(I.getOperand(1)),
504 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000505 I.setOperand(0, Op->getOperand(0));
506 I.setOperand(1, Folded);
507 return true;
508 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
509 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
510 isOnlyUse(Op) && isOnlyUse(Op1)) {
511 Constant *C1 = cast<Constant>(Op->getOperand(1));
512 Constant *C2 = cast<Constant>(Op1->getOperand(1));
513
514 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000515 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000516 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000517 Op1->getOperand(0),
518 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000519 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000520 I.setOperand(0, New);
521 I.setOperand(1, Folded);
522 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000523 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000524 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000525 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000526}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000527
Reid Spencere4d87aa2006-12-23 06:05:41 +0000528/// SimplifyCompare - For a CmpInst this function just orders the operands
529/// so that theyare listed from right (least complex) to left (most complex).
530/// This puts constants before unary operators before binary operators.
531bool InstCombiner::SimplifyCompare(CmpInst &I) {
532 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
533 return false;
534 I.swapOperands();
535 // Compare instructions are not associative so there's nothing else we can do.
536 return true;
537}
538
Chris Lattner8d969642003-03-10 23:06:50 +0000539// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
540// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000541//
Chris Lattner8d969642003-03-10 23:06:50 +0000542static inline Value *dyn_castNegVal(Value *V) {
543 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000544 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000545
Chris Lattner0ce85802004-12-14 20:08:06 +0000546 // Constants can be considered to be negated values if they can be folded.
547 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
548 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000549 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000550}
551
Chris Lattner8d969642003-03-10 23:06:50 +0000552static inline Value *dyn_castNotVal(Value *V) {
553 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000554 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000555
556 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000557 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000558 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000559 return 0;
560}
561
Chris Lattnerc8802d22003-03-11 00:12:48 +0000562// dyn_castFoldableMul - If this value is a multiply that can be folded into
563// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000564// non-constant operand of the multiply, and set CST to point to the multiplier.
565// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000566//
Chris Lattner50af16a2004-11-13 19:50:12 +0000567static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000568 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000569 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000570 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000571 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000572 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000573 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000574 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000575 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000576 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000577 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000578 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000579 return I->getOperand(0);
580 }
581 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000582 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000583}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000584
Chris Lattner574da9b2005-01-13 20:14:25 +0000585/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
586/// expression, return it.
587static User *dyn_castGetElementPtr(Value *V) {
588 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
589 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
590 if (CE->getOpcode() == Instruction::GetElementPtr)
591 return cast<User>(V);
592 return false;
593}
594
Dan Gohmaneee962e2008-04-10 18:43:06 +0000595/// getOpcode - If this is an Instruction or a ConstantExpr, return the
596/// opcode value. Otherwise return UserOp1.
597static unsigned getOpcode(User *U) {
598 if (Instruction *I = dyn_cast<Instruction>(U))
599 return I->getOpcode();
600 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U))
601 return CE->getOpcode();
602 // Use UserOp1 to mean there's no opcode.
603 return Instruction::UserOp1;
604}
605
Reid Spencer7177c3a2007-03-25 05:33:51 +0000606/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000607static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000608 APInt Val(C->getValue());
609 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000610}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000611/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000612static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000613 APInt Val(C->getValue());
614 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000615}
616/// Add - Add two ConstantInts together
617static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
618 return ConstantInt::get(C1->getValue() + C2->getValue());
619}
620/// And - Bitwise AND two ConstantInts together
621static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
622 return ConstantInt::get(C1->getValue() & C2->getValue());
623}
624/// Subtract - Subtract one ConstantInt from another
625static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
626 return ConstantInt::get(C1->getValue() - C2->getValue());
627}
628/// Multiply - Multiply two ConstantInts together
629static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
630 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000631}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000632/// MultiplyOverflows - True if the multiply can not be expressed in an int
633/// this size.
634static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
635 uint32_t W = C1->getBitWidth();
636 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
637 if (sign) {
638 LHSExt.sext(W * 2);
639 RHSExt.sext(W * 2);
640 } else {
641 LHSExt.zext(W * 2);
642 RHSExt.zext(W * 2);
643 }
644
645 APInt MulExt = LHSExt * RHSExt;
646
647 if (sign) {
648 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
649 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
650 return MulExt.slt(Min) || MulExt.sgt(Max);
651 } else
652 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
653}
Chris Lattner955f3312004-09-28 21:48:02 +0000654
Chris Lattner68d5ff22006-02-09 07:38:58 +0000655/// ComputeMaskedBits - Determine which of the bits specified in Mask are
656/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000657/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
658/// processing.
659/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
660/// we cannot optimize based on the assumption that it is zero without changing
661/// it to be an explicit zero. If we don't change it to zero, other code could
662/// optimized based on the contradictory assumption that it is non-zero.
663/// Because instcombine aggressively folds operations with undef args anyway,
664/// this won't lose us code quality.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000665void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
666 APInt& KnownZero, APInt& KnownOne,
667 unsigned Depth) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000668 assert(V && "No Value?");
669 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000670 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000671 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
672 "Not integer or pointer type!");
673 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
674 (!isa<IntegerType>(V->getType()) ||
675 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000676 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000677 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000678 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000679 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
680 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000681 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000682 KnownZero = ~KnownOne & Mask;
683 return;
684 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000685 // Null is all-zeros.
686 if (isa<ConstantPointerNull>(V)) {
687 KnownOne.clear();
688 KnownZero = Mask;
689 return;
690 }
691 // The address of an aligned GlobalValue has trailing zeros.
692 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
693 unsigned Align = GV->getAlignment();
694 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
695 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
696 if (Align > 0)
697 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
698 CountTrailingZeros_32(Align));
699 else
700 KnownZero.clear();
701 KnownOne.clear();
702 return;
703 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000704
Dan Gohman23e8b712008-04-28 17:02:21 +0000705 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
706
Reid Spencer3e7594f2007-03-08 01:46:38 +0000707 if (Depth == 6 || Mask == 0)
708 return; // Limit search depth.
709
Dan Gohmaneee962e2008-04-10 18:43:06 +0000710 User *I = dyn_cast<User>(V);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000711 if (!I) return;
712
713 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000714 switch (getOpcode(I)) {
715 default: break;
Reid Spencer2b812072007-03-25 02:03:12 +0000716 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000717 // If either the LHS or the RHS are Zero, the result is zero.
718 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000719 APInt Mask2(Mask & ~KnownZero);
720 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000721 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
722 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
723
724 // Output known-1 bits are only known if set in both the LHS & RHS.
725 KnownOne &= KnownOne2;
726 // Output known-0 are known to be clear if zero in either the LHS | RHS.
727 KnownZero |= KnownZero2;
728 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000729 }
730 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000731 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000732 APInt Mask2(Mask & ~KnownOne);
733 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000734 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
735 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
736
737 // Output known-0 bits are only known if clear in both the LHS & RHS.
738 KnownZero &= KnownZero2;
739 // Output known-1 are known to be set if set in either the LHS | RHS.
740 KnownOne |= KnownOne2;
741 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000742 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000743 case Instruction::Xor: {
744 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
745 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
746 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
747 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
748
749 // Output known-0 bits are known if clear or set in both the LHS & RHS.
750 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
751 // Output known-1 are known to be set if set in only one of the LHS, RHS.
752 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
753 KnownZero = KnownZeroOut;
754 return;
755 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000756 case Instruction::Mul: {
757 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
758 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
759 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
760 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
761 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
762
763 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohman23e8b712008-04-28 17:02:21 +0000764 // Also compute a conserative estimate for high known-0 bits.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000765 // More trickiness is possible, but this is sufficient for the
766 // interesting case of alignment computation.
767 KnownOne.clear();
768 unsigned TrailZ = KnownZero.countTrailingOnes() +
769 KnownZero2.countTrailingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +0000770 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
Dan Gohman42ac9292008-05-07 00:35:55 +0000771 KnownZero2.countLeadingOnes(),
772 BitWidth) - BitWidth;
Dan Gohman23e8b712008-04-28 17:02:21 +0000773
Dan Gohmaneee962e2008-04-10 18:43:06 +0000774 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000775 LeadZ = std::min(LeadZ, BitWidth);
776 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
777 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000778 KnownZero &= Mask;
779 return;
780 }
Dan Gohman23e8b712008-04-28 17:02:21 +0000781 case Instruction::UDiv: {
782 // For the purposes of computing leading zeros we can conservatively
783 // treat a udiv as a logical right shift by the power of 2 known to
Dan Gohman1d9cd502008-05-02 21:30:02 +0000784 // be less than the denominator.
Dan Gohman23e8b712008-04-28 17:02:21 +0000785 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
786 ComputeMaskedBits(I->getOperand(0),
787 AllOnes, KnownZero2, KnownOne2, Depth+1);
788 unsigned LeadZ = KnownZero2.countLeadingOnes();
789
790 KnownOne2.clear();
791 KnownZero2.clear();
792 ComputeMaskedBits(I->getOperand(1),
793 AllOnes, KnownZero2, KnownOne2, Depth+1);
Dan Gohman1d9cd502008-05-02 21:30:02 +0000794 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
795 if (RHSUnknownLeadingOnes != BitWidth)
796 LeadZ = std::min(BitWidth,
797 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000798
799 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
800 return;
801 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000802 case Instruction::Select:
803 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
804 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
805 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
806 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
807
808 // Only known if known in both the LHS and RHS.
809 KnownOne &= KnownOne2;
810 KnownZero &= KnownZero2;
811 return;
812 case Instruction::FPTrunc:
813 case Instruction::FPExt:
814 case Instruction::FPToUI:
815 case Instruction::FPToSI:
816 case Instruction::SIToFP:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000817 case Instruction::UIToFP:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000818 return; // Can't work with floating point.
819 case Instruction::PtrToInt:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000820 case Instruction::IntToPtr:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000821 // We can't handle these if we don't know the pointer size.
822 if (!TD) return;
823 // Fall through and handle them the same as zext/trunc.
824 case Instruction::ZExt:
Zhou Sheng771dbf72007-03-13 02:23:10 +0000825 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000826 // All these have integer operands
Dan Gohmaneee962e2008-04-10 18:43:06 +0000827 const Type *SrcTy = I->getOperand(0)->getType();
828 uint32_t SrcBitWidth = TD ?
829 TD->getTypeSizeInBits(SrcTy) :
830 SrcTy->getPrimitiveSizeInBits();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000831 APInt MaskIn(Mask);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000832 MaskIn.zextOrTrunc(SrcBitWidth);
833 KnownZero.zextOrTrunc(SrcBitWidth);
834 KnownOne.zextOrTrunc(SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000835 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000836 KnownZero.zextOrTrunc(BitWidth);
837 KnownOne.zextOrTrunc(BitWidth);
838 // Any top bits are known to be zero.
839 if (BitWidth > SrcBitWidth)
840 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000841 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000842 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000843 case Instruction::BitCast: {
844 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000845 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000846 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
847 return;
848 }
849 break;
850 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000851 case Instruction::SExt: {
852 // Compute the bits in the result that are not present in the input.
853 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000854 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000855
Zhou Shengaa305ab2007-03-28 02:19:03 +0000856 APInt MaskIn(Mask);
857 MaskIn.trunc(SrcBitWidth);
858 KnownZero.trunc(SrcBitWidth);
859 KnownOne.trunc(SrcBitWidth);
860 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000861 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000862 KnownZero.zext(BitWidth);
863 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000864
865 // If the sign bit of the input is known set or clear, then we know the
866 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000867 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000868 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000869 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000870 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000871 return;
872 }
873 case Instruction::Shl:
874 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
875 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000876 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000877 APInt Mask2(Mask.lshr(ShiftAmt));
878 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000879 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000880 KnownZero <<= ShiftAmt;
881 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000882 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000883 return;
884 }
885 break;
886 case Instruction::LShr:
887 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
888 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
889 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000890 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000891
892 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000893 APInt Mask2(Mask.shl(ShiftAmt));
894 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000895 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
896 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
897 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000898 // high bits known zero.
899 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000900 return;
901 }
902 break;
903 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000904 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000905 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
906 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000907 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000908
909 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000910 APInt Mask2(Mask.shl(ShiftAmt));
911 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000912 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
913 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
914 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
915
Zhou Shengaa305ab2007-03-28 02:19:03 +0000916 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
917 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000918 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000919 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000920 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000921 return;
922 }
923 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000924 case Instruction::Sub: {
925 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
926 // We know that the top bits of C-X are clear if X contains less bits
927 // than C (i.e. no wrap-around can happen). For example, 20-X is
928 // positive if we can prove that X is >= 0 and < 16.
929 if (!CLHS->getValue().isNegative()) {
930 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
931 // NLZ can't be BitWidth with no sign bit
932 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000933 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
934 Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000935
Dan Gohman23e8b712008-04-28 17:02:21 +0000936 // If all of the MaskV bits are known to be zero, then we know the
937 // output top bits are zero, because we now know that the output is
938 // from [0-C].
939 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohmaneee962e2008-04-10 18:43:06 +0000940 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
941 // Top bits known zero.
942 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000943 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000944 }
945 }
946 }
947 // fall through
Duncan Sands1d57a752008-03-21 08:32:17 +0000948 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000949 // Output known-0 bits are known if clear or set in both the low clear bits
950 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
951 // low 3 bits clear.
Dan Gohman23e8b712008-04-28 17:02:21 +0000952 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
953 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
954 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
955 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
956
957 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
958 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
959 KnownZeroOut = std::min(KnownZeroOut,
960 KnownZero2.countTrailingOnes());
961
962 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000963 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000964 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000965 case Instruction::SRem:
966 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
967 APInt RA = Rem->getValue();
968 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +0000969 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000970 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
971 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
972
973 // The sign of a remainder is equal to the sign of the first
974 // operand (zero being positive).
975 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
976 KnownZero2 |= ~LowBits;
977 else if (KnownOne2[BitWidth-1])
978 KnownOne2 |= ~LowBits;
979
980 KnownZero |= KnownZero2 & Mask;
981 KnownOne |= KnownOne2 & Mask;
982
983 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
984 }
985 }
986 break;
Dan Gohman23e8b712008-04-28 17:02:21 +0000987 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000988 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
989 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +0000990 if (RA.isPowerOf2()) {
991 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000992 APInt Mask2 = LowBits & Mask;
993 KnownZero |= ~LowBits & Mask;
994 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
995 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +0000996 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000997 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000998 }
Dan Gohman23e8b712008-04-28 17:02:21 +0000999
1000 // Since the result is less than or equal to either operand, any leading
1001 // zero bits in either operand must also exist in the result.
1002 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1003 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1004 Depth+1);
1005 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1006 Depth+1);
1007
1008 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1009 KnownZero2.countLeadingOnes());
1010 KnownOne.clear();
1011 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001012 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001013 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00001014
1015 case Instruction::Alloca:
1016 case Instruction::Malloc: {
1017 AllocationInst *AI = cast<AllocationInst>(V);
1018 unsigned Align = AI->getAlignment();
1019 if (Align == 0 && TD) {
1020 if (isa<AllocaInst>(AI))
1021 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1022 else if (isa<MallocInst>(AI)) {
1023 // Malloc returns maximally aligned memory.
1024 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1025 Align =
1026 std::max(Align,
1027 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1028 Align =
1029 std::max(Align,
1030 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1031 }
1032 }
1033
1034 if (Align > 0)
1035 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1036 CountTrailingZeros_32(Align));
1037 break;
1038 }
1039 case Instruction::GetElementPtr: {
1040 // Analyze all of the subscripts of this getelementptr instruction
1041 // to determine if we can prove known low zero bits.
1042 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1043 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1044 ComputeMaskedBits(I->getOperand(0), LocalMask,
1045 LocalKnownZero, LocalKnownOne, Depth+1);
1046 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1047
1048 gep_type_iterator GTI = gep_type_begin(I);
1049 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1050 Value *Index = I->getOperand(i);
1051 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1052 // Handle struct member offset arithmetic.
1053 if (!TD) return;
1054 const StructLayout *SL = TD->getStructLayout(STy);
1055 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1056 uint64_t Offset = SL->getElementOffset(Idx);
1057 TrailZ = std::min(TrailZ,
1058 CountTrailingZeros_64(Offset));
1059 } else {
1060 // Handle array index arithmetic.
1061 const Type *IndexedTy = GTI.getIndexedType();
1062 if (!IndexedTy->isSized()) return;
1063 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1064 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1065 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1066 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1067 ComputeMaskedBits(Index, LocalMask,
1068 LocalKnownZero, LocalKnownOne, Depth+1);
1069 TrailZ = std::min(TrailZ,
1070 CountTrailingZeros_64(TypeSize) +
1071 LocalKnownZero.countTrailingOnes());
1072 }
1073 }
1074
1075 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1076 break;
1077 }
1078 case Instruction::PHI: {
1079 PHINode *P = cast<PHINode>(I);
1080 // Handle the case of a simple two-predecessor recurrence PHI.
1081 // There's a lot more that could theoretically be done here, but
1082 // this is sufficient to catch some interesting cases.
1083 if (P->getNumIncomingValues() == 2) {
1084 for (unsigned i = 0; i != 2; ++i) {
1085 Value *L = P->getIncomingValue(i);
1086 Value *R = P->getIncomingValue(!i);
1087 User *LU = dyn_cast<User>(L);
1088 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1089 // Check for operations that have the property that if
1090 // both their operands have low zero bits, the result
1091 // will have low zero bits.
1092 if (Opcode == Instruction::Add ||
1093 Opcode == Instruction::Sub ||
1094 Opcode == Instruction::And ||
1095 Opcode == Instruction::Or ||
1096 Opcode == Instruction::Mul) {
1097 Value *LL = LU->getOperand(0);
1098 Value *LR = LU->getOperand(1);
1099 // Find a recurrence.
1100 if (LL == I)
1101 L = LR;
1102 else if (LR == I)
1103 L = LL;
1104 else
1105 break;
1106 // Ok, we have a PHI of the form L op= R. Check for low
1107 // zero bits.
1108 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1109 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1110 Mask2 = APInt::getLowBitsSet(BitWidth,
1111 KnownZero2.countTrailingOnes());
1112 KnownOne2.clear();
1113 KnownZero2.clear();
1114 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1115 KnownZero = Mask &
1116 APInt::getLowBitsSet(BitWidth,
1117 KnownZero2.countTrailingOnes());
1118 break;
1119 }
1120 }
1121 }
1122 break;
1123 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001124 case Instruction::Call:
1125 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1126 switch (II->getIntrinsicID()) {
1127 default: break;
1128 case Intrinsic::ctpop:
1129 case Intrinsic::ctlz:
1130 case Intrinsic::cttz: {
1131 unsigned LowBits = Log2_32(BitWidth)+1;
1132 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1133 break;
1134 }
1135 }
1136 }
1137 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +00001138 }
1139}
1140
Reid Spencere7816b52007-03-08 01:52:58 +00001141/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1142/// this predicate to simplify operations downstream. Mask is known to be zero
1143/// for bits that V cannot have.
Dan Gohmaneee962e2008-04-10 18:43:06 +00001144bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1145 unsigned Depth) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001146 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001147 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1148 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1149 return (KnownZero & Mask) == Mask;
1150}
1151
Chris Lattner255d8912006-02-11 09:31:47 +00001152/// ShrinkDemandedConstant - Check to see if the specified operand of the
1153/// specified instruction is a constant integer. If so, check to see if there
1154/// are any bits set in the constant that are not demanded. If so, shrink the
1155/// constant and return true.
1156static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001157 APInt Demanded) {
1158 assert(I && "No instruction?");
1159 assert(OpNo < I->getNumOperands() && "Operand index too large");
1160
1161 // If the operand is not a constant integer, nothing to do.
1162 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1163 if (!OpC) return false;
1164
1165 // If there are no bits set that aren't demanded, nothing to do.
1166 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1167 if ((~Demanded & OpC->getValue()) == 0)
1168 return false;
1169
1170 // This instruction is producing bits that are not demanded. Shrink the RHS.
1171 Demanded &= OpC->getValue();
1172 I->setOperand(OpNo, ConstantInt::get(Demanded));
1173 return true;
1174}
1175
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001176// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1177// set of known zero and one bits, compute the maximum and minimum values that
1178// could have the specified known zero and known one bits, returning them in
1179// min/max.
1180static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +00001181 const APInt& KnownZero,
1182 const APInt& KnownOne,
1183 APInt& Min, APInt& Max) {
1184 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1185 assert(KnownZero.getBitWidth() == BitWidth &&
1186 KnownOne.getBitWidth() == BitWidth &&
1187 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1188 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001189 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001190
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001191 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1192 // bit if it is unknown.
1193 Min = KnownOne;
1194 Max = KnownOne|UnknownBits;
1195
Zhou Sheng4acf1552007-03-28 05:15:57 +00001196 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001197 Min.set(BitWidth-1);
1198 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001199 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001200}
1201
1202// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1203// a set of known zero and one bits, compute the maximum and minimum values that
1204// could have the specified known zero and known one bits, returning them in
1205// min/max.
1206static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001207 const APInt &KnownZero,
1208 const APInt &KnownOne,
1209 APInt &Min, APInt &Max) {
1210 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +00001211 assert(KnownZero.getBitWidth() == BitWidth &&
1212 KnownOne.getBitWidth() == BitWidth &&
1213 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1214 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001215 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001216
1217 // The minimum value is when the unknown bits are all zeros.
1218 Min = KnownOne;
1219 // The maximum value is when the unknown bits are all ones.
1220 Max = KnownOne|UnknownBits;
1221}
Chris Lattner255d8912006-02-11 09:31:47 +00001222
Reid Spencer8cb68342007-03-12 17:25:59 +00001223/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1224/// value based on the demanded bits. When this function is called, it is known
1225/// that only the bits set in DemandedMask of the result of V are ever used
1226/// downstream. Consequently, depending on the mask and V, it may be possible
1227/// to replace V with a constant or one of its operands. In such cases, this
1228/// function does the replacement and returns true. In all other cases, it
1229/// returns false after analyzing the expression and setting KnownOne and known
1230/// to be one in the expression. KnownZero contains all the bits that are known
1231/// to be zero in the expression. These are provided to potentially allow the
1232/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1233/// the expression. KnownOne and KnownZero always follow the invariant that
1234/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1235/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1236/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1237/// and KnownOne must all be the same.
1238bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1239 APInt& KnownZero, APInt& KnownOne,
1240 unsigned Depth) {
1241 assert(V != 0 && "Null pointer of Value???");
1242 assert(Depth <= 6 && "Limit Search Depth");
1243 uint32_t BitWidth = DemandedMask.getBitWidth();
1244 const IntegerType *VTy = cast<IntegerType>(V->getType());
1245 assert(VTy->getBitWidth() == BitWidth &&
1246 KnownZero.getBitWidth() == BitWidth &&
1247 KnownOne.getBitWidth() == BitWidth &&
1248 "Value *V, DemandedMask, KnownZero and KnownOne \
1249 must have same BitWidth");
1250 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1251 // We know all of the bits for a constant!
1252 KnownOne = CI->getValue() & DemandedMask;
1253 KnownZero = ~KnownOne & DemandedMask;
1254 return false;
1255 }
1256
Zhou Sheng96704452007-03-14 03:21:24 +00001257 KnownZero.clear();
1258 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001259 if (!V->hasOneUse()) { // Other users may use these bits.
1260 if (Depth != 0) { // Not at the root.
1261 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1262 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1263 return false;
1264 }
1265 // If this is the root being simplified, allow it to have multiple uses,
1266 // just set the DemandedMask to all bits.
1267 DemandedMask = APInt::getAllOnesValue(BitWidth);
1268 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1269 if (V != UndefValue::get(VTy))
1270 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1271 return false;
1272 } else if (Depth == 6) { // Limit search depth.
1273 return false;
1274 }
1275
1276 Instruction *I = dyn_cast<Instruction>(V);
1277 if (!I) return false; // Only analyze instructions.
1278
Reid Spencer8cb68342007-03-12 17:25:59 +00001279 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1280 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1281 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001282 default:
1283 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1284 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 case Instruction::And:
1286 // If either the LHS or the RHS are Zero, the result is zero.
1287 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1288 RHSKnownZero, RHSKnownOne, Depth+1))
1289 return true;
1290 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1291 "Bits known to be one AND zero?");
1292
1293 // If something is known zero on the RHS, the bits aren't demanded on the
1294 // LHS.
1295 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1296 LHSKnownZero, LHSKnownOne, Depth+1))
1297 return true;
1298 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1299 "Bits known to be one AND zero?");
1300
1301 // If all of the demanded bits are known 1 on one side, return the other.
1302 // These bits cannot contribute to the result of the 'and'.
1303 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1304 (DemandedMask & ~LHSKnownZero))
1305 return UpdateValueUsesWith(I, I->getOperand(0));
1306 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1307 (DemandedMask & ~RHSKnownZero))
1308 return UpdateValueUsesWith(I, I->getOperand(1));
1309
1310 // If all of the demanded bits in the inputs are known zeros, return zero.
1311 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1312 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1313
1314 // If the RHS is a constant, see if we can simplify it.
1315 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1316 return UpdateValueUsesWith(I, I);
1317
1318 // Output known-1 bits are only known if set in both the LHS & RHS.
1319 RHSKnownOne &= LHSKnownOne;
1320 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1321 RHSKnownZero |= LHSKnownZero;
1322 break;
1323 case Instruction::Or:
1324 // If either the LHS or the RHS are One, the result is One.
1325 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1326 RHSKnownZero, RHSKnownOne, Depth+1))
1327 return true;
1328 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1329 "Bits known to be one AND zero?");
1330 // If something is known one on the RHS, the bits aren't demanded on the
1331 // LHS.
1332 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1333 LHSKnownZero, LHSKnownOne, Depth+1))
1334 return true;
1335 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1336 "Bits known to be one AND zero?");
1337
1338 // If all of the demanded bits are known zero on one side, return the other.
1339 // These bits cannot contribute to the result of the 'or'.
1340 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1341 (DemandedMask & ~LHSKnownOne))
1342 return UpdateValueUsesWith(I, I->getOperand(0));
1343 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1344 (DemandedMask & ~RHSKnownOne))
1345 return UpdateValueUsesWith(I, I->getOperand(1));
1346
1347 // If all of the potentially set bits on one side are known to be set on
1348 // the other side, just use the 'other' side.
1349 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1350 (DemandedMask & (~RHSKnownZero)))
1351 return UpdateValueUsesWith(I, I->getOperand(0));
1352 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1353 (DemandedMask & (~LHSKnownZero)))
1354 return UpdateValueUsesWith(I, I->getOperand(1));
1355
1356 // If the RHS is a constant, see if we can simplify it.
1357 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1358 return UpdateValueUsesWith(I, I);
1359
1360 // Output known-0 bits are only known if clear in both the LHS & RHS.
1361 RHSKnownZero &= LHSKnownZero;
1362 // Output known-1 are known to be set if set in either the LHS | RHS.
1363 RHSKnownOne |= LHSKnownOne;
1364 break;
1365 case Instruction::Xor: {
1366 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1367 RHSKnownZero, RHSKnownOne, Depth+1))
1368 return true;
1369 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1370 "Bits known to be one AND zero?");
1371 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1372 LHSKnownZero, LHSKnownOne, Depth+1))
1373 return true;
1374 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1375 "Bits known to be one AND zero?");
1376
1377 // If all of the demanded bits are known zero on one side, return the other.
1378 // These bits cannot contribute to the result of the 'xor'.
1379 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1380 return UpdateValueUsesWith(I, I->getOperand(0));
1381 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1382 return UpdateValueUsesWith(I, I->getOperand(1));
1383
1384 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1385 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1386 (RHSKnownOne & LHSKnownOne);
1387 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1388 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1389 (RHSKnownOne & LHSKnownZero);
1390
1391 // If all of the demanded bits are known to be zero on one side or the
1392 // other, turn this into an *inclusive* or.
1393 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1394 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1395 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001396 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001397 I->getName());
1398 InsertNewInstBefore(Or, *I);
1399 return UpdateValueUsesWith(I, Or);
1400 }
1401
1402 // If all of the demanded bits on one side are known, and all of the set
1403 // bits on that side are also known to be set on the other side, turn this
1404 // into an AND, as we know the bits will be cleared.
1405 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1406 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1407 // all known
1408 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1409 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1410 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001411 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +00001412 InsertNewInstBefore(And, *I);
1413 return UpdateValueUsesWith(I, And);
1414 }
1415 }
1416
1417 // If the RHS is a constant, see if we can simplify it.
1418 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1419 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1420 return UpdateValueUsesWith(I, I);
1421
1422 RHSKnownZero = KnownZeroOut;
1423 RHSKnownOne = KnownOneOut;
1424 break;
1425 }
1426 case Instruction::Select:
1427 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1428 RHSKnownZero, RHSKnownOne, Depth+1))
1429 return true;
1430 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1431 LHSKnownZero, LHSKnownOne, Depth+1))
1432 return true;
1433 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1434 "Bits known to be one AND zero?");
1435 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1436 "Bits known to be one AND zero?");
1437
1438 // If the operands are constants, see if we can simplify them.
1439 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1440 return UpdateValueUsesWith(I, I);
1441 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1442 return UpdateValueUsesWith(I, I);
1443
1444 // Only known if known in both the LHS and RHS.
1445 RHSKnownOne &= LHSKnownOne;
1446 RHSKnownZero &= LHSKnownZero;
1447 break;
1448 case Instruction::Trunc: {
1449 uint32_t truncBf =
1450 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001451 DemandedMask.zext(truncBf);
1452 RHSKnownZero.zext(truncBf);
1453 RHSKnownOne.zext(truncBf);
1454 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1455 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001456 return true;
1457 DemandedMask.trunc(BitWidth);
1458 RHSKnownZero.trunc(BitWidth);
1459 RHSKnownOne.trunc(BitWidth);
1460 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1461 "Bits known to be one AND zero?");
1462 break;
1463 }
1464 case Instruction::BitCast:
1465 if (!I->getOperand(0)->getType()->isInteger())
1466 return false;
1467
1468 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1469 RHSKnownZero, RHSKnownOne, Depth+1))
1470 return true;
1471 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1472 "Bits known to be one AND zero?");
1473 break;
1474 case Instruction::ZExt: {
1475 // Compute the bits in the result that are not present in the input.
1476 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001477 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001478
Zhou Shengd48653a2007-03-29 04:45:55 +00001479 DemandedMask.trunc(SrcBitWidth);
1480 RHSKnownZero.trunc(SrcBitWidth);
1481 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001482 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1483 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001484 return true;
1485 DemandedMask.zext(BitWidth);
1486 RHSKnownZero.zext(BitWidth);
1487 RHSKnownOne.zext(BitWidth);
1488 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1489 "Bits known to be one AND zero?");
1490 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001491 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001492 break;
1493 }
1494 case Instruction::SExt: {
1495 // Compute the bits in the result that are not present in the input.
1496 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001497 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001498
Reid Spencer8cb68342007-03-12 17:25:59 +00001499 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001500 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001501
Zhou Sheng01542f32007-03-29 02:26:30 +00001502 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001503 // If any of the sign extended bits are demanded, we know that the sign
1504 // bit is demanded.
1505 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001506 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001507
Zhou Shengd48653a2007-03-29 04:45:55 +00001508 InputDemandedBits.trunc(SrcBitWidth);
1509 RHSKnownZero.trunc(SrcBitWidth);
1510 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001511 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1512 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001513 return true;
1514 InputDemandedBits.zext(BitWidth);
1515 RHSKnownZero.zext(BitWidth);
1516 RHSKnownOne.zext(BitWidth);
1517 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1518 "Bits known to be one AND zero?");
1519
1520 // If the sign bit of the input is known set or clear, then we know the
1521 // top bits of the result.
1522
1523 // If the input sign bit is known zero, or if the NewBits are not demanded
1524 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001525 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001526 {
1527 // Convert to ZExt cast
1528 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1529 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001530 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001531 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001532 }
1533 break;
1534 }
1535 case Instruction::Add: {
1536 // Figure out what the input bits are. If the top bits of the and result
1537 // are not demanded, then the add doesn't demand them from its input
1538 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001539 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001540
1541 // If there is a constant on the RHS, there are a variety of xformations
1542 // we can do.
1543 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1544 // If null, this should be simplified elsewhere. Some of the xforms here
1545 // won't work if the RHS is zero.
1546 if (RHS->isZero())
1547 break;
1548
1549 // If the top bit of the output is demanded, demand everything from the
1550 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001551 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001552
1553 // Find information about known zero/one bits in the input.
1554 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1555 LHSKnownZero, LHSKnownOne, Depth+1))
1556 return true;
1557
1558 // If the RHS of the add has bits set that can't affect the input, reduce
1559 // the constant.
1560 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1561 return UpdateValueUsesWith(I, I);
1562
1563 // Avoid excess work.
1564 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1565 break;
1566
1567 // Turn it into OR if input bits are zero.
1568 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1569 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001570 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001571 I->getName());
1572 InsertNewInstBefore(Or, *I);
1573 return UpdateValueUsesWith(I, Or);
1574 }
1575
1576 // We can say something about the output known-zero and known-one bits,
1577 // depending on potential carries from the input constant and the
1578 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1579 // bits set and the RHS constant is 0x01001, then we know we have a known
1580 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1581
1582 // To compute this, we first compute the potential carry bits. These are
1583 // the bits which may be modified. I'm not aware of a better way to do
1584 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001585 const APInt& RHSVal = RHS->getValue();
1586 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001587
1588 // Now that we know which bits have carries, compute the known-1/0 sets.
1589
1590 // Bits are known one if they are known zero in one operand and one in the
1591 // other, and there is no input carry.
1592 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1593 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1594
1595 // Bits are known zero if they are known zero in both operands and there
1596 // is no input carry.
1597 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1598 } else {
1599 // If the high-bits of this ADD are not demanded, then it does not demand
1600 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001601 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001602 // Right fill the mask of bits for this ADD to demand the most
1603 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001604 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001605 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1606 LHSKnownZero, LHSKnownOne, Depth+1))
1607 return true;
1608 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1609 LHSKnownZero, LHSKnownOne, Depth+1))
1610 return true;
1611 }
1612 }
1613 break;
1614 }
1615 case Instruction::Sub:
1616 // If the high-bits of this SUB are not demanded, then it does not demand
1617 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001618 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001619 // Right fill the mask of bits for this SUB to demand the most
1620 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001621 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001622 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001623 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1624 LHSKnownZero, LHSKnownOne, Depth+1))
1625 return true;
1626 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1627 LHSKnownZero, LHSKnownOne, Depth+1))
1628 return true;
1629 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001630 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1631 // the known zeros and ones.
1632 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001633 break;
1634 case Instruction::Shl:
1635 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001636 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001637 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1638 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001639 RHSKnownZero, RHSKnownOne, Depth+1))
1640 return true;
1641 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1642 "Bits known to be one AND zero?");
1643 RHSKnownZero <<= ShiftAmt;
1644 RHSKnownOne <<= ShiftAmt;
1645 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001646 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001647 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001648 }
1649 break;
1650 case Instruction::LShr:
1651 // For a logical shift right
1652 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001653 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001654
Reid Spencer8cb68342007-03-12 17:25:59 +00001655 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001656 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1657 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001658 RHSKnownZero, RHSKnownOne, Depth+1))
1659 return true;
1660 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1661 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001662 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1663 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001664 if (ShiftAmt) {
1665 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001666 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001667 RHSKnownZero |= HighBits; // high bits known zero.
1668 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001669 }
1670 break;
1671 case Instruction::AShr:
1672 // If this is an arithmetic shift right and only the low-bit is set, we can
1673 // always convert this into a logical shr, even if the shift amount is
1674 // variable. The low bit of the shift cannot be an input sign bit unless
1675 // the shift amount is >= the size of the datatype, which is undefined.
1676 if (DemandedMask == 1) {
1677 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001678 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001679 I->getOperand(0), I->getOperand(1), I->getName());
1680 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1681 return UpdateValueUsesWith(I, NewVal);
1682 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001683
1684 // If the sign bit is the only bit demanded by this ashr, then there is no
1685 // need to do it, the shift doesn't change the high bit.
1686 if (DemandedMask.isSignBit())
1687 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001688
1689 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001690 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001691
Reid Spencer8cb68342007-03-12 17:25:59 +00001692 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001693 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001694 // If any of the "high bits" are demanded, we should set the sign bit as
1695 // demanded.
1696 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1697 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001698 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001699 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001700 RHSKnownZero, RHSKnownOne, Depth+1))
1701 return true;
1702 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1703 "Bits known to be one AND zero?");
1704 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001705 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001706 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1707 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1708
1709 // Handle the sign bits.
1710 APInt SignBit(APInt::getSignBit(BitWidth));
1711 // Adjust to where it is now in the mask.
1712 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1713
1714 // If the input sign bit is known to be zero, or if none of the top bits
1715 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001716 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001717 (HighBits & ~DemandedMask) == HighBits) {
1718 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001719 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001720 I->getOperand(0), SA, I->getName());
1721 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1722 return UpdateValueUsesWith(I, NewVal);
1723 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1724 RHSKnownOne |= HighBits;
1725 }
1726 }
1727 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001728 case Instruction::SRem:
1729 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1730 APInt RA = Rem->getValue();
1731 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001732 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001733 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1734 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1735 LHSKnownZero, LHSKnownOne, Depth+1))
1736 return true;
1737
1738 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1739 LHSKnownZero |= ~LowBits;
1740 else if (LHSKnownOne[BitWidth-1])
1741 LHSKnownOne |= ~LowBits;
1742
1743 KnownZero |= LHSKnownZero & DemandedMask;
1744 KnownOne |= LHSKnownOne & DemandedMask;
1745
1746 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1747 }
1748 }
1749 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001750 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001751 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1752 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001753 if (RA.isPowerOf2()) {
1754 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001755 APInt Mask2 = LowBits & DemandedMask;
1756 KnownZero |= ~LowBits & DemandedMask;
1757 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1758 KnownZero, KnownOne, Depth+1))
1759 return true;
1760
1761 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001762 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001763 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001764 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001765
1766 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1767 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001768 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1769 KnownZero2, KnownOne2, Depth+1))
1770 return true;
1771
Dan Gohman23e8b712008-04-28 17:02:21 +00001772 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001773 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001774 KnownZero2, KnownOne2, Depth+1))
1775 return true;
1776
1777 Leaders = std::max(Leaders,
1778 KnownZero2.countLeadingOnes());
1779 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001780 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001781 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001782 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001783
1784 // If the client is only demanding bits that we know, return the known
1785 // constant.
1786 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1787 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1788 return false;
1789}
1790
Chris Lattner867b99f2006-10-05 06:55:50 +00001791
1792/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1793/// 64 or fewer elements. DemandedElts contains the set of elements that are
1794/// actually used by the caller. This method analyzes which elements of the
1795/// operand are undef and returns that information in UndefElts.
1796///
1797/// If the information about demanded elements can be used to simplify the
1798/// operation, the operation is simplified, then the resultant value is
1799/// returned. This returns null if no change was made.
1800Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1801 uint64_t &UndefElts,
1802 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001803 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001804 assert(VWidth <= 64 && "Vector too wide to analyze!");
1805 uint64_t EltMask = ~0ULL >> (64-VWidth);
1806 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1807 "Invalid DemandedElts!");
1808
1809 if (isa<UndefValue>(V)) {
1810 // If the entire vector is undefined, just return this info.
1811 UndefElts = EltMask;
1812 return 0;
1813 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1814 UndefElts = EltMask;
1815 return UndefValue::get(V->getType());
1816 }
1817
1818 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001819 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1820 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001821 Constant *Undef = UndefValue::get(EltTy);
1822
1823 std::vector<Constant*> Elts;
1824 for (unsigned i = 0; i != VWidth; ++i)
1825 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1826 Elts.push_back(Undef);
1827 UndefElts |= (1ULL << i);
1828 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1829 Elts.push_back(Undef);
1830 UndefElts |= (1ULL << i);
1831 } else { // Otherwise, defined.
1832 Elts.push_back(CP->getOperand(i));
1833 }
1834
1835 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001836 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001837 return NewCP != CP ? NewCP : 0;
1838 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001839 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001840 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001841 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001842 Constant *Zero = Constant::getNullValue(EltTy);
1843 Constant *Undef = UndefValue::get(EltTy);
1844 std::vector<Constant*> Elts;
1845 for (unsigned i = 0; i != VWidth; ++i)
1846 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1847 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001848 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001849 }
1850
1851 if (!V->hasOneUse()) { // Other users may use these bits.
1852 if (Depth != 0) { // Not at the root.
1853 // TODO: Just compute the UndefElts information recursively.
1854 return false;
1855 }
1856 return false;
1857 } else if (Depth == 10) { // Limit search depth.
1858 return false;
1859 }
1860
1861 Instruction *I = dyn_cast<Instruction>(V);
1862 if (!I) return false; // Only analyze instructions.
1863
1864 bool MadeChange = false;
1865 uint64_t UndefElts2;
1866 Value *TmpV;
1867 switch (I->getOpcode()) {
1868 default: break;
1869
1870 case Instruction::InsertElement: {
1871 // If this is a variable index, we don't know which element it overwrites.
1872 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001873 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001874 if (Idx == 0) {
1875 // Note that we can't propagate undef elt info, because we don't know
1876 // which elt is getting updated.
1877 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1878 UndefElts2, Depth+1);
1879 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1880 break;
1881 }
1882
1883 // If this is inserting an element that isn't demanded, remove this
1884 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001885 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001886 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1887 return AddSoonDeadInstToWorklist(*I, 0);
1888
1889 // Otherwise, the element inserted overwrites whatever was there, so the
1890 // input demanded set is simpler than the output set.
1891 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1892 DemandedElts & ~(1ULL << IdxNo),
1893 UndefElts, Depth+1);
1894 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1895
1896 // The inserted element is defined.
1897 UndefElts |= 1ULL << IdxNo;
1898 break;
1899 }
Chris Lattner69878332007-04-14 22:29:23 +00001900 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001901 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001902 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1903 if (!VTy) break;
1904 unsigned InVWidth = VTy->getNumElements();
1905 uint64_t InputDemandedElts = 0;
1906 unsigned Ratio;
1907
1908 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001909 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001910 // elements as are demanded of us.
1911 Ratio = 1;
1912 InputDemandedElts = DemandedElts;
1913 } else if (VWidth > InVWidth) {
1914 // Untested so far.
1915 break;
1916
1917 // If there are more elements in the result than there are in the source,
1918 // then an input element is live if any of the corresponding output
1919 // elements are live.
1920 Ratio = VWidth/InVWidth;
1921 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1922 if (DemandedElts & (1ULL << OutIdx))
1923 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1924 }
1925 } else {
1926 // Untested so far.
1927 break;
1928
1929 // If there are more elements in the source than there are in the result,
1930 // then an input element is live if the corresponding output element is
1931 // live.
1932 Ratio = InVWidth/VWidth;
1933 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1934 if (DemandedElts & (1ULL << InIdx/Ratio))
1935 InputDemandedElts |= 1ULL << InIdx;
1936 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001937
Chris Lattner69878332007-04-14 22:29:23 +00001938 // div/rem demand all inputs, because they don't want divide by zero.
1939 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1940 UndefElts2, Depth+1);
1941 if (TmpV) {
1942 I->setOperand(0, TmpV);
1943 MadeChange = true;
1944 }
1945
1946 UndefElts = UndefElts2;
1947 if (VWidth > InVWidth) {
1948 assert(0 && "Unimp");
1949 // If there are more elements in the result than there are in the source,
1950 // then an output element is undef if the corresponding input element is
1951 // undef.
1952 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1953 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1954 UndefElts |= 1ULL << OutIdx;
1955 } else if (VWidth < InVWidth) {
1956 assert(0 && "Unimp");
1957 // If there are more elements in the source than there are in the result,
1958 // then a result element is undef if all of the corresponding input
1959 // elements are undef.
1960 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1961 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1962 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1963 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1964 }
1965 break;
1966 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001967 case Instruction::And:
1968 case Instruction::Or:
1969 case Instruction::Xor:
1970 case Instruction::Add:
1971 case Instruction::Sub:
1972 case Instruction::Mul:
1973 // div/rem demand all inputs, because they don't want divide by zero.
1974 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1975 UndefElts, Depth+1);
1976 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1977 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1978 UndefElts2, Depth+1);
1979 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1980
1981 // Output elements are undefined if both are undefined. Consider things
1982 // like undef&0. The result is known zero, not undef.
1983 UndefElts &= UndefElts2;
1984 break;
1985
1986 case Instruction::Call: {
1987 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1988 if (!II) break;
1989 switch (II->getIntrinsicID()) {
1990 default: break;
1991
1992 // Binary vector operations that work column-wise. A dest element is a
1993 // function of the corresponding input elements from the two inputs.
1994 case Intrinsic::x86_sse_sub_ss:
1995 case Intrinsic::x86_sse_mul_ss:
1996 case Intrinsic::x86_sse_min_ss:
1997 case Intrinsic::x86_sse_max_ss:
1998 case Intrinsic::x86_sse2_sub_sd:
1999 case Intrinsic::x86_sse2_mul_sd:
2000 case Intrinsic::x86_sse2_min_sd:
2001 case Intrinsic::x86_sse2_max_sd:
2002 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2003 UndefElts, Depth+1);
2004 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2005 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2006 UndefElts2, Depth+1);
2007 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2008
2009 // If only the low elt is demanded and this is a scalarizable intrinsic,
2010 // scalarize it now.
2011 if (DemandedElts == 1) {
2012 switch (II->getIntrinsicID()) {
2013 default: break;
2014 case Intrinsic::x86_sse_sub_ss:
2015 case Intrinsic::x86_sse_mul_ss:
2016 case Intrinsic::x86_sse2_sub_sd:
2017 case Intrinsic::x86_sse2_mul_sd:
2018 // TODO: Lower MIN/MAX/ABS/etc
2019 Value *LHS = II->getOperand(1);
2020 Value *RHS = II->getOperand(2);
2021 // Extract the element as scalars.
2022 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2023 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2024
2025 switch (II->getIntrinsicID()) {
2026 default: assert(0 && "Case stmts out of sync!");
2027 case Intrinsic::x86_sse_sub_ss:
2028 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002029 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002030 II->getName()), *II);
2031 break;
2032 case Intrinsic::x86_sse_mul_ss:
2033 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002034 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002035 II->getName()), *II);
2036 break;
2037 }
2038
2039 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00002040 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2041 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00002042 InsertNewInstBefore(New, *II);
2043 AddSoonDeadInstToWorklist(*II, 0);
2044 return New;
2045 }
2046 }
2047
2048 // Output elements are undefined if both are undefined. Consider things
2049 // like undef&0. The result is known zero, not undef.
2050 UndefElts &= UndefElts2;
2051 break;
2052 }
2053 break;
2054 }
2055 }
2056 return MadeChange ? I : 0;
2057}
2058
Nick Lewycky455e1762007-09-06 02:40:25 +00002059/// @returns true if the specified compare predicate is
Reid Spencere4d87aa2006-12-23 06:05:41 +00002060/// true when both operands are equal...
Nick Lewycky455e1762007-09-06 02:40:25 +00002061/// @brief Determine if the icmp Predicate is true when both operands are equal
2062static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002063 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
2064 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
2065 pred == ICmpInst::ICMP_SLE;
2066}
2067
Nick Lewycky455e1762007-09-06 02:40:25 +00002068/// @returns true if the specified compare instruction is
2069/// true when both operands are equal...
2070/// @brief Determine if the ICmpInst returns true when both operands are equal
2071static bool isTrueWhenEqual(ICmpInst &ICI) {
2072 return isTrueWhenEqual(ICI.getPredicate());
2073}
2074
Chris Lattner564a7272003-08-13 19:01:45 +00002075/// AssociativeOpt - Perform an optimization on an associative operator. This
2076/// function is designed to check a chain of associative operators for a
2077/// potential to apply a certain optimization. Since the optimization may be
2078/// applicable if the expression was reassociated, this checks the chain, then
2079/// reassociates the expression as necessary to expose the optimization
2080/// opportunity. This makes use of a special Functor, which must define
2081/// 'shouldApply' and 'apply' methods.
2082///
2083template<typename Functor>
2084Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2085 unsigned Opcode = Root.getOpcode();
2086 Value *LHS = Root.getOperand(0);
2087
2088 // Quick check, see if the immediate LHS matches...
2089 if (F.shouldApply(LHS))
2090 return F.apply(Root);
2091
2092 // Otherwise, if the LHS is not of the same opcode as the root, return.
2093 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002094 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002095 // Should we apply this transform to the RHS?
2096 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2097
2098 // If not to the RHS, check to see if we should apply to the LHS...
2099 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2100 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2101 ShouldApply = true;
2102 }
2103
2104 // If the functor wants to apply the optimization to the RHS of LHSI,
2105 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2106 if (ShouldApply) {
2107 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002108
Chris Lattner564a7272003-08-13 19:01:45 +00002109 // Now all of the instructions are in the current basic block, go ahead
2110 // and perform the reassociation.
2111 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2112
2113 // First move the selected RHS to the LHS of the root...
2114 Root.setOperand(0, LHSI->getOperand(1));
2115
2116 // Make what used to be the LHS of the root be the user of the root...
2117 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002118 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002119 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2120 return 0;
2121 }
Chris Lattner65725312004-04-16 18:08:07 +00002122 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002123 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002124 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2125 BasicBlock::iterator ARI = &Root; ++ARI;
2126 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2127 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002128
2129 // Now propagate the ExtraOperand down the chain of instructions until we
2130 // get to LHSI.
2131 while (TmpLHSI != LHSI) {
2132 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002133 // Move the instruction to immediately before the chain we are
2134 // constructing to avoid breaking dominance properties.
2135 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2136 BB->getInstList().insert(ARI, NextLHSI);
2137 ARI = NextLHSI;
2138
Chris Lattner564a7272003-08-13 19:01:45 +00002139 Value *NextOp = NextLHSI->getOperand(1);
2140 NextLHSI->setOperand(1, ExtraOperand);
2141 TmpLHSI = NextLHSI;
2142 ExtraOperand = NextOp;
2143 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002144
Chris Lattner564a7272003-08-13 19:01:45 +00002145 // Now that the instructions are reassociated, have the functor perform
2146 // the transformation...
2147 return F.apply(Root);
2148 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002149
Chris Lattner564a7272003-08-13 19:01:45 +00002150 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2151 }
2152 return 0;
2153}
2154
Dan Gohman844731a2008-05-13 00:00:25 +00002155namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002156
2157// AddRHS - Implements: X + X --> X << 1
2158struct AddRHS {
2159 Value *RHS;
2160 AddRHS(Value *rhs) : RHS(rhs) {}
2161 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2162 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002163 return BinaryOperator::CreateShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00002164 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002165 }
2166};
2167
2168// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2169// iff C1&C2 == 0
2170struct AddMaskingAnd {
2171 Constant *C2;
2172 AddMaskingAnd(Constant *c) : C2(c) {}
2173 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002174 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002175 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002176 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002177 }
2178 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002179 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002180 }
2181};
2182
Dan Gohman844731a2008-05-13 00:00:25 +00002183}
2184
Chris Lattner6e7ba452005-01-01 16:22:27 +00002185static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002186 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002187 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002188 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002189 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002190
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002191 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00002192 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002193 }
2194
Chris Lattner2eefe512004-04-09 19:05:30 +00002195 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002196 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2197 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002198
Chris Lattner2eefe512004-04-09 19:05:30 +00002199 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2200 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002201 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2202 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002203 }
2204
2205 Value *Op0 = SO, *Op1 = ConstOperand;
2206 if (!ConstIsRHS)
2207 std::swap(Op0, Op1);
2208 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002209 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002210 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002211 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002212 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002213 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002214 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002215 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002216 abort();
2217 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002218 return IC->InsertNewInstBefore(New, I);
2219}
2220
2221// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2222// constant as the other operand, try to fold the binary operator into the
2223// select arguments. This also works for Cast instructions, which obviously do
2224// not have a second operand.
2225static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2226 InstCombiner *IC) {
2227 // Don't modify shared select instructions
2228 if (!SI->hasOneUse()) return 0;
2229 Value *TV = SI->getOperand(1);
2230 Value *FV = SI->getOperand(2);
2231
2232 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002233 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002234 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002235
Chris Lattner6e7ba452005-01-01 16:22:27 +00002236 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2237 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2238
Gabor Greif051a9502008-04-06 20:25:17 +00002239 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2240 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002241 }
2242 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002243}
2244
Chris Lattner4e998b22004-09-29 05:07:12 +00002245
2246/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2247/// node as operand #0, see if we can fold the instruction into the PHI (which
2248/// is only possible if all operands to the PHI are constants).
2249Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2250 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002251 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002252 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002253
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002254 // Check to see if all of the operands of the PHI are constants. If there is
2255 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002256 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002257 BasicBlock *NonConstBB = 0;
2258 for (unsigned i = 0; i != NumPHIValues; ++i)
2259 if (!isa<Constant>(PN->getIncomingValue(i))) {
2260 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002261 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002262 NonConstBB = PN->getIncomingBlock(i);
2263
2264 // If the incoming non-constant value is in I's block, we have an infinite
2265 // loop.
2266 if (NonConstBB == I.getParent())
2267 return 0;
2268 }
2269
2270 // If there is exactly one non-constant value, we can insert a copy of the
2271 // operation in that block. However, if this is a critical edge, we would be
2272 // inserting the computation one some other paths (e.g. inside a loop). Only
2273 // do this if the pred block is unconditionally branching into the phi block.
2274 if (NonConstBB) {
2275 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2276 if (!BI || !BI->isUnconditional()) return 0;
2277 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002278
2279 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002280 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002281 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002282 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002283 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002284
2285 // Next, add all of the operands to the PHI.
2286 if (I.getNumOperands() == 2) {
2287 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002288 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002289 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002290 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002291 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2292 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2293 else
2294 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002295 } else {
2296 assert(PN->getIncomingBlock(i) == NonConstBB);
2297 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002298 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002299 PN->getIncomingValue(i), C, "phitmp",
2300 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002301 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002302 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002303 CI->getPredicate(),
2304 PN->getIncomingValue(i), C, "phitmp",
2305 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002306 else
2307 assert(0 && "Unknown binop!");
2308
Chris Lattnerdbab3862007-03-02 21:28:56 +00002309 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002310 }
2311 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002312 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002313 } else {
2314 CastInst *CI = cast<CastInst>(&I);
2315 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002316 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002317 Value *InV;
2318 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002319 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002320 } else {
2321 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002322 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002323 I.getType(), "phitmp",
2324 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002325 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002326 }
2327 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002328 }
2329 }
2330 return ReplaceInstUsesWith(I, NewPN);
2331}
2332
Chris Lattner2454a2e2008-01-29 06:52:45 +00002333
2334/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2335/// value is never equal to -0.0.
2336///
2337/// Note that this function will need to be revisited when we support nondefault
2338/// rounding modes!
2339///
2340static bool CannotBeNegativeZero(const Value *V) {
2341 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2342 return !CFP->getValueAPF().isNegZero();
2343
2344 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2345 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2346 if (I->getOpcode() == Instruction::Add &&
2347 isa<ConstantFP>(I->getOperand(1)) &&
2348 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2349 return true;
2350
2351 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2352 if (II->getIntrinsicID() == Intrinsic::sqrt)
2353 return CannotBeNegativeZero(II->getOperand(1));
2354
2355 if (const CallInst *CI = dyn_cast<CallInst>(I))
2356 if (const Function *F = CI->getCalledFunction()) {
2357 if (F->isDeclaration()) {
2358 switch (F->getNameLen()) {
2359 case 3: // abs(x) != -0.0
2360 if (!strcmp(F->getNameStart(), "abs")) return true;
2361 break;
2362 case 4: // abs[lf](x) != -0.0
2363 if (!strcmp(F->getNameStart(), "absf")) return true;
2364 if (!strcmp(F->getNameStart(), "absl")) return true;
2365 break;
2366 }
2367 }
2368 }
2369 }
2370
2371 return false;
2372}
2373
2374
Chris Lattner7e708292002-06-25 16:13:24 +00002375Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002376 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002377 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002378
Chris Lattner66331a42004-04-10 22:01:55 +00002379 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002380 // X + undef -> undef
2381 if (isa<UndefValue>(RHS))
2382 return ReplaceInstUsesWith(I, RHS);
2383
Chris Lattner66331a42004-04-10 22:01:55 +00002384 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002385 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002386 if (RHSC->isNullValue())
2387 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002388 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002389 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2390 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002391 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002392 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002393
Chris Lattner66331a42004-04-10 22:01:55 +00002394 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002395 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002396 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002397 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002398 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002399 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002400
2401 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2402 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002403 if (!isa<VectorType>(I.getType())) {
2404 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2405 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2406 KnownZero, KnownOne))
2407 return &I;
2408 }
Chris Lattner66331a42004-04-10 22:01:55 +00002409 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002410
2411 if (isa<PHINode>(LHS))
2412 if (Instruction *NV = FoldOpIntoPhi(I))
2413 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002414
Chris Lattner4f637d42006-01-06 17:59:59 +00002415 ConstantInt *XorRHS = 0;
2416 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002417 if (isa<ConstantInt>(RHSC) &&
2418 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002419 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002420 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002421
Zhou Sheng4351c642007-04-02 08:20:41 +00002422 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002423 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2424 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002425 do {
2426 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002427 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2428 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002429 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2430 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002431 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002432 if (!MaskedValueIsZero(XorLHS,
2433 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002434 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002435 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002436 }
2437 }
2438 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002439 C0080Val = APIntOps::lshr(C0080Val, Size);
2440 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2441 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002442
Reid Spencer35c38852007-03-28 01:36:16 +00002443 // FIXME: This shouldn't be necessary. When the backends can handle types
2444 // with funny bit widths then this whole cascade of if statements should
2445 // be removed. It is just here to get the size of the "middle" type back
2446 // up to something that the back ends can handle.
2447 const Type *MiddleType = 0;
2448 switch (Size) {
2449 default: break;
2450 case 32: MiddleType = Type::Int32Ty; break;
2451 case 16: MiddleType = Type::Int16Ty; break;
2452 case 8: MiddleType = Type::Int8Ty; break;
2453 }
2454 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002455 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002456 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002457 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002458 }
2459 }
Chris Lattner66331a42004-04-10 22:01:55 +00002460 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002461
Chris Lattner564a7272003-08-13 19:01:45 +00002462 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002463 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002464 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002465
2466 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2467 if (RHSI->getOpcode() == Instruction::Sub)
2468 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2469 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2470 }
2471 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2472 if (LHSI->getOpcode() == Instruction::Sub)
2473 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2474 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2475 }
Robert Bocchino71698282004-07-27 21:02:21 +00002476 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002477
Chris Lattner5c4afb92002-05-08 22:46:53 +00002478 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002479 // -A + -B --> -(A + B)
2480 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002481 if (LHS->getType()->isIntOrIntVector()) {
2482 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002483 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002484 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002485 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002486 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002487 }
2488
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002489 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002490 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002491
2492 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002493 if (!isa<Constant>(RHS))
2494 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002495 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002496
Misha Brukmanfd939082005-04-21 23:48:37 +00002497
Chris Lattner50af16a2004-11-13 19:50:12 +00002498 ConstantInt *C2;
2499 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2500 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002501 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002502
2503 // X*C1 + X*C2 --> X * (C1+C2)
2504 ConstantInt *C1;
2505 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002506 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002507 }
2508
2509 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002510 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002511 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002512
Chris Lattnere617c9e2007-01-05 02:17:46 +00002513 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002514 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2515 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002516
Chris Lattnerad3448c2003-02-18 19:57:07 +00002517
Chris Lattner564a7272003-08-13 19:01:45 +00002518 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002519 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002520 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2521 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002522
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002523 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002524 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002525 Value *W, *X, *Y, *Z;
2526 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2527 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2528 if (W != Y) {
2529 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002530 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002531 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002532 std::swap(W, X);
2533 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002534 std::swap(Y, Z);
2535 std::swap(W, X);
2536 }
2537 }
2538
2539 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002540 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002541 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002542 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002543 }
2544 }
2545 }
2546
Chris Lattner6b032052003-10-02 15:11:26 +00002547 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002548 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002549 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002550 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002551
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002552 // (X & FF00) + xx00 -> (X+xx00) & FF00
2553 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002554 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002555 if (Anded == CRHS) {
2556 // See if all bits from the first bit set in the Add RHS up are included
2557 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002558 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002559
2560 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002561 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002562
2563 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002564 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002565
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002566 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2567 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002568 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002569 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002570 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002571 }
2572 }
2573 }
2574
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002575 // Try to fold constant add into select arguments.
2576 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002577 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002578 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002579 }
2580
Reid Spencer1628cec2006-10-26 06:15:43 +00002581 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002582 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002583 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002584 CastInst *CI = dyn_cast<CastInst>(LHS);
2585 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002586 if (!CI) {
2587 CI = dyn_cast<CastInst>(RHS);
2588 Other = LHS;
2589 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002590 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002591 (CI->getType()->getPrimitiveSizeInBits() ==
2592 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002593 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002594 unsigned AS =
2595 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002596 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2597 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002598 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002599 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002600 }
2601 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002602
Chris Lattner42790482007-12-20 01:56:58 +00002603 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002604 {
2605 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2606 Value *Other = RHS;
2607 if (!SI) {
2608 SI = dyn_cast<SelectInst>(RHS);
2609 Other = LHS;
2610 }
Chris Lattner42790482007-12-20 01:56:58 +00002611 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002612 Value *TV = SI->getTrueValue();
2613 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002614 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002615
2616 // Can we fold the add into the argument of the select?
2617 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002618 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2619 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002620 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002621 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2622 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002623 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002624 }
2625 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002626
2627 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2628 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2629 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2630 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002631
Chris Lattner7e708292002-06-25 16:13:24 +00002632 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002633}
2634
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002635// isSignBit - Return true if the value represented by the constant only has the
2636// highest order bit set.
2637static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002638 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002639 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002640}
2641
Chris Lattner7e708292002-06-25 16:13:24 +00002642Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002643 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002644
Chris Lattner233f7dc2002-08-12 21:17:25 +00002645 if (Op0 == Op1) // sub X, X -> 0
2646 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002647
Chris Lattner233f7dc2002-08-12 21:17:25 +00002648 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002649 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002650 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002651
Chris Lattnere87597f2004-10-16 18:11:37 +00002652 if (isa<UndefValue>(Op0))
2653 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2654 if (isa<UndefValue>(Op1))
2655 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2656
Chris Lattnerd65460f2003-11-05 01:06:05 +00002657 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2658 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002659 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002660 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002661
Chris Lattnerd65460f2003-11-05 01:06:05 +00002662 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002663 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002664 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002665 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002666
Chris Lattner76b7a062007-01-15 07:02:54 +00002667 // -(X >>u 31) -> (X >>s 31)
2668 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002669 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002670 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002671 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002672 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002673 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002674 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002675 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002676 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002677 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002678 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002679 }
2680 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002681 }
2682 else if (SI->getOpcode() == Instruction::AShr) {
2683 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2684 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002685 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002686 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002687 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002688 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002689 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002690 }
2691 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002692 }
2693 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002694 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002695
2696 // Try to fold constant sub into select arguments.
2697 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002698 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002699 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002700
2701 if (isa<PHINode>(Op0))
2702 if (Instruction *NV = FoldOpIntoPhi(I))
2703 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002704 }
2705
Chris Lattner43d84d62005-04-07 16:15:25 +00002706 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2707 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002708 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002709 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002710 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002711 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002712 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002713 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2714 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2715 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002716 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002717 Op1I->getOperand(0));
2718 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002719 }
2720
Chris Lattnerfd059242003-10-15 16:48:29 +00002721 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002722 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2723 // is not used by anyone else...
2724 //
Chris Lattner0517e722004-02-02 20:09:56 +00002725 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002726 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002727 // Swap the two operands of the subexpr...
2728 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2729 Op1I->setOperand(0, IIOp1);
2730 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002731
Chris Lattnera2881962003-02-18 19:28:33 +00002732 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002733 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002734 }
2735
2736 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2737 //
2738 if (Op1I->getOpcode() == Instruction::And &&
2739 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2740 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2741
Chris Lattnerf523d062004-06-09 05:08:07 +00002742 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002743 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2744 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002745 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002746
Reid Spencerac5209e2006-10-16 23:08:08 +00002747 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002748 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002749 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002750 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002751 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002752 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002753 ConstantExpr::getNeg(DivRHS));
2754
Chris Lattnerad3448c2003-02-18 19:57:07 +00002755 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002756 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002757 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002758 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002759 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002760 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002761
2762 // X - ((X / Y) * Y) --> X % Y
2763 if (Op1I->getOpcode() == Instruction::Mul)
2764 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2765 if (Op0 == I->getOperand(0) &&
2766 Op1I->getOperand(1) == I->getOperand(1)) {
2767 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002768 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002769 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002770 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00002771 }
Chris Lattner40371712002-05-09 01:29:19 +00002772 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002773 }
Chris Lattnera2881962003-02-18 19:28:33 +00002774
Chris Lattner9919e3d2006-12-02 00:13:08 +00002775 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002776 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002777 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002778 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2779 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2780 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2781 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002782 } else if (Op0I->getOpcode() == Instruction::Sub) {
2783 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002784 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002785 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002786 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002787
Chris Lattner50af16a2004-11-13 19:50:12 +00002788 ConstantInt *C1;
2789 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002790 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002791 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002792
Chris Lattner50af16a2004-11-13 19:50:12 +00002793 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2794 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002795 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002796 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002797 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002798}
2799
Chris Lattnera0141b92007-07-15 20:42:37 +00002800/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2801/// comparison only checks the sign bit. If it only checks the sign bit, set
2802/// TrueIfSigned if the result of the comparison is true when the input value is
2803/// signed.
2804static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2805 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002806 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002807 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2808 TrueIfSigned = true;
2809 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002810 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2811 TrueIfSigned = true;
2812 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002813 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2814 TrueIfSigned = false;
2815 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002816 case ICmpInst::ICMP_UGT:
2817 // True if LHS u> RHS and RHS == high-bit-mask - 1
2818 TrueIfSigned = true;
2819 return RHS->getValue() ==
2820 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2821 case ICmpInst::ICMP_UGE:
2822 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2823 TrueIfSigned = true;
2824 return RHS->getValue() ==
2825 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002826 default:
2827 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002828 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002829}
2830
Chris Lattner7e708292002-06-25 16:13:24 +00002831Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002832 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002833 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002834
Chris Lattnere87597f2004-10-16 18:11:37 +00002835 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2836 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2837
Chris Lattner233f7dc2002-08-12 21:17:25 +00002838 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002839 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2840 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002841
2842 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002843 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002844 if (SI->getOpcode() == Instruction::Shl)
2845 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002846 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00002847 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002848
Zhou Sheng843f07672007-04-19 05:39:12 +00002849 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002850 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2851 if (CI->equalsInt(1)) // X * 1 == X
2852 return ReplaceInstUsesWith(I, Op0);
2853 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002854 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002855
Zhou Sheng97b52c22007-03-29 01:57:21 +00002856 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002857 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002858 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002859 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002860 }
Robert Bocchino71698282004-07-27 21:02:21 +00002861 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002862 if (Op1F->isNullValue())
2863 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002864
Chris Lattnera2881962003-02-18 19:28:33 +00002865 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2866 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002867 // We need a better interface for long double here.
2868 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2869 if (Op1F->isExactlyValue(1.0))
2870 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002871 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002872
2873 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2874 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2875 isa<ConstantInt>(Op0I->getOperand(1))) {
2876 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002877 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002878 Op1, "tmp");
2879 InsertNewInstBefore(Add, I);
2880 Value *C1C2 = ConstantExpr::getMul(Op1,
2881 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002882 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002883
2884 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002885
2886 // Try to fold constant mul into select arguments.
2887 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002888 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002889 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002890
2891 if (isa<PHINode>(Op0))
2892 if (Instruction *NV = FoldOpIntoPhi(I))
2893 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002894 }
2895
Chris Lattnera4f445b2003-03-10 23:23:04 +00002896 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2897 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002898 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002899
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002900 // If one of the operands of the multiply is a cast from a boolean value, then
2901 // we know the bool is either zero or one, so this is a 'masking' multiply.
2902 // See if we can simplify things based on how the boolean was originally
2903 // formed.
2904 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002905 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002906 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002907 BoolCast = CI;
2908 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002909 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002910 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002911 BoolCast = CI;
2912 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002913 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002914 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2915 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002916 bool TIS = false;
2917
Reid Spencere4d87aa2006-12-23 06:05:41 +00002918 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002919 // multiply into a shift/and combination.
2920 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002921 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2922 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002923 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002924 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002925 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002926 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002927 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002928 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002929 BoolCast->getOperand(0)->getName()+
2930 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002931
2932 // If the multiply type is not the same as the source type, sign extend
2933 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002934 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002935 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2936 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002937 Instruction::CastOps opcode =
2938 (SrcBits == DstBits ? Instruction::BitCast :
2939 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2940 V = InsertCastBefore(opcode, V, I.getType(), I);
2941 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002942
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002943 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002944 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002945 }
2946 }
2947 }
2948
Chris Lattner7e708292002-06-25 16:13:24 +00002949 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002950}
2951
Reid Spencer1628cec2006-10-26 06:15:43 +00002952/// This function implements the transforms on div instructions that work
2953/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2954/// used by the visitors to those instructions.
2955/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002956Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002957 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002958
Chris Lattner50b2ca42008-02-19 06:12:18 +00002959 // undef / X -> 0 for integer.
2960 // undef / X -> undef for FP (the undef could be a snan).
2961 if (isa<UndefValue>(Op0)) {
2962 if (Op0->getType()->isFPOrFPVector())
2963 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002964 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002965 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002966
2967 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002968 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002969 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002970
Chris Lattner25feae52008-01-28 00:58:18 +00002971 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2972 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002973 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002974 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2975 // the same basic block, then we replace the select with Y, and the
2976 // condition of the select with false (if the cond value is in the same BB).
2977 // If the select has uses other than the div, this allows them to be
2978 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2979 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002980 if (ST->isNullValue()) {
2981 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2982 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002983 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002984 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2985 I.setOperand(1, SI->getOperand(2));
2986 else
2987 UpdateValueUsesWith(SI, SI->getOperand(2));
2988 return &I;
2989 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002990
Chris Lattner25feae52008-01-28 00:58:18 +00002991 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2992 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002993 if (ST->isNullValue()) {
2994 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2995 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002996 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002997 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2998 I.setOperand(1, SI->getOperand(1));
2999 else
3000 UpdateValueUsesWith(SI, SI->getOperand(1));
3001 return &I;
3002 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003003 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003004
Reid Spencer1628cec2006-10-26 06:15:43 +00003005 return 0;
3006}
Misha Brukmanfd939082005-04-21 23:48:37 +00003007
Reid Spencer1628cec2006-10-26 06:15:43 +00003008/// This function implements the transforms common to both integer division
3009/// instructions (udiv and sdiv). It is called by the visitors to those integer
3010/// division instructions.
3011/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003012Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003013 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3014
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003015 // (sdiv X, X) --> 1 (udiv X, X) --> 1
3016 if (Op0 == Op1)
3017 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
3018
Reid Spencer1628cec2006-10-26 06:15:43 +00003019 if (Instruction *Common = commonDivTransforms(I))
3020 return Common;
3021
3022 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3023 // div X, 1 == X
3024 if (RHS->equalsInt(1))
3025 return ReplaceInstUsesWith(I, Op0);
3026
3027 // (X / C1) / C2 -> X / (C1*C2)
3028 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3029 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3030 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003031 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3032 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3033 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003034 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003035 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003036 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003037
Reid Spencerbca0e382007-03-23 20:05:17 +00003038 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003039 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3040 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3041 return R;
3042 if (isa<PHINode>(Op0))
3043 if (Instruction *NV = FoldOpIntoPhi(I))
3044 return NV;
3045 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003046 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003047
Chris Lattnera2881962003-02-18 19:28:33 +00003048 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003049 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003050 if (LHS->equalsInt(0))
3051 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3052
Reid Spencer1628cec2006-10-26 06:15:43 +00003053 return 0;
3054}
3055
3056Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3057 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3058
3059 // Handle the integer div common cases
3060 if (Instruction *Common = commonIDivTransforms(I))
3061 return Common;
3062
3063 // X udiv C^2 -> X >> C
3064 // Check to see if this is an unsigned division with an exact power of 2,
3065 // if so, convert to a right shift.
3066 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00003067 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003068 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003069 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003070 }
3071
3072 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003073 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003074 if (RHSI->getOpcode() == Instruction::Shl &&
3075 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003076 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003077 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003078 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003079 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003080 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003081 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003082 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003083 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003084 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003085 }
3086 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003087 }
3088
Reid Spencer1628cec2006-10-26 06:15:43 +00003089 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3090 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003091 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003092 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003093 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003094 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003095 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003096 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003097 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003098 // Construct the "on true" case of the select
3099 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003100 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003101 Op0, TC, SI->getName()+".t");
3102 TSI = InsertNewInstBefore(TSI, I);
3103
3104 // Construct the "on false" case of the select
3105 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003106 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003107 Op0, FC, SI->getName()+".f");
3108 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003109
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003110 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003111 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003112 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003113 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003114 return 0;
3115}
3116
Reid Spencer1628cec2006-10-26 06:15:43 +00003117Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3118 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3119
3120 // Handle the integer div common cases
3121 if (Instruction *Common = commonIDivTransforms(I))
3122 return Common;
3123
3124 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3125 // sdiv X, -1 == -X
3126 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003127 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003128
3129 // -X/C -> X/-C
3130 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003131 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003132 }
3133
3134 // If the sign bits of both operands are zero (i.e. we can prove they are
3135 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003136 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003137 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003138 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003139 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003140 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003141 }
3142 }
3143
3144 return 0;
3145}
3146
3147Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3148 return commonDivTransforms(I);
3149}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003150
Reid Spencer0a783f72006-11-02 01:53:59 +00003151/// This function implements the transforms on rem instructions that work
3152/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3153/// is used by the visitors to those instructions.
3154/// @brief Transforms common to all three rem instructions
3155Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003156 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003157
Chris Lattner50b2ca42008-02-19 06:12:18 +00003158 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003159 if (Constant *LHS = dyn_cast<Constant>(Op0))
3160 if (LHS->isNullValue())
3161 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3162
Chris Lattner50b2ca42008-02-19 06:12:18 +00003163 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3164 if (I.getType()->isFPOrFPVector())
3165 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003166 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003167 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003168 if (isa<UndefValue>(Op1))
3169 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003170
3171 // Handle cases involving: rem X, (select Cond, Y, Z)
3172 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3173 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3174 // the same basic block, then we replace the select with Y, and the
3175 // condition of the select with false (if the cond value is in the same
3176 // BB). If the select has uses other than the div, this allows them to be
3177 // simplified also.
3178 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3179 if (ST->isNullValue()) {
3180 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3181 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003182 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003183 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3184 I.setOperand(1, SI->getOperand(2));
3185 else
3186 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003187 return &I;
3188 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003189 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3190 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3191 if (ST->isNullValue()) {
3192 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3193 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003194 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003195 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3196 I.setOperand(1, SI->getOperand(1));
3197 else
3198 UpdateValueUsesWith(SI, SI->getOperand(1));
3199 return &I;
3200 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003201 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003202
Reid Spencer0a783f72006-11-02 01:53:59 +00003203 return 0;
3204}
3205
3206/// This function implements the transforms common to both integer remainder
3207/// instructions (urem and srem). It is called by the visitors to those integer
3208/// remainder instructions.
3209/// @brief Common integer remainder transforms
3210Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3211 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3212
3213 if (Instruction *common = commonRemTransforms(I))
3214 return common;
3215
Chris Lattner857e8cd2004-12-12 21:48:58 +00003216 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003217 // X % 0 == undef, we don't need to preserve faults!
3218 if (RHS->equalsInt(0))
3219 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3220
Chris Lattnera2881962003-02-18 19:28:33 +00003221 if (RHS->equalsInt(1)) // X % 1 == 0
3222 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3223
Chris Lattner97943922006-02-28 05:49:21 +00003224 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3225 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3226 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3227 return R;
3228 } else if (isa<PHINode>(Op0I)) {
3229 if (Instruction *NV = FoldOpIntoPhi(I))
3230 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003231 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003232
3233 // See if we can fold away this rem instruction.
3234 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3235 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3236 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3237 KnownZero, KnownOne))
3238 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003239 }
Chris Lattnera2881962003-02-18 19:28:33 +00003240 }
3241
Reid Spencer0a783f72006-11-02 01:53:59 +00003242 return 0;
3243}
3244
3245Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3246 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3247
3248 if (Instruction *common = commonIRemTransforms(I))
3249 return common;
3250
3251 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3252 // X urem C^2 -> X and C
3253 // Check to see if this is an unsigned remainder with an exact power of 2,
3254 // if so, convert to a bitwise and.
3255 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003256 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003257 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003258 }
3259
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003260 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003261 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3262 if (RHSI->getOpcode() == Instruction::Shl &&
3263 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003264 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003265 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003266 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003267 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003268 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003269 }
3270 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003271 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003272
Reid Spencer0a783f72006-11-02 01:53:59 +00003273 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3274 // where C1&C2 are powers of two.
3275 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3276 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3277 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3278 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003279 if ((STO->getValue().isPowerOf2()) &&
3280 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003281 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003282 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003283 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003284 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003285 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003286 }
3287 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003288 }
3289
Chris Lattner3f5b8772002-05-06 16:14:14 +00003290 return 0;
3291}
3292
Reid Spencer0a783f72006-11-02 01:53:59 +00003293Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3294 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3295
Dan Gohmancff55092007-11-05 23:16:33 +00003296 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003297 if (Instruction *common = commonIRemTransforms(I))
3298 return common;
3299
3300 if (Value *RHSNeg = dyn_castNegVal(Op1))
3301 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003302 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003303 // X % -Y -> X % Y
3304 AddUsesToWorkList(I);
3305 I.setOperand(1, RHSNeg);
3306 return &I;
3307 }
3308
Dan Gohmancff55092007-11-05 23:16:33 +00003309 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003310 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003311 if (I.getType()->isInteger()) {
3312 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3313 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3314 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003315 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003316 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003317 }
3318
3319 return 0;
3320}
3321
3322Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003323 return commonRemTransforms(I);
3324}
3325
Chris Lattner8b170942002-08-09 23:47:40 +00003326// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003327static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003328 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003329 if (!isSigned)
3330 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3331 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003332}
3333
3334// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003335static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003336 if (!isSigned)
3337 return C->getValue() == 1; // unsigned
3338
3339 // Calculate 1111111111000000000000
3340 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3341 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003342}
3343
Chris Lattner457dd822004-06-09 07:59:58 +00003344// isOneBitSet - Return true if there is exactly one bit set in the specified
3345// constant.
3346static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003347 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003348}
3349
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003350// isHighOnes - Return true if the constant is of the form 1+0+.
3351// This is the same as lowones(~X).
3352static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003353 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003354}
3355
Reid Spencere4d87aa2006-12-23 06:05:41 +00003356/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003357/// are carefully arranged to allow folding of expressions such as:
3358///
3359/// (A < B) | (A > B) --> (A != B)
3360///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003361/// Note that this is only valid if the first and second predicates have the
3362/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003363///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003364/// Three bits are used to represent the condition, as follows:
3365/// 0 A > B
3366/// 1 A == B
3367/// 2 A < B
3368///
3369/// <=> Value Definition
3370/// 000 0 Always false
3371/// 001 1 A > B
3372/// 010 2 A == B
3373/// 011 3 A >= B
3374/// 100 4 A < B
3375/// 101 5 A != B
3376/// 110 6 A <= B
3377/// 111 7 Always true
3378///
3379static unsigned getICmpCode(const ICmpInst *ICI) {
3380 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003381 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003382 case ICmpInst::ICMP_UGT: return 1; // 001
3383 case ICmpInst::ICMP_SGT: return 1; // 001
3384 case ICmpInst::ICMP_EQ: return 2; // 010
3385 case ICmpInst::ICMP_UGE: return 3; // 011
3386 case ICmpInst::ICMP_SGE: return 3; // 011
3387 case ICmpInst::ICMP_ULT: return 4; // 100
3388 case ICmpInst::ICMP_SLT: return 4; // 100
3389 case ICmpInst::ICMP_NE: return 5; // 101
3390 case ICmpInst::ICMP_ULE: return 6; // 110
3391 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003392 // True -> 7
3393 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003394 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003395 return 0;
3396 }
3397}
3398
Reid Spencere4d87aa2006-12-23 06:05:41 +00003399/// getICmpValue - This is the complement of getICmpCode, which turns an
3400/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003401/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003402/// of predicate to use in new icmp instructions.
3403static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3404 switch (code) {
3405 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003406 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003407 case 1:
3408 if (sign)
3409 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3410 else
3411 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3412 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3413 case 3:
3414 if (sign)
3415 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3416 else
3417 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3418 case 4:
3419 if (sign)
3420 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3421 else
3422 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3423 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3424 case 6:
3425 if (sign)
3426 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3427 else
3428 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003429 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003430 }
3431}
3432
Reid Spencere4d87aa2006-12-23 06:05:41 +00003433static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3434 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3435 (ICmpInst::isSignedPredicate(p1) &&
3436 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3437 (ICmpInst::isSignedPredicate(p2) &&
3438 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3439}
3440
3441namespace {
3442// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3443struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003444 InstCombiner &IC;
3445 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003446 ICmpInst::Predicate pred;
3447 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3448 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3449 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003450 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003451 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3452 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003453 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3454 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003455 return false;
3456 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003457 Instruction *apply(Instruction &Log) const {
3458 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3459 if (ICI->getOperand(0) != LHS) {
3460 assert(ICI->getOperand(1) == LHS);
3461 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003462 }
3463
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003464 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003465 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003466 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003467 unsigned Code;
3468 switch (Log.getOpcode()) {
3469 case Instruction::And: Code = LHSCode & RHSCode; break;
3470 case Instruction::Or: Code = LHSCode | RHSCode; break;
3471 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003472 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003473 }
3474
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003475 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3476 ICmpInst::isSignedPredicate(ICI->getPredicate());
3477
3478 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003479 if (Instruction *I = dyn_cast<Instruction>(RV))
3480 return I;
3481 // Otherwise, it's a constant boolean value...
3482 return IC.ReplaceInstUsesWith(Log, RV);
3483 }
3484};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003485} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003486
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003487// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3488// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003489// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003490Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003491 ConstantInt *OpRHS,
3492 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003493 BinaryOperator &TheAnd) {
3494 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003495 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003496 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003497 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003498
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003499 switch (Op->getOpcode()) {
3500 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003501 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003502 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003503 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003504 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003505 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003506 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003507 }
3508 break;
3509 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003510 if (Together == AndRHS) // (X | C) & C --> C
3511 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003512
Chris Lattner6e7ba452005-01-01 16:22:27 +00003513 if (Op->hasOneUse() && Together != OpRHS) {
3514 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003515 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003516 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003517 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003518 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003519 }
3520 break;
3521 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003522 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003523 // Adding a one to a single bit bit-field should be turned into an XOR
3524 // of the bit. First thing to check is to see if this AND is with a
3525 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003526 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003527
3528 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003529 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003530 // Ok, at this point, we know that we are masking the result of the
3531 // ADD down to exactly one bit. If the constant we are adding has
3532 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003533 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003534
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003535 // Check to see if any bits below the one bit set in AndRHSV are set.
3536 if ((AddRHS & (AndRHSV-1)) == 0) {
3537 // If not, the only thing that can effect the output of the AND is
3538 // the bit specified by AndRHSV. If that bit is set, the effect of
3539 // the XOR is to toggle the bit. If it is clear, then the ADD has
3540 // no effect.
3541 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3542 TheAnd.setOperand(0, X);
3543 return &TheAnd;
3544 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003545 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003546 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003547 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003548 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003549 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003550 }
3551 }
3552 }
3553 }
3554 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003555
3556 case Instruction::Shl: {
3557 // We know that the AND will not produce any of the bits shifted in, so if
3558 // the anded constant includes them, clear them now!
3559 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003560 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003561 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003562 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3563 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003564
Zhou Sheng290bec52007-03-29 08:15:12 +00003565 if (CI->getValue() == ShlMask) {
3566 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003567 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3568 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003569 TheAnd.setOperand(1, CI);
3570 return &TheAnd;
3571 }
3572 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003573 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003574 case Instruction::LShr:
3575 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003576 // We know that the AND will not produce any of the bits shifted in, so if
3577 // the anded constant includes them, clear them now! This only applies to
3578 // unsigned shifts, because a signed shr may bring in set bits!
3579 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003580 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003581 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003582 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3583 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003584
Zhou Sheng290bec52007-03-29 08:15:12 +00003585 if (CI->getValue() == ShrMask) {
3586 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003587 return ReplaceInstUsesWith(TheAnd, Op);
3588 } else if (CI != AndRHS) {
3589 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3590 return &TheAnd;
3591 }
3592 break;
3593 }
3594 case Instruction::AShr:
3595 // Signed shr.
3596 // See if this is shifting in some sign extension, then masking it out
3597 // with an and.
3598 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003599 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003600 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003601 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3602 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003603 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003604 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003605 // Make the argument unsigned.
3606 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003607 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003608 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003609 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003610 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003611 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003612 }
3613 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003614 }
3615 return 0;
3616}
3617
Chris Lattner8b170942002-08-09 23:47:40 +00003618
Chris Lattnera96879a2004-09-29 17:40:11 +00003619/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3620/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003621/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3622/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003623/// insert new instructions.
3624Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003625 bool isSigned, bool Inside,
3626 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003627 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003628 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003629 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003630
Chris Lattnera96879a2004-09-29 17:40:11 +00003631 if (Inside) {
3632 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003633 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003634
Reid Spencere4d87aa2006-12-23 06:05:41 +00003635 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003636 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003637 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003638 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3639 return new ICmpInst(pred, V, Hi);
3640 }
3641
3642 // Emit V-Lo <u Hi-Lo
3643 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003644 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003645 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003646 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3647 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003648 }
3649
3650 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003651 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003652
Reid Spencere4e40032007-03-21 23:19:50 +00003653 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003654 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003655 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003656 ICmpInst::Predicate pred = (isSigned ?
3657 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3658 return new ICmpInst(pred, V, Hi);
3659 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003660
Reid Spencere4e40032007-03-21 23:19:50 +00003661 // Emit V-Lo >u Hi-1-Lo
3662 // Note that Hi has already had one subtracted from it, above.
3663 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003664 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003665 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003666 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3667 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003668}
3669
Chris Lattner7203e152005-09-18 07:22:02 +00003670// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3671// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3672// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3673// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003674static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003675 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003676 uint32_t BitWidth = Val->getType()->getBitWidth();
3677 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003678
3679 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003680 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003681 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003682 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003683 return true;
3684}
3685
Chris Lattner7203e152005-09-18 07:22:02 +00003686/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3687/// where isSub determines whether the operator is a sub. If we can fold one of
3688/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003689///
3690/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3691/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3692/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3693///
3694/// return (A +/- B).
3695///
3696Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003697 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003698 Instruction &I) {
3699 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3700 if (!LHSI || LHSI->getNumOperands() != 2 ||
3701 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3702
3703 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3704
3705 switch (LHSI->getOpcode()) {
3706 default: return 0;
3707 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003708 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003709 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003710 if ((Mask->getValue().countLeadingZeros() +
3711 Mask->getValue().countPopulation()) ==
3712 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003713 break;
3714
3715 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3716 // part, we don't need any explicit masks to take them out of A. If that
3717 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003718 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003719 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003720 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003721 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003722 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003723 break;
3724 }
3725 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003726 return 0;
3727 case Instruction::Or:
3728 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003729 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003730 if ((Mask->getValue().countLeadingZeros() +
3731 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003732 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003733 break;
3734 return 0;
3735 }
3736
3737 Instruction *New;
3738 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003739 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003740 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003741 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003742 return InsertNewInstBefore(New, I);
3743}
3744
Chris Lattner7e708292002-06-25 16:13:24 +00003745Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003746 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003747 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003748
Chris Lattnere87597f2004-10-16 18:11:37 +00003749 if (isa<UndefValue>(Op1)) // X & undef -> 0
3750 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3751
Chris Lattner6e7ba452005-01-01 16:22:27 +00003752 // and X, X = X
3753 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003754 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003755
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003756 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003757 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003758 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003759 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3760 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3761 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003762 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003763 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003764 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003765 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003766 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003767 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003768 } else if (isa<ConstantAggregateZero>(Op1)) {
3769 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003770 }
3771 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003772
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003773 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003774 const APInt& AndRHSMask = AndRHS->getValue();
3775 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003776
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003777 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003778 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003779 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003780 Value *Op0LHS = Op0I->getOperand(0);
3781 Value *Op0RHS = Op0I->getOperand(1);
3782 switch (Op0I->getOpcode()) {
3783 case Instruction::Xor:
3784 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003785 // If the mask is only needed on one incoming arm, push it up.
3786 if (Op0I->hasOneUse()) {
3787 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3788 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003789 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003790 Op0RHS->getName()+".masked");
3791 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003792 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003793 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003794 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003795 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003796 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3797 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003798 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00003799 Op0LHS->getName()+".masked");
3800 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003801 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00003802 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3803 }
3804 }
3805
Chris Lattner6e7ba452005-01-01 16:22:27 +00003806 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003807 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003808 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3809 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3810 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3811 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003812 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00003813 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003814 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003815 break;
3816
3817 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003818 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3819 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3820 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3821 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003822 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003823 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003824 }
3825
Chris Lattner58403262003-07-23 19:25:52 +00003826 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003827 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003828 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003829 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003830 // If this is an integer truncation or change from signed-to-unsigned, and
3831 // if the source is an and/or with immediate, transform it. This
3832 // frequently occurs for bitfield accesses.
3833 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003834 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003835 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003836 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003837 if (CastOp->getOpcode() == Instruction::And) {
3838 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003839 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3840 // This will fold the two constants together, which may allow
3841 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003842 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00003843 CastOp->getOperand(0), I.getType(),
3844 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003845 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003846 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003847 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003848 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003849 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00003850 } else if (CastOp->getOpcode() == Instruction::Or) {
3851 // Change: and (cast (or X, C1) to T), C2
3852 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003853 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003854 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3855 return ReplaceInstUsesWith(I, AndRHS);
3856 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003857 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003858 }
Chris Lattner06782f82003-07-23 19:36:21 +00003859 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003860
3861 // Try to fold constant and into select arguments.
3862 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003863 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003864 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003865 if (isa<PHINode>(Op0))
3866 if (Instruction *NV = FoldOpIntoPhi(I))
3867 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003868 }
3869
Chris Lattner8d969642003-03-10 23:06:50 +00003870 Value *Op0NotVal = dyn_castNotVal(Op0);
3871 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003872
Chris Lattner5b62aa72004-06-18 06:07:51 +00003873 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3874 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3875
Misha Brukmancb6267b2004-07-30 12:50:08 +00003876 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003877 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003878 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00003879 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003880 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003881 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00003882 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003883
3884 {
Chris Lattner003b6202007-06-15 05:58:24 +00003885 Value *A = 0, *B = 0, *C = 0, *D = 0;
3886 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003887 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3888 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003889
3890 // (A|B) & ~(A&B) -> A^B
3891 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3892 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003893 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003894 }
3895 }
3896
3897 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003898 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3899 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003900
3901 // ~(A&B) & (A|B) -> A^B
3902 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3903 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003904 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00003905 }
3906 }
Chris Lattner64daab52006-04-01 08:03:55 +00003907
3908 if (Op0->hasOneUse() &&
3909 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3910 if (A == Op1) { // (A^B)&A -> A&(A^B)
3911 I.swapOperands(); // Simplify below
3912 std::swap(Op0, Op1);
3913 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3914 cast<BinaryOperator>(Op0)->swapOperands();
3915 I.swapOperands(); // Simplify below
3916 std::swap(Op0, Op1);
3917 }
3918 }
3919 if (Op1->hasOneUse() &&
3920 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3921 if (B == Op0) { // B&(A^B) -> B&(B^A)
3922 cast<BinaryOperator>(Op1)->swapOperands();
3923 std::swap(A, B);
3924 }
3925 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003926 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00003927 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003928 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00003929 }
3930 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003931 }
3932
Reid Spencere4d87aa2006-12-23 06:05:41 +00003933 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3934 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3935 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003936 return R;
3937
Chris Lattner955f3312004-09-28 21:48:02 +00003938 Value *LHSVal, *RHSVal;
3939 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003940 ICmpInst::Predicate LHSCC, RHSCC;
3941 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3942 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3943 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3944 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3945 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3946 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3947 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003948 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3949
3950 // Don't try to fold ICMP_SLT + ICMP_ULT.
3951 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3952 ICmpInst::isSignedPredicate(LHSCC) ==
3953 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003954 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003955 ICmpInst::Predicate GT;
3956 if (ICmpInst::isSignedPredicate(LHSCC) ||
3957 (ICmpInst::isEquality(LHSCC) &&
3958 ICmpInst::isSignedPredicate(RHSCC)))
3959 GT = ICmpInst::ICMP_SGT;
3960 else
3961 GT = ICmpInst::ICMP_UGT;
3962
Reid Spencere4d87aa2006-12-23 06:05:41 +00003963 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3964 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003965 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003966 std::swap(LHS, RHS);
3967 std::swap(LHSCst, RHSCst);
3968 std::swap(LHSCC, RHSCC);
3969 }
3970
Reid Spencere4d87aa2006-12-23 06:05:41 +00003971 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003972 // comparing a value against two constants and and'ing the result
3973 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003974 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3975 // (from the FoldICmpLogical check above), that the two constants
3976 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003977 assert(LHSCst != RHSCst && "Compares not folded above?");
3978
3979 switch (LHSCC) {
3980 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003981 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003982 switch (RHSCC) {
3983 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003984 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3985 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3986 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003987 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003988 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3989 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3990 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003991 return ReplaceInstUsesWith(I, LHS);
3992 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003993 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003994 switch (RHSCC) {
3995 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003996 case ICmpInst::ICMP_ULT:
3997 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3998 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3999 break; // (X != 13 & X u< 15) -> no change
4000 case ICmpInst::ICMP_SLT:
4001 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4002 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4003 break; // (X != 13 & X s< 15) -> no change
4004 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4005 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4006 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00004007 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004008 case ICmpInst::ICMP_NE:
4009 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00004010 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004011 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00004012 LHSVal->getName()+".off");
4013 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00004014 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4015 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00004016 }
4017 break; // (X != 13 & X != 15) -> no change
4018 }
4019 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004020 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00004021 switch (RHSCC) {
4022 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004023 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4024 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004025 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004026 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4027 break;
4028 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4029 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00004030 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004031 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4032 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004033 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004034 break;
4035 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00004036 switch (RHSCC) {
4037 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004038 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4039 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004040 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004041 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4042 break;
4043 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4044 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00004045 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004046 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4047 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004048 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004049 break;
4050 case ICmpInst::ICMP_UGT:
4051 switch (RHSCC) {
4052 default: assert(0 && "Unknown integer condition code!");
4053 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4054 return ReplaceInstUsesWith(I, LHS);
4055 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4056 return ReplaceInstUsesWith(I, RHS);
4057 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4058 break;
4059 case ICmpInst::ICMP_NE:
4060 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4061 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4062 break; // (X u> 13 & X != 15) -> no change
4063 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4064 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4065 true, I);
4066 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4067 break;
4068 }
4069 break;
4070 case ICmpInst::ICMP_SGT:
4071 switch (RHSCC) {
4072 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004073 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004074 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4075 return ReplaceInstUsesWith(I, RHS);
4076 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4077 break;
4078 case ICmpInst::ICMP_NE:
4079 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4080 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4081 break; // (X s> 13 & X != 15) -> no change
4082 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4083 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4084 true, I);
4085 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4086 break;
4087 }
4088 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004089 }
4090 }
4091 }
4092
Chris Lattner6fc205f2006-05-05 06:39:07 +00004093 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004094 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4095 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4096 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4097 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004098 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004099 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004100 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4101 I.getType(), TD) &&
4102 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4103 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004104 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004105 Op1C->getOperand(0),
4106 I.getName());
4107 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004108 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004109 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004110 }
Chris Lattnere511b742006-11-14 07:46:50 +00004111
4112 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004113 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4114 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4115 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004116 SI0->getOperand(1) == SI1->getOperand(1) &&
4117 (SI0->hasOneUse() || SI1->hasOneUse())) {
4118 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004119 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004120 SI1->getOperand(0),
4121 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004122 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004123 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004124 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004125 }
4126
Chris Lattner99c65742007-10-24 05:38:08 +00004127 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4128 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4129 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4130 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4131 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4132 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4133 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4134 // If either of the constants are nans, then the whole thing returns
4135 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004136 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004137 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4138 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4139 RHS->getOperand(0));
4140 }
4141 }
4142 }
4143
Chris Lattner7e708292002-06-25 16:13:24 +00004144 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004145}
4146
Chris Lattnerafe91a52006-06-15 19:07:26 +00004147/// CollectBSwapParts - Look to see if the specified value defines a single byte
4148/// in the result. If it does, and if the specified byte hasn't been filled in
4149/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004150static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004151 Instruction *I = dyn_cast<Instruction>(V);
4152 if (I == 0) return true;
4153
4154 // If this is an or instruction, it is an inner node of the bswap.
4155 if (I->getOpcode() == Instruction::Or)
4156 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4157 CollectBSwapParts(I->getOperand(1), ByteValues);
4158
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004159 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004160 // If this is a shift by a constant int, and it is "24", then its operand
4161 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004162 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004163 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004164 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004165 8*(ByteValues.size()-1))
4166 return true;
4167
4168 unsigned DestNo;
4169 if (I->getOpcode() == Instruction::Shl) {
4170 // X << 24 defines the top byte with the lowest of the input bytes.
4171 DestNo = ByteValues.size()-1;
4172 } else {
4173 // X >>u 24 defines the low byte with the highest of the input bytes.
4174 DestNo = 0;
4175 }
4176
4177 // If the destination byte value is already defined, the values are or'd
4178 // together, which isn't a bswap (unless it's an or of the same bits).
4179 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4180 return true;
4181 ByteValues[DestNo] = I->getOperand(0);
4182 return false;
4183 }
4184
4185 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4186 // don't have this.
4187 Value *Shift = 0, *ShiftLHS = 0;
4188 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4189 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4190 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4191 return true;
4192 Instruction *SI = cast<Instruction>(Shift);
4193
4194 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004195 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4196 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004197 return true;
4198
4199 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4200 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004201 if (AndAmt->getValue().getActiveBits() > 64)
4202 return true;
4203 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004204 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004205 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004206 break;
4207 // Unknown mask for bswap.
4208 if (DestByte == ByteValues.size()) return true;
4209
Reid Spencerb83eb642006-10-20 07:07:24 +00004210 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004211 unsigned SrcByte;
4212 if (SI->getOpcode() == Instruction::Shl)
4213 SrcByte = DestByte - ShiftBytes;
4214 else
4215 SrcByte = DestByte + ShiftBytes;
4216
4217 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4218 if (SrcByte != ByteValues.size()-DestByte-1)
4219 return true;
4220
4221 // If the destination byte value is already defined, the values are or'd
4222 // together, which isn't a bswap (unless it's an or of the same bits).
4223 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4224 return true;
4225 ByteValues[DestByte] = SI->getOperand(0);
4226 return false;
4227}
4228
4229/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4230/// If so, insert the new bswap intrinsic and return it.
4231Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004232 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4233 if (!ITy || ITy->getBitWidth() % 16)
4234 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004235
4236 /// ByteValues - For each byte of the result, we keep track of which value
4237 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004238 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004239 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004240
4241 // Try to find all the pieces corresponding to the bswap.
4242 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4243 CollectBSwapParts(I.getOperand(1), ByteValues))
4244 return 0;
4245
4246 // Check to see if all of the bytes come from the same value.
4247 Value *V = ByteValues[0];
4248 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4249
4250 // Check to make sure that all of the bytes come from the same value.
4251 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4252 if (ByteValues[i] != V)
4253 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004254 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004255 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004256 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004257 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004258}
4259
4260
Chris Lattner7e708292002-06-25 16:13:24 +00004261Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004262 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004263 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004264
Chris Lattner42593e62007-03-24 23:56:43 +00004265 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004266 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004267
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004268 // or X, X = X
4269 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004270 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004271
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004272 // See if we can simplify any instructions used by the instruction whose sole
4273 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004274 if (!isa<VectorType>(I.getType())) {
4275 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4276 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4277 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4278 KnownZero, KnownOne))
4279 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004280 } else if (isa<ConstantAggregateZero>(Op1)) {
4281 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4282 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4283 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4284 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004285 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004286
4287
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004288
Chris Lattner3f5b8772002-05-06 16:14:14 +00004289 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004290 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004291 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004292 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4293 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004294 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004295 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004296 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004297 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004298 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004299 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004300
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004301 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4302 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004303 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004304 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004305 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004306 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004307 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004308 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004309
4310 // Try to fold constant and into select arguments.
4311 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004312 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004313 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004314 if (isa<PHINode>(Op0))
4315 if (Instruction *NV = FoldOpIntoPhi(I))
4316 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004317 }
4318
Chris Lattner4f637d42006-01-06 17:59:59 +00004319 Value *A = 0, *B = 0;
4320 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004321
4322 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4323 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4324 return ReplaceInstUsesWith(I, Op1);
4325 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4326 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4327 return ReplaceInstUsesWith(I, Op0);
4328
Chris Lattner6423d4c2006-07-10 20:25:24 +00004329 // (A | B) | C and A | (B | C) -> bswap if possible.
4330 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004331 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004332 match(Op1, m_Or(m_Value(), m_Value())) ||
4333 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4334 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004335 if (Instruction *BSwap = MatchBSwap(I))
4336 return BSwap;
4337 }
4338
Chris Lattner6e4c6492005-05-09 04:58:36 +00004339 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4340 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004341 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004342 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004343 InsertNewInstBefore(NOr, I);
4344 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004345 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004346 }
4347
4348 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4349 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004350 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004351 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004352 InsertNewInstBefore(NOr, I);
4353 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004354 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004355 }
4356
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004357 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004358 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004359 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4360 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004361 Value *V1 = 0, *V2 = 0, *V3 = 0;
4362 C1 = dyn_cast<ConstantInt>(C);
4363 C2 = dyn_cast<ConstantInt>(D);
4364 if (C1 && C2) { // (A & C1)|(B & C2)
4365 // If we have: ((V + N) & C1) | (V & C2)
4366 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4367 // replace with V+N.
4368 if (C1->getValue() == ~C2->getValue()) {
4369 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4370 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4371 // Add commutes, try both ways.
4372 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4373 return ReplaceInstUsesWith(I, A);
4374 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4375 return ReplaceInstUsesWith(I, A);
4376 }
4377 // Or commutes, try both ways.
4378 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4379 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4380 // Add commutes, try both ways.
4381 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4382 return ReplaceInstUsesWith(I, B);
4383 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4384 return ReplaceInstUsesWith(I, B);
4385 }
4386 }
Chris Lattner044e5332007-04-08 08:01:49 +00004387 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004388 }
4389
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004390 // Check to see if we have any common things being and'ed. If so, find the
4391 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004392 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4393 if (A == B) // (A & C)|(A & D) == A & (C|D)
4394 V1 = A, V2 = C, V3 = D;
4395 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4396 V1 = A, V2 = B, V3 = C;
4397 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4398 V1 = C, V2 = A, V3 = D;
4399 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4400 V1 = C, V2 = A, V3 = B;
4401
4402 if (V1) {
4403 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004404 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4405 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004406 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004407 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004408 }
Chris Lattnere511b742006-11-14 07:46:50 +00004409
4410 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004411 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4412 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4413 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004414 SI0->getOperand(1) == SI1->getOperand(1) &&
4415 (SI0->hasOneUse() || SI1->hasOneUse())) {
4416 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004417 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004418 SI1->getOperand(0),
4419 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004420 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004421 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004422 }
4423 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004424
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004425 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4426 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004427 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004428 } else {
4429 A = 0;
4430 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004431 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004432 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4433 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004434 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004435
Misha Brukmancb6267b2004-07-30 12:50:08 +00004436 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004437 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004438 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004439 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004440 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004441 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004442 }
Chris Lattnera2881962003-02-18 19:28:33 +00004443
Reid Spencere4d87aa2006-12-23 06:05:41 +00004444 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4445 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4446 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004447 return R;
4448
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004449 Value *LHSVal, *RHSVal;
4450 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004451 ICmpInst::Predicate LHSCC, RHSCC;
4452 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4453 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4454 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4455 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4456 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4457 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4458 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004459 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4460 // We can't fold (ugt x, C) | (sgt x, C2).
4461 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004462 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004463 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004464 bool NeedsSwap;
4465 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004466 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004467 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004468 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004469
4470 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004471 std::swap(LHS, RHS);
4472 std::swap(LHSCst, RHSCst);
4473 std::swap(LHSCC, RHSCC);
4474 }
4475
Reid Spencere4d87aa2006-12-23 06:05:41 +00004476 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004477 // comparing a value against two constants and or'ing the result
4478 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004479 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4480 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004481 // equal.
4482 assert(LHSCst != RHSCst && "Compares not folded above?");
4483
4484 switch (LHSCC) {
4485 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004486 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004487 switch (RHSCC) {
4488 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004489 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004490 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4491 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004492 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004493 LHSVal->getName()+".off");
4494 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004495 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004496 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004497 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004498 break; // (X == 13 | X == 15) -> no change
4499 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4500 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004501 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004502 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4503 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4504 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004505 return ReplaceInstUsesWith(I, RHS);
4506 }
4507 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004508 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004509 switch (RHSCC) {
4510 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004511 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4512 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4513 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004514 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004515 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4516 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4517 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004518 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004519 }
4520 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004521 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004522 switch (RHSCC) {
4523 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004524 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004525 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004526 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004527 // If RHSCst is [us]MAXINT, it is always false. Not handling
4528 // this can cause overflow.
4529 if (RHSCst->isMaxValue(false))
4530 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004531 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4532 false, I);
4533 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4534 break;
4535 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4536 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004537 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004538 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4539 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004540 }
4541 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004542 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004543 switch (RHSCC) {
4544 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004545 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4546 break;
4547 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004548 // If RHSCst is [us]MAXINT, it is always false. Not handling
4549 // this can cause overflow.
4550 if (RHSCst->isMaxValue(true))
4551 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004552 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4553 false, I);
4554 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4555 break;
4556 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4557 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4558 return ReplaceInstUsesWith(I, RHS);
4559 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4560 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004561 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004562 break;
4563 case ICmpInst::ICMP_UGT:
4564 switch (RHSCC) {
4565 default: assert(0 && "Unknown integer condition code!");
4566 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4567 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4568 return ReplaceInstUsesWith(I, LHS);
4569 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4570 break;
4571 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4572 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004573 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004574 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4575 break;
4576 }
4577 break;
4578 case ICmpInst::ICMP_SGT:
4579 switch (RHSCC) {
4580 default: assert(0 && "Unknown integer condition code!");
4581 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4582 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4583 return ReplaceInstUsesWith(I, LHS);
4584 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4585 break;
4586 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4587 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004588 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004589 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4590 break;
4591 }
4592 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004593 }
4594 }
4595 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004596
4597 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004598 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004599 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004600 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004601 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4602 !isa<ICmpInst>(Op1C->getOperand(0))) {
4603 const Type *SrcTy = Op0C->getOperand(0)->getType();
4604 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4605 // Only do this if the casts both really cause code to be
4606 // generated.
4607 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4608 I.getType(), TD) &&
4609 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4610 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004611 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004612 Op1C->getOperand(0),
4613 I.getName());
4614 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004615 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004616 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004617 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004618 }
Chris Lattner99c65742007-10-24 05:38:08 +00004619 }
4620
4621
4622 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4623 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4624 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4625 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004626 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4627 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004628 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4629 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4630 // If either of the constants are nans, then the whole thing returns
4631 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004632 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004633 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4634
4635 // Otherwise, no need to compare the two constants, compare the
4636 // rest.
4637 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4638 RHS->getOperand(0));
4639 }
4640 }
4641 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004642
Chris Lattner7e708292002-06-25 16:13:24 +00004643 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004644}
4645
Dan Gohman844731a2008-05-13 00:00:25 +00004646namespace {
4647
Chris Lattnerc317d392004-02-16 01:20:27 +00004648// XorSelf - Implements: X ^ X --> 0
4649struct XorSelf {
4650 Value *RHS;
4651 XorSelf(Value *rhs) : RHS(rhs) {}
4652 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4653 Instruction *apply(BinaryOperator &Xor) const {
4654 return &Xor;
4655 }
4656};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004657
Dan Gohman844731a2008-05-13 00:00:25 +00004658}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004659
Chris Lattner7e708292002-06-25 16:13:24 +00004660Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004661 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004662 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004663
Evan Chengd34af782008-03-25 20:07:13 +00004664 if (isa<UndefValue>(Op1)) {
4665 if (isa<UndefValue>(Op0))
4666 // Handle undef ^ undef -> 0 special case. This is a common
4667 // idiom (misuse).
4668 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004669 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004670 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004671
Chris Lattnerc317d392004-02-16 01:20:27 +00004672 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4673 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004674 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004675 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004676 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004677
4678 // See if we can simplify any instructions used by the instruction whose sole
4679 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004680 if (!isa<VectorType>(I.getType())) {
4681 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4682 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4683 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4684 KnownZero, KnownOne))
4685 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004686 } else if (isa<ConstantAggregateZero>(Op1)) {
4687 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004688 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004689
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004690 // Is this a ~ operation?
4691 if (Value *NotOp = dyn_castNotVal(&I)) {
4692 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4693 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4694 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4695 if (Op0I->getOpcode() == Instruction::And ||
4696 Op0I->getOpcode() == Instruction::Or) {
4697 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4698 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4699 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004700 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004701 Op0I->getOperand(1)->getName()+".not");
4702 InsertNewInstBefore(NotY, I);
4703 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004704 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004705 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004706 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004707 }
4708 }
4709 }
4710 }
4711
4712
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004713 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004714 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4715 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4716 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004717 return new ICmpInst(ICI->getInversePredicate(),
4718 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004719
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004720 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4721 return new FCmpInst(FCI->getInversePredicate(),
4722 FCI->getOperand(0), FCI->getOperand(1));
4723 }
4724
Reid Spencere4d87aa2006-12-23 06:05:41 +00004725 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004726 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004727 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4728 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004729 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4730 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004731 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004732 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004733 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004734
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004735 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004736 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004737 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004738 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004739 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004740 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00004741 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004742 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004743 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004744 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004745 // (X + C) ^ signbit -> (X + C + signbit)
4746 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004747 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004748
Chris Lattner7c4049c2004-01-12 19:35:11 +00004749 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004750 } else if (Op0I->getOpcode() == Instruction::Or) {
4751 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004752 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004753 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4754 // Anything in both C1 and C2 is known to be zero, remove it from
4755 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004756 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004757 NewRHS = ConstantExpr::getAnd(NewRHS,
4758 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004759 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004760 I.setOperand(0, Op0I->getOperand(0));
4761 I.setOperand(1, NewRHS);
4762 return &I;
4763 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004764 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004765 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004766 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004767
4768 // Try to fold constant and into select arguments.
4769 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004770 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004771 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004772 if (isa<PHINode>(Op0))
4773 if (Instruction *NV = FoldOpIntoPhi(I))
4774 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004775 }
4776
Chris Lattner8d969642003-03-10 23:06:50 +00004777 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004778 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004779 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004780
Chris Lattner8d969642003-03-10 23:06:50 +00004781 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004782 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004783 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004784
Chris Lattner318bf792007-03-18 22:51:34 +00004785
4786 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4787 if (Op1I) {
4788 Value *A, *B;
4789 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4790 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004791 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004792 I.swapOperands();
4793 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004794 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004795 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004796 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004797 }
Chris Lattner318bf792007-03-18 22:51:34 +00004798 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4799 if (Op0 == A) // A^(A^B) == B
4800 return ReplaceInstUsesWith(I, B);
4801 else if (Op0 == B) // A^(B^A) == B
4802 return ReplaceInstUsesWith(I, A);
4803 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004804 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004805 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004806 std::swap(A, B);
4807 }
Chris Lattner318bf792007-03-18 22:51:34 +00004808 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004809 I.swapOperands(); // Simplified below.
4810 std::swap(Op0, Op1);
4811 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004812 }
Chris Lattner318bf792007-03-18 22:51:34 +00004813 }
4814
4815 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4816 if (Op0I) {
4817 Value *A, *B;
4818 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4819 if (A == Op1) // (B|A)^B == (A|B)^B
4820 std::swap(A, B);
4821 if (B == Op1) { // (A|B)^B == A & ~B
4822 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004823 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4824 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004825 }
Chris Lattner318bf792007-03-18 22:51:34 +00004826 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4827 if (Op1 == A) // (A^B)^A == B
4828 return ReplaceInstUsesWith(I, B);
4829 else if (Op1 == B) // (B^A)^A == B
4830 return ReplaceInstUsesWith(I, A);
4831 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4832 if (A == Op1) // (A&B)^A -> (B&A)^A
4833 std::swap(A, B);
4834 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004835 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004836 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004837 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4838 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00004839 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004840 }
Chris Lattner318bf792007-03-18 22:51:34 +00004841 }
4842
4843 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4844 if (Op0I && Op1I && Op0I->isShift() &&
4845 Op0I->getOpcode() == Op1I->getOpcode() &&
4846 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4847 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4848 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004849 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00004850 Op1I->getOperand(0),
4851 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004852 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00004853 Op1I->getOperand(1));
4854 }
4855
4856 if (Op0I && Op1I) {
4857 Value *A, *B, *C, *D;
4858 // (A & B)^(A | B) -> A ^ B
4859 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4860 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4861 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004862 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004863 }
4864 // (A | B)^(A & B) -> A ^ B
4865 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4866 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4867 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004868 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00004869 }
4870
4871 // (A & B)^(C & D)
4872 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4873 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4874 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4875 // (X & Y)^(X & Y) -> (Y^Z) & X
4876 Value *X = 0, *Y = 0, *Z = 0;
4877 if (A == C)
4878 X = A, Y = B, Z = D;
4879 else if (A == D)
4880 X = A, Y = B, Z = C;
4881 else if (B == C)
4882 X = B, Y = A, Z = D;
4883 else if (B == D)
4884 X = B, Y = A, Z = C;
4885
4886 if (X) {
4887 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004888 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4889 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00004890 }
4891 }
4892 }
4893
Reid Spencere4d87aa2006-12-23 06:05:41 +00004894 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4895 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4896 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004897 return R;
4898
Chris Lattner6fc205f2006-05-05 06:39:07 +00004899 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004900 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004901 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004902 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4903 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004904 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004905 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004906 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4907 I.getType(), TD) &&
4908 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4909 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004910 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004911 Op1C->getOperand(0),
4912 I.getName());
4913 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004914 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004915 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004916 }
Chris Lattner99c65742007-10-24 05:38:08 +00004917 }
Chris Lattner7e708292002-06-25 16:13:24 +00004918 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004919}
4920
Chris Lattnera96879a2004-09-29 17:40:11 +00004921/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4922/// overflowed for this type.
4923static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004924 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004925 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004926
Reid Spencere4e40032007-03-21 23:19:50 +00004927 if (IsSigned)
4928 if (In2->getValue().isNegative())
4929 return Result->getValue().sgt(In1->getValue());
4930 else
4931 return Result->getValue().slt(In1->getValue());
4932 else
4933 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004934}
4935
Chris Lattner574da9b2005-01-13 20:14:25 +00004936/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4937/// code necessary to compute the offset from the base pointer (without adding
4938/// in the base pointer). Return the result as a signed integer of intptr size.
4939static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4940 TargetData &TD = IC.getTargetData();
4941 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004942 const Type *IntPtrTy = TD.getIntPtrType();
4943 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004944
4945 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00004946 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00004947 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004948
Chris Lattner574da9b2005-01-13 20:14:25 +00004949 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4950 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004951 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004952 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4953 if (OpC->isZero()) continue;
4954
4955 // Handle a struct index, which adds its field offset to the pointer.
4956 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4957 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4958
4959 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4960 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004961 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004962 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004963 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00004964 ConstantInt::get(IntPtrTy, Size),
4965 GEP->getName()+".offs"), I);
4966 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004967 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004968
4969 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4970 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4971 Scale = ConstantExpr::getMul(OC, Scale);
4972 if (Constant *RC = dyn_cast<Constant>(Result))
4973 Result = ConstantExpr::getAdd(RC, Scale);
4974 else {
4975 // Emit an add instruction.
4976 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004977 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004978 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004979 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004980 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004981 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004982 // Convert to correct type.
4983 if (Op->getType() != IntPtrTy) {
4984 if (Constant *OpC = dyn_cast<Constant>(Op))
4985 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4986 else
4987 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4988 Op->getName()+".c"), I);
4989 }
4990 if (Size != 1) {
4991 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4992 if (Constant *OpC = dyn_cast<Constant>(Op))
4993 Op = ConstantExpr::getMul(OpC, Scale);
4994 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004995 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00004996 GEP->getName()+".idx"), I);
4997 }
4998
4999 // Emit an add instruction.
5000 if (isa<Constant>(Op) && isa<Constant>(Result))
5001 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5002 cast<Constant>(Result));
5003 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005004 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005005 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005006 }
5007 return Result;
5008}
5009
Chris Lattner10c0d912008-04-22 02:53:33 +00005010
5011/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5012/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5013/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5014/// complex, and scales are involved. The above expression would also be legal
5015/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5016/// later form is less amenable to optimization though, and we are allowed to
5017/// generate the first by knowing that pointer arithmetic doesn't overflow.
5018///
5019/// If we can't emit an optimized form for this expression, this returns null.
5020///
5021static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5022 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005023 TargetData &TD = IC.getTargetData();
5024 gep_type_iterator GTI = gep_type_begin(GEP);
5025
5026 // Check to see if this gep only has a single variable index. If so, and if
5027 // any constant indices are a multiple of its scale, then we can compute this
5028 // in terms of the scale of the variable index. For example, if the GEP
5029 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5030 // because the expression will cross zero at the same point.
5031 unsigned i, e = GEP->getNumOperands();
5032 int64_t Offset = 0;
5033 for (i = 1; i != e; ++i, ++GTI) {
5034 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5035 // Compute the aggregate offset of constant indices.
5036 if (CI->isZero()) continue;
5037
5038 // Handle a struct index, which adds its field offset to the pointer.
5039 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5040 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5041 } else {
5042 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5043 Offset += Size*CI->getSExtValue();
5044 }
5045 } else {
5046 // Found our variable index.
5047 break;
5048 }
5049 }
5050
5051 // If there are no variable indices, we must have a constant offset, just
5052 // evaluate it the general way.
5053 if (i == e) return 0;
5054
5055 Value *VariableIdx = GEP->getOperand(i);
5056 // Determine the scale factor of the variable element. For example, this is
5057 // 4 if the variable index is into an array of i32.
5058 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5059
5060 // Verify that there are no other variable indices. If so, emit the hard way.
5061 for (++i, ++GTI; i != e; ++i, ++GTI) {
5062 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5063 if (!CI) return 0;
5064
5065 // Compute the aggregate offset of constant indices.
5066 if (CI->isZero()) continue;
5067
5068 // Handle a struct index, which adds its field offset to the pointer.
5069 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5070 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5071 } else {
5072 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5073 Offset += Size*CI->getSExtValue();
5074 }
5075 }
5076
5077 // Okay, we know we have a single variable index, which must be a
5078 // pointer/array/vector index. If there is no offset, life is simple, return
5079 // the index.
5080 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5081 if (Offset == 0) {
5082 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5083 // we don't need to bother extending: the extension won't affect where the
5084 // computation crosses zero.
5085 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5086 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5087 VariableIdx->getNameStart(), &I);
5088 return VariableIdx;
5089 }
5090
5091 // Otherwise, there is an index. The computation we will do will be modulo
5092 // the pointer size, so get it.
5093 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5094
5095 Offset &= PtrSizeMask;
5096 VariableScale &= PtrSizeMask;
5097
5098 // To do this transformation, any constant index must be a multiple of the
5099 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5100 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5101 // multiple of the variable scale.
5102 int64_t NewOffs = Offset / (int64_t)VariableScale;
5103 if (Offset != NewOffs*(int64_t)VariableScale)
5104 return 0;
5105
5106 // Okay, we can do this evaluation. Start by converting the index to intptr.
5107 const Type *IntPtrTy = TD.getIntPtrType();
5108 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005109 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005110 true /*SExt*/,
5111 VariableIdx->getNameStart(), &I);
5112 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005113 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005114}
5115
5116
Reid Spencere4d87aa2006-12-23 06:05:41 +00005117/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005118/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005119Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5120 ICmpInst::Predicate Cond,
5121 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005122 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005123
Chris Lattner10c0d912008-04-22 02:53:33 +00005124 // Look through bitcasts.
5125 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5126 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005127
Chris Lattner574da9b2005-01-13 20:14:25 +00005128 Value *PtrBase = GEPLHS->getOperand(0);
5129 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005130 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005131 // This transformation (ignoring the base and scales) is valid because we
5132 // know pointers can't overflow. See if we can output an optimized form.
5133 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5134
5135 // If not, synthesize the offset the hard way.
5136 if (Offset == 0)
5137 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005138 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5139 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005140 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005141 // If the base pointers are different, but the indices are the same, just
5142 // compare the base pointer.
5143 if (PtrBase != GEPRHS->getOperand(0)) {
5144 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005145 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005146 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005147 if (IndicesTheSame)
5148 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5149 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5150 IndicesTheSame = false;
5151 break;
5152 }
5153
5154 // If all indices are the same, just compare the base pointers.
5155 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005156 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5157 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005158
5159 // Otherwise, the base pointers are different and the indices are
5160 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005161 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005162 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005163
Chris Lattnere9d782b2005-01-13 22:25:21 +00005164 // If one of the GEPs has all zero indices, recurse.
5165 bool AllZeros = true;
5166 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5167 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5168 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5169 AllZeros = false;
5170 break;
5171 }
5172 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005173 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5174 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005175
5176 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005177 AllZeros = true;
5178 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5179 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5180 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5181 AllZeros = false;
5182 break;
5183 }
5184 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005185 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005186
Chris Lattner4401c9c2005-01-14 00:20:05 +00005187 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5188 // If the GEPs only differ by one index, compare it.
5189 unsigned NumDifferences = 0; // Keep track of # differences.
5190 unsigned DiffOperand = 0; // The operand that differs.
5191 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5192 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005193 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5194 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005195 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005196 NumDifferences = 2;
5197 break;
5198 } else {
5199 if (NumDifferences++) break;
5200 DiffOperand = i;
5201 }
5202 }
5203
5204 if (NumDifferences == 0) // SAME GEP?
5205 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005206 ConstantInt::get(Type::Int1Ty,
5207 isTrueWhenEqual(Cond)));
5208
Chris Lattner4401c9c2005-01-14 00:20:05 +00005209 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005210 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5211 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005212 // Make sure we do a signed comparison here.
5213 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005214 }
5215 }
5216
Reid Spencere4d87aa2006-12-23 06:05:41 +00005217 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005218 // the result to fold to a constant!
5219 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5220 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5221 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5222 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5223 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005224 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005225 }
5226 }
5227 return 0;
5228}
5229
Reid Spencere4d87aa2006-12-23 06:05:41 +00005230Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5231 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005232 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005233
Chris Lattner58e97462007-01-14 19:42:17 +00005234 // Fold trivial predicates.
5235 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5236 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5237 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5238 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5239
5240 // Simplify 'fcmp pred X, X'
5241 if (Op0 == Op1) {
5242 switch (I.getPredicate()) {
5243 default: assert(0 && "Unknown predicate!");
5244 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5245 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5246 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5247 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5248 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5249 case FCmpInst::FCMP_OLT: // True if ordered and less than
5250 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5251 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5252
5253 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5254 case FCmpInst::FCMP_ULT: // True if unordered or less than
5255 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5256 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5257 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5258 I.setPredicate(FCmpInst::FCMP_UNO);
5259 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5260 return &I;
5261
5262 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5263 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5264 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5265 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5266 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5267 I.setPredicate(FCmpInst::FCMP_ORD);
5268 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5269 return &I;
5270 }
5271 }
5272
Reid Spencere4d87aa2006-12-23 06:05:41 +00005273 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005274 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005275
Reid Spencere4d87aa2006-12-23 06:05:41 +00005276 // Handle fcmp with constant RHS
5277 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5278 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5279 switch (LHSI->getOpcode()) {
5280 case Instruction::PHI:
5281 if (Instruction *NV = FoldOpIntoPhi(I))
5282 return NV;
5283 break;
5284 case Instruction::Select:
5285 // If either operand of the select is a constant, we can fold the
5286 // comparison into the select arms, which will cause one to be
5287 // constant folded and the select turned into a bitwise or.
5288 Value *Op1 = 0, *Op2 = 0;
5289 if (LHSI->hasOneUse()) {
5290 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5291 // Fold the known value into the constant operand.
5292 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5293 // Insert a new FCmp of the other select operand.
5294 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5295 LHSI->getOperand(2), RHSC,
5296 I.getName()), I);
5297 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5298 // Fold the known value into the constant operand.
5299 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5300 // Insert a new FCmp of the other select operand.
5301 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5302 LHSI->getOperand(1), RHSC,
5303 I.getName()), I);
5304 }
5305 }
5306
5307 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005308 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005309 break;
5310 }
5311 }
5312
5313 return Changed ? &I : 0;
5314}
5315
5316Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5317 bool Changed = SimplifyCompare(I);
5318 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5319 const Type *Ty = Op0->getType();
5320
5321 // icmp X, X
5322 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005323 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5324 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005325
5326 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005327 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005328
Reid Spencere4d87aa2006-12-23 06:05:41 +00005329 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005330 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005331 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5332 isa<ConstantPointerNull>(Op0)) &&
5333 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005334 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005335 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5336 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00005337
Reid Spencere4d87aa2006-12-23 06:05:41 +00005338 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005339 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005340 switch (I.getPredicate()) {
5341 default: assert(0 && "Invalid icmp instruction!");
5342 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005343 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005344 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005345 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005346 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005347 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005348 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005349
Reid Spencere4d87aa2006-12-23 06:05:41 +00005350 case ICmpInst::ICMP_UGT:
5351 case ICmpInst::ICMP_SGT:
5352 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005353 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005354 case ICmpInst::ICMP_ULT:
5355 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005356 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005357 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005358 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005359 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005360 case ICmpInst::ICMP_UGE:
5361 case ICmpInst::ICMP_SGE:
5362 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005363 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005364 case ICmpInst::ICMP_ULE:
5365 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005366 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005367 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005368 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005369 }
5370 }
Chris Lattner8b170942002-08-09 23:47:40 +00005371 }
5372
Chris Lattner2be51ae2004-06-09 04:24:29 +00005373 // See if we are doing a comparison between a constant and an instruction that
5374 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005375 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005376 Value *A, *B;
5377
Chris Lattnerb6566012008-01-05 01:18:20 +00005378 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5379 if (I.isEquality() && CI->isNullValue() &&
5380 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5381 // (icmp cond A B) if cond is equality
5382 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005383 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005384
Reid Spencere4d87aa2006-12-23 06:05:41 +00005385 switch (I.getPredicate()) {
5386 default: break;
5387 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5388 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005389 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005390 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5391 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5392 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5393 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005394 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5395 if (CI->isMinValue(true))
5396 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5397 ConstantInt::getAllOnesValue(Op0->getType()));
5398
Reid Spencere4d87aa2006-12-23 06:05:41 +00005399 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005400
Reid Spencere4d87aa2006-12-23 06:05:41 +00005401 case ICmpInst::ICMP_SLT:
5402 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005403 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005404 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5405 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5406 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5407 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5408 break;
5409
5410 case ICmpInst::ICMP_UGT:
5411 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005412 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005413 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5414 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5415 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5416 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005417
5418 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5419 if (CI->isMaxValue(true))
5420 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5421 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005422 break;
5423
5424 case ICmpInst::ICMP_SGT:
5425 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005426 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005427 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5428 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5429 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5430 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5431 break;
5432
5433 case ICmpInst::ICMP_ULE:
5434 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005435 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005436 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5437 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5438 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5439 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5440 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005441
Reid Spencere4d87aa2006-12-23 06:05:41 +00005442 case ICmpInst::ICMP_SLE:
5443 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005444 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005445 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5446 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5447 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5448 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5449 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005450
Reid Spencere4d87aa2006-12-23 06:05:41 +00005451 case ICmpInst::ICMP_UGE:
5452 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005453 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005454 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5455 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5456 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5457 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5458 break;
5459
5460 case ICmpInst::ICMP_SGE:
5461 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005462 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005463 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5464 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5465 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5466 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5467 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005468 }
5469
Reid Spencere4d87aa2006-12-23 06:05:41 +00005470 // If we still have a icmp le or icmp ge instruction, turn it into the
5471 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005472 // already been handled above, this requires little checking.
5473 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005474 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005475 default: break;
5476 case ICmpInst::ICMP_ULE:
5477 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5478 case ICmpInst::ICMP_SLE:
5479 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5480 case ICmpInst::ICMP_UGE:
5481 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5482 case ICmpInst::ICMP_SGE:
5483 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005484 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005485
5486 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005487 // in the input. If this comparison is a normal comparison, it demands all
5488 // bits, if it is a sign bit comparison, it only demands the sign bit.
5489
5490 bool UnusedBit;
5491 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5492
Reid Spencer0460fb32007-03-22 20:36:03 +00005493 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5494 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005495 if (SimplifyDemandedBits(Op0,
5496 isSignBit ? APInt::getSignBit(BitWidth)
5497 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005498 KnownZero, KnownOne, 0))
5499 return &I;
5500
5501 // Given the known and unknown bits, compute a range that the LHS could be
5502 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005503 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005504 // Compute the Min, Max and RHS values based on the known bits. For the
5505 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005506 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5507 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005508 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005509 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5510 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005511 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005512 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5513 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005514 }
5515 switch (I.getPredicate()) { // LE/GE have been folded already.
5516 default: assert(0 && "Unknown icmp opcode!");
5517 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005518 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005519 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005520 break;
5521 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005522 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005523 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005524 break;
5525 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005526 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005527 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005528 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005529 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005530 break;
5531 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005532 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005533 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005534 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005535 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005536 break;
5537 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005538 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005539 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005540 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005541 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005542 break;
5543 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005544 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005545 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005546 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005547 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005548 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005549 }
5550 }
5551
Reid Spencere4d87aa2006-12-23 06:05:41 +00005552 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005553 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005554 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005555 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005556 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5557 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005558 }
5559
Chris Lattner01deb9d2007-04-03 17:43:25 +00005560 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005561 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5562 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5563 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005564 case Instruction::GetElementPtr:
5565 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005566 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005567 bool isAllZeros = true;
5568 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5569 if (!isa<Constant>(LHSI->getOperand(i)) ||
5570 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5571 isAllZeros = false;
5572 break;
5573 }
5574 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005575 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005576 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5577 }
5578 break;
5579
Chris Lattner6970b662005-04-23 15:31:55 +00005580 case Instruction::PHI:
5581 if (Instruction *NV = FoldOpIntoPhi(I))
5582 return NV;
5583 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005584 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005585 // If either operand of the select is a constant, we can fold the
5586 // comparison into the select arms, which will cause one to be
5587 // constant folded and the select turned into a bitwise or.
5588 Value *Op1 = 0, *Op2 = 0;
5589 if (LHSI->hasOneUse()) {
5590 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5591 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005592 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5593 // Insert a new ICmp of the other select operand.
5594 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5595 LHSI->getOperand(2), RHSC,
5596 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005597 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5598 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005599 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5600 // Insert a new ICmp of the other select operand.
5601 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5602 LHSI->getOperand(1), RHSC,
5603 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005604 }
5605 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005606
Chris Lattner6970b662005-04-23 15:31:55 +00005607 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005608 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00005609 break;
5610 }
Chris Lattner4802d902007-04-06 18:57:34 +00005611 case Instruction::Malloc:
5612 // If we have (malloc != null), and if the malloc has a single use, we
5613 // can assume it is successful and remove the malloc.
5614 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5615 AddToWorkList(LHSI);
5616 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5617 !isTrueWhenEqual(I)));
5618 }
5619 break;
5620 }
Chris Lattner6970b662005-04-23 15:31:55 +00005621 }
5622
Reid Spencere4d87aa2006-12-23 06:05:41 +00005623 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005624 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005625 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005626 return NI;
5627 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005628 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5629 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005630 return NI;
5631
Reid Spencere4d87aa2006-12-23 06:05:41 +00005632 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005633 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5634 // now.
5635 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5636 if (isa<PointerType>(Op0->getType()) &&
5637 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005638 // We keep moving the cast from the left operand over to the right
5639 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005640 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005641
Chris Lattner57d86372007-01-06 01:45:59 +00005642 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5643 // so eliminate it as well.
5644 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5645 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005646
Chris Lattnerde90b762003-11-03 04:25:02 +00005647 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005648 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005649 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005650 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005651 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005652 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005653 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005654 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005655 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005656 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005657 }
Chris Lattner57d86372007-01-06 01:45:59 +00005658 }
5659
5660 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005661 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005662 // This comes up when you have code like
5663 // int X = A < B;
5664 // if (X) ...
5665 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005666 // with a constant or another cast from the same type.
5667 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005668 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005669 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005670 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005671
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005672 // ~x < ~y --> y < x
5673 { Value *A, *B;
5674 if (match(Op0, m_Not(m_Value(A))) &&
5675 match(Op1, m_Not(m_Value(B))))
5676 return new ICmpInst(I.getPredicate(), B, A);
5677 }
5678
Chris Lattner65b72ba2006-09-18 04:22:48 +00005679 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005680 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00005681
5682 // -x == -y --> x == y
5683 if (match(Op0, m_Neg(m_Value(A))) &&
5684 match(Op1, m_Neg(m_Value(B))))
5685 return new ICmpInst(I.getPredicate(), A, B);
5686
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005687 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5688 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5689 Value *OtherVal = A == Op1 ? B : A;
5690 return new ICmpInst(I.getPredicate(), OtherVal,
5691 Constant::getNullValue(A->getType()));
5692 }
5693
5694 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5695 // A^c1 == C^c2 --> A == C^(c1^c2)
5696 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5697 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5698 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005699 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005700 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005701 return new ICmpInst(I.getPredicate(), A,
5702 InsertNewInstBefore(Xor, I));
5703 }
5704
5705 // A^B == A^D -> B == D
5706 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5707 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5708 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5709 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5710 }
5711 }
5712
5713 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5714 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005715 // A == (A^B) -> B == 0
5716 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005717 return new ICmpInst(I.getPredicate(), OtherVal,
5718 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005719 }
5720 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005721 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005722 return new ICmpInst(I.getPredicate(), B,
5723 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005724 }
5725 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005726 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005727 return new ICmpInst(I.getPredicate(), B,
5728 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005729 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005730
Chris Lattner9c2328e2006-11-14 06:06:06 +00005731 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5732 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5733 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5734 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5735 Value *X = 0, *Y = 0, *Z = 0;
5736
5737 if (A == C) {
5738 X = B; Y = D; Z = A;
5739 } else if (A == D) {
5740 X = B; Y = C; Z = A;
5741 } else if (B == C) {
5742 X = A; Y = D; Z = B;
5743 } else if (B == D) {
5744 X = A; Y = C; Z = B;
5745 }
5746
5747 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005748 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5749 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00005750 I.setOperand(0, Op1);
5751 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5752 return &I;
5753 }
5754 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005755 }
Chris Lattner7e708292002-06-25 16:13:24 +00005756 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005757}
5758
Chris Lattner562ef782007-06-20 23:46:26 +00005759
5760/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5761/// and CmpRHS are both known to be integer constants.
5762Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5763 ConstantInt *DivRHS) {
5764 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5765 const APInt &CmpRHSV = CmpRHS->getValue();
5766
5767 // FIXME: If the operand types don't match the type of the divide
5768 // then don't attempt this transform. The code below doesn't have the
5769 // logic to deal with a signed divide and an unsigned compare (and
5770 // vice versa). This is because (x /s C1) <s C2 produces different
5771 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5772 // (x /u C1) <u C2. Simply casting the operands and result won't
5773 // work. :( The if statement below tests that condition and bails
5774 // if it finds it.
5775 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5776 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5777 return 0;
5778 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005779 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005780
5781 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5782 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5783 // C2 (CI). By solving for X we can turn this into a range check
5784 // instead of computing a divide.
5785 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5786
5787 // Determine if the product overflows by seeing if the product is
5788 // not equal to the divide. Make sure we do the same kind of divide
5789 // as in the LHS instruction that we're folding.
5790 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5791 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5792
5793 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005794 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005795
Chris Lattner1dbfd482007-06-21 18:11:19 +00005796 // Figure out the interval that is being checked. For example, a comparison
5797 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5798 // Compute this interval based on the constants involved and the signedness of
5799 // the compare/divide. This computes a half-open interval, keeping track of
5800 // whether either value in the interval overflows. After analysis each
5801 // overflow variable is set to 0 if it's corresponding bound variable is valid
5802 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5803 int LoOverflow = 0, HiOverflow = 0;
5804 ConstantInt *LoBound = 0, *HiBound = 0;
5805
5806
Chris Lattner562ef782007-06-20 23:46:26 +00005807 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005808 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005809 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005810 HiOverflow = LoOverflow = ProdOV;
5811 if (!HiOverflow)
5812 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005813 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005814 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005815 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005816 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5817 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005818 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005819 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5820 HiOverflow = LoOverflow = ProdOV;
5821 if (!HiOverflow)
5822 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005823 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005824 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005825 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5826 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005827 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005828 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005829 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005830 }
Dan Gohman76491272008-02-13 22:09:18 +00005831 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005832 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005833 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005834 LoBound = AddOne(DivRHS);
5835 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005836 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5837 HiOverflow = 1; // [INTMIN+1, overflow)
5838 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5839 }
Dan Gohman76491272008-02-13 22:09:18 +00005840 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005841 // e.g. X/-5 op 3 --> [-19, -14)
5842 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005843 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005844 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005845 HiBound = AddOne(Prod);
5846 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005847 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005848 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005849 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005850 HiBound = Subtract(Prod, DivRHS);
5851 }
5852
Chris Lattner1dbfd482007-06-21 18:11:19 +00005853 // Dividing by a negative swaps the condition. LT <-> GT
5854 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005855 }
5856
5857 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005858 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005859 default: assert(0 && "Unhandled icmp opcode!");
5860 case ICmpInst::ICMP_EQ:
5861 if (LoOverflow && HiOverflow)
5862 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5863 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005864 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005865 ICmpInst::ICMP_UGE, X, LoBound);
5866 else if (LoOverflow)
5867 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5868 ICmpInst::ICMP_ULT, X, HiBound);
5869 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005870 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005871 case ICmpInst::ICMP_NE:
5872 if (LoOverflow && HiOverflow)
5873 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5874 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005875 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005876 ICmpInst::ICMP_ULT, X, LoBound);
5877 else if (LoOverflow)
5878 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5879 ICmpInst::ICMP_UGE, X, HiBound);
5880 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005881 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005882 case ICmpInst::ICMP_ULT:
5883 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005884 if (LoOverflow == +1) // Low bound is greater than input range.
5885 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5886 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005887 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005888 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005889 case ICmpInst::ICMP_UGT:
5890 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005891 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005892 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005893 else if (HiOverflow == -1) // High bound less than input range.
5894 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5895 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005896 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5897 else
5898 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5899 }
5900}
5901
5902
Chris Lattner01deb9d2007-04-03 17:43:25 +00005903/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5904///
5905Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5906 Instruction *LHSI,
5907 ConstantInt *RHS) {
5908 const APInt &RHSV = RHS->getValue();
5909
5910 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005911 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005912 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5913 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5914 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005915 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5916 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005917 Value *CompareVal = LHSI->getOperand(0);
5918
5919 // If the sign bit of the XorCST is not set, there is no change to
5920 // the operation, just stop using the Xor.
5921 if (!XorCST->getValue().isNegative()) {
5922 ICI.setOperand(0, CompareVal);
5923 AddToWorkList(LHSI);
5924 return &ICI;
5925 }
5926
5927 // Was the old condition true if the operand is positive?
5928 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5929
5930 // If so, the new one isn't.
5931 isTrueIfPositive ^= true;
5932
5933 if (isTrueIfPositive)
5934 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5935 else
5936 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5937 }
5938 }
5939 break;
5940 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5941 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5942 LHSI->getOperand(0)->hasOneUse()) {
5943 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5944
5945 // If the LHS is an AND of a truncating cast, we can widen the
5946 // and/compare to be the input width without changing the value
5947 // produced, eliminating a cast.
5948 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5949 // We can do this transformation if either the AND constant does not
5950 // have its sign bit set or if it is an equality comparison.
5951 // Extending a relational comparison when we're checking the sign
5952 // bit would not work.
5953 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005954 (ICI.isEquality() ||
5955 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005956 uint32_t BitWidth =
5957 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5958 APInt NewCST = AndCST->getValue();
5959 NewCST.zext(BitWidth);
5960 APInt NewCI = RHSV;
5961 NewCI.zext(BitWidth);
5962 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005963 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00005964 ConstantInt::get(NewCST),LHSI->getName());
5965 InsertNewInstBefore(NewAnd, ICI);
5966 return new ICmpInst(ICI.getPredicate(), NewAnd,
5967 ConstantInt::get(NewCI));
5968 }
5969 }
5970
5971 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5972 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5973 // happens a LOT in code produced by the C front-end, for bitfield
5974 // access.
5975 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5976 if (Shift && !Shift->isShift())
5977 Shift = 0;
5978
5979 ConstantInt *ShAmt;
5980 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5981 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5982 const Type *AndTy = AndCST->getType(); // Type of the and.
5983
5984 // We can fold this as long as we can't shift unknown bits
5985 // into the mask. This can only happen with signed shift
5986 // rights, as they sign-extend.
5987 if (ShAmt) {
5988 bool CanFold = Shift->isLogicalShift();
5989 if (!CanFold) {
5990 // To test for the bad case of the signed shr, see if any
5991 // of the bits shifted in could be tested after the mask.
5992 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5993 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5994
5995 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5996 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5997 AndCST->getValue()) == 0)
5998 CanFold = true;
5999 }
6000
6001 if (CanFold) {
6002 Constant *NewCst;
6003 if (Shift->getOpcode() == Instruction::Shl)
6004 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6005 else
6006 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6007
6008 // Check to see if we are shifting out any of the bits being
6009 // compared.
6010 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6011 // If we shifted bits out, the fold is not going to work out.
6012 // As a special case, check to see if this means that the
6013 // result is always true or false now.
6014 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6015 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6016 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6017 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6018 } else {
6019 ICI.setOperand(1, NewCst);
6020 Constant *NewAndCST;
6021 if (Shift->getOpcode() == Instruction::Shl)
6022 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6023 else
6024 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6025 LHSI->setOperand(1, NewAndCST);
6026 LHSI->setOperand(0, Shift->getOperand(0));
6027 AddToWorkList(Shift); // Shift is dead.
6028 AddUsesToWorkList(ICI);
6029 return &ICI;
6030 }
6031 }
6032 }
6033
6034 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6035 // preferable because it allows the C<<Y expression to be hoisted out
6036 // of a loop if Y is invariant and X is not.
6037 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6038 ICI.isEquality() && !Shift->isArithmeticShift() &&
6039 isa<Instruction>(Shift->getOperand(0))) {
6040 // Compute C << Y.
6041 Value *NS;
6042 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006043 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006044 Shift->getOperand(1), "tmp");
6045 } else {
6046 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006047 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006048 Shift->getOperand(1), "tmp");
6049 }
6050 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6051
6052 // Compute X & (C << Y).
6053 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006054 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006055 InsertNewInstBefore(NewAnd, ICI);
6056
6057 ICI.setOperand(0, NewAnd);
6058 return &ICI;
6059 }
6060 }
6061 break;
6062
Chris Lattnera0141b92007-07-15 20:42:37 +00006063 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6064 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6065 if (!ShAmt) break;
6066
6067 uint32_t TypeBits = RHSV.getBitWidth();
6068
6069 // Check that the shift amount is in range. If not, don't perform
6070 // undefined shifts. When the shift is visited it will be
6071 // simplified.
6072 if (ShAmt->uge(TypeBits))
6073 break;
6074
6075 if (ICI.isEquality()) {
6076 // If we are comparing against bits always shifted out, the
6077 // comparison cannot succeed.
6078 Constant *Comp =
6079 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6080 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6081 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6082 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6083 return ReplaceInstUsesWith(ICI, Cst);
6084 }
6085
6086 if (LHSI->hasOneUse()) {
6087 // Otherwise strength reduce the shift into an and.
6088 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6089 Constant *Mask =
6090 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006091
Chris Lattnera0141b92007-07-15 20:42:37 +00006092 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006093 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006094 Mask, LHSI->getName()+".mask");
6095 Value *And = InsertNewInstBefore(AndI, ICI);
6096 return new ICmpInst(ICI.getPredicate(), And,
6097 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006098 }
6099 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006100
6101 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6102 bool TrueIfSigned = false;
6103 if (LHSI->hasOneUse() &&
6104 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6105 // (X << 31) <s 0 --> (X&1) != 0
6106 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6107 (TypeBits-ShAmt->getZExtValue()-1));
6108 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006109 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006110 Mask, LHSI->getName()+".mask");
6111 Value *And = InsertNewInstBefore(AndI, ICI);
6112
6113 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6114 And, Constant::getNullValue(And->getType()));
6115 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006116 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006117 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006118
6119 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006120 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006121 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006122 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006123 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006124
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006125 // Check that the shift amount is in range. If not, don't perform
6126 // undefined shifts. When the shift is visited it will be
6127 // simplified.
6128 uint32_t TypeBits = RHSV.getBitWidth();
6129 if (ShAmt->uge(TypeBits))
6130 break;
6131
6132 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006133
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006134 // If we are comparing against bits always shifted out, the
6135 // comparison cannot succeed.
6136 APInt Comp = RHSV << ShAmtVal;
6137 if (LHSI->getOpcode() == Instruction::LShr)
6138 Comp = Comp.lshr(ShAmtVal);
6139 else
6140 Comp = Comp.ashr(ShAmtVal);
6141
6142 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6143 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6144 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6145 return ReplaceInstUsesWith(ICI, Cst);
6146 }
6147
6148 // Otherwise, check to see if the bits shifted out are known to be zero.
6149 // If so, we can compare against the unshifted value:
6150 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006151 if (LHSI->hasOneUse() &&
6152 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006153 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6154 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6155 ConstantExpr::getShl(RHS, ShAmt));
6156 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006157
Evan Chengf30752c2008-04-23 00:38:06 +00006158 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006159 // Otherwise strength reduce the shift into an and.
6160 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6161 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006162
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006163 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006164 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006165 Mask, LHSI->getName()+".mask");
6166 Value *And = InsertNewInstBefore(AndI, ICI);
6167 return new ICmpInst(ICI.getPredicate(), And,
6168 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006169 }
6170 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006171 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006172
6173 case Instruction::SDiv:
6174 case Instruction::UDiv:
6175 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6176 // Fold this div into the comparison, producing a range check.
6177 // Determine, based on the divide type, what the range is being
6178 // checked. If there is an overflow on the low or high side, remember
6179 // it, otherwise compute the range [low, hi) bounding the new value.
6180 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006181 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6182 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6183 DivRHS))
6184 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006185 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006186
6187 case Instruction::Add:
6188 // Fold: icmp pred (add, X, C1), C2
6189
6190 if (!ICI.isEquality()) {
6191 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6192 if (!LHSC) break;
6193 const APInt &LHSV = LHSC->getValue();
6194
6195 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6196 .subtract(LHSV);
6197
6198 if (ICI.isSignedPredicate()) {
6199 if (CR.getLower().isSignBit()) {
6200 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6201 ConstantInt::get(CR.getUpper()));
6202 } else if (CR.getUpper().isSignBit()) {
6203 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6204 ConstantInt::get(CR.getLower()));
6205 }
6206 } else {
6207 if (CR.getLower().isMinValue()) {
6208 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6209 ConstantInt::get(CR.getUpper()));
6210 } else if (CR.getUpper().isMinValue()) {
6211 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6212 ConstantInt::get(CR.getLower()));
6213 }
6214 }
6215 }
6216 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006217 }
6218
6219 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6220 if (ICI.isEquality()) {
6221 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6222
6223 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6224 // the second operand is a constant, simplify a bit.
6225 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6226 switch (BO->getOpcode()) {
6227 case Instruction::SRem:
6228 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6229 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6230 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6231 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6232 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006233 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006234 BO->getName());
6235 InsertNewInstBefore(NewRem, ICI);
6236 return new ICmpInst(ICI.getPredicate(), NewRem,
6237 Constant::getNullValue(BO->getType()));
6238 }
6239 }
6240 break;
6241 case Instruction::Add:
6242 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6243 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6244 if (BO->hasOneUse())
6245 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6246 Subtract(RHS, BOp1C));
6247 } else if (RHSV == 0) {
6248 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6249 // efficiently invertible, or if the add has just this one use.
6250 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6251
6252 if (Value *NegVal = dyn_castNegVal(BOp1))
6253 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6254 else if (Value *NegVal = dyn_castNegVal(BOp0))
6255 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6256 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006257 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006258 InsertNewInstBefore(Neg, ICI);
6259 Neg->takeName(BO);
6260 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6261 }
6262 }
6263 break;
6264 case Instruction::Xor:
6265 // For the xor case, we can xor two constants together, eliminating
6266 // the explicit xor.
6267 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6268 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6269 ConstantExpr::getXor(RHS, BOC));
6270
6271 // FALLTHROUGH
6272 case Instruction::Sub:
6273 // Replace (([sub|xor] A, B) != 0) with (A != B)
6274 if (RHSV == 0)
6275 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6276 BO->getOperand(1));
6277 break;
6278
6279 case Instruction::Or:
6280 // If bits are being or'd in that are not present in the constant we
6281 // are comparing against, then the comparison could never succeed!
6282 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6283 Constant *NotCI = ConstantExpr::getNot(RHS);
6284 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6285 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6286 isICMP_NE));
6287 }
6288 break;
6289
6290 case Instruction::And:
6291 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6292 // If bits are being compared against that are and'd out, then the
6293 // comparison can never succeed!
6294 if ((RHSV & ~BOC->getValue()) != 0)
6295 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6296 isICMP_NE));
6297
6298 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6299 if (RHS == BOC && RHSV.isPowerOf2())
6300 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6301 ICmpInst::ICMP_NE, LHSI,
6302 Constant::getNullValue(RHS->getType()));
6303
6304 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6305 if (isSignBit(BOC)) {
6306 Value *X = BO->getOperand(0);
6307 Constant *Zero = Constant::getNullValue(X->getType());
6308 ICmpInst::Predicate pred = isICMP_NE ?
6309 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6310 return new ICmpInst(pred, X, Zero);
6311 }
6312
6313 // ((X & ~7) == 0) --> X < 8
6314 if (RHSV == 0 && isHighOnes(BOC)) {
6315 Value *X = BO->getOperand(0);
6316 Constant *NegX = ConstantExpr::getNeg(BOC);
6317 ICmpInst::Predicate pred = isICMP_NE ?
6318 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6319 return new ICmpInst(pred, X, NegX);
6320 }
6321 }
6322 default: break;
6323 }
6324 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6325 // Handle icmp {eq|ne} <intrinsic>, intcst.
6326 if (II->getIntrinsicID() == Intrinsic::bswap) {
6327 AddToWorkList(II);
6328 ICI.setOperand(0, II->getOperand(1));
6329 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6330 return &ICI;
6331 }
6332 }
6333 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006334 // If the LHS is a cast from an integral value of the same size,
6335 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006336 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6337 Value *CastOp = Cast->getOperand(0);
6338 const Type *SrcTy = CastOp->getType();
6339 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6340 if (SrcTy->isInteger() &&
6341 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6342 // If this is an unsigned comparison, try to make the comparison use
6343 // smaller constant values.
6344 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6345 // X u< 128 => X s> -1
6346 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6347 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6348 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6349 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6350 // X u> 127 => X s< 0
6351 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6352 Constant::getNullValue(SrcTy));
6353 }
6354 }
6355 }
6356 }
6357 return 0;
6358}
6359
6360/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6361/// We only handle extending casts so far.
6362///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006363Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6364 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006365 Value *LHSCIOp = LHSCI->getOperand(0);
6366 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006367 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006368 Value *RHSCIOp;
6369
Chris Lattner8c756c12007-05-05 22:41:33 +00006370 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6371 // integer type is the same size as the pointer type.
6372 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6373 getTargetData().getPointerSizeInBits() ==
6374 cast<IntegerType>(DestTy)->getBitWidth()) {
6375 Value *RHSOp = 0;
6376 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006377 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006378 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6379 RHSOp = RHSC->getOperand(0);
6380 // If the pointer types don't match, insert a bitcast.
6381 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006382 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006383 }
6384
6385 if (RHSOp)
6386 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6387 }
6388
6389 // The code below only handles extension cast instructions, so far.
6390 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006391 if (LHSCI->getOpcode() != Instruction::ZExt &&
6392 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006393 return 0;
6394
Reid Spencere4d87aa2006-12-23 06:05:41 +00006395 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6396 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006397
Reid Spencere4d87aa2006-12-23 06:05:41 +00006398 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006399 // Not an extension from the same type?
6400 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006401 if (RHSCIOp->getType() != LHSCIOp->getType())
6402 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006403
Nick Lewycky4189a532008-01-28 03:48:02 +00006404 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006405 // and the other is a zext), then we can't handle this.
6406 if (CI->getOpcode() != LHSCI->getOpcode())
6407 return 0;
6408
Nick Lewycky4189a532008-01-28 03:48:02 +00006409 // Deal with equality cases early.
6410 if (ICI.isEquality())
6411 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6412
6413 // A signed comparison of sign extended values simplifies into a
6414 // signed comparison.
6415 if (isSignedCmp && isSignedExt)
6416 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6417
6418 // The other three cases all fold into an unsigned comparison.
6419 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006420 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006421
Reid Spencere4d87aa2006-12-23 06:05:41 +00006422 // If we aren't dealing with a constant on the RHS, exit early
6423 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6424 if (!CI)
6425 return 0;
6426
6427 // Compute the constant that would happen if we truncated to SrcTy then
6428 // reextended to DestTy.
6429 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6430 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6431
6432 // If the re-extended constant didn't change...
6433 if (Res2 == CI) {
6434 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6435 // For example, we might have:
6436 // %A = sext short %X to uint
6437 // %B = icmp ugt uint %A, 1330
6438 // It is incorrect to transform this into
6439 // %B = icmp ugt short %X, 1330
6440 // because %A may have negative value.
6441 //
6442 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6443 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006444 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006445 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6446 else
6447 return 0;
6448 }
6449
6450 // The re-extended constant changed so the constant cannot be represented
6451 // in the shorter type. Consequently, we cannot emit a simple comparison.
6452
6453 // First, handle some easy cases. We know the result cannot be equal at this
6454 // point so handle the ICI.isEquality() cases
6455 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006456 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006457 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006458 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006459
6460 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6461 // should have been folded away previously and not enter in here.
6462 Value *Result;
6463 if (isSignedCmp) {
6464 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006465 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006466 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006467 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006468 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006469 } else {
6470 // We're performing an unsigned comparison.
6471 if (isSignedExt) {
6472 // We're performing an unsigned comp with a sign extended value.
6473 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006474 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006475 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6476 NegOne, ICI.getName()), ICI);
6477 } else {
6478 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006479 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006480 }
6481 }
6482
6483 // Finally, return the value computed.
6484 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6485 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6486 return ReplaceInstUsesWith(ICI, Result);
6487 } else {
6488 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6489 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6490 "ICmp should be folded!");
6491 if (Constant *CI = dyn_cast<Constant>(Result))
6492 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6493 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006494 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006495 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006496}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006497
Reid Spencer832254e2007-02-02 02:16:23 +00006498Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6499 return commonShiftTransforms(I);
6500}
6501
6502Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6503 return commonShiftTransforms(I);
6504}
6505
6506Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006507 if (Instruction *R = commonShiftTransforms(I))
6508 return R;
6509
6510 Value *Op0 = I.getOperand(0);
6511
6512 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6513 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6514 if (CSI->isAllOnesValue())
6515 return ReplaceInstUsesWith(I, CSI);
6516
6517 // See if we can turn a signed shr into an unsigned shr.
6518 if (MaskedValueIsZero(Op0,
6519 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006520 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006521
6522 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006523}
6524
6525Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6526 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006527 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006528
6529 // shl X, 0 == X and shr X, 0 == X
6530 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006531 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006532 Op0 == Constant::getNullValue(Op0->getType()))
6533 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006534
Reid Spencere4d87aa2006-12-23 06:05:41 +00006535 if (isa<UndefValue>(Op0)) {
6536 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006537 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006538 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006539 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6540 }
6541 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006542 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6543 return ReplaceInstUsesWith(I, Op0);
6544 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006545 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006546 }
6547
Chris Lattner2eefe512004-04-09 19:05:30 +00006548 // Try to fold constant and into select arguments.
6549 if (isa<Constant>(Op0))
6550 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006551 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006552 return R;
6553
Reid Spencerb83eb642006-10-20 07:07:24 +00006554 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006555 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6556 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006557 return 0;
6558}
6559
Reid Spencerb83eb642006-10-20 07:07:24 +00006560Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006561 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006562 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006563
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006564 // See if we can simplify any instructions used by the instruction whose sole
6565 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006566 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6567 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6568 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006569 KnownZero, KnownOne))
6570 return &I;
6571
Chris Lattner4d5542c2006-01-06 07:12:35 +00006572 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6573 // of a signed value.
6574 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006575 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006576 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006577 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6578 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006579 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006580 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006581 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006582 }
6583
6584 // ((X*C1) << C2) == (X * (C1 << C2))
6585 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6586 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6587 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006588 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006589 ConstantExpr::getShl(BOOp, Op1));
6590
6591 // Try to fold constant and into select arguments.
6592 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6593 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6594 return R;
6595 if (isa<PHINode>(Op0))
6596 if (Instruction *NV = FoldOpIntoPhi(I))
6597 return NV;
6598
Chris Lattner8999dd32007-12-22 09:07:47 +00006599 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6600 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6601 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6602 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6603 // place. Don't try to do this transformation in this case. Also, we
6604 // require that the input operand is a shift-by-constant so that we have
6605 // confidence that the shifts will get folded together. We could do this
6606 // xform in more cases, but it is unlikely to be profitable.
6607 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6608 isa<ConstantInt>(TrOp->getOperand(1))) {
6609 // Okay, we'll do this xform. Make the shift of shift.
6610 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006611 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00006612 I.getName());
6613 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6614
6615 // For logical shifts, the truncation has the effect of making the high
6616 // part of the register be zeros. Emulate this by inserting an AND to
6617 // clear the top bits as needed. This 'and' will usually be zapped by
6618 // other xforms later if dead.
6619 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6620 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6621 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6622
6623 // The mask we constructed says what the trunc would do if occurring
6624 // between the shifts. We want to know the effect *after* the second
6625 // shift. We know that it is a logical shift by a constant, so adjust the
6626 // mask as appropriate.
6627 if (I.getOpcode() == Instruction::Shl)
6628 MaskV <<= Op1->getZExtValue();
6629 else {
6630 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6631 MaskV = MaskV.lshr(Op1->getZExtValue());
6632 }
6633
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006634 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00006635 TI->getName());
6636 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6637
6638 // Return the value truncated to the interesting size.
6639 return new TruncInst(And, I.getType());
6640 }
6641 }
6642
Chris Lattner4d5542c2006-01-06 07:12:35 +00006643 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006644 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6645 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6646 Value *V1, *V2;
6647 ConstantInt *CC;
6648 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006649 default: break;
6650 case Instruction::Add:
6651 case Instruction::And:
6652 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006653 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006654 // These operators commute.
6655 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006656 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6657 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006658 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006659 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006660 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006661 Op0BO->getName());
6662 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006663 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006664 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006665 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006666 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006667 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006668 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006669 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006670 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006671
Chris Lattner150f12a2005-09-18 06:30:59 +00006672 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006673 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006674 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006675 match(Op0BOOp1,
6676 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006677 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6678 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006679 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006680 Op0BO->getOperand(0), Op1,
6681 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006682 InsertNewInstBefore(YS, I); // (Y << C)
6683 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006684 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006685 V1->getName()+".mask");
6686 InsertNewInstBefore(XM, I); // X & (CC << C)
6687
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006688 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00006689 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006690 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006691
Reid Spencera07cb7d2007-02-02 14:41:37 +00006692 // FALL THROUGH.
6693 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006694 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006695 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6696 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006697 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006698 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006699 Op0BO->getOperand(1), Op1,
6700 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006701 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006702 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006703 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006704 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006705 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006706 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006707 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00006708 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006709 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006710
Chris Lattner13d4ab42006-05-31 21:14:00 +00006711 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006712 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6713 match(Op0BO->getOperand(0),
6714 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006715 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006716 cast<BinaryOperator>(Op0BO->getOperand(0))
6717 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006718 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006719 Op0BO->getOperand(1), Op1,
6720 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006721 InsertNewInstBefore(YS, I); // (Y << C)
6722 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006723 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006724 V1->getName()+".mask");
6725 InsertNewInstBefore(XM, I); // X & (CC << C)
6726
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006727 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006728 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006729
Chris Lattner11021cb2005-09-18 05:12:10 +00006730 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006731 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006732 }
6733
6734
6735 // If the operand is an bitwise operator with a constant RHS, and the
6736 // shift is the only use, we can pull it out of the shift.
6737 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6738 bool isValid = true; // Valid only for And, Or, Xor
6739 bool highBitSet = false; // Transform if high bit of constant set?
6740
6741 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006742 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006743 case Instruction::Add:
6744 isValid = isLeftShift;
6745 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006746 case Instruction::Or:
6747 case Instruction::Xor:
6748 highBitSet = false;
6749 break;
6750 case Instruction::And:
6751 highBitSet = true;
6752 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006753 }
6754
6755 // If this is a signed shift right, and the high bit is modified
6756 // by the logical operation, do not perform the transformation.
6757 // The highBitSet boolean indicates the value of the high bit of
6758 // the constant which would cause it to be modified for this
6759 // operation.
6760 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006761 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006762 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006763
6764 if (isValid) {
6765 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6766
6767 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006768 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006769 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006770 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006771
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006772 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00006773 NewRHS);
6774 }
6775 }
6776 }
6777 }
6778
Chris Lattnerad0124c2006-01-06 07:52:12 +00006779 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006780 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6781 if (ShiftOp && !ShiftOp->isShift())
6782 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006783
Reid Spencerb83eb642006-10-20 07:07:24 +00006784 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006785 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006786 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6787 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006788 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6789 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6790 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006791
Zhou Sheng4351c642007-04-02 08:20:41 +00006792 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006793 if (AmtSum > TypeBits)
6794 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006795
6796 const IntegerType *Ty = cast<IntegerType>(I.getType());
6797
6798 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006799 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006800 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006801 ConstantInt::get(Ty, AmtSum));
6802 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6803 I.getOpcode() == Instruction::AShr) {
6804 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006805 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006806 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6807 I.getOpcode() == Instruction::LShr) {
6808 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6809 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006810 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006811 InsertNewInstBefore(Shift, I);
6812
Zhou Shenge9e03f62007-03-28 15:02:20 +00006813 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006814 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006815 }
6816
Chris Lattnerb87056f2007-02-05 00:57:54 +00006817 // Okay, if we get here, one shift must be left, and the other shift must be
6818 // right. See if the amounts are equal.
6819 if (ShiftAmt1 == ShiftAmt2) {
6820 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6821 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006822 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006823 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006824 }
6825 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6826 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006827 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006828 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006829 }
6830 // We can simplify ((X << C) >>s C) into a trunc + sext.
6831 // NOTE: we could do this for any C, but that would make 'unusual' integer
6832 // types. For now, just stick to ones well-supported by the code
6833 // generators.
6834 const Type *SExtType = 0;
6835 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006836 case 1 :
6837 case 8 :
6838 case 16 :
6839 case 32 :
6840 case 64 :
6841 case 128:
6842 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6843 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006844 default: break;
6845 }
6846 if (SExtType) {
6847 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6848 InsertNewInstBefore(NewTrunc, I);
6849 return new SExtInst(NewTrunc, Ty);
6850 }
6851 // Otherwise, we can't handle it yet.
6852 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006853 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006854
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006855 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006856 if (I.getOpcode() == Instruction::Shl) {
6857 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6858 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006859 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006860 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006861 InsertNewInstBefore(Shift, I);
6862
Reid Spencer55702aa2007-03-25 21:11:44 +00006863 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006864 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006865 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006866
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006867 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006868 if (I.getOpcode() == Instruction::LShr) {
6869 assert(ShiftOp->getOpcode() == Instruction::Shl);
6870 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006871 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006872 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006873
Reid Spencerd5e30f02007-03-26 17:18:58 +00006874 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006875 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006876 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006877
6878 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6879 } else {
6880 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006881 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006882
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006883 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006884 if (I.getOpcode() == Instruction::Shl) {
6885 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6886 ShiftOp->getOpcode() == Instruction::AShr);
6887 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006888 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00006889 ConstantInt::get(Ty, ShiftDiff));
6890 InsertNewInstBefore(Shift, I);
6891
Reid Spencer55702aa2007-03-25 21:11:44 +00006892 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006893 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006894 }
6895
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006896 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006897 if (I.getOpcode() == Instruction::LShr) {
6898 assert(ShiftOp->getOpcode() == Instruction::Shl);
6899 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006900 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006901 InsertNewInstBefore(Shift, I);
6902
Reid Spencer68d27cf2007-03-26 23:45:51 +00006903 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006904 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006905 }
6906
6907 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006908 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006909 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006910 return 0;
6911}
6912
Chris Lattnera1be5662002-05-02 17:06:02 +00006913
Chris Lattnercfd65102005-10-29 04:36:15 +00006914/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6915/// expression. If so, decompose it, returning some value X, such that Val is
6916/// X*Scale+Offset.
6917///
6918static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006919 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006920 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006921 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006922 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006923 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006924 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006925 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6926 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6927 if (I->getOpcode() == Instruction::Shl) {
6928 // This is a value scaled by '1 << the shift amt'.
6929 Scale = 1U << RHS->getZExtValue();
6930 Offset = 0;
6931 return I->getOperand(0);
6932 } else if (I->getOpcode() == Instruction::Mul) {
6933 // This value is scaled by 'RHS'.
6934 Scale = RHS->getZExtValue();
6935 Offset = 0;
6936 return I->getOperand(0);
6937 } else if (I->getOpcode() == Instruction::Add) {
6938 // We have X+C. Check to see if we really have (X*C2)+C1,
6939 // where C1 is divisible by C2.
6940 unsigned SubScale;
6941 Value *SubVal =
6942 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6943 Offset += RHS->getZExtValue();
6944 Scale = SubScale;
6945 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006946 }
6947 }
6948 }
6949
6950 // Otherwise, we can't look past this.
6951 Scale = 1;
6952 Offset = 0;
6953 return Val;
6954}
6955
6956
Chris Lattnerb3f83972005-10-24 06:03:58 +00006957/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6958/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006959Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006960 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006961 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006962
Chris Lattnerb53c2382005-10-24 06:22:12 +00006963 // Remove any uses of AI that are dead.
6964 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006965
Chris Lattnerb53c2382005-10-24 06:22:12 +00006966 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6967 Instruction *User = cast<Instruction>(*UI++);
6968 if (isInstructionTriviallyDead(User)) {
6969 while (UI != E && *UI == User)
6970 ++UI; // If this instruction uses AI more than once, don't break UI.
6971
Chris Lattnerb53c2382005-10-24 06:22:12 +00006972 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006973 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006974 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006975 }
6976 }
6977
Chris Lattnerb3f83972005-10-24 06:03:58 +00006978 // Get the type really allocated and the type casted to.
6979 const Type *AllocElTy = AI.getAllocatedType();
6980 const Type *CastElTy = PTy->getElementType();
6981 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006982
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006983 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6984 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006985 if (CastElTyAlign < AllocElTyAlign) return 0;
6986
Chris Lattner39387a52005-10-24 06:35:18 +00006987 // If the allocation has multiple uses, only promote it if we are strictly
6988 // increasing the alignment of the resultant allocation. If we keep it the
6989 // same, we open the door to infinite loops of various kinds.
6990 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6991
Duncan Sands514ab342007-11-01 20:53:16 +00006992 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6993 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006994 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006995
Chris Lattner455fcc82005-10-29 03:19:53 +00006996 // See if we can satisfy the modulus by pulling a scale out of the array
6997 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006998 unsigned ArraySizeScale;
6999 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007000 Value *NumElements = // See if the array size is a decomposable linear expr.
7001 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7002
Chris Lattner455fcc82005-10-29 03:19:53 +00007003 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7004 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007005 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7006 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007007
Chris Lattner455fcc82005-10-29 03:19:53 +00007008 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7009 Value *Amt = 0;
7010 if (Scale == 1) {
7011 Amt = NumElements;
7012 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007013 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007014 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7015 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007016 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007017 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007018 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007019 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007020 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007021 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007022 }
7023
Jeff Cohen86796be2007-04-04 16:58:57 +00007024 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7025 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007026 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007027 Amt = InsertNewInstBefore(Tmp, AI);
7028 }
7029
Chris Lattnerb3f83972005-10-24 06:03:58 +00007030 AllocationInst *New;
7031 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007032 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007033 else
Chris Lattner6934a042007-02-11 01:23:03 +00007034 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007035 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007036 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007037
7038 // If the allocation has multiple uses, insert a cast and change all things
7039 // that used it to use the new cast. This will also hack on CI, but it will
7040 // die soon.
7041 if (!AI.hasOneUse()) {
7042 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007043 // New is the allocation instruction, pointer typed. AI is the original
7044 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7045 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007046 InsertNewInstBefore(NewCast, AI);
7047 AI.replaceAllUsesWith(NewCast);
7048 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007049 return ReplaceInstUsesWith(CI, New);
7050}
7051
Chris Lattner70074e02006-05-13 02:06:03 +00007052/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007053/// and return it as type Ty without inserting any new casts and without
7054/// changing the computed value. This is used by code that tries to decide
7055/// whether promoting or shrinking integer operations to wider or smaller types
7056/// will allow us to eliminate a truncate or extend.
7057///
7058/// This is a truncation operation if Ty is smaller than V->getType(), or an
7059/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00007060bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7061 unsigned CastOpc,
7062 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007063 // We can always evaluate constants in another type.
7064 if (isa<ConstantInt>(V))
7065 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007066
7067 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007068 if (!I) return false;
7069
7070 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007071
Chris Lattner951626b2007-08-02 06:11:14 +00007072 // If this is an extension or truncate, we can often eliminate it.
7073 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7074 // If this is a cast from the destination type, we can trivially eliminate
7075 // it, and this will remove a cast overall.
7076 if (I->getOperand(0)->getType() == Ty) {
7077 // If the first operand is itself a cast, and is eliminable, do not count
7078 // this as an eliminable cast. We would prefer to eliminate those two
7079 // casts first.
7080 if (!isa<CastInst>(I->getOperand(0)))
7081 ++NumCastsRemoved;
7082 return true;
7083 }
7084 }
7085
7086 // We can't extend or shrink something that has multiple uses: doing so would
7087 // require duplicating the instruction in general, which isn't profitable.
7088 if (!I->hasOneUse()) return false;
7089
Chris Lattner70074e02006-05-13 02:06:03 +00007090 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007091 case Instruction::Add:
7092 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00007093 case Instruction::And:
7094 case Instruction::Or:
7095 case Instruction::Xor:
7096 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007097 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7098 NumCastsRemoved) &&
7099 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7100 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007101
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007102 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007103 // A multiply can be truncated by truncating its operands.
7104 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7105 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7106 NumCastsRemoved) &&
7107 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7108 NumCastsRemoved);
7109
Chris Lattner46b96052006-11-29 07:18:39 +00007110 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007111 // If we are truncating the result of this SHL, and if it's a shift of a
7112 // constant amount, we can always perform a SHL in a smaller type.
7113 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007114 uint32_t BitWidth = Ty->getBitWidth();
7115 if (BitWidth < OrigTy->getBitWidth() &&
7116 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007117 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7118 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007119 }
7120 break;
7121 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007122 // If this is a truncate of a logical shr, we can truncate it to a smaller
7123 // lshr iff we know that the bits we would otherwise be shifting in are
7124 // already zeros.
7125 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007126 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7127 uint32_t BitWidth = Ty->getBitWidth();
7128 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007129 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007130 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7131 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007132 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7133 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007134 }
7135 }
Chris Lattner46b96052006-11-29 07:18:39 +00007136 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007137 case Instruction::ZExt:
7138 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007139 case Instruction::Trunc:
7140 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007141 // can safely replace it. Note that replacing it does not reduce the number
7142 // of casts in the input.
7143 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007144 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00007145
Reid Spencer3da59db2006-11-27 01:05:10 +00007146 break;
7147 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007148 // TODO: Can handle more cases here.
7149 break;
7150 }
7151
7152 return false;
7153}
7154
7155/// EvaluateInDifferentType - Given an expression that
7156/// CanEvaluateInDifferentType returns true for, actually insert the code to
7157/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007158Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007159 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007160 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007161 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007162
7163 // Otherwise, it must be an instruction.
7164 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007165 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007166 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007167 case Instruction::Add:
7168 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007169 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007170 case Instruction::And:
7171 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007172 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007173 case Instruction::AShr:
7174 case Instruction::LShr:
7175 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007176 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007177 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007178 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00007179 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00007180 break;
7181 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007182 case Instruction::Trunc:
7183 case Instruction::ZExt:
7184 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007185 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007186 // just return the source. There's no need to insert it because it is not
7187 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007188 if (I->getOperand(0)->getType() == Ty)
7189 return I->getOperand(0);
7190
Chris Lattner951626b2007-08-02 06:11:14 +00007191 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007192 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00007193 Ty, I->getName());
7194 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007195 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007196 // TODO: Can handle more cases here.
7197 assert(0 && "Unreachable!");
7198 break;
7199 }
7200
7201 return InsertNewInstBefore(Res, *I);
7202}
7203
Reid Spencer3da59db2006-11-27 01:05:10 +00007204/// @brief Implement the transforms common to all CastInst visitors.
7205Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007206 Value *Src = CI.getOperand(0);
7207
Dan Gohman23d9d272007-05-11 21:10:54 +00007208 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007209 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007210 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007211 if (Instruction::CastOps opc =
7212 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7213 // The first cast (CSrc) is eliminable so we need to fix up or replace
7214 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007215 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007216 }
7217 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007218
Reid Spencer3da59db2006-11-27 01:05:10 +00007219 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007220 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7221 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7222 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007223
7224 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007225 if (isa<PHINode>(Src))
7226 if (Instruction *NV = FoldOpIntoPhi(CI))
7227 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007228
Reid Spencer3da59db2006-11-27 01:05:10 +00007229 return 0;
7230}
7231
Chris Lattnerd3e28342007-04-27 17:44:50 +00007232/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7233Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7234 Value *Src = CI.getOperand(0);
7235
Chris Lattnerd3e28342007-04-27 17:44:50 +00007236 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007237 // If casting the result of a getelementptr instruction with no offset, turn
7238 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007239 if (GEP->hasAllZeroIndices()) {
7240 // Changing the cast operand is usually not a good idea but it is safe
7241 // here because the pointer operand is being replaced with another
7242 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007243 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007244 CI.setOperand(0, GEP->getOperand(0));
7245 return &CI;
7246 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007247
7248 // If the GEP has a single use, and the base pointer is a bitcast, and the
7249 // GEP computes a constant offset, see if we can convert these three
7250 // instructions into fewer. This typically happens with unions and other
7251 // non-type-safe code.
7252 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7253 if (GEP->hasAllConstantIndices()) {
7254 // We are guaranteed to get a constant from EmitGEPOffset.
7255 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7256 int64_t Offset = OffsetV->getSExtValue();
7257
7258 // Get the base pointer input of the bitcast, and the type it points to.
7259 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7260 const Type *GEPIdxTy =
7261 cast<PointerType>(OrigBase->getType())->getElementType();
7262 if (GEPIdxTy->isSized()) {
7263 SmallVector<Value*, 8> NewIndices;
7264
Chris Lattnerc42e2262007-05-05 01:59:31 +00007265 // Start with the index over the outer type. Note that the type size
7266 // might be zero (even if the offset isn't zero) if the indexed type
7267 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007268 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007269 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007270 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007271 FirstIdx = Offset/TySize;
7272 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007273
Chris Lattnerc42e2262007-05-05 01:59:31 +00007274 // Handle silly modulus not returning values values [0..TySize).
7275 if (Offset < 0) {
7276 --FirstIdx;
7277 Offset += TySize;
7278 assert(Offset >= 0);
7279 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007280 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007281 }
7282
7283 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007284
7285 // Index into the types. If we fail, set OrigBase to null.
7286 while (Offset) {
7287 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7288 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007289 if (Offset < (int64_t)SL->getSizeInBytes()) {
7290 unsigned Elt = SL->getElementContainingOffset(Offset);
7291 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007292
Chris Lattner6b6aef82007-05-15 00:16:00 +00007293 Offset -= SL->getElementOffset(Elt);
7294 GEPIdxTy = STy->getElementType(Elt);
7295 } else {
7296 // Otherwise, we can't index into this, bail out.
7297 Offset = 0;
7298 OrigBase = 0;
7299 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007300 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7301 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007302 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007303 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7304 Offset %= EltSize;
7305 } else {
7306 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7307 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007308 GEPIdxTy = STy->getElementType();
7309 } else {
7310 // Otherwise, we can't index into this, bail out.
7311 Offset = 0;
7312 OrigBase = 0;
7313 }
7314 }
7315 if (OrigBase) {
7316 // If we were able to index down into an element, create the GEP
7317 // and bitcast the result. This eliminates one bitcast, potentially
7318 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007319 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7320 NewIndices.begin(),
7321 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007322 InsertNewInstBefore(NGEP, CI);
7323 NGEP->takeName(GEP);
7324
Chris Lattner9bc14642007-04-28 00:57:34 +00007325 if (isa<BitCastInst>(CI))
7326 return new BitCastInst(NGEP, CI.getType());
7327 assert(isa<PtrToIntInst>(CI));
7328 return new PtrToIntInst(NGEP, CI.getType());
7329 }
7330 }
7331 }
7332 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007333 }
7334
7335 return commonCastTransforms(CI);
7336}
7337
7338
7339
Chris Lattnerc739cd62007-03-03 05:27:34 +00007340/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7341/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007342/// cases.
7343/// @brief Implement the transforms common to CastInst with integer operands
7344Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7345 if (Instruction *Result = commonCastTransforms(CI))
7346 return Result;
7347
7348 Value *Src = CI.getOperand(0);
7349 const Type *SrcTy = Src->getType();
7350 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007351 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7352 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007353
Reid Spencer3da59db2006-11-27 01:05:10 +00007354 // See if we can simplify any instructions used by the LHS whose sole
7355 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007356 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7357 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007358 KnownZero, KnownOne))
7359 return &CI;
7360
7361 // If the source isn't an instruction or has more than one use then we
7362 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007363 Instruction *SrcI = dyn_cast<Instruction>(Src);
7364 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007365 return 0;
7366
Chris Lattnerc739cd62007-03-03 05:27:34 +00007367 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007368 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007369 if (!isa<BitCastInst>(CI) &&
7370 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007371 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007372 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007373 // eliminates the cast, so it is always a win. If this is a zero-extension,
7374 // we need to do an AND to maintain the clear top-part of the computation,
7375 // so we require that the input have eliminated at least one cast. If this
7376 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007377 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007378 bool DoXForm;
7379 switch (CI.getOpcode()) {
7380 default:
7381 // All the others use floating point so we shouldn't actually
7382 // get here because of the check above.
7383 assert(0 && "Unknown cast type");
7384 case Instruction::Trunc:
7385 DoXForm = true;
7386 break;
7387 case Instruction::ZExt:
7388 DoXForm = NumCastsRemoved >= 1;
7389 break;
7390 case Instruction::SExt:
7391 DoXForm = NumCastsRemoved >= 2;
7392 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007393 }
7394
7395 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007396 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7397 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007398 assert(Res->getType() == DestTy);
7399 switch (CI.getOpcode()) {
7400 default: assert(0 && "Unknown cast type!");
7401 case Instruction::Trunc:
7402 case Instruction::BitCast:
7403 // Just replace this cast with the result.
7404 return ReplaceInstUsesWith(CI, Res);
7405 case Instruction::ZExt: {
7406 // We need to emit an AND to clear the high bits.
7407 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007408 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7409 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007410 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007411 }
7412 case Instruction::SExt:
7413 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007414 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007415 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7416 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007417 }
7418 }
7419 }
7420
7421 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7422 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7423
7424 switch (SrcI->getOpcode()) {
7425 case Instruction::Add:
7426 case Instruction::Mul:
7427 case Instruction::And:
7428 case Instruction::Or:
7429 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007430 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007431 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7432 // Don't insert two casts if they cannot be eliminated. We allow
7433 // two casts to be inserted if the sizes are the same. This could
7434 // only be converting signedness, which is a noop.
7435 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007436 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7437 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007438 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007439 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7440 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007441 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007442 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007443 }
7444 }
7445
7446 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7447 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7448 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007449 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007450 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007451 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007452 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007453 }
7454 break;
7455 case Instruction::SDiv:
7456 case Instruction::UDiv:
7457 case Instruction::SRem:
7458 case Instruction::URem:
7459 // If we are just changing the sign, rewrite.
7460 if (DestBitSize == SrcBitSize) {
7461 // Don't insert two casts if they cannot be eliminated. We allow
7462 // two casts to be inserted if the sizes are the same. This could
7463 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007464 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7465 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007466 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7467 Op0, DestTy, SrcI);
7468 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7469 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007470 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007471 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7472 }
7473 }
7474 break;
7475
7476 case Instruction::Shl:
7477 // Allow changing the sign of the source operand. Do not allow
7478 // changing the size of the shift, UNLESS the shift amount is a
7479 // constant. We must not change variable sized shifts to a smaller
7480 // size, because it is undefined to shift more bits out than exist
7481 // in the value.
7482 if (DestBitSize == SrcBitSize ||
7483 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007484 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7485 Instruction::BitCast : Instruction::Trunc);
7486 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007487 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007488 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007489 }
7490 break;
7491 case Instruction::AShr:
7492 // If this is a signed shr, and if all bits shifted in are about to be
7493 // truncated off, turn it into an unsigned shr to allow greater
7494 // simplifications.
7495 if (DestBitSize < SrcBitSize &&
7496 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007497 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007498 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7499 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007500 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007501 }
7502 }
7503 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007504 }
7505 return 0;
7506}
7507
Chris Lattner8a9f5712007-04-11 06:57:46 +00007508Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007509 if (Instruction *Result = commonIntCastTransforms(CI))
7510 return Result;
7511
7512 Value *Src = CI.getOperand(0);
7513 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007514 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7515 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007516
7517 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7518 switch (SrcI->getOpcode()) {
7519 default: break;
7520 case Instruction::LShr:
7521 // We can shrink lshr to something smaller if we know the bits shifted in
7522 // are already zeros.
7523 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007524 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007525
7526 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007527 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007528 Value* SrcIOp0 = SrcI->getOperand(0);
7529 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007530 if (ShAmt >= DestBitWidth) // All zeros.
7531 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7532
7533 // Okay, we can shrink this. Truncate the input, then return a new
7534 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007535 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7536 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7537 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007538 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007539 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007540 } else { // This is a variable shr.
7541
7542 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7543 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7544 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007545 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007546 Value *One = ConstantInt::get(SrcI->getType(), 1);
7547
Reid Spencer832254e2007-02-02 02:16:23 +00007548 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007549 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007550 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007551 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007552 SrcI->getOperand(0),
7553 "tmp"), CI);
7554 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007555 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007556 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007557 }
7558 break;
7559 }
7560 }
7561
7562 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007563}
7564
Evan Chengb98a10e2008-03-24 00:21:34 +00007565/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7566/// in order to eliminate the icmp.
7567Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7568 bool DoXform) {
7569 // If we are just checking for a icmp eq of a single bit and zext'ing it
7570 // to an integer, then shift the bit to the appropriate place and then
7571 // cast to integer to avoid the comparison.
7572 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7573 const APInt &Op1CV = Op1C->getValue();
7574
7575 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7576 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7577 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7578 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7579 if (!DoXform) return ICI;
7580
7581 Value *In = ICI->getOperand(0);
7582 Value *Sh = ConstantInt::get(In->getType(),
7583 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007584 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00007585 In->getName()+".lobit"),
7586 CI);
7587 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007588 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00007589 false/*ZExt*/, "tmp", &CI);
7590
7591 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7592 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007593 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00007594 In->getName()+".not"),
7595 CI);
7596 }
7597
7598 return ReplaceInstUsesWith(CI, In);
7599 }
7600
7601
7602
7603 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7604 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7605 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7606 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7607 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7608 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7609 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7610 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7611 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7612 // This only works for EQ and NE
7613 ICI->isEquality()) {
7614 // If Op1C some other power of two, convert:
7615 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7616 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7617 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7618 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7619
7620 APInt KnownZeroMask(~KnownZero);
7621 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7622 if (!DoXform) return ICI;
7623
7624 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7625 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7626 // (X&4) == 2 --> false
7627 // (X&4) != 2 --> true
7628 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7629 Res = ConstantExpr::getZExt(Res, CI.getType());
7630 return ReplaceInstUsesWith(CI, Res);
7631 }
7632
7633 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7634 Value *In = ICI->getOperand(0);
7635 if (ShiftAmt) {
7636 // Perform a logical shr by shiftamt.
7637 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007638 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00007639 ConstantInt::get(In->getType(), ShiftAmt),
7640 In->getName()+".lobit"), CI);
7641 }
7642
7643 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7644 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007645 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00007646 InsertNewInstBefore(cast<Instruction>(In), CI);
7647 }
7648
7649 if (CI.getType() == In->getType())
7650 return ReplaceInstUsesWith(CI, In);
7651 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007652 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00007653 }
7654 }
7655 }
7656
7657 return 0;
7658}
7659
Chris Lattner8a9f5712007-04-11 06:57:46 +00007660Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007661 // If one of the common conversion will work ..
7662 if (Instruction *Result = commonIntCastTransforms(CI))
7663 return Result;
7664
7665 Value *Src = CI.getOperand(0);
7666
7667 // If this is a cast of a cast
7668 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007669 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7670 // types and if the sizes are just right we can convert this into a logical
7671 // 'and' which will be much cheaper than the pair of casts.
7672 if (isa<TruncInst>(CSrc)) {
7673 // Get the sizes of the types involved
7674 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007675 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7676 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7677 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007678 // If we're actually extending zero bits and the trunc is a no-op
7679 if (MidSize < DstSize && SrcSize == DstSize) {
7680 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007681 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007682 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007683 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007684 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00007685 // Unfortunately, if the type changed, we need to cast it back.
7686 if (And->getType() != CI.getType()) {
7687 And->setName(CSrc->getName()+".mask");
7688 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007689 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007690 }
7691 return And;
7692 }
7693 }
7694 }
7695
Evan Chengb98a10e2008-03-24 00:21:34 +00007696 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7697 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007698
Evan Chengb98a10e2008-03-24 00:21:34 +00007699 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7700 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7701 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7702 // of the (zext icmp) will be transformed.
7703 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7704 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7705 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7706 (transformZExtICmp(LHS, CI, false) ||
7707 transformZExtICmp(RHS, CI, false))) {
7708 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7709 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007710 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007711 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007712 }
7713
Reid Spencer3da59db2006-11-27 01:05:10 +00007714 return 0;
7715}
7716
Chris Lattner8a9f5712007-04-11 06:57:46 +00007717Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007718 if (Instruction *I = commonIntCastTransforms(CI))
7719 return I;
7720
Chris Lattner8a9f5712007-04-11 06:57:46 +00007721 Value *Src = CI.getOperand(0);
7722
7723 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7724 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7725 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7726 // If we are just checking for a icmp eq of a single bit and zext'ing it
7727 // to an integer, then shift the bit to the appropriate place and then
7728 // cast to integer to avoid the comparison.
7729 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7730 const APInt &Op1CV = Op1C->getValue();
7731
7732 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7733 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7734 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7735 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7736 Value *In = ICI->getOperand(0);
7737 Value *Sh = ConstantInt::get(In->getType(),
7738 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007739 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007740 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007741 CI);
7742 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007743 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007744 true/*SExt*/, "tmp", &CI);
7745
7746 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007747 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00007748 In->getName()+".not"), CI);
7749
7750 return ReplaceInstUsesWith(CI, In);
7751 }
7752 }
7753 }
7754
Chris Lattnerba417832007-04-11 06:12:58 +00007755 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007756}
7757
Chris Lattnerb7530652008-01-27 05:29:54 +00007758/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7759/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00007760static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00007761 APFloat F = CFP->getValueAPF();
7762 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00007763 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00007764 return 0;
7765}
7766
7767/// LookThroughFPExtensions - If this is an fp extension instruction, look
7768/// through it until we get the source value.
7769static Value *LookThroughFPExtensions(Value *V) {
7770 if (Instruction *I = dyn_cast<Instruction>(V))
7771 if (I->getOpcode() == Instruction::FPExt)
7772 return LookThroughFPExtensions(I->getOperand(0));
7773
7774 // If this value is a constant, return the constant in the smallest FP type
7775 // that can accurately represent it. This allows us to turn
7776 // (float)((double)X+2.0) into x+2.0f.
7777 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7778 if (CFP->getType() == Type::PPC_FP128Ty)
7779 return V; // No constant folding of this.
7780 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00007781 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00007782 return V;
7783 if (CFP->getType() == Type::DoubleTy)
7784 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00007785 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00007786 return V;
7787 // Don't try to shrink to various long double types.
7788 }
7789
7790 return V;
7791}
7792
7793Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7794 if (Instruction *I = commonCastTransforms(CI))
7795 return I;
7796
7797 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7798 // smaller than the destination type, we can eliminate the truncate by doing
7799 // the add as the smaller type. This applies to add/sub/mul/div as well as
7800 // many builtins (sqrt, etc).
7801 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7802 if (OpI && OpI->hasOneUse()) {
7803 switch (OpI->getOpcode()) {
7804 default: break;
7805 case Instruction::Add:
7806 case Instruction::Sub:
7807 case Instruction::Mul:
7808 case Instruction::FDiv:
7809 case Instruction::FRem:
7810 const Type *SrcTy = OpI->getType();
7811 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7812 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7813 if (LHSTrunc->getType() != SrcTy &&
7814 RHSTrunc->getType() != SrcTy) {
7815 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7816 // If the source types were both smaller than the destination type of
7817 // the cast, do this xform.
7818 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7819 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7820 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7821 CI.getType(), CI);
7822 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7823 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007824 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00007825 }
7826 }
7827 break;
7828 }
7829 }
7830 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007831}
7832
7833Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7834 return commonCastTransforms(CI);
7835}
7836
7837Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007838 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007839}
7840
7841Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007842 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007843}
7844
7845Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7846 return commonCastTransforms(CI);
7847}
7848
7849Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7850 return commonCastTransforms(CI);
7851}
7852
7853Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007854 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007855}
7856
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007857Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7858 if (Instruction *I = commonCastTransforms(CI))
7859 return I;
7860
7861 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7862 if (!DestPointee->isSized()) return 0;
7863
7864 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7865 ConstantInt *Cst;
7866 Value *X;
7867 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7868 m_ConstantInt(Cst)))) {
7869 // If the source and destination operands have the same type, see if this
7870 // is a single-index GEP.
7871 if (X->getType() == CI.getType()) {
7872 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007873 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007874
7875 // Convert the constant to intptr type.
7876 APInt Offset = Cst->getValue();
7877 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7878
7879 // If Offset is evenly divisible by Size, we can do this xform.
7880 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7881 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00007882 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007883 }
7884 }
7885 // TODO: Could handle other cases, e.g. where add is indexing into field of
7886 // struct etc.
7887 } else if (CI.getOperand(0)->hasOneUse() &&
7888 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7889 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7890 // "inttoptr+GEP" instead of "add+intptr".
7891
7892 // Get the size of the pointee type.
7893 uint64_t Size = TD->getABITypeSize(DestPointee);
7894
7895 // Convert the constant to intptr type.
7896 APInt Offset = Cst->getValue();
7897 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7898
7899 // If Offset is evenly divisible by Size, we can do this xform.
7900 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7901 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7902
7903 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7904 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00007905 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007906 }
7907 }
7908 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007909}
7910
Chris Lattnerd3e28342007-04-27 17:44:50 +00007911Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007912 // If the operands are integer typed then apply the integer transforms,
7913 // otherwise just apply the common ones.
7914 Value *Src = CI.getOperand(0);
7915 const Type *SrcTy = Src->getType();
7916 const Type *DestTy = CI.getType();
7917
Chris Lattner42a75512007-01-15 02:27:26 +00007918 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007919 if (Instruction *Result = commonIntCastTransforms(CI))
7920 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007921 } else if (isa<PointerType>(SrcTy)) {
7922 if (Instruction *I = commonPointerCastTransforms(CI))
7923 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007924 } else {
7925 if (Instruction *Result = commonCastTransforms(CI))
7926 return Result;
7927 }
7928
7929
7930 // Get rid of casts from one type to the same type. These are useless and can
7931 // be replaced by the operand.
7932 if (DestTy == Src->getType())
7933 return ReplaceInstUsesWith(CI, Src);
7934
Reid Spencer3da59db2006-11-27 01:05:10 +00007935 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007936 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7937 const Type *DstElTy = DstPTy->getElementType();
7938 const Type *SrcElTy = SrcPTy->getElementType();
7939
Nate Begeman83ad90a2008-03-31 00:22:16 +00007940 // If the address spaces don't match, don't eliminate the bitcast, which is
7941 // required for changing types.
7942 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7943 return 0;
7944
Chris Lattnerd3e28342007-04-27 17:44:50 +00007945 // If we are casting a malloc or alloca to a pointer to a type of the same
7946 // size, rewrite the allocation instruction to allocate the "right" type.
7947 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7948 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7949 return V;
7950
Chris Lattnerd717c182007-05-05 22:32:24 +00007951 // If the source and destination are pointers, and this cast is equivalent
7952 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007953 // This can enhance SROA and other transforms that want type-safe pointers.
7954 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7955 unsigned NumZeros = 0;
7956 while (SrcElTy != DstElTy &&
7957 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7958 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7959 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7960 ++NumZeros;
7961 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007962
Chris Lattnerd3e28342007-04-27 17:44:50 +00007963 // If we found a path from the src to dest, create the getelementptr now.
7964 if (SrcElTy == DstElTy) {
7965 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00007966 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7967 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007968 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007969 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007970
Reid Spencer3da59db2006-11-27 01:05:10 +00007971 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7972 if (SVI->hasOneUse()) {
7973 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7974 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007975 if (isa<VectorType>(DestTy) &&
7976 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007977 SVI->getType()->getNumElements()) {
7978 CastInst *Tmp;
7979 // If either of the operands is a cast from CI.getType(), then
7980 // evaluating the shuffle in the casted destination's type will allow
7981 // us to eliminate at least one cast.
7982 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7983 Tmp->getOperand(0)->getType() == DestTy) ||
7984 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7985 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007986 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7987 SVI->getOperand(0), DestTy, &CI);
7988 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7989 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007990 // Return a new shuffle vector. Use the same element ID's, as we
7991 // know the vector types match #elts.
7992 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007993 }
7994 }
7995 }
7996 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007997 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007998}
7999
Chris Lattnere576b912004-04-09 23:46:01 +00008000/// GetSelectFoldableOperands - We want to turn code that looks like this:
8001/// %C = or %A, %B
8002/// %D = select %cond, %C, %A
8003/// into:
8004/// %C = select %cond, %B, 0
8005/// %D = or %A, %C
8006///
8007/// Assuming that the specified instruction is an operand to the select, return
8008/// a bitmask indicating which operands of this instruction are foldable if they
8009/// equal the other incoming value of the select.
8010///
8011static unsigned GetSelectFoldableOperands(Instruction *I) {
8012 switch (I->getOpcode()) {
8013 case Instruction::Add:
8014 case Instruction::Mul:
8015 case Instruction::And:
8016 case Instruction::Or:
8017 case Instruction::Xor:
8018 return 3; // Can fold through either operand.
8019 case Instruction::Sub: // Can only fold on the amount subtracted.
8020 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008021 case Instruction::LShr:
8022 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008023 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008024 default:
8025 return 0; // Cannot fold
8026 }
8027}
8028
8029/// GetSelectFoldableConstant - For the same transformation as the previous
8030/// function, return the identity constant that goes into the select.
8031static Constant *GetSelectFoldableConstant(Instruction *I) {
8032 switch (I->getOpcode()) {
8033 default: assert(0 && "This cannot happen!"); abort();
8034 case Instruction::Add:
8035 case Instruction::Sub:
8036 case Instruction::Or:
8037 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008038 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008039 case Instruction::LShr:
8040 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008041 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008042 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008043 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008044 case Instruction::Mul:
8045 return ConstantInt::get(I->getType(), 1);
8046 }
8047}
8048
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008049/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8050/// have the same opcode and only one use each. Try to simplify this.
8051Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8052 Instruction *FI) {
8053 if (TI->getNumOperands() == 1) {
8054 // If this is a non-volatile load or a cast from the same type,
8055 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008056 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008057 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8058 return 0;
8059 } else {
8060 return 0; // unknown unary op.
8061 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008062
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008063 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008064 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8065 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008066 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008067 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008068 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008069 }
8070
Reid Spencer832254e2007-02-02 02:16:23 +00008071 // Only handle binary operators here.
8072 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008073 return 0;
8074
8075 // Figure out if the operations have any operands in common.
8076 Value *MatchOp, *OtherOpT, *OtherOpF;
8077 bool MatchIsOpZero;
8078 if (TI->getOperand(0) == FI->getOperand(0)) {
8079 MatchOp = TI->getOperand(0);
8080 OtherOpT = TI->getOperand(1);
8081 OtherOpF = FI->getOperand(1);
8082 MatchIsOpZero = true;
8083 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8084 MatchOp = TI->getOperand(1);
8085 OtherOpT = TI->getOperand(0);
8086 OtherOpF = FI->getOperand(0);
8087 MatchIsOpZero = false;
8088 } else if (!TI->isCommutative()) {
8089 return 0;
8090 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8091 MatchOp = TI->getOperand(0);
8092 OtherOpT = TI->getOperand(1);
8093 OtherOpF = FI->getOperand(0);
8094 MatchIsOpZero = true;
8095 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8096 MatchOp = TI->getOperand(1);
8097 OtherOpT = TI->getOperand(0);
8098 OtherOpF = FI->getOperand(1);
8099 MatchIsOpZero = true;
8100 } else {
8101 return 0;
8102 }
8103
8104 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008105 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8106 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008107 InsertNewInstBefore(NewSI, SI);
8108
8109 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8110 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008111 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008112 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008113 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008114 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008115 assert(0 && "Shouldn't get here");
8116 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008117}
8118
Chris Lattner3d69f462004-03-12 05:52:32 +00008119Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008120 Value *CondVal = SI.getCondition();
8121 Value *TrueVal = SI.getTrueValue();
8122 Value *FalseVal = SI.getFalseValue();
8123
8124 // select true, X, Y -> X
8125 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008126 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008127 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008128
8129 // select C, X, X -> X
8130 if (TrueVal == FalseVal)
8131 return ReplaceInstUsesWith(SI, TrueVal);
8132
Chris Lattnere87597f2004-10-16 18:11:37 +00008133 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8134 return ReplaceInstUsesWith(SI, FalseVal);
8135 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8136 return ReplaceInstUsesWith(SI, TrueVal);
8137 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8138 if (isa<Constant>(TrueVal))
8139 return ReplaceInstUsesWith(SI, TrueVal);
8140 else
8141 return ReplaceInstUsesWith(SI, FalseVal);
8142 }
8143
Reid Spencer4fe16d62007-01-11 18:21:29 +00008144 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008145 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008146 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008147 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008148 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008149 } else {
8150 // Change: A = select B, false, C --> A = and !B, C
8151 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008152 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008153 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008154 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008155 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008156 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008157 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008158 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008159 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008160 } else {
8161 // Change: A = select B, C, true --> A = or !B, C
8162 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008163 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008164 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008165 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008166 }
8167 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008168
8169 // select a, b, a -> a&b
8170 // select a, a, b -> a|b
8171 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008172 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008173 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008174 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008175 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008176
Chris Lattner2eefe512004-04-09 19:05:30 +00008177 // Selecting between two integer constants?
8178 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8179 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008180 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008181 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008182 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008183 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008184 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008185 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008186 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008187 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008188 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008189 }
Chris Lattnerba417832007-04-11 06:12:58 +00008190
8191 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008192
Reid Spencere4d87aa2006-12-23 06:05:41 +00008193 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008194
Reid Spencere4d87aa2006-12-23 06:05:41 +00008195 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008196 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008197 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008198 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008199 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008200 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008201 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008202 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008203 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008204 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008205 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008206 InsertNewInstBefore(SRA, SI);
8207
Reid Spencer3da59db2006-11-27 01:05:10 +00008208 // Finally, convert to the type of the select RHS. We figure out
8209 // if this requires a SExt, Trunc or BitCast based on the sizes.
8210 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008211 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8212 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008213 if (SRASize < SISize)
8214 opc = Instruction::SExt;
8215 else if (SRASize > SISize)
8216 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008217 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008218 }
8219 }
8220
8221
8222 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008223 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008224 // non-constant value, eliminate this whole mess. This corresponds to
8225 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008226 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008227 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008228 cast<Constant>(IC->getOperand(1))->isNullValue())
8229 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8230 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008231 isa<ConstantInt>(ICA->getOperand(1)) &&
8232 (ICA->getOperand(1) == TrueValC ||
8233 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008234 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8235 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008236 // know whether we have a icmp_ne or icmp_eq and whether the
8237 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008238 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008239 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008240 Value *V = ICA;
8241 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008242 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008243 Instruction::Xor, V, ICA->getOperand(1)), SI);
8244 return ReplaceInstUsesWith(SI, V);
8245 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008246 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008247 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008248
8249 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008250 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8251 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008252 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008253 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8254 // This is not safe in general for floating point:
8255 // consider X== -0, Y== +0.
8256 // It becomes safe if either operand is a nonzero constant.
8257 ConstantFP *CFPt, *CFPf;
8258 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8259 !CFPt->getValueAPF().isZero()) ||
8260 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8261 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008262 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008263 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008264 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008265 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008266 return ReplaceInstUsesWith(SI, TrueVal);
8267 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8268
Reid Spencere4d87aa2006-12-23 06:05:41 +00008269 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008270 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008271 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8272 // This is not safe in general for floating point:
8273 // consider X== -0, Y== +0.
8274 // It becomes safe if either operand is a nonzero constant.
8275 ConstantFP *CFPt, *CFPf;
8276 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8277 !CFPt->getValueAPF().isZero()) ||
8278 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8279 !CFPf->getValueAPF().isZero()))
8280 return ReplaceInstUsesWith(SI, FalseVal);
8281 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008282 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008283 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8284 return ReplaceInstUsesWith(SI, TrueVal);
8285 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8286 }
8287 }
8288
8289 // See if we are selecting two values based on a comparison of the two values.
8290 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8291 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8292 // Transform (X == Y) ? X : Y -> Y
8293 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8294 return ReplaceInstUsesWith(SI, FalseVal);
8295 // Transform (X != Y) ? X : Y -> X
8296 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8297 return ReplaceInstUsesWith(SI, TrueVal);
8298 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8299
8300 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8301 // Transform (X == Y) ? Y : X -> X
8302 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8303 return ReplaceInstUsesWith(SI, FalseVal);
8304 // Transform (X != Y) ? Y : X -> Y
8305 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008306 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008307 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8308 }
8309 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008310
Chris Lattner87875da2005-01-13 22:52:24 +00008311 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8312 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8313 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008314 Instruction *AddOp = 0, *SubOp = 0;
8315
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008316 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8317 if (TI->getOpcode() == FI->getOpcode())
8318 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8319 return IV;
8320
8321 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8322 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008323 if (TI->getOpcode() == Instruction::Sub &&
8324 FI->getOpcode() == Instruction::Add) {
8325 AddOp = FI; SubOp = TI;
8326 } else if (FI->getOpcode() == Instruction::Sub &&
8327 TI->getOpcode() == Instruction::Add) {
8328 AddOp = TI; SubOp = FI;
8329 }
8330
8331 if (AddOp) {
8332 Value *OtherAddOp = 0;
8333 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8334 OtherAddOp = AddOp->getOperand(1);
8335 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8336 OtherAddOp = AddOp->getOperand(0);
8337 }
8338
8339 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008340 // So at this point we know we have (Y -> OtherAddOp):
8341 // select C, (add X, Y), (sub X, Z)
8342 Value *NegVal; // Compute -Z
8343 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8344 NegVal = ConstantExpr::getNeg(C);
8345 } else {
8346 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008347 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008348 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008349
8350 Value *NewTrueOp = OtherAddOp;
8351 Value *NewFalseOp = NegVal;
8352 if (AddOp != TI)
8353 std::swap(NewTrueOp, NewFalseOp);
8354 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008355 SelectInst::Create(CondVal, NewTrueOp,
8356 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008357
8358 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008359 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008360 }
8361 }
8362 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008363
Chris Lattnere576b912004-04-09 23:46:01 +00008364 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008365 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008366 // See the comment above GetSelectFoldableOperands for a description of the
8367 // transformation we are doing here.
8368 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8369 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8370 !isa<Constant>(FalseVal))
8371 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8372 unsigned OpToFold = 0;
8373 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8374 OpToFold = 1;
8375 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8376 OpToFold = 2;
8377 }
8378
8379 if (OpToFold) {
8380 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008381 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008382 SelectInst::Create(SI.getCondition(),
8383 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008384 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008385 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008386 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008387 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008388 else {
8389 assert(0 && "Unknown instruction!!");
8390 }
8391 }
8392 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008393
Chris Lattnere576b912004-04-09 23:46:01 +00008394 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8395 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8396 !isa<Constant>(TrueVal))
8397 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8398 unsigned OpToFold = 0;
8399 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8400 OpToFold = 1;
8401 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8402 OpToFold = 2;
8403 }
8404
8405 if (OpToFold) {
8406 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008407 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008408 SelectInst::Create(SI.getCondition(), C,
8409 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008410 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008411 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008412 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008413 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008414 else
Chris Lattnere576b912004-04-09 23:46:01 +00008415 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008416 }
8417 }
8418 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008419
8420 if (BinaryOperator::isNot(CondVal)) {
8421 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8422 SI.setOperand(1, FalseVal);
8423 SI.setOperand(2, TrueVal);
8424 return &SI;
8425 }
8426
Chris Lattner3d69f462004-03-12 05:52:32 +00008427 return 0;
8428}
8429
Dan Gohmaneee962e2008-04-10 18:43:06 +00008430/// EnforceKnownAlignment - If the specified pointer points to an object that
8431/// we control, modify the object's alignment to PrefAlign. This isn't
8432/// often possible though. If alignment is important, a more reliable approach
8433/// is to simply align all global variables and allocation instructions to
8434/// their preferred alignment from the beginning.
8435///
8436static unsigned EnforceKnownAlignment(Value *V,
8437 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008438
Dan Gohmaneee962e2008-04-10 18:43:06 +00008439 User *U = dyn_cast<User>(V);
8440 if (!U) return Align;
8441
8442 switch (getOpcode(U)) {
8443 default: break;
8444 case Instruction::BitCast:
8445 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8446 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008447 // If all indexes are zero, it is just the alignment of the base pointer.
8448 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008449 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8450 if (!isa<Constant>(U->getOperand(i)) ||
8451 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008452 AllZeroOperands = false;
8453 break;
8454 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008455
8456 if (AllZeroOperands) {
8457 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008458 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008459 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008460 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008461 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008462 }
8463
8464 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8465 // If there is a large requested alignment and we can, bump up the alignment
8466 // of the global.
8467 if (!GV->isDeclaration()) {
8468 GV->setAlignment(PrefAlign);
8469 Align = PrefAlign;
8470 }
8471 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8472 // If there is a requested alignment and if this is an alloca, round up. We
8473 // don't do this for malloc, because some systems can't respect the request.
8474 if (isa<AllocaInst>(AI)) {
8475 AI->setAlignment(PrefAlign);
8476 Align = PrefAlign;
8477 }
8478 }
8479
8480 return Align;
8481}
8482
8483/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8484/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8485/// and it is more than the alignment of the ultimate object, see if we can
8486/// increase the alignment of the ultimate object, making this check succeed.
8487unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8488 unsigned PrefAlign) {
8489 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8490 sizeof(PrefAlign) * CHAR_BIT;
8491 APInt Mask = APInt::getAllOnesValue(BitWidth);
8492 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8493 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8494 unsigned TrailZ = KnownZero.countTrailingOnes();
8495 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8496
8497 if (PrefAlign > Align)
8498 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8499
8500 // We don't need to make any adjustment.
8501 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008502}
8503
Chris Lattnerf497b022008-01-13 23:50:23 +00008504Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008505 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8506 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008507 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8508 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8509
8510 if (CopyAlign < MinAlign) {
8511 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8512 return MI;
8513 }
8514
8515 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8516 // load/store.
8517 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8518 if (MemOpLength == 0) return 0;
8519
Chris Lattner37ac6082008-01-14 00:28:35 +00008520 // Source and destination pointer types are always "i8*" for intrinsic. See
8521 // if the size is something we can handle with a single primitive load/store.
8522 // A single load+store correctly handles overlapping memory in the memmove
8523 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008524 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008525 if (Size == 0) return MI; // Delete this mem transfer.
8526
8527 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008528 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008529
Chris Lattner37ac6082008-01-14 00:28:35 +00008530 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008531 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008532
8533 // Memcpy forces the use of i8* for the source and destination. That means
8534 // that if you're using memcpy to move one double around, you'll get a cast
8535 // from double* to i8*. We'd much rather use a double load+store rather than
8536 // an i64 load+store, here because this improves the odds that the source or
8537 // dest address will be promotable. See if we can find a better type than the
8538 // integer datatype.
8539 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8540 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8541 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8542 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8543 // down through these levels if so.
8544 while (!SrcETy->isFirstClassType()) {
8545 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8546 if (STy->getNumElements() == 1)
8547 SrcETy = STy->getElementType(0);
8548 else
8549 break;
8550 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8551 if (ATy->getNumElements() == 1)
8552 SrcETy = ATy->getElementType();
8553 else
8554 break;
8555 } else
8556 break;
8557 }
8558
8559 if (SrcETy->isFirstClassType())
8560 NewPtrTy = PointerType::getUnqual(SrcETy);
8561 }
8562 }
8563
8564
Chris Lattnerf497b022008-01-13 23:50:23 +00008565 // If the memcpy/memmove provides better alignment info than we can
8566 // infer, use it.
8567 SrcAlign = std::max(SrcAlign, CopyAlign);
8568 DstAlign = std::max(DstAlign, CopyAlign);
8569
8570 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8571 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008572 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8573 InsertNewInstBefore(L, *MI);
8574 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8575
8576 // Set the size of the copy to 0, it will be deleted on the next iteration.
8577 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8578 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008579}
Chris Lattner3d69f462004-03-12 05:52:32 +00008580
Chris Lattner69ea9d22008-04-30 06:39:11 +00008581Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8582 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8583 if (MI->getAlignment()->getZExtValue() < Alignment) {
8584 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8585 return MI;
8586 }
8587
8588 // Extract the length and alignment and fill if they are constant.
8589 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8590 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8591 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8592 return 0;
8593 uint64_t Len = LenC->getZExtValue();
8594 Alignment = MI->getAlignment()->getZExtValue();
8595
8596 // If the length is zero, this is a no-op
8597 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8598
8599 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8600 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8601 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8602
8603 Value *Dest = MI->getDest();
8604 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8605
8606 // Alignment 0 is identity for alignment 1 for memset, but not store.
8607 if (Alignment == 0) Alignment = 1;
8608
8609 // Extract the fill value and store.
8610 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8611 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8612 Alignment), *MI);
8613
8614 // Set the size of the copy to 0, it will be deleted on the next iteration.
8615 MI->setLength(Constant::getNullValue(LenC->getType()));
8616 return MI;
8617 }
8618
8619 return 0;
8620}
8621
8622
Chris Lattner8b0ea312006-01-13 20:11:04 +00008623/// visitCallInst - CallInst simplification. This mostly only handles folding
8624/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8625/// the heavy lifting.
8626///
Chris Lattner9fe38862003-06-19 17:00:31 +00008627Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008628 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8629 if (!II) return visitCallSite(&CI);
8630
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008631 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8632 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008633 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008634 bool Changed = false;
8635
8636 // memmove/cpy/set of zero bytes is a noop.
8637 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8638 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8639
Chris Lattner35b9e482004-10-12 04:52:52 +00008640 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008641 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008642 // Replace the instruction with just byte operations. We would
8643 // transform other cases to loads/stores, but we don't know if
8644 // alignment is sufficient.
8645 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008646 }
8647
Chris Lattner35b9e482004-10-12 04:52:52 +00008648 // If we have a memmove and the source operation is a constant global,
8649 // then the source and dest pointers can't alias, so we can change this
8650 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008651 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008652 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8653 if (GVSrc->isConstant()) {
8654 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008655 Intrinsic::ID MemCpyID;
8656 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8657 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008658 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008659 MemCpyID = Intrinsic::memcpy_i64;
8660 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008661 Changed = true;
8662 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008663 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008664
Chris Lattner95a959d2006-03-06 20:18:44 +00008665 // If we can determine a pointer alignment that is bigger than currently
8666 // set, update the alignment.
8667 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008668 if (Instruction *I = SimplifyMemTransfer(MI))
8669 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00008670 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8671 if (Instruction *I = SimplifyMemSet(MSI))
8672 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008673 }
8674
Chris Lattner8b0ea312006-01-13 20:11:04 +00008675 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008676 } else {
8677 switch (II->getIntrinsicID()) {
8678 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008679 case Intrinsic::ppc_altivec_lvx:
8680 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008681 case Intrinsic::x86_sse_loadu_ps:
8682 case Intrinsic::x86_sse2_loadu_pd:
8683 case Intrinsic::x86_sse2_loadu_dq:
8684 // Turn PPC lvx -> load if the pointer is known aligned.
8685 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008686 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008687 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8688 PointerType::getUnqual(II->getType()),
8689 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008690 return new LoadInst(Ptr);
8691 }
8692 break;
8693 case Intrinsic::ppc_altivec_stvx:
8694 case Intrinsic::ppc_altivec_stvxl:
8695 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008696 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008697 const Type *OpPtrTy =
8698 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008699 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008700 return new StoreInst(II->getOperand(1), Ptr);
8701 }
8702 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008703 case Intrinsic::x86_sse_storeu_ps:
8704 case Intrinsic::x86_sse2_storeu_pd:
8705 case Intrinsic::x86_sse2_storeu_dq:
8706 case Intrinsic::x86_sse2_storel_dq:
8707 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008708 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008709 const Type *OpPtrTy =
8710 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008711 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008712 return new StoreInst(II->getOperand(2), Ptr);
8713 }
8714 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008715
8716 case Intrinsic::x86_sse_cvttss2si: {
8717 // These intrinsics only demands the 0th element of its input vector. If
8718 // we can simplify the input based on that, do so now.
8719 uint64_t UndefElts;
8720 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8721 UndefElts)) {
8722 II->setOperand(1, V);
8723 return II;
8724 }
8725 break;
8726 }
8727
Chris Lattnere2ed0572006-04-06 19:19:17 +00008728 case Intrinsic::ppc_altivec_vperm:
8729 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008730 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008731 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8732
8733 // Check that all of the elements are integer constants or undefs.
8734 bool AllEltsOk = true;
8735 for (unsigned i = 0; i != 16; ++i) {
8736 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8737 !isa<UndefValue>(Mask->getOperand(i))) {
8738 AllEltsOk = false;
8739 break;
8740 }
8741 }
8742
8743 if (AllEltsOk) {
8744 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008745 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8746 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008747 Value *Result = UndefValue::get(Op0->getType());
8748
8749 // Only extract each element once.
8750 Value *ExtractedElts[32];
8751 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8752
8753 for (unsigned i = 0; i != 16; ++i) {
8754 if (isa<UndefValue>(Mask->getOperand(i)))
8755 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008756 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008757 Idx &= 31; // Match the hardware behavior.
8758
8759 if (ExtractedElts[Idx] == 0) {
8760 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008761 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008762 InsertNewInstBefore(Elt, CI);
8763 ExtractedElts[Idx] = Elt;
8764 }
8765
8766 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008767 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8768 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008769 InsertNewInstBefore(cast<Instruction>(Result), CI);
8770 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008771 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008772 }
8773 }
8774 break;
8775
Chris Lattnera728ddc2006-01-13 21:28:09 +00008776 case Intrinsic::stackrestore: {
8777 // If the save is right next to the restore, remove the restore. This can
8778 // happen when variable allocas are DCE'd.
8779 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8780 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8781 BasicBlock::iterator BI = SS;
8782 if (&*++BI == II)
8783 return EraseInstFromFunction(CI);
8784 }
8785 }
8786
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008787 // Scan down this block to see if there is another stack restore in the
8788 // same block without an intervening call/alloca.
8789 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008790 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008791 bool CannotRemove = false;
8792 for (++BI; &*BI != TI; ++BI) {
8793 if (isa<AllocaInst>(BI)) {
8794 CannotRemove = true;
8795 break;
8796 }
8797 if (isa<CallInst>(BI)) {
8798 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008799 CannotRemove = true;
8800 break;
8801 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008802 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008803 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008804 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008805 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008806
8807 // If the stack restore is in a return/unwind block and if there are no
8808 // allocas or calls between the restore and the return, nuke the restore.
8809 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8810 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008811 break;
8812 }
8813 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008814 }
8815
Chris Lattner8b0ea312006-01-13 20:11:04 +00008816 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008817}
8818
8819// InvokeInst simplification
8820//
8821Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008822 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008823}
8824
Dale Johannesenda30ccb2008-04-25 21:16:07 +00008825/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8826/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00008827static bool isSafeToEliminateVarargsCast(const CallSite CS,
8828 const CastInst * const CI,
8829 const TargetData * const TD,
8830 const int ix) {
8831 if (!CI->isLosslessCast())
8832 return false;
8833
8834 // The size of ByVal arguments is derived from the type, so we
8835 // can't change to a type with a different size. If the size were
8836 // passed explicitly we could avoid this check.
8837 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8838 return true;
8839
8840 const Type* SrcTy =
8841 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8842 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8843 if (!SrcTy->isSized() || !DstTy->isSized())
8844 return false;
8845 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8846 return false;
8847 return true;
8848}
8849
Chris Lattnera44d8a22003-10-07 22:32:43 +00008850// visitCallSite - Improvements for call and invoke instructions.
8851//
8852Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008853 bool Changed = false;
8854
8855 // If the callee is a constexpr cast of a function, attempt to move the cast
8856 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008857 if (transformConstExprCastCall(CS)) return 0;
8858
Chris Lattner6c266db2003-10-07 22:54:13 +00008859 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008860
Chris Lattner08b22ec2005-05-13 07:09:09 +00008861 if (Function *CalleeF = dyn_cast<Function>(Callee))
8862 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8863 Instruction *OldCall = CS.getInstruction();
8864 // If the call and callee calling conventions don't match, this call must
8865 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008866 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008867 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8868 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008869 if (!OldCall->use_empty())
8870 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8871 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8872 return EraseInstFromFunction(*OldCall);
8873 return 0;
8874 }
8875
Chris Lattner17be6352004-10-18 02:59:09 +00008876 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8877 // This instruction is not reachable, just remove it. We insert a store to
8878 // undef so that we know that this code is not reachable, despite the fact
8879 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008880 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008881 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008882 CS.getInstruction());
8883
8884 if (!CS.getInstruction()->use_empty())
8885 CS.getInstruction()->
8886 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8887
8888 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8889 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00008890 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8891 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008892 }
Chris Lattner17be6352004-10-18 02:59:09 +00008893 return EraseInstFromFunction(*CS.getInstruction());
8894 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008895
Duncan Sandscdb6d922007-09-17 10:26:40 +00008896 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8897 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8898 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8899 return transformCallThroughTrampoline(CS);
8900
Chris Lattner6c266db2003-10-07 22:54:13 +00008901 const PointerType *PTy = cast<PointerType>(Callee->getType());
8902 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8903 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00008904 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00008905 // See if we can optimize any arguments passed through the varargs area of
8906 // the call.
8907 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00008908 E = CS.arg_end(); I != E; ++I, ++ix) {
8909 CastInst *CI = dyn_cast<CastInst>(*I);
8910 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8911 *I = CI->getOperand(0);
8912 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00008913 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00008914 }
Chris Lattner6c266db2003-10-07 22:54:13 +00008915 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008916
Duncan Sandsf0c33542007-12-19 21:13:37 +00008917 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008918 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008919 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008920 Changed = true;
8921 }
8922
Chris Lattner6c266db2003-10-07 22:54:13 +00008923 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008924}
8925
Chris Lattner9fe38862003-06-19 17:00:31 +00008926// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8927// attempt to move the cast to the arguments of the call/invoke.
8928//
8929bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8930 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8931 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008932 if (CE->getOpcode() != Instruction::BitCast ||
8933 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008934 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008935 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008936 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008937 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008938
8939 // Okay, this is a cast from a function to a different type. Unless doing so
8940 // would cause a type conversion of one of our arguments, change this call to
8941 // be a direct call with arguments casted to the appropriate types.
8942 //
8943 const FunctionType *FT = Callee->getFunctionType();
8944 const Type *OldRetTy = Caller->getType();
8945
Devang Patel75e6f022008-03-11 18:04:06 +00008946 if (isa<StructType>(FT->getReturnType()))
8947 return false; // TODO: Handle multiple return values.
8948
Chris Lattnerf78616b2004-01-14 06:06:08 +00008949 // Check to see if we are changing the return type...
8950 if (OldRetTy != FT->getReturnType()) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00008951 if (Callee->isDeclaration() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008952 // Conversion is ok if changing from pointer to int of same size.
8953 !(isa<PointerType>(FT->getReturnType()) &&
8954 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008955 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008956
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008957 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008958 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008959 FT->getReturnType() != Type::VoidTy &&
8960 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008961 return false; // Cannot transform this return value.
8962
Chris Lattner58d74912008-03-12 17:45:29 +00008963 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8964 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00008965 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8966 return false; // Attribute not compatible with transformed value.
8967 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008968
Chris Lattnerf78616b2004-01-14 06:06:08 +00008969 // If the callsite is an invoke instruction, and the return value is used by
8970 // a PHI node in a successor, we cannot change the return type of the call
8971 // because there is no place to put the cast instruction (without breaking
8972 // the critical edge). Bail out in this case.
8973 if (!Caller->use_empty())
8974 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8975 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8976 UI != E; ++UI)
8977 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8978 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008979 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008980 return false;
8981 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008982
8983 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8984 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008985
Chris Lattner9fe38862003-06-19 17:00:31 +00008986 CallSite::arg_iterator AI = CS.arg_begin();
8987 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8988 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008989 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008990
8991 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008992 return false; // Cannot transform this parameter value.
8993
Chris Lattner58d74912008-03-12 17:45:29 +00008994 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8995 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008996
Reid Spencer3da59db2006-11-27 01:05:10 +00008997 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008998 // Some conversions are safe even if we do not have a body.
8999 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00009000 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00009001 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00009002 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009003 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9004 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00009005 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00009006 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009007 }
9008
9009 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009010 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009011 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009012
Chris Lattner58d74912008-03-12 17:45:29 +00009013 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9014 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009015 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009016 // won't be dropping them. Check that these extra arguments have attributes
9017 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009018 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9019 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009020 break;
Chris Lattner58d74912008-03-12 17:45:29 +00009021 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00009022 if (PAttrs & ParamAttr::VarArgsIncompatible)
9023 return false;
9024 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009025
Chris Lattner9fe38862003-06-19 17:00:31 +00009026 // Okay, we decided that this is a safe thing to do: go ahead and start
9027 // inserting cast instructions as necessary...
9028 std::vector<Value*> Args;
9029 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00009030 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009031 attrVec.reserve(NumCommonArgs);
9032
9033 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009034 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009035
9036 // If the return value is not being used, the type may not be compatible
9037 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00009038 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009039
9040 // Add the new return attributes.
9041 if (RAttrs)
9042 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009043
9044 AI = CS.arg_begin();
9045 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9046 const Type *ParamTy = FT->getParamType(i);
9047 if ((*AI)->getType() == ParamTy) {
9048 Args.push_back(*AI);
9049 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009050 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009051 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009052 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009053 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009054 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009055
9056 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009057 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009058 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009059 }
9060
9061 // If the function takes more arguments than the call was taking, add them
9062 // now...
9063 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9064 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9065
9066 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009067 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009068 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009069 cerr << "WARNING: While resolving call to function '"
9070 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009071 } else {
9072 // Add all of the arguments in their promoted form to the arg list...
9073 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9074 const Type *PTy = getPromotedType((*AI)->getType());
9075 if (PTy != (*AI)->getType()) {
9076 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009077 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9078 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009079 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009080 InsertNewInstBefore(Cast, *Caller);
9081 Args.push_back(Cast);
9082 } else {
9083 Args.push_back(*AI);
9084 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009085
Duncan Sandse1e520f2008-01-13 08:02:44 +00009086 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009087 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009088 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9089 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009090 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009091 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009092
9093 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009094 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009095
Chris Lattner58d74912008-03-12 17:45:29 +00009096 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009097
Chris Lattner9fe38862003-06-19 17:00:31 +00009098 Instruction *NC;
9099 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009100 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009101 Args.begin(), Args.end(),
9102 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009103 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009104 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009105 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009106 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9107 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009108 CallInst *CI = cast<CallInst>(Caller);
9109 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009110 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009111 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009112 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009113 }
9114
Chris Lattner6934a042007-02-11 01:23:03 +00009115 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009116 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009117 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009118 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009119 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009120 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009121 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009122
9123 // If this is an invoke instruction, we should insert it after the first
9124 // non-phi, instruction in the normal successor block.
9125 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9126 BasicBlock::iterator I = II->getNormalDest()->begin();
9127 while (isa<PHINode>(I)) ++I;
9128 InsertNewInstBefore(NC, *I);
9129 } else {
9130 // Otherwise, it's a call, just insert cast right after the call instr
9131 InsertNewInstBefore(NC, *Caller);
9132 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009133 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009134 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009135 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009136 }
9137 }
9138
9139 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9140 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009141 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009142 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009143 return true;
9144}
9145
Duncan Sandscdb6d922007-09-17 10:26:40 +00009146// transformCallThroughTrampoline - Turn a call to a function created by the
9147// init_trampoline intrinsic into a direct call to the underlying function.
9148//
9149Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9150 Value *Callee = CS.getCalledValue();
9151 const PointerType *PTy = cast<PointerType>(Callee->getType());
9152 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009153 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009154
9155 // If the call already has the 'nest' attribute somewhere then give up -
9156 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009157 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009158 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009159
9160 IntrinsicInst *Tramp =
9161 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9162
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009163 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009164 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9165 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9166
Chris Lattner58d74912008-03-12 17:45:29 +00009167 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9168 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009169 unsigned NestIdx = 1;
9170 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009171 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009172
9173 // Look for a parameter marked with the 'nest' attribute.
9174 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9175 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009176 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009177 // Record the parameter type and any other attributes.
9178 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009179 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009180 break;
9181 }
9182
9183 if (NestTy) {
9184 Instruction *Caller = CS.getInstruction();
9185 std::vector<Value*> NewArgs;
9186 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9187
Chris Lattner58d74912008-03-12 17:45:29 +00009188 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9189 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009190
Duncan Sandscdb6d922007-09-17 10:26:40 +00009191 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009192 // mean appending it. Likewise for attributes.
9193
9194 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009195 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9196 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009197
Duncan Sandscdb6d922007-09-17 10:26:40 +00009198 {
9199 unsigned Idx = 1;
9200 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9201 do {
9202 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009203 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009204 Value *NestVal = Tramp->getOperand(3);
9205 if (NestVal->getType() != NestTy)
9206 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9207 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009208 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009209 }
9210
9211 if (I == E)
9212 break;
9213
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009214 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009215 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009216 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009217 NewAttrs.push_back
9218 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009219
9220 ++Idx, ++I;
9221 } while (1);
9222 }
9223
9224 // The trampoline may have been bitcast to a bogus type (FTy).
9225 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009226 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009227
Duncan Sandscdb6d922007-09-17 10:26:40 +00009228 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009229 NewTypes.reserve(FTy->getNumParams()+1);
9230
Duncan Sandscdb6d922007-09-17 10:26:40 +00009231 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009232 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009233 {
9234 unsigned Idx = 1;
9235 FunctionType::param_iterator I = FTy->param_begin(),
9236 E = FTy->param_end();
9237
9238 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009239 if (Idx == NestIdx)
9240 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009241 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009242
9243 if (I == E)
9244 break;
9245
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009246 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009247 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009248
9249 ++Idx, ++I;
9250 } while (1);
9251 }
9252
9253 // Replace the trampoline call with a direct call. Let the generic
9254 // code sort out any function type mismatches.
9255 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009256 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009257 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9258 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009259 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009260
9261 Instruction *NewCaller;
9262 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009263 NewCaller = InvokeInst::Create(NewCallee,
9264 II->getNormalDest(), II->getUnwindDest(),
9265 NewArgs.begin(), NewArgs.end(),
9266 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009267 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009268 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009269 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009270 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9271 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009272 if (cast<CallInst>(Caller)->isTailCall())
9273 cast<CallInst>(NewCaller)->setTailCall();
9274 cast<CallInst>(NewCaller)->
9275 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009276 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009277 }
9278 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9279 Caller->replaceAllUsesWith(NewCaller);
9280 Caller->eraseFromParent();
9281 RemoveFromWorkList(Caller);
9282 return 0;
9283 }
9284 }
9285
9286 // Replace the trampoline call with a direct call. Since there is no 'nest'
9287 // parameter, there is no need to adjust the argument list. Let the generic
9288 // code sort out any function type mismatches.
9289 Constant *NewCallee =
9290 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9291 CS.setCalledFunction(NewCallee);
9292 return CS.getInstruction();
9293}
9294
Chris Lattner7da52b22006-11-01 04:51:18 +00009295/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9296/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9297/// and a single binop.
9298Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9299 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009300 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9301 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009302 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009303 Value *LHSVal = FirstInst->getOperand(0);
9304 Value *RHSVal = FirstInst->getOperand(1);
9305
9306 const Type *LHSType = LHSVal->getType();
9307 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009308
9309 // Scan to see if all operands are the same opcode, all have one use, and all
9310 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009311 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009312 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009313 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009314 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009315 // types or GEP's with different index types.
9316 I->getOperand(0)->getType() != LHSType ||
9317 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009318 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009319
9320 // If they are CmpInst instructions, check their predicates
9321 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9322 if (cast<CmpInst>(I)->getPredicate() !=
9323 cast<CmpInst>(FirstInst)->getPredicate())
9324 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009325
9326 // Keep track of which operand needs a phi node.
9327 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9328 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009329 }
9330
Chris Lattner53738a42006-11-08 19:42:28 +00009331 // Otherwise, this is safe to transform, determine if it is profitable.
9332
9333 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9334 // Indexes are often folded into load/store instructions, so we don't want to
9335 // hide them behind a phi.
9336 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9337 return 0;
9338
Chris Lattner7da52b22006-11-01 04:51:18 +00009339 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009340 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009341 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009342 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009343 NewLHS = PHINode::Create(LHSType,
9344 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009345 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9346 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009347 InsertNewInstBefore(NewLHS, PN);
9348 LHSVal = NewLHS;
9349 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009350
9351 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009352 NewRHS = PHINode::Create(RHSType,
9353 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009354 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9355 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009356 InsertNewInstBefore(NewRHS, PN);
9357 RHSVal = NewRHS;
9358 }
9359
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009360 // Add all operands to the new PHIs.
9361 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9362 if (NewLHS) {
9363 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9364 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9365 }
9366 if (NewRHS) {
9367 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9368 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9369 }
9370 }
9371
Chris Lattner7da52b22006-11-01 04:51:18 +00009372 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009373 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009374 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009375 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009376 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009377 else {
9378 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009379 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009380 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009381}
9382
Chris Lattner76c73142006-11-01 07:13:54 +00009383/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9384/// of the block that defines it. This means that it must be obvious the value
9385/// of the load is not changed from the point of the load to the end of the
9386/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009387///
9388/// Finally, it is safe, but not profitable, to sink a load targetting a
9389/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9390/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009391static bool isSafeToSinkLoad(LoadInst *L) {
9392 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9393
9394 for (++BBI; BBI != E; ++BBI)
9395 if (BBI->mayWriteToMemory())
9396 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009397
9398 // Check for non-address taken alloca. If not address-taken already, it isn't
9399 // profitable to do this xform.
9400 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9401 bool isAddressTaken = false;
9402 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9403 UI != E; ++UI) {
9404 if (isa<LoadInst>(UI)) continue;
9405 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9406 // If storing TO the alloca, then the address isn't taken.
9407 if (SI->getOperand(1) == AI) continue;
9408 }
9409 isAddressTaken = true;
9410 break;
9411 }
9412
9413 if (!isAddressTaken)
9414 return false;
9415 }
9416
Chris Lattner76c73142006-11-01 07:13:54 +00009417 return true;
9418}
9419
Chris Lattner9fe38862003-06-19 17:00:31 +00009420
Chris Lattnerbac32862004-11-14 19:13:23 +00009421// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9422// operator and they all are only used by the PHI, PHI together their
9423// inputs, and do the operation once, to the result of the PHI.
9424Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9425 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9426
9427 // Scan the instruction, looking for input operations that can be folded away.
9428 // If all input operands to the phi are the same instruction (e.g. a cast from
9429 // the same type or "+42") we can pull the operation through the PHI, reducing
9430 // code size and simplifying code.
9431 Constant *ConstantOp = 0;
9432 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009433 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009434 if (isa<CastInst>(FirstInst)) {
9435 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009436 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009437 // Can fold binop, compare or shift here if the RHS is a constant,
9438 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009439 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009440 if (ConstantOp == 0)
9441 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009442 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9443 isVolatile = LI->isVolatile();
9444 // We can't sink the load if the loaded value could be modified between the
9445 // load and the PHI.
9446 if (LI->getParent() != PN.getIncomingBlock(0) ||
9447 !isSafeToSinkLoad(LI))
9448 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009449 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009450 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009451 return FoldPHIArgBinOpIntoPHI(PN);
9452 // Can't handle general GEPs yet.
9453 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009454 } else {
9455 return 0; // Cannot fold this operation.
9456 }
9457
9458 // Check to see if all arguments are the same operation.
9459 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9460 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9461 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009462 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009463 return 0;
9464 if (CastSrcTy) {
9465 if (I->getOperand(0)->getType() != CastSrcTy)
9466 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009467 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009468 // We can't sink the load if the loaded value could be modified between
9469 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009470 if (LI->isVolatile() != isVolatile ||
9471 LI->getParent() != PN.getIncomingBlock(i) ||
9472 !isSafeToSinkLoad(LI))
9473 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009474
9475 // If the PHI is volatile and its block has multiple successors, sinking
9476 // it would remove a load of the volatile value from the path through the
9477 // other successor.
9478 if (isVolatile &&
9479 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9480 return 0;
9481
9482
Chris Lattnerbac32862004-11-14 19:13:23 +00009483 } else if (I->getOperand(1) != ConstantOp) {
9484 return 0;
9485 }
9486 }
9487
9488 // Okay, they are all the same operation. Create a new PHI node of the
9489 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009490 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9491 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009492 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009493
9494 Value *InVal = FirstInst->getOperand(0);
9495 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009496
9497 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009498 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9499 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9500 if (NewInVal != InVal)
9501 InVal = 0;
9502 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9503 }
9504
9505 Value *PhiVal;
9506 if (InVal) {
9507 // The new PHI unions all of the same values together. This is really
9508 // common, so we handle it intelligently here for compile-time speed.
9509 PhiVal = InVal;
9510 delete NewPN;
9511 } else {
9512 InsertNewInstBefore(NewPN, PN);
9513 PhiVal = NewPN;
9514 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009515
Chris Lattnerbac32862004-11-14 19:13:23 +00009516 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009517 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009518 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009519 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009520 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009521 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009522 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009523 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009524 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9525
9526 // If this was a volatile load that we are merging, make sure to loop through
9527 // and mark all the input loads as non-volatile. If we don't do this, we will
9528 // insert a new volatile load and the old ones will not be deletable.
9529 if (isVolatile)
9530 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9531 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9532
9533 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009534}
Chris Lattnera1be5662002-05-02 17:06:02 +00009535
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009536/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9537/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009538static bool DeadPHICycle(PHINode *PN,
9539 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009540 if (PN->use_empty()) return true;
9541 if (!PN->hasOneUse()) return false;
9542
9543 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009544 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009545 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009546
9547 // Don't scan crazily complex things.
9548 if (PotentiallyDeadPHIs.size() == 16)
9549 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009550
9551 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9552 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009553
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009554 return false;
9555}
9556
Chris Lattnercf5008a2007-11-06 21:52:06 +00009557/// PHIsEqualValue - Return true if this phi node is always equal to
9558/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9559/// z = some value; x = phi (y, z); y = phi (x, z)
9560static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9561 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9562 // See if we already saw this PHI node.
9563 if (!ValueEqualPHIs.insert(PN))
9564 return true;
9565
9566 // Don't scan crazily complex things.
9567 if (ValueEqualPHIs.size() == 16)
9568 return false;
9569
9570 // Scan the operands to see if they are either phi nodes or are equal to
9571 // the value.
9572 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9573 Value *Op = PN->getIncomingValue(i);
9574 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9575 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9576 return false;
9577 } else if (Op != NonPhiInVal)
9578 return false;
9579 }
9580
9581 return true;
9582}
9583
9584
Chris Lattner473945d2002-05-06 18:06:38 +00009585// PHINode simplification
9586//
Chris Lattner7e708292002-06-25 16:13:24 +00009587Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009588 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009589 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009590
Owen Anderson7e057142006-07-10 22:03:18 +00009591 if (Value *V = PN.hasConstantValue())
9592 return ReplaceInstUsesWith(PN, V);
9593
Owen Anderson7e057142006-07-10 22:03:18 +00009594 // If all PHI operands are the same operation, pull them through the PHI,
9595 // reducing code size.
9596 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9597 PN.getIncomingValue(0)->hasOneUse())
9598 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9599 return Result;
9600
9601 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9602 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9603 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009604 if (PN.hasOneUse()) {
9605 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9606 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009607 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009608 PotentiallyDeadPHIs.insert(&PN);
9609 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9610 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9611 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009612
9613 // If this phi has a single use, and if that use just computes a value for
9614 // the next iteration of a loop, delete the phi. This occurs with unused
9615 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9616 // common case here is good because the only other things that catch this
9617 // are induction variable analysis (sometimes) and ADCE, which is only run
9618 // late.
9619 if (PHIUser->hasOneUse() &&
9620 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9621 PHIUser->use_back() == &PN) {
9622 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9623 }
9624 }
Owen Anderson7e057142006-07-10 22:03:18 +00009625
Chris Lattnercf5008a2007-11-06 21:52:06 +00009626 // We sometimes end up with phi cycles that non-obviously end up being the
9627 // same value, for example:
9628 // z = some value; x = phi (y, z); y = phi (x, z)
9629 // where the phi nodes don't necessarily need to be in the same block. Do a
9630 // quick check to see if the PHI node only contains a single non-phi value, if
9631 // so, scan to see if the phi cycle is actually equal to that value.
9632 {
9633 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9634 // Scan for the first non-phi operand.
9635 while (InValNo != NumOperandVals &&
9636 isa<PHINode>(PN.getIncomingValue(InValNo)))
9637 ++InValNo;
9638
9639 if (InValNo != NumOperandVals) {
9640 Value *NonPhiInVal = PN.getOperand(InValNo);
9641
9642 // Scan the rest of the operands to see if there are any conflicts, if so
9643 // there is no need to recursively scan other phis.
9644 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9645 Value *OpVal = PN.getIncomingValue(InValNo);
9646 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9647 break;
9648 }
9649
9650 // If we scanned over all operands, then we have one unique value plus
9651 // phi values. Scan PHI nodes to see if they all merge in each other or
9652 // the value.
9653 if (InValNo == NumOperandVals) {
9654 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9655 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9656 return ReplaceInstUsesWith(PN, NonPhiInVal);
9657 }
9658 }
9659 }
Chris Lattner60921c92003-12-19 05:58:40 +00009660 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009661}
9662
Reid Spencer17212df2006-12-12 09:18:51 +00009663static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9664 Instruction *InsertPoint,
9665 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009666 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9667 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009668 // We must cast correctly to the pointer type. Ensure that we
9669 // sign extend the integer value if it is smaller as this is
9670 // used for address computation.
9671 Instruction::CastOps opcode =
9672 (VTySize < PtrSize ? Instruction::SExt :
9673 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9674 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009675}
9676
Chris Lattnera1be5662002-05-02 17:06:02 +00009677
Chris Lattner7e708292002-06-25 16:13:24 +00009678Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009679 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009680 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009681 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009682 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009683 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009684
Chris Lattnere87597f2004-10-16 18:11:37 +00009685 if (isa<UndefValue>(GEP.getOperand(0)))
9686 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9687
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009688 bool HasZeroPointerIndex = false;
9689 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9690 HasZeroPointerIndex = C->isNullValue();
9691
9692 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009693 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009694
Chris Lattner28977af2004-04-05 01:30:19 +00009695 // Eliminate unneeded casts for indices.
9696 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009697
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009698 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009699 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009700 if (isa<SequentialType>(*GTI)) {
9701 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009702 if (CI->getOpcode() == Instruction::ZExt ||
9703 CI->getOpcode() == Instruction::SExt) {
9704 const Type *SrcTy = CI->getOperand(0)->getType();
9705 // We can eliminate a cast from i32 to i64 iff the target
9706 // is a 32-bit pointer target.
9707 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9708 MadeChange = true;
9709 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009710 }
9711 }
9712 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009713 // If we are using a wider index than needed for this platform, shrink it
9714 // to what we need. If the incoming value needs a cast instruction,
9715 // insert it. This explicit cast can make subsequent optimizations more
9716 // obvious.
9717 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009718 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009719 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009720 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009721 MadeChange = true;
9722 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009723 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9724 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009725 GEP.setOperand(i, Op);
9726 MadeChange = true;
9727 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009728 }
Chris Lattner28977af2004-04-05 01:30:19 +00009729 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009730 }
Chris Lattner28977af2004-04-05 01:30:19 +00009731 if (MadeChange) return &GEP;
9732
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009733 // If this GEP instruction doesn't move the pointer, and if the input operand
9734 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9735 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009736 if (GEP.hasAllZeroIndices()) {
9737 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9738 // If the bitcast is of an allocation, and the allocation will be
9739 // converted to match the type of the cast, don't touch this.
9740 if (isa<AllocationInst>(BCI->getOperand(0))) {
9741 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009742 if (Instruction *I = visitBitCast(*BCI)) {
9743 if (I != BCI) {
9744 I->takeName(BCI);
9745 BCI->getParent()->getInstList().insert(BCI, I);
9746 ReplaceInstUsesWith(*BCI, I);
9747 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009748 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009749 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009750 }
9751 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9752 }
9753 }
9754
Chris Lattner90ac28c2002-08-02 19:29:35 +00009755 // Combine Indices - If the source pointer to this getelementptr instruction
9756 // is a getelementptr instruction, combine the indices of the two
9757 // getelementptr instructions into a single instruction.
9758 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009759 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009760 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009761 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009762
9763 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009764 // Note that if our source is a gep chain itself that we wait for that
9765 // chain to be resolved before we perform this transformation. This
9766 // avoids us creating a TON of code in some cases.
9767 //
9768 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9769 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9770 return 0; // Wait until our source is folded to completion.
9771
Chris Lattner72588fc2007-02-15 22:48:32 +00009772 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009773
9774 // Find out whether the last index in the source GEP is a sequential idx.
9775 bool EndsWithSequential = false;
9776 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9777 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009778 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009779
Chris Lattner90ac28c2002-08-02 19:29:35 +00009780 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009781 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009782 // Replace: gep (gep %P, long B), long A, ...
9783 // With: T = long A+B; gep %P, T, ...
9784 //
Chris Lattner620ce142004-05-07 22:09:22 +00009785 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009786 if (SO1 == Constant::getNullValue(SO1->getType())) {
9787 Sum = GO1;
9788 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9789 Sum = SO1;
9790 } else {
9791 // If they aren't the same type, convert both to an integer of the
9792 // target's pointer size.
9793 if (SO1->getType() != GO1->getType()) {
9794 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009795 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009796 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009797 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009798 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009799 unsigned PS = TD->getPointerSizeInBits();
9800 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009801 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009802 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009803
Duncan Sands514ab342007-11-01 20:53:16 +00009804 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009805 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009806 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009807 } else {
9808 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009809 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9810 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009811 }
9812 }
9813 }
Chris Lattner620ce142004-05-07 22:09:22 +00009814 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9815 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9816 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009817 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +00009818 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009819 }
Chris Lattner28977af2004-04-05 01:30:19 +00009820 }
Chris Lattner620ce142004-05-07 22:09:22 +00009821
9822 // Recycle the GEP we already have if possible.
9823 if (SrcGEPOperands.size() == 2) {
9824 GEP.setOperand(0, SrcGEPOperands[0]);
9825 GEP.setOperand(1, Sum);
9826 return &GEP;
9827 } else {
9828 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9829 SrcGEPOperands.end()-1);
9830 Indices.push_back(Sum);
9831 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9832 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009833 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009834 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009835 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009836 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009837 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9838 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009839 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9840 }
9841
9842 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +00009843 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9844 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009845
Chris Lattner620ce142004-05-07 22:09:22 +00009846 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009847 // GEP of global variable. If all of the indices for this GEP are
9848 // constants, we can promote this to a constexpr instead of an instruction.
9849
9850 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009851 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009852 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9853 for (; I != E && isa<Constant>(*I); ++I)
9854 Indices.push_back(cast<Constant>(*I));
9855
9856 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009857 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9858 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009859
9860 // Replace all uses of the GEP with the new constexpr...
9861 return ReplaceInstUsesWith(GEP, CE);
9862 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009863 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009864 if (!isa<PointerType>(X->getType())) {
9865 // Not interesting. Source pointer must be a cast from pointer.
9866 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009867 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9868 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009869 //
9870 // This occurs when the program declares an array extern like "int X[];"
9871 //
9872 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9873 const PointerType *XTy = cast<PointerType>(X->getType());
9874 if (const ArrayType *XATy =
9875 dyn_cast<ArrayType>(XTy->getElementType()))
9876 if (const ArrayType *CATy =
9877 dyn_cast<ArrayType>(CPTy->getElementType()))
9878 if (CATy->getElementType() == XATy->getElementType()) {
9879 // At this point, we know that the cast source type is a pointer
9880 // to an array of the same type as the destination pointer
9881 // array. Because the array type is never stepped over (there
9882 // is a leading zero) we can fold the cast into this GEP.
9883 GEP.setOperand(0, X);
9884 return &GEP;
9885 }
9886 } else if (GEP.getNumOperands() == 2) {
9887 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009888 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9889 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009890 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9891 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9892 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009893 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9894 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009895 Value *Idx[2];
9896 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9897 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009898 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +00009899 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009900 // V and GEP are both pointer types --> BitCast
9901 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009902 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009903
9904 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009905 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009906 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009907 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009908
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009909 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009910 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009911 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009912
9913 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9914 // allow either a mul, shift, or constant here.
9915 Value *NewIdx = 0;
9916 ConstantInt *Scale = 0;
9917 if (ArrayEltSize == 1) {
9918 NewIdx = GEP.getOperand(1);
9919 Scale = ConstantInt::get(NewIdx->getType(), 1);
9920 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009921 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009922 Scale = CI;
9923 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9924 if (Inst->getOpcode() == Instruction::Shl &&
9925 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009926 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9927 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9928 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009929 NewIdx = Inst->getOperand(0);
9930 } else if (Inst->getOpcode() == Instruction::Mul &&
9931 isa<ConstantInt>(Inst->getOperand(1))) {
9932 Scale = cast<ConstantInt>(Inst->getOperand(1));
9933 NewIdx = Inst->getOperand(0);
9934 }
9935 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009936
Chris Lattner7835cdd2005-09-13 18:36:04 +00009937 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009938 // out, perform the transformation. Note, we don't know whether Scale is
9939 // signed or not. We'll use unsigned version of division/modulo
9940 // operation after making sure Scale doesn't have the sign bit set.
9941 if (Scale && Scale->getSExtValue() >= 0LL &&
9942 Scale->getZExtValue() % ArrayEltSize == 0) {
9943 Scale = ConstantInt::get(Scale->getType(),
9944 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009945 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009946 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009947 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009948 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00009949 NewIdx = InsertNewInstBefore(Sc, GEP);
9950 }
9951
9952 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009953 Value *Idx[2];
9954 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9955 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009956 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +00009957 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009958 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9959 // The NewGEP must be pointer typed, so must the old one -> BitCast
9960 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009961 }
9962 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009963 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009964 }
9965
Chris Lattner8a2a3112001-12-14 16:52:21 +00009966 return 0;
9967}
9968
Chris Lattner0864acf2002-11-04 16:18:53 +00009969Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9970 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009971 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009972 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9973 const Type *NewTy =
9974 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009975 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009976
9977 // Create and insert the replacement instruction...
9978 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009979 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009980 else {
9981 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009982 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009983 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009984
9985 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009986
Chris Lattner0864acf2002-11-04 16:18:53 +00009987 // Scan to the end of the allocation instructions, to skip over a block of
9988 // allocas if possible...
9989 //
9990 BasicBlock::iterator It = New;
9991 while (isa<AllocationInst>(*It)) ++It;
9992
9993 // Now that I is pointing to the first non-allocation-inst in the block,
9994 // insert our getelementptr instruction...
9995 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009996 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009997 Value *Idx[2];
9998 Idx[0] = NullIdx;
9999 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010000 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10001 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010002
10003 // Now make everything use the getelementptr instead of the original
10004 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010005 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010006 } else if (isa<UndefValue>(AI.getArraySize())) {
10007 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010008 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010009 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010010
10011 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10012 // Note that we only do this for alloca's, because malloc should allocate and
10013 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +000010014 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +000010015 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +000010016 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10017
Chris Lattner0864acf2002-11-04 16:18:53 +000010018 return 0;
10019}
10020
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010021Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10022 Value *Op = FI.getOperand(0);
10023
Chris Lattner17be6352004-10-18 02:59:09 +000010024 // free undef -> unreachable.
10025 if (isa<UndefValue>(Op)) {
10026 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010027 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010028 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010029 return EraseInstFromFunction(FI);
10030 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010031
Chris Lattner6160e852004-02-28 04:57:37 +000010032 // If we have 'free null' delete the instruction. This can happen in stl code
10033 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010034 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010035 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010036
10037 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10038 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10039 FI.setOperand(0, CI->getOperand(0));
10040 return &FI;
10041 }
10042
10043 // Change free (gep X, 0,0,0,0) into free(X)
10044 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10045 if (GEPI->hasAllZeroIndices()) {
10046 AddToWorkList(GEPI);
10047 FI.setOperand(0, GEPI->getOperand(0));
10048 return &FI;
10049 }
10050 }
10051
10052 // Change free(malloc) into nothing, if the malloc has a single use.
10053 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10054 if (MI->hasOneUse()) {
10055 EraseInstFromFunction(FI);
10056 return EraseInstFromFunction(*MI);
10057 }
Chris Lattner6160e852004-02-28 04:57:37 +000010058
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010059 return 0;
10060}
10061
10062
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010063/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010064static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010065 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010066 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010067 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010068
Devang Patel99db6ad2007-10-18 19:52:32 +000010069 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10070 // Instead of loading constant c string, use corresponding integer value
10071 // directly if string length is small enough.
10072 const std::string &Str = CE->getOperand(0)->getStringValue();
10073 if (!Str.empty()) {
10074 unsigned len = Str.length();
10075 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10076 unsigned numBits = Ty->getPrimitiveSizeInBits();
10077 // Replace LI with immediate integer store.
10078 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010079 APInt StrVal(numBits, 0);
10080 APInt SingleChar(numBits, 0);
10081 if (TD->isLittleEndian()) {
10082 for (signed i = len-1; i >= 0; i--) {
10083 SingleChar = (uint64_t) Str[i];
10084 StrVal = (StrVal << 8) | SingleChar;
10085 }
10086 } else {
10087 for (unsigned i = 0; i < len; i++) {
10088 SingleChar = (uint64_t) Str[i];
10089 StrVal = (StrVal << 8) | SingleChar;
10090 }
10091 // Append NULL at the end.
10092 SingleChar = 0;
10093 StrVal = (StrVal << 8) | SingleChar;
10094 }
10095 Value *NL = ConstantInt::get(StrVal);
10096 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010097 }
10098 }
10099 }
10100
Chris Lattnerb89e0712004-07-13 01:49:43 +000010101 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010102 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010103 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010104
Reid Spencer42230162007-01-22 05:51:25 +000010105 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010106 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010107 // If the source is an array, the code below will not succeed. Check to
10108 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10109 // constants.
10110 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10111 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10112 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010113 Value *Idxs[2];
10114 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10115 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010116 SrcTy = cast<PointerType>(CastOp->getType());
10117 SrcPTy = SrcTy->getElementType();
10118 }
10119
Reid Spencer42230162007-01-22 05:51:25 +000010120 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010121 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010122 // Do not allow turning this into a load of an integer, which is then
10123 // casted to a pointer, this pessimizes pointer analysis a lot.
10124 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010125 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10126 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010127
Chris Lattnerf9527852005-01-31 04:50:46 +000010128 // Okay, we are casting from one integer or pointer type to another of
10129 // the same size. Instead of casting the pointer before the load, cast
10130 // the result of the loaded value.
10131 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10132 CI->getName(),
10133 LI.isVolatile()),LI);
10134 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010135 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010136 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010137 }
10138 }
10139 return 0;
10140}
10141
Chris Lattnerc10aced2004-09-19 18:43:46 +000010142/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010143/// from this value cannot trap. If it is not obviously safe to load from the
10144/// specified pointer, we do a quick local scan of the basic block containing
10145/// ScanFrom, to determine if the address is already accessed.
10146static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010147 // If it is an alloca it is always safe to load from.
10148 if (isa<AllocaInst>(V)) return true;
10149
Duncan Sands46318cd2007-09-19 10:25:38 +000010150 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010151 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010152 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010153 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010154
10155 // Otherwise, be a little bit agressive by scanning the local block where we
10156 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010157 // from/to. If so, the previous load or store would have already trapped,
10158 // so there is no harm doing an extra load (also, CSE will later eliminate
10159 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010160 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10161
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010162 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010163 --BBI;
10164
10165 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10166 if (LI->getOperand(0) == V) return true;
10167 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10168 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010169
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010170 }
Chris Lattner8a375202004-09-19 19:18:10 +000010171 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010172}
10173
Chris Lattner8d2e8882007-08-11 18:48:48 +000010174/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10175/// until we find the underlying object a pointer is referring to or something
10176/// we don't understand. Note that the returned pointer may be offset from the
10177/// input, because we ignore GEP indices.
10178static Value *GetUnderlyingObject(Value *Ptr) {
10179 while (1) {
10180 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10181 if (CE->getOpcode() == Instruction::BitCast ||
10182 CE->getOpcode() == Instruction::GetElementPtr)
10183 Ptr = CE->getOperand(0);
10184 else
10185 return Ptr;
10186 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10187 Ptr = BCI->getOperand(0);
10188 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10189 Ptr = GEP->getOperand(0);
10190 } else {
10191 return Ptr;
10192 }
10193 }
10194}
10195
Chris Lattner833b8a42003-06-26 05:06:25 +000010196Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10197 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010198
Dan Gohman9941f742007-07-20 16:34:21 +000010199 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010200 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10201 if (KnownAlign >
10202 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10203 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010204 LI.setAlignment(KnownAlign);
10205
Chris Lattner37366c12005-05-01 04:24:53 +000010206 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010207 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010208 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010209 return Res;
10210
10211 // None of the following transforms are legal for volatile loads.
10212 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010213
Chris Lattner62f254d2005-09-12 22:00:15 +000010214 if (&LI.getParent()->front() != &LI) {
10215 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010216 // If the instruction immediately before this is a store to the same
10217 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010218 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10219 if (SI->getOperand(1) == LI.getOperand(0))
10220 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010221 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10222 if (LIB->getOperand(0) == LI.getOperand(0))
10223 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010224 }
Chris Lattner37366c12005-05-01 04:24:53 +000010225
Christopher Lambb15147e2007-12-29 07:56:53 +000010226 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10227 const Value *GEPI0 = GEPI->getOperand(0);
10228 // TODO: Consider a target hook for valid address spaces for this xform.
10229 if (isa<ConstantPointerNull>(GEPI0) &&
10230 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010231 // Insert a new store to null instruction before the load to indicate
10232 // that this code is not reachable. We do this instead of inserting
10233 // an unreachable instruction directly because we cannot modify the
10234 // CFG.
10235 new StoreInst(UndefValue::get(LI.getType()),
10236 Constant::getNullValue(Op->getType()), &LI);
10237 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10238 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010239 }
Chris Lattner37366c12005-05-01 04:24:53 +000010240
Chris Lattnere87597f2004-10-16 18:11:37 +000010241 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010242 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010243 // TODO: Consider a target hook for valid address spaces for this xform.
10244 if (isa<UndefValue>(C) || (C->isNullValue() &&
10245 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010246 // Insert a new store to null instruction before the load to indicate that
10247 // this code is not reachable. We do this instead of inserting an
10248 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010249 new StoreInst(UndefValue::get(LI.getType()),
10250 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010251 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010252 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010253
Chris Lattnere87597f2004-10-16 18:11:37 +000010254 // Instcombine load (constant global) into the value loaded.
10255 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010256 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010257 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010258
Chris Lattnere87597f2004-10-16 18:11:37 +000010259 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010260 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010261 if (CE->getOpcode() == Instruction::GetElementPtr) {
10262 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010263 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010264 if (Constant *V =
10265 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010266 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010267 if (CE->getOperand(0)->isNullValue()) {
10268 // Insert a new store to null instruction before the load to indicate
10269 // that this code is not reachable. We do this instead of inserting
10270 // an unreachable instruction directly because we cannot modify the
10271 // CFG.
10272 new StoreInst(UndefValue::get(LI.getType()),
10273 Constant::getNullValue(Op->getType()), &LI);
10274 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10275 }
10276
Reid Spencer3da59db2006-11-27 01:05:10 +000010277 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010278 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010279 return Res;
10280 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010281 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010282 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010283
10284 // If this load comes from anywhere in a constant global, and if the global
10285 // is all undef or zero, we know what it loads.
10286 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10287 if (GV->isConstant() && GV->hasInitializer()) {
10288 if (GV->getInitializer()->isNullValue())
10289 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10290 else if (isa<UndefValue>(GV->getInitializer()))
10291 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10292 }
10293 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010294
Chris Lattner37366c12005-05-01 04:24:53 +000010295 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010296 // Change select and PHI nodes to select values instead of addresses: this
10297 // helps alias analysis out a lot, allows many others simplifications, and
10298 // exposes redundancy in the code.
10299 //
10300 // Note that we cannot do the transformation unless we know that the
10301 // introduced loads cannot trap! Something like this is valid as long as
10302 // the condition is always false: load (select bool %C, int* null, int* %G),
10303 // but it would not be valid if we transformed it to load from null
10304 // unconditionally.
10305 //
10306 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10307 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010308 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10309 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010310 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010311 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010312 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010313 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010314 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010315 }
10316
Chris Lattner684fe212004-09-23 15:46:00 +000010317 // load (select (cond, null, P)) -> load P
10318 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10319 if (C->isNullValue()) {
10320 LI.setOperand(0, SI->getOperand(2));
10321 return &LI;
10322 }
10323
10324 // load (select (cond, P, null)) -> load P
10325 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10326 if (C->isNullValue()) {
10327 LI.setOperand(0, SI->getOperand(1));
10328 return &LI;
10329 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010330 }
10331 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010332 return 0;
10333}
10334
Reid Spencer55af2b52007-01-19 21:20:31 +000010335/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010336/// when possible.
10337static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10338 User *CI = cast<User>(SI.getOperand(1));
10339 Value *CastOp = CI->getOperand(0);
10340
10341 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10342 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10343 const Type *SrcPTy = SrcTy->getElementType();
10344
Reid Spencer42230162007-01-22 05:51:25 +000010345 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010346 // If the source is an array, the code below will not succeed. Check to
10347 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10348 // constants.
10349 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10350 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10351 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010352 Value* Idxs[2];
10353 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10354 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010355 SrcTy = cast<PointerType>(CastOp->getType());
10356 SrcPTy = SrcTy->getElementType();
10357 }
10358
Reid Spencer67f827c2007-01-20 23:35:48 +000010359 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10360 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10361 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010362
10363 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010364 // the same size. Instead of casting the pointer before
10365 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010366 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010367 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010368 Instruction::CastOps opcode = Instruction::BitCast;
10369 const Type* CastSrcTy = SIOp0->getType();
10370 const Type* CastDstTy = SrcPTy;
10371 if (isa<PointerType>(CastDstTy)) {
10372 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010373 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010374 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010375 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010376 opcode = Instruction::PtrToInt;
10377 }
10378 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010379 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010380 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010381 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010382 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010383 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010384 return new StoreInst(NewCast, CastOp);
10385 }
10386 }
10387 }
10388 return 0;
10389}
10390
Chris Lattner2f503e62005-01-31 05:36:43 +000010391Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10392 Value *Val = SI.getOperand(0);
10393 Value *Ptr = SI.getOperand(1);
10394
10395 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010396 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010397 ++NumCombined;
10398 return 0;
10399 }
Chris Lattner836692d2007-01-15 06:51:56 +000010400
10401 // If the RHS is an alloca with a single use, zapify the store, making the
10402 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010403 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010404 if (isa<AllocaInst>(Ptr)) {
10405 EraseInstFromFunction(SI);
10406 ++NumCombined;
10407 return 0;
10408 }
10409
10410 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10411 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10412 GEP->getOperand(0)->hasOneUse()) {
10413 EraseInstFromFunction(SI);
10414 ++NumCombined;
10415 return 0;
10416 }
10417 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010418
Dan Gohman9941f742007-07-20 16:34:21 +000010419 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010420 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10421 if (KnownAlign >
10422 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10423 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010424 SI.setAlignment(KnownAlign);
10425
Chris Lattner9ca96412006-02-08 03:25:32 +000010426 // Do really simple DSE, to catch cases where there are several consequtive
10427 // stores to the same location, separated by a few arithmetic operations. This
10428 // situation often occurs with bitfield accesses.
10429 BasicBlock::iterator BBI = &SI;
10430 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10431 --ScanInsts) {
10432 --BBI;
10433
10434 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10435 // Prev store isn't volatile, and stores to the same location?
10436 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10437 ++NumDeadStore;
10438 ++BBI;
10439 EraseInstFromFunction(*PrevSI);
10440 continue;
10441 }
10442 break;
10443 }
10444
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010445 // If this is a load, we have to stop. However, if the loaded value is from
10446 // the pointer we're loading and is producing the pointer we're storing,
10447 // then *this* store is dead (X = load P; store X -> P).
10448 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010449 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010450 EraseInstFromFunction(SI);
10451 ++NumCombined;
10452 return 0;
10453 }
10454 // Otherwise, this is a load from some other location. Stores before it
10455 // may not be dead.
10456 break;
10457 }
10458
Chris Lattner9ca96412006-02-08 03:25:32 +000010459 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010460 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010461 break;
10462 }
10463
10464
10465 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010466
10467 // store X, null -> turns into 'unreachable' in SimplifyCFG
10468 if (isa<ConstantPointerNull>(Ptr)) {
10469 if (!isa<UndefValue>(Val)) {
10470 SI.setOperand(0, UndefValue::get(Val->getType()));
10471 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010472 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010473 ++NumCombined;
10474 }
10475 return 0; // Do not modify these!
10476 }
10477
10478 // store undef, Ptr -> noop
10479 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010480 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010481 ++NumCombined;
10482 return 0;
10483 }
10484
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010485 // If the pointer destination is a cast, see if we can fold the cast into the
10486 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010487 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010488 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10489 return Res;
10490 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010491 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010492 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10493 return Res;
10494
Chris Lattner408902b2005-09-12 23:23:25 +000010495
10496 // If this store is the last instruction in the basic block, and if the block
10497 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010498 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010499 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010500 if (BI->isUnconditional())
10501 if (SimplifyStoreAtEndOfBlock(SI))
10502 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010503
Chris Lattner2f503e62005-01-31 05:36:43 +000010504 return 0;
10505}
10506
Chris Lattner3284d1f2007-04-15 00:07:55 +000010507/// SimplifyStoreAtEndOfBlock - Turn things like:
10508/// if () { *P = v1; } else { *P = v2 }
10509/// into a phi node with a store in the successor.
10510///
Chris Lattner31755a02007-04-15 01:02:18 +000010511/// Simplify things like:
10512/// *P = v1; if () { *P = v2; }
10513/// into a phi node with a store in the successor.
10514///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010515bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10516 BasicBlock *StoreBB = SI.getParent();
10517
10518 // Check to see if the successor block has exactly two incoming edges. If
10519 // so, see if the other predecessor contains a store to the same location.
10520 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010521 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010522
10523 // Determine whether Dest has exactly two predecessors and, if so, compute
10524 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010525 pred_iterator PI = pred_begin(DestBB);
10526 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010527 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010528 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010529 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010530 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010531 return false;
10532
10533 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010534 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010535 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010536 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010537 }
Chris Lattner31755a02007-04-15 01:02:18 +000010538 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010539 return false;
10540
10541
Chris Lattner31755a02007-04-15 01:02:18 +000010542 // Verify that the other block ends in a branch and is not otherwise empty.
10543 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010544 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010545 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010546 return false;
10547
Chris Lattner31755a02007-04-15 01:02:18 +000010548 // If the other block ends in an unconditional branch, check for the 'if then
10549 // else' case. there is an instruction before the branch.
10550 StoreInst *OtherStore = 0;
10551 if (OtherBr->isUnconditional()) {
10552 // If this isn't a store, or isn't a store to the same location, bail out.
10553 --BBI;
10554 OtherStore = dyn_cast<StoreInst>(BBI);
10555 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10556 return false;
10557 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010558 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010559 // destinations is StoreBB, then we have the if/then case.
10560 if (OtherBr->getSuccessor(0) != StoreBB &&
10561 OtherBr->getSuccessor(1) != StoreBB)
10562 return false;
10563
10564 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010565 // if/then triangle. See if there is a store to the same ptr as SI that
10566 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010567 for (;; --BBI) {
10568 // Check to see if we find the matching store.
10569 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10570 if (OtherStore->getOperand(1) != SI.getOperand(1))
10571 return false;
10572 break;
10573 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010574 // If we find something that may be using the stored value, or if we run
10575 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010576 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10577 BBI == OtherBB->begin())
10578 return false;
10579 }
10580
10581 // In order to eliminate the store in OtherBr, we have to
10582 // make sure nothing reads the stored value in StoreBB.
10583 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10584 // FIXME: This should really be AA driven.
10585 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10586 return false;
10587 }
10588 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010589
Chris Lattner31755a02007-04-15 01:02:18 +000010590 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010591 Value *MergedVal = OtherStore->getOperand(0);
10592 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010593 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000010594 PN->reserveOperandSpace(2);
10595 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010596 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10597 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010598 }
10599
10600 // Advance to a place where it is safe to insert the new store and
10601 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010602 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010603 while (isa<PHINode>(BBI)) ++BBI;
10604 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10605 OtherStore->isVolatile()), *BBI);
10606
10607 // Nuke the old stores.
10608 EraseInstFromFunction(SI);
10609 EraseInstFromFunction(*OtherStore);
10610 ++NumCombined;
10611 return true;
10612}
10613
Chris Lattner2f503e62005-01-31 05:36:43 +000010614
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010615Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10616 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010617 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010618 BasicBlock *TrueDest;
10619 BasicBlock *FalseDest;
10620 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10621 !isa<Constant>(X)) {
10622 // Swap Destinations and condition...
10623 BI.setCondition(X);
10624 BI.setSuccessor(0, FalseDest);
10625 BI.setSuccessor(1, TrueDest);
10626 return &BI;
10627 }
10628
Reid Spencere4d87aa2006-12-23 06:05:41 +000010629 // Cannonicalize fcmp_one -> fcmp_oeq
10630 FCmpInst::Predicate FPred; Value *Y;
10631 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10632 TrueDest, FalseDest)))
10633 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10634 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10635 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010636 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010637 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10638 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010639 // Swap Destinations and condition...
10640 BI.setCondition(NewSCC);
10641 BI.setSuccessor(0, FalseDest);
10642 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010643 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010644 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010645 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010646 return &BI;
10647 }
10648
10649 // Cannonicalize icmp_ne -> icmp_eq
10650 ICmpInst::Predicate IPred;
10651 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10652 TrueDest, FalseDest)))
10653 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10654 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10655 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10656 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010657 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010658 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10659 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010660 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010661 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010662 BI.setSuccessor(0, FalseDest);
10663 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010664 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010665 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010666 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010667 return &BI;
10668 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010669
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010670 return 0;
10671}
Chris Lattner0864acf2002-11-04 16:18:53 +000010672
Chris Lattner46238a62004-07-03 00:26:11 +000010673Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10674 Value *Cond = SI.getCondition();
10675 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10676 if (I->getOpcode() == Instruction::Add)
10677 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10678 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10679 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010680 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010681 AddRHS));
10682 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010683 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010684 return &SI;
10685 }
10686 }
10687 return 0;
10688}
10689
Chris Lattner220b0cf2006-03-05 00:22:33 +000010690/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10691/// is to leave as a vector operation.
10692static bool CheapToScalarize(Value *V, bool isConstant) {
10693 if (isa<ConstantAggregateZero>(V))
10694 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010695 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010696 if (isConstant) return true;
10697 // If all elts are the same, we can extract.
10698 Constant *Op0 = C->getOperand(0);
10699 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10700 if (C->getOperand(i) != Op0)
10701 return false;
10702 return true;
10703 }
10704 Instruction *I = dyn_cast<Instruction>(V);
10705 if (!I) return false;
10706
10707 // Insert element gets simplified to the inserted element or is deleted if
10708 // this is constant idx extract element and its a constant idx insertelt.
10709 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10710 isa<ConstantInt>(I->getOperand(2)))
10711 return true;
10712 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10713 return true;
10714 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10715 if (BO->hasOneUse() &&
10716 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10717 CheapToScalarize(BO->getOperand(1), isConstant)))
10718 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010719 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10720 if (CI->hasOneUse() &&
10721 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10722 CheapToScalarize(CI->getOperand(1), isConstant)))
10723 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010724
10725 return false;
10726}
10727
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010728/// Read and decode a shufflevector mask.
10729///
10730/// It turns undef elements into values that are larger than the number of
10731/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010732static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10733 unsigned NElts = SVI->getType()->getNumElements();
10734 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10735 return std::vector<unsigned>(NElts, 0);
10736 if (isa<UndefValue>(SVI->getOperand(2)))
10737 return std::vector<unsigned>(NElts, 2*NElts);
10738
10739 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010740 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010741 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10742 if (isa<UndefValue>(CP->getOperand(i)))
10743 Result.push_back(NElts*2); // undef -> 8
10744 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010745 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010746 return Result;
10747}
10748
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010749/// FindScalarElement - Given a vector and an element number, see if the scalar
10750/// value is already around as a register, for example if it were inserted then
10751/// extracted from the vector.
10752static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010753 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10754 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010755 unsigned Width = PTy->getNumElements();
10756 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010757 return UndefValue::get(PTy->getElementType());
10758
10759 if (isa<UndefValue>(V))
10760 return UndefValue::get(PTy->getElementType());
10761 else if (isa<ConstantAggregateZero>(V))
10762 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010763 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010764 return CP->getOperand(EltNo);
10765 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10766 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010767 if (!isa<ConstantInt>(III->getOperand(2)))
10768 return 0;
10769 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010770
10771 // If this is an insert to the element we are looking for, return the
10772 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010773 if (EltNo == IIElt)
10774 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010775
10776 // Otherwise, the insertelement doesn't modify the value, recurse on its
10777 // vector input.
10778 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010779 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010780 unsigned InEl = getShuffleMask(SVI)[EltNo];
10781 if (InEl < Width)
10782 return FindScalarElement(SVI->getOperand(0), InEl);
10783 else if (InEl < Width*2)
10784 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10785 else
10786 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010787 }
10788
10789 // Otherwise, we don't know.
10790 return 0;
10791}
10792
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010793Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010794
Dan Gohman07a96762007-07-16 14:29:03 +000010795 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010796 if (isa<UndefValue>(EI.getOperand(0)))
10797 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10798
Dan Gohman07a96762007-07-16 14:29:03 +000010799 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010800 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10801 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10802
Reid Spencer9d6565a2007-02-15 02:26:10 +000010803 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010804 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010805 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010806 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010807 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010808 if (C->getOperand(i) != op0) {
10809 op0 = 0;
10810 break;
10811 }
10812 if (op0)
10813 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010814 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010815
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010816 // If extracting a specified index from the vector, see if we can recursively
10817 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010818 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010819 unsigned IndexVal = IdxC->getZExtValue();
10820 unsigned VectorWidth =
10821 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10822
10823 // If this is extracting an invalid index, turn this into undef, to avoid
10824 // crashing the code below.
10825 if (IndexVal >= VectorWidth)
10826 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10827
Chris Lattner867b99f2006-10-05 06:55:50 +000010828 // This instruction only demands the single element from the input vector.
10829 // If the input vector has a single use, simplify it based on this use
10830 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010831 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010832 uint64_t UndefElts;
10833 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010834 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010835 UndefElts)) {
10836 EI.setOperand(0, V);
10837 return &EI;
10838 }
10839 }
10840
Reid Spencerb83eb642006-10-20 07:07:24 +000010841 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010842 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010843
10844 // If the this extractelement is directly using a bitcast from a vector of
10845 // the same number of elements, see if we can find the source element from
10846 // it. In this case, we will end up needing to bitcast the scalars.
10847 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10848 if (const VectorType *VT =
10849 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10850 if (VT->getNumElements() == VectorWidth)
10851 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10852 return new BitCastInst(Elt, EI.getType());
10853 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010854 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010855
Chris Lattner73fa49d2006-05-25 22:53:38 +000010856 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010857 if (I->hasOneUse()) {
10858 // Push extractelement into predecessor operation if legal and
10859 // profitable to do so
10860 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010861 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10862 if (CheapToScalarize(BO, isConstantElt)) {
10863 ExtractElementInst *newEI0 =
10864 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10865 EI.getName()+".lhs");
10866 ExtractElementInst *newEI1 =
10867 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10868 EI.getName()+".rhs");
10869 InsertNewInstBefore(newEI0, EI);
10870 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010871 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000010872 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010873 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010874 unsigned AS =
10875 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010876 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10877 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010878 GetElementPtrInst *GEP =
10879 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010880 InsertNewInstBefore(GEP, EI);
10881 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010882 }
10883 }
10884 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10885 // Extracting the inserted element?
10886 if (IE->getOperand(2) == EI.getOperand(1))
10887 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10888 // If the inserted and extracted elements are constants, they must not
10889 // be the same value, extract from the pre-inserted value instead.
10890 if (isa<Constant>(IE->getOperand(2)) &&
10891 isa<Constant>(EI.getOperand(1))) {
10892 AddUsesToWorkList(EI);
10893 EI.setOperand(0, IE->getOperand(0));
10894 return &EI;
10895 }
10896 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10897 // If this is extracting an element from a shufflevector, figure out where
10898 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010899 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10900 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010901 Value *Src;
10902 if (SrcIdx < SVI->getType()->getNumElements())
10903 Src = SVI->getOperand(0);
10904 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10905 SrcIdx -= SVI->getType()->getNumElements();
10906 Src = SVI->getOperand(1);
10907 } else {
10908 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010909 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010910 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010911 }
10912 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010913 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010914 return 0;
10915}
10916
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010917/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10918/// elements from either LHS or RHS, return the shuffle mask and true.
10919/// Otherwise, return false.
10920static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10921 std::vector<Constant*> &Mask) {
10922 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10923 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010924 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010925
10926 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010927 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010928 return true;
10929 } else if (V == LHS) {
10930 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010931 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010932 return true;
10933 } else if (V == RHS) {
10934 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010935 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010936 return true;
10937 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10938 // If this is an insert of an extract from some other vector, include it.
10939 Value *VecOp = IEI->getOperand(0);
10940 Value *ScalarOp = IEI->getOperand(1);
10941 Value *IdxOp = IEI->getOperand(2);
10942
Chris Lattnerd929f062006-04-27 21:14:21 +000010943 if (!isa<ConstantInt>(IdxOp))
10944 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010945 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010946
10947 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10948 // Okay, we can handle this if the vector we are insertinting into is
10949 // transitively ok.
10950 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10951 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010952 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010953 return true;
10954 }
10955 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10956 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010957 EI->getOperand(0)->getType() == V->getType()) {
10958 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010959 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010960
10961 // This must be extracting from either LHS or RHS.
10962 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10963 // Okay, we can handle this if the vector we are insertinting into is
10964 // transitively ok.
10965 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10966 // If so, update the mask to reflect the inserted value.
10967 if (EI->getOperand(0) == LHS) {
10968 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010969 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010970 } else {
10971 assert(EI->getOperand(0) == RHS);
10972 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010973 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010974
10975 }
10976 return true;
10977 }
10978 }
10979 }
10980 }
10981 }
10982 // TODO: Handle shufflevector here!
10983
10984 return false;
10985}
10986
10987/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10988/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10989/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010990static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010991 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010992 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010993 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010994 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010995 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010996
10997 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010998 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010999 return V;
11000 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011001 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011002 return V;
11003 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11004 // If this is an insert of an extract from some other vector, include it.
11005 Value *VecOp = IEI->getOperand(0);
11006 Value *ScalarOp = IEI->getOperand(1);
11007 Value *IdxOp = IEI->getOperand(2);
11008
11009 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11010 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11011 EI->getOperand(0)->getType() == V->getType()) {
11012 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011013 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11014 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011015
11016 // Either the extracted from or inserted into vector must be RHSVec,
11017 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011018 if (EI->getOperand(0) == RHS || RHS == 0) {
11019 RHS = EI->getOperand(0);
11020 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011021 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011022 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011023 return V;
11024 }
11025
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011026 if (VecOp == RHS) {
11027 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011028 // Everything but the extracted element is replaced with the RHS.
11029 for (unsigned i = 0; i != NumElts; ++i) {
11030 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011031 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011032 }
11033 return V;
11034 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011035
11036 // If this insertelement is a chain that comes from exactly these two
11037 // vectors, return the vector and the effective shuffle.
11038 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11039 return EI->getOperand(0);
11040
Chris Lattnerefb47352006-04-15 01:39:45 +000011041 }
11042 }
11043 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011044 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011045
11046 // Otherwise, can't do anything fancy. Return an identity vector.
11047 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011048 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011049 return V;
11050}
11051
11052Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11053 Value *VecOp = IE.getOperand(0);
11054 Value *ScalarOp = IE.getOperand(1);
11055 Value *IdxOp = IE.getOperand(2);
11056
Chris Lattner599ded12007-04-09 01:11:16 +000011057 // Inserting an undef or into an undefined place, remove this.
11058 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11059 ReplaceInstUsesWith(IE, VecOp);
11060
Chris Lattnerefb47352006-04-15 01:39:45 +000011061 // If the inserted element was extracted from some other vector, and if the
11062 // indexes are constant, try to turn this into a shufflevector operation.
11063 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11064 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11065 EI->getOperand(0)->getType() == IE.getType()) {
11066 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011067 unsigned ExtractedIdx =
11068 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011069 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011070
11071 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11072 return ReplaceInstUsesWith(IE, VecOp);
11073
11074 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11075 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11076
11077 // If we are extracting a value from a vector, then inserting it right
11078 // back into the same place, just use the input vector.
11079 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11080 return ReplaceInstUsesWith(IE, VecOp);
11081
11082 // We could theoretically do this for ANY input. However, doing so could
11083 // turn chains of insertelement instructions into a chain of shufflevector
11084 // instructions, and right now we do not merge shufflevectors. As such,
11085 // only do this in a situation where it is clear that there is benefit.
11086 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11087 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11088 // the values of VecOp, except then one read from EIOp0.
11089 // Build a new shuffle mask.
11090 std::vector<Constant*> Mask;
11091 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011092 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011093 else {
11094 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011095 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011096 NumVectorElts));
11097 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011098 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011099 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011100 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011101 }
11102
11103 // If this insertelement isn't used by some other insertelement, turn it
11104 // (and any insertelements it points to), into one big shuffle.
11105 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11106 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011107 Value *RHS = 0;
11108 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11109 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11110 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011111 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011112 }
11113 }
11114 }
11115
11116 return 0;
11117}
11118
11119
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011120Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11121 Value *LHS = SVI.getOperand(0);
11122 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011123 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011124
11125 bool MadeChange = false;
11126
Chris Lattner867b99f2006-10-05 06:55:50 +000011127 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011128 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011129 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11130
Chris Lattnere4929dd2007-01-05 07:36:08 +000011131 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011132 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011133 if (isa<UndefValue>(SVI.getOperand(1))) {
11134 // Scan to see if there are any references to the RHS. If so, replace them
11135 // with undef element refs and set MadeChange to true.
11136 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11137 if (Mask[i] >= e && Mask[i] != 2*e) {
11138 Mask[i] = 2*e;
11139 MadeChange = true;
11140 }
11141 }
11142
11143 if (MadeChange) {
11144 // Remap any references to RHS to use LHS.
11145 std::vector<Constant*> Elts;
11146 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11147 if (Mask[i] == 2*e)
11148 Elts.push_back(UndefValue::get(Type::Int32Ty));
11149 else
11150 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11151 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011152 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011153 }
11154 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011155
Chris Lattner863bcff2006-05-25 23:48:38 +000011156 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11157 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11158 if (LHS == RHS || isa<UndefValue>(LHS)) {
11159 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011160 // shuffle(undef,undef,mask) -> undef.
11161 return ReplaceInstUsesWith(SVI, LHS);
11162 }
11163
Chris Lattner863bcff2006-05-25 23:48:38 +000011164 // Remap any references to RHS to use LHS.
11165 std::vector<Constant*> Elts;
11166 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011167 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011168 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011169 else {
11170 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11171 (Mask[i] < e && isa<UndefValue>(LHS)))
11172 Mask[i] = 2*e; // Turn into undef.
11173 else
11174 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011175 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011176 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011177 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011178 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011179 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011180 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011181 LHS = SVI.getOperand(0);
11182 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011183 MadeChange = true;
11184 }
11185
Chris Lattner7b2e27922006-05-26 00:29:06 +000011186 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011187 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011188
Chris Lattner863bcff2006-05-25 23:48:38 +000011189 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11190 if (Mask[i] >= e*2) continue; // Ignore undef values.
11191 // Is this an identity shuffle of the LHS value?
11192 isLHSID &= (Mask[i] == i);
11193
11194 // Is this an identity shuffle of the RHS value?
11195 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011196 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011197
Chris Lattner863bcff2006-05-25 23:48:38 +000011198 // Eliminate identity shuffles.
11199 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11200 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011201
Chris Lattner7b2e27922006-05-26 00:29:06 +000011202 // If the LHS is a shufflevector itself, see if we can combine it with this
11203 // one without producing an unusual shuffle. Here we are really conservative:
11204 // we are absolutely afraid of producing a shuffle mask not in the input
11205 // program, because the code gen may not be smart enough to turn a merged
11206 // shuffle into two specific shuffles: it may produce worse code. As such,
11207 // we only merge two shuffles if the result is one of the two input shuffle
11208 // masks. In this case, merging the shuffles just removes one instruction,
11209 // which we know is safe. This is good for things like turning:
11210 // (splat(splat)) -> splat.
11211 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11212 if (isa<UndefValue>(RHS)) {
11213 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11214
11215 std::vector<unsigned> NewMask;
11216 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11217 if (Mask[i] >= 2*e)
11218 NewMask.push_back(2*e);
11219 else
11220 NewMask.push_back(LHSMask[Mask[i]]);
11221
11222 // If the result mask is equal to the src shuffle or this shuffle mask, do
11223 // the replacement.
11224 if (NewMask == LHSMask || NewMask == Mask) {
11225 std::vector<Constant*> Elts;
11226 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11227 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011228 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011229 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011230 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011231 }
11232 }
11233 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11234 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011235 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011236 }
11237 }
11238 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011239
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011240 return MadeChange ? &SVI : 0;
11241}
11242
11243
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011244
Chris Lattnerea1c4542004-12-08 23:43:58 +000011245
11246/// TryToSinkInstruction - Try to move the specified instruction from its
11247/// current block into the beginning of DestBlock, which can only happen if it's
11248/// safe to move the instruction past all of the instructions between it and the
11249/// end of its block.
11250static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11251 assert(I->hasOneUse() && "Invariants didn't hold!");
11252
Chris Lattner108e9022005-10-27 17:13:11 +000011253 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011254 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11255 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011256
Chris Lattnerea1c4542004-12-08 23:43:58 +000011257 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011258 if (isa<AllocaInst>(I) && I->getParent() ==
11259 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011260 return false;
11261
Chris Lattner96a52a62004-12-09 07:14:34 +000011262 // We can only sink load instructions if there is nothing between the load and
11263 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011264 if (I->mayReadFromMemory()) {
11265 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011266 Scan != E; ++Scan)
11267 if (Scan->mayWriteToMemory())
11268 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011269 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011270
11271 BasicBlock::iterator InsertPos = DestBlock->begin();
11272 while (isa<PHINode>(InsertPos)) ++InsertPos;
11273
Chris Lattner4bc5f802005-08-08 19:11:57 +000011274 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011275 ++NumSunkInst;
11276 return true;
11277}
11278
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011279
11280/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11281/// all reachable code to the worklist.
11282///
11283/// This has a couple of tricks to make the code faster and more powerful. In
11284/// particular, we constant fold and DCE instructions as we go, to avoid adding
11285/// them to the worklist (this significantly speeds up instcombine on code where
11286/// many instructions are dead or constant). Additionally, if we find a branch
11287/// whose condition is a known constant, we only visit the reachable successors.
11288///
11289static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011290 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011291 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011292 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011293 std::vector<BasicBlock*> Worklist;
11294 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011295
Chris Lattner2c7718a2007-03-23 19:17:18 +000011296 while (!Worklist.empty()) {
11297 BB = Worklist.back();
11298 Worklist.pop_back();
11299
11300 // We have now visited this block! If we've already been here, ignore it.
11301 if (!Visited.insert(BB)) continue;
11302
11303 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11304 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011305
Chris Lattner2c7718a2007-03-23 19:17:18 +000011306 // DCE instruction if trivially dead.
11307 if (isInstructionTriviallyDead(Inst)) {
11308 ++NumDeadInst;
11309 DOUT << "IC: DCE: " << *Inst;
11310 Inst->eraseFromParent();
11311 continue;
11312 }
11313
11314 // ConstantProp instruction if trivially constant.
11315 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11316 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11317 Inst->replaceAllUsesWith(C);
11318 ++NumConstProp;
11319 Inst->eraseFromParent();
11320 continue;
11321 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011322
Chris Lattner2c7718a2007-03-23 19:17:18 +000011323 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011324 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011325
11326 // Recursively visit successors. If this is a branch or switch on a
11327 // constant, only visit the reachable successor.
11328 TerminatorInst *TI = BB->getTerminator();
11329 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11330 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11331 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011332 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011333 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011334 continue;
11335 }
11336 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11337 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11338 // See if this is an explicit destination.
11339 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11340 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011341 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011342 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011343 continue;
11344 }
11345
11346 // Otherwise it is the default destination.
11347 Worklist.push_back(SI->getSuccessor(0));
11348 continue;
11349 }
11350 }
11351
11352 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11353 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011354 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011355}
11356
Chris Lattnerec9c3582007-03-03 02:04:50 +000011357bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011358 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011359 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011360
11361 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11362 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011363
Chris Lattnerb3d59702005-07-07 20:40:38 +000011364 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011365 // Do a depth-first traversal of the function, populate the worklist with
11366 // the reachable instructions. Ignore blocks that are not reachable. Keep
11367 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011368 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011369 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011370
Chris Lattnerb3d59702005-07-07 20:40:38 +000011371 // Do a quick scan over the function. If we find any blocks that are
11372 // unreachable, remove any instructions inside of them. This prevents
11373 // the instcombine code from having to deal with some bad special cases.
11374 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11375 if (!Visited.count(BB)) {
11376 Instruction *Term = BB->getTerminator();
11377 while (Term != BB->begin()) { // Remove instrs bottom-up
11378 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011379
Bill Wendlingb7427032006-11-26 09:46:52 +000011380 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011381 ++NumDeadInst;
11382
11383 if (!I->use_empty())
11384 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11385 I->eraseFromParent();
11386 }
11387 }
11388 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011389
Chris Lattnerdbab3862007-03-02 21:28:56 +000011390 while (!Worklist.empty()) {
11391 Instruction *I = RemoveOneFromWorkList();
11392 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011393
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011394 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011395 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011396 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011397 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011398 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011399 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011400
Bill Wendlingb7427032006-11-26 09:46:52 +000011401 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011402
11403 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011404 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011405 continue;
11406 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011407
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011408 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011409 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011410 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011411
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011412 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011413 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011414 ReplaceInstUsesWith(*I, C);
11415
Chris Lattner62b14df2002-09-02 04:59:56 +000011416 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011417 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011418 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011419 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011420 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011421
Chris Lattnerea1c4542004-12-08 23:43:58 +000011422 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011423 // FIXME: Remove GetResultInst test when first class support for aggregates
11424 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011425 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011426 BasicBlock *BB = I->getParent();
11427 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11428 if (UserParent != BB) {
11429 bool UserIsSuccessor = false;
11430 // See if the user is one of our successors.
11431 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11432 if (*SI == UserParent) {
11433 UserIsSuccessor = true;
11434 break;
11435 }
11436
11437 // If the user is one of our immediate successors, and if that successor
11438 // only has us as a predecessors (we'd have to split the critical edge
11439 // otherwise), we can keep going.
11440 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11441 next(pred_begin(UserParent)) == pred_end(UserParent))
11442 // Okay, the CFG is simple enough, try to sink this instruction.
11443 Changed |= TryToSinkInstruction(I, UserParent);
11444 }
11445 }
11446
Chris Lattner8a2a3112001-12-14 16:52:21 +000011447 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011448#ifndef NDEBUG
11449 std::string OrigI;
11450#endif
11451 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011452 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011453 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011454 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011455 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011456 DOUT << "IC: Old = " << *I
11457 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011458
Chris Lattnerf523d062004-06-09 05:08:07 +000011459 // Everything uses the new instruction now.
11460 I->replaceAllUsesWith(Result);
11461
11462 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011463 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011464 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011465
Chris Lattner6934a042007-02-11 01:23:03 +000011466 // Move the name to the new instruction first.
11467 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011468
11469 // Insert the new instruction into the basic block...
11470 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011471 BasicBlock::iterator InsertPos = I;
11472
11473 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11474 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11475 ++InsertPos;
11476
11477 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011478
Chris Lattner00d51312004-05-01 23:27:23 +000011479 // Make sure that we reprocess all operands now that we reduced their
11480 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011481 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011482
Chris Lattnerf523d062004-06-09 05:08:07 +000011483 // Instructions can end up on the worklist more than once. Make sure
11484 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011485 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011486
11487 // Erase the old instruction.
11488 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011489 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011490#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011491 DOUT << "IC: Mod = " << OrigI
11492 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011493#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011494
Chris Lattner90ac28c2002-08-02 19:29:35 +000011495 // If the instruction was modified, it's possible that it is now dead.
11496 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011497 if (isInstructionTriviallyDead(I)) {
11498 // Make sure we process all operands now that we are reducing their
11499 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011500 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011501
Chris Lattner00d51312004-05-01 23:27:23 +000011502 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011503 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011504 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011505 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011506 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011507 AddToWorkList(I);
11508 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011509 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011510 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011511 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011512 }
11513 }
11514
Chris Lattnerec9c3582007-03-03 02:04:50 +000011515 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011516
11517 // Do an explicit clear, this shrinks the map if needed.
11518 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011519 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011520}
11521
Chris Lattnerec9c3582007-03-03 02:04:50 +000011522
11523bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011524 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11525
Chris Lattnerec9c3582007-03-03 02:04:50 +000011526 bool EverMadeChange = false;
11527
11528 // Iterate while there is work to do.
11529 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011530 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011531 EverMadeChange = true;
11532 return EverMadeChange;
11533}
11534
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011535FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011536 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011537}
Brian Gaeked0fde302003-11-11 22:41:34 +000011538