blob: 8e99dcc7db2cfe893a2d90df2da8ed43bbd5f089 [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
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// 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"
Dale Johannesen22c39792008-02-22 22:17:59 +000042#include "llvm/ParamAttrsList.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000043#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000049#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000051#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000052#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000053#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000054#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000055#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000056#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000057#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000058#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000059#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000060#include <algorithm>
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);
Chris Lattner9fe38862003-06-19 17:00:31 +0000240
Chris Lattner28977af2004-04-05 01:30:19 +0000241 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000242 // InsertNewInstBefore - insert an instruction New before instruction Old
243 // in the program. Add the new instruction to the worklist.
244 //
Chris Lattner955f3312004-09-28 21:48:02 +0000245 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000246 assert(New && New->getParent() == 0 &&
247 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000248 BasicBlock *BB = Old.getParent();
249 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000250 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000251 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000252 }
253
Chris Lattner0c967662004-09-24 15:21:34 +0000254 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
255 /// This also adds the cast to the worklist. Finally, this returns the
256 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000257 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
258 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000259 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000260
Chris Lattnere2ed0572006-04-06 19:19:17 +0000261 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000262 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000263
Reid Spencer17212df2006-12-12 09:18:51 +0000264 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000265 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000266 return C;
267 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000268
269 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
270 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
271 }
272
Chris Lattner0c967662004-09-24 15:21:34 +0000273
Chris Lattner8b170942002-08-09 23:47:40 +0000274 // ReplaceInstUsesWith - This method is to be used when an instruction is
275 // found to be dead, replacable with another preexisting expression. Here
276 // we add all uses of I to the worklist, replace all uses of I with the new
277 // value, then return I, so that the inst combiner will know that I was
278 // modified.
279 //
280 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000281 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000282 if (&I != V) {
283 I.replaceAllUsesWith(V);
284 return &I;
285 } else {
286 // If we are replacing the instruction with itself, this must be in a
287 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000288 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000289 return &I;
290 }
Chris Lattner8b170942002-08-09 23:47:40 +0000291 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000292
Chris Lattner6dce1a72006-02-07 06:56:34 +0000293 // UpdateValueUsesWith - This method is to be used when an value is
294 // found to be replacable with another preexisting expression or was
295 // updated. Here we add all uses of I to the worklist, replace all uses of
296 // I with the new value (unless the instruction was just updated), then
297 // return true, so that the inst combiner will know that I was modified.
298 //
299 bool UpdateValueUsesWith(Value *Old, Value *New) {
300 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
301 if (Old != New)
302 Old->replaceAllUsesWith(New);
303 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000304 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000305 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000306 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000307 return true;
308 }
309
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000310 // EraseInstFromFunction - When dealing with an instruction that has side
311 // effects or produces a void value, we can't rely on DCE to delete the
312 // instruction. Instead, visit methods should return the value returned by
313 // this function.
314 Instruction *EraseInstFromFunction(Instruction &I) {
315 assert(I.use_empty() && "Cannot erase instruction that is used!");
316 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000317 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000318 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000319 return 0; // Don't do anything with FI
320 }
321
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000322 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000323 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
324 /// InsertBefore instruction. This is specialized a bit to avoid inserting
325 /// casts that are known to not do anything...
326 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000327 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
328 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000329 Instruction *InsertBefore);
330
Reid Spencere4d87aa2006-12-23 06:05:41 +0000331 /// SimplifyCommutative - This performs a few simplifications for
332 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000333 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000334
Reid Spencere4d87aa2006-12-23 06:05:41 +0000335 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
336 /// most-complex to least-complex order.
337 bool SimplifyCompare(CmpInst &I);
338
Reid Spencer2ec619a2007-03-23 21:24:59 +0000339 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
340 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000341 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
342 APInt& KnownZero, APInt& KnownOne,
343 unsigned Depth = 0);
344
Chris Lattner867b99f2006-10-05 06:55:50 +0000345 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
346 uint64_t &UndefElts, unsigned Depth = 0);
347
Chris Lattner4e998b22004-09-29 05:07:12 +0000348 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
349 // PHI node as operand #0, see if we can fold the instruction into the PHI
350 // (which is only possible if all operands to the PHI are constants).
351 Instruction *FoldOpIntoPhi(Instruction &I);
352
Chris Lattnerbac32862004-11-14 19:13:23 +0000353 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
354 // operator and they all are only used by the PHI, PHI together their
355 // inputs, and do the operation once, to the result of the PHI.
356 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000357 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
358
359
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000360 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
361 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000362
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000363 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000364 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000365 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000366 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000367 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000368 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000369 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000370 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
371
Chris Lattnerafe91a52006-06-15 19:07:26 +0000372
Reid Spencerc55b2432006-12-13 18:21:21 +0000373 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000374 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000375
Devang Patel19974732007-05-03 01:11:54 +0000376 char InstCombiner::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000377 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000378}
379
Chris Lattner4f98c562003-03-10 21:43:22 +0000380// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000381// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000382static unsigned getComplexity(Value *V) {
383 if (isa<Instruction>(V)) {
384 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000385 return 3;
386 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000387 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000388 if (isa<Argument>(V)) return 3;
389 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000390}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000391
Chris Lattnerc8802d22003-03-11 00:12:48 +0000392// isOnlyUse - Return true if this instruction will be deleted if we stop using
393// it.
394static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000395 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000396}
397
Chris Lattner4cb170c2004-02-23 06:38:22 +0000398// getPromotedType - Return the specified type promoted as it would be to pass
399// though a va_arg area...
400static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000401 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
402 if (ITy->getBitWidth() < 32)
403 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000404 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000405 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000406}
407
Reid Spencer3da59db2006-11-27 01:05:10 +0000408/// getBitCastOperand - If the specified operand is a CastInst or a constant
409/// expression bitcast, return the operand value, otherwise return null.
410static Value *getBitCastOperand(Value *V) {
411 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000412 return I->getOperand(0);
413 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000414 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000415 return CE->getOperand(0);
416 return 0;
417}
418
Reid Spencer3da59db2006-11-27 01:05:10 +0000419/// This function is a wrapper around CastInst::isEliminableCastPair. It
420/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000421static Instruction::CastOps
422isEliminableCastPair(
423 const CastInst *CI, ///< The first cast instruction
424 unsigned opcode, ///< The opcode of the second cast instruction
425 const Type *DstTy, ///< The target type for the second cast instruction
426 TargetData *TD ///< The target data for pointer size
427) {
428
429 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
430 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000431
Reid Spencer3da59db2006-11-27 01:05:10 +0000432 // Get the opcodes of the two Cast instructions
433 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
434 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000435
Reid Spencer3da59db2006-11-27 01:05:10 +0000436 return Instruction::CastOps(
437 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
438 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000439}
440
441/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
442/// in any code being generated. It does not require codegen if V is simple
443/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000444static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
445 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000446 if (V->getType() == Ty || isa<Constant>(V)) return false;
447
Chris Lattner01575b72006-05-25 23:24:33 +0000448 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000449 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000450 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000451 return false;
452 return true;
453}
454
455/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
456/// InsertBefore instruction. This is specialized a bit to avoid inserting
457/// casts that are known to not do anything...
458///
Reid Spencer17212df2006-12-12 09:18:51 +0000459Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
460 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000461 Instruction *InsertBefore) {
462 if (V->getType() == DestTy) return V;
463 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000464 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000465
Reid Spencer17212df2006-12-12 09:18:51 +0000466 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000467}
468
Chris Lattner4f98c562003-03-10 21:43:22 +0000469// SimplifyCommutative - This performs a few simplifications for commutative
470// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000471//
Chris Lattner4f98c562003-03-10 21:43:22 +0000472// 1. Order operands such that they are listed from right (least complex) to
473// left (most complex). This puts constants before unary operators before
474// binary operators.
475//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000476// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
477// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000478//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000479bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000480 bool Changed = false;
481 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
482 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000483
Chris Lattner4f98c562003-03-10 21:43:22 +0000484 if (!I.isAssociative()) return Changed;
485 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000486 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
487 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
488 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000489 Constant *Folded = ConstantExpr::get(I.getOpcode(),
490 cast<Constant>(I.getOperand(1)),
491 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000492 I.setOperand(0, Op->getOperand(0));
493 I.setOperand(1, Folded);
494 return true;
495 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
496 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
497 isOnlyUse(Op) && isOnlyUse(Op1)) {
498 Constant *C1 = cast<Constant>(Op->getOperand(1));
499 Constant *C2 = cast<Constant>(Op1->getOperand(1));
500
501 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000502 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000503 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
504 Op1->getOperand(0),
505 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000506 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000507 I.setOperand(0, New);
508 I.setOperand(1, Folded);
509 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000510 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000511 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000512 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000513}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000514
Reid Spencere4d87aa2006-12-23 06:05:41 +0000515/// SimplifyCompare - For a CmpInst this function just orders the operands
516/// so that theyare listed from right (least complex) to left (most complex).
517/// This puts constants before unary operators before binary operators.
518bool InstCombiner::SimplifyCompare(CmpInst &I) {
519 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
520 return false;
521 I.swapOperands();
522 // Compare instructions are not associative so there's nothing else we can do.
523 return true;
524}
525
Chris Lattner8d969642003-03-10 23:06:50 +0000526// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
527// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000528//
Chris Lattner8d969642003-03-10 23:06:50 +0000529static inline Value *dyn_castNegVal(Value *V) {
530 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000531 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000532
Chris Lattner0ce85802004-12-14 20:08:06 +0000533 // Constants can be considered to be negated values if they can be folded.
534 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
535 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000536 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000537}
538
Chris Lattner8d969642003-03-10 23:06:50 +0000539static inline Value *dyn_castNotVal(Value *V) {
540 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000541 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000542
543 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000544 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000545 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000546 return 0;
547}
548
Chris Lattnerc8802d22003-03-11 00:12:48 +0000549// dyn_castFoldableMul - If this value is a multiply that can be folded into
550// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000551// non-constant operand of the multiply, and set CST to point to the multiplier.
552// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000553//
Chris Lattner50af16a2004-11-13 19:50:12 +0000554static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000555 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000556 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000557 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000558 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000559 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000560 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000561 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000562 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000563 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000564 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000565 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000566 return I->getOperand(0);
567 }
568 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000569 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000570}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000571
Chris Lattner574da9b2005-01-13 20:14:25 +0000572/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
573/// expression, return it.
574static User *dyn_castGetElementPtr(Value *V) {
575 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
576 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
577 if (CE->getOpcode() == Instruction::GetElementPtr)
578 return cast<User>(V);
579 return false;
580}
581
Reid Spencer7177c3a2007-03-25 05:33:51 +0000582/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000583static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000584 APInt Val(C->getValue());
585 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000586}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000587/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000588static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000589 APInt Val(C->getValue());
590 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000591}
592/// Add - Add two ConstantInts together
593static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
594 return ConstantInt::get(C1->getValue() + C2->getValue());
595}
596/// And - Bitwise AND two ConstantInts together
597static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
598 return ConstantInt::get(C1->getValue() & C2->getValue());
599}
600/// Subtract - Subtract one ConstantInt from another
601static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
602 return ConstantInt::get(C1->getValue() - C2->getValue());
603}
604/// Multiply - Multiply two ConstantInts together
605static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
606 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000607}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000608/// MultiplyOverflows - True if the multiply can not be expressed in an int
609/// this size.
610static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
611 uint32_t W = C1->getBitWidth();
612 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
613 if (sign) {
614 LHSExt.sext(W * 2);
615 RHSExt.sext(W * 2);
616 } else {
617 LHSExt.zext(W * 2);
618 RHSExt.zext(W * 2);
619 }
620
621 APInt MulExt = LHSExt * RHSExt;
622
623 if (sign) {
624 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
625 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
626 return MulExt.slt(Min) || MulExt.sgt(Max);
627 } else
628 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
629}
Chris Lattner955f3312004-09-28 21:48:02 +0000630
Chris Lattner68d5ff22006-02-09 07:38:58 +0000631/// ComputeMaskedBits - Determine which of the bits specified in Mask are
632/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000633/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
634/// processing.
635/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
636/// we cannot optimize based on the assumption that it is zero without changing
637/// it to be an explicit zero. If we don't change it to zero, other code could
638/// optimized based on the contradictory assumption that it is non-zero.
639/// Because instcombine aggressively folds operations with undef args anyway,
640/// this won't lose us code quality.
Reid Spencer55702aa2007-03-25 21:11:44 +0000641static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spencer3e7594f2007-03-08 01:46:38 +0000642 APInt& KnownOne, unsigned Depth = 0) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000643 assert(V && "No Value?");
644 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000645 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000646 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000647 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000648 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000649 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000650 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
651 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000652 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000653 KnownZero = ~KnownOne & Mask;
654 return;
655 }
656
Reid Spencer3e7594f2007-03-08 01:46:38 +0000657 if (Depth == 6 || Mask == 0)
658 return; // Limit search depth.
659
660 Instruction *I = dyn_cast<Instruction>(V);
661 if (!I) return;
662
Zhou Sheng771dbf72007-03-13 02:23:10 +0000663 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000664 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000665
666 switch (I->getOpcode()) {
Reid Spencer2b812072007-03-25 02:03:12 +0000667 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000668 // If either the LHS or the RHS are Zero, the result is zero.
669 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000670 APInt Mask2(Mask & ~KnownZero);
671 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000672 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
673 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
674
675 // Output known-1 bits are only known if set in both the LHS & RHS.
676 KnownOne &= KnownOne2;
677 // Output known-0 are known to be clear if zero in either the LHS | RHS.
678 KnownZero |= KnownZero2;
679 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000680 }
681 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000682 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000683 APInt Mask2(Mask & ~KnownOne);
684 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000685 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
686 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
687
688 // Output known-0 bits are only known if clear in both the LHS & RHS.
689 KnownZero &= KnownZero2;
690 // Output known-1 are known to be set if set in either the LHS | RHS.
691 KnownOne |= KnownOne2;
692 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000693 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000694 case Instruction::Xor: {
695 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
696 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
697 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
698 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
699
700 // Output known-0 bits are known if clear or set in both the LHS & RHS.
701 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
702 // Output known-1 are known to be set if set in only one of the LHS, RHS.
703 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
704 KnownZero = KnownZeroOut;
705 return;
706 }
707 case Instruction::Select:
708 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
709 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
710 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
711 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
712
713 // Only known if known in both the LHS and RHS.
714 KnownOne &= KnownOne2;
715 KnownZero &= KnownZero2;
716 return;
717 case Instruction::FPTrunc:
718 case Instruction::FPExt:
719 case Instruction::FPToUI:
720 case Instruction::FPToSI:
721 case Instruction::SIToFP:
722 case Instruction::PtrToInt:
723 case Instruction::UIToFP:
724 case Instruction::IntToPtr:
725 return; // Can't work with floating point or pointers
Zhou Sheng771dbf72007-03-13 02:23:10 +0000726 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000727 // All these have integer operands
Zhou Sheng771dbf72007-03-13 02:23:10 +0000728 uint32_t SrcBitWidth =
729 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000730 APInt MaskIn(Mask);
731 MaskIn.zext(SrcBitWidth);
732 KnownZero.zext(SrcBitWidth);
733 KnownOne.zext(SrcBitWidth);
734 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Sheng771dbf72007-03-13 02:23:10 +0000735 KnownZero.trunc(BitWidth);
736 KnownOne.trunc(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000737 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000738 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000739 case Instruction::BitCast: {
740 const Type *SrcTy = I->getOperand(0)->getType();
741 if (SrcTy->isInteger()) {
742 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
743 return;
744 }
745 break;
746 }
747 case Instruction::ZExt: {
748 // Compute the bits in the result that are not present in the input.
749 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000750 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000751
Zhou Shengaa305ab2007-03-28 02:19:03 +0000752 APInt MaskIn(Mask);
753 MaskIn.trunc(SrcBitWidth);
754 KnownZero.trunc(SrcBitWidth);
755 KnownOne.trunc(SrcBitWidth);
756 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000757 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
758 // The top bits are known to be zero.
Zhou Sheng771dbf72007-03-13 02:23:10 +0000759 KnownZero.zext(BitWidth);
760 KnownOne.zext(BitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000761 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000762 return;
763 }
764 case Instruction::SExt: {
765 // Compute the bits in the result that are not present in the input.
766 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000767 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000768
Zhou Shengaa305ab2007-03-28 02:19:03 +0000769 APInt MaskIn(Mask);
770 MaskIn.trunc(SrcBitWidth);
771 KnownZero.trunc(SrcBitWidth);
772 KnownOne.trunc(SrcBitWidth);
773 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000774 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000775 KnownZero.zext(BitWidth);
776 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000777
778 // If the sign bit of the input is known set or clear, then we know the
779 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000780 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000781 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000782 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000783 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000784 return;
785 }
786 case Instruction::Shl:
787 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
788 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000789 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000790 APInt Mask2(Mask.lshr(ShiftAmt));
791 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000792 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000793 KnownZero <<= ShiftAmt;
794 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000795 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000796 return;
797 }
798 break;
799 case Instruction::LShr:
800 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
801 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
802 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000803 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000804
805 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000806 APInt Mask2(Mask.shl(ShiftAmt));
807 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000808 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
809 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
810 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000811 // high bits known zero.
812 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000813 return;
814 }
815 break;
816 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000817 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000818 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
819 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000820 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000821
822 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000823 APInt Mask2(Mask.shl(ShiftAmt));
824 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000825 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
826 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
827 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
828
Zhou Shengaa305ab2007-03-28 02:19:03 +0000829 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
830 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000831 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000832 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000833 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000834 return;
835 }
836 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000837 case Instruction::SRem:
838 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
839 APInt RA = Rem->getValue();
840 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
841 APInt LowBits = RA.isStrictlyPositive() ? ((RA - 1) | RA) : ~RA;
842 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
843 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
844
845 // The sign of a remainder is equal to the sign of the first
846 // operand (zero being positive).
847 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
848 KnownZero2 |= ~LowBits;
849 else if (KnownOne2[BitWidth-1])
850 KnownOne2 |= ~LowBits;
851
852 KnownZero |= KnownZero2 & Mask;
853 KnownOne |= KnownOne2 & Mask;
854
855 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
856 }
857 }
858 break;
859 case Instruction::URem:
860 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
861 APInt RA = Rem->getValue();
862 if (RA.isStrictlyPositive() && RA.isPowerOf2()) {
863 APInt LowBits = (RA - 1) | RA;
864 APInt Mask2 = LowBits & Mask;
865 KnownZero |= ~LowBits & Mask;
866 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
867 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
868 }
869 } else {
870 // Since the result is less than or equal to RHS, any leading zero bits
871 // in RHS must also exist in the result.
872 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
873 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2, Depth+1);
874
875 uint32_t Leaders = KnownZero2.countLeadingOnes();
876 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
877 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
878 }
879 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000880 }
881}
882
Reid Spencere7816b52007-03-08 01:52:58 +0000883/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
884/// this predicate to simplify operations downstream. Mask is known to be zero
885/// for bits that V cannot have.
886static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengedd089c2007-03-12 16:54:56 +0000887 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +0000888 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
889 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
890 return (KnownZero & Mask) == Mask;
891}
892
Chris Lattner255d8912006-02-11 09:31:47 +0000893/// ShrinkDemandedConstant - Check to see if the specified operand of the
894/// specified instruction is a constant integer. If so, check to see if there
895/// are any bits set in the constant that are not demanded. If so, shrink the
896/// constant and return true.
897static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000898 APInt Demanded) {
899 assert(I && "No instruction?");
900 assert(OpNo < I->getNumOperands() && "Operand index too large");
901
902 // If the operand is not a constant integer, nothing to do.
903 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
904 if (!OpC) return false;
905
906 // If there are no bits set that aren't demanded, nothing to do.
907 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
908 if ((~Demanded & OpC->getValue()) == 0)
909 return false;
910
911 // This instruction is producing bits that are not demanded. Shrink the RHS.
912 Demanded &= OpC->getValue();
913 I->setOperand(OpNo, ConstantInt::get(Demanded));
914 return true;
915}
916
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000917// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
918// set of known zero and one bits, compute the maximum and minimum values that
919// could have the specified known zero and known one bits, returning them in
920// min/max.
921static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000922 const APInt& KnownZero,
923 const APInt& KnownOne,
924 APInt& Min, APInt& Max) {
925 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
926 assert(KnownZero.getBitWidth() == BitWidth &&
927 KnownOne.getBitWidth() == BitWidth &&
928 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
929 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000930 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000931
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000932 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
933 // bit if it is unknown.
934 Min = KnownOne;
935 Max = KnownOne|UnknownBits;
936
Zhou Sheng4acf1552007-03-28 05:15:57 +0000937 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000938 Min.set(BitWidth-1);
939 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000940 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000941}
942
943// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
944// a set of known zero and one bits, compute the maximum and minimum values that
945// could have the specified known zero and known one bits, returning them in
946// min/max.
947static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000948 const APInt &KnownZero,
949 const APInt &KnownOne,
950 APInt &Min, APInt &Max) {
951 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000952 assert(KnownZero.getBitWidth() == BitWidth &&
953 KnownOne.getBitWidth() == BitWidth &&
954 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
955 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000956 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000957
958 // The minimum value is when the unknown bits are all zeros.
959 Min = KnownOne;
960 // The maximum value is when the unknown bits are all ones.
961 Max = KnownOne|UnknownBits;
962}
Chris Lattner255d8912006-02-11 09:31:47 +0000963
Reid Spencer8cb68342007-03-12 17:25:59 +0000964/// SimplifyDemandedBits - This function attempts to replace V with a simpler
965/// value based on the demanded bits. When this function is called, it is known
966/// that only the bits set in DemandedMask of the result of V are ever used
967/// downstream. Consequently, depending on the mask and V, it may be possible
968/// to replace V with a constant or one of its operands. In such cases, this
969/// function does the replacement and returns true. In all other cases, it
970/// returns false after analyzing the expression and setting KnownOne and known
971/// to be one in the expression. KnownZero contains all the bits that are known
972/// to be zero in the expression. These are provided to potentially allow the
973/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
974/// the expression. KnownOne and KnownZero always follow the invariant that
975/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
976/// the bits in KnownOne and KnownZero may only be accurate for those bits set
977/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
978/// and KnownOne must all be the same.
979bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
980 APInt& KnownZero, APInt& KnownOne,
981 unsigned Depth) {
982 assert(V != 0 && "Null pointer of Value???");
983 assert(Depth <= 6 && "Limit Search Depth");
984 uint32_t BitWidth = DemandedMask.getBitWidth();
985 const IntegerType *VTy = cast<IntegerType>(V->getType());
986 assert(VTy->getBitWidth() == BitWidth &&
987 KnownZero.getBitWidth() == BitWidth &&
988 KnownOne.getBitWidth() == BitWidth &&
989 "Value *V, DemandedMask, KnownZero and KnownOne \
990 must have same BitWidth");
991 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
992 // We know all of the bits for a constant!
993 KnownOne = CI->getValue() & DemandedMask;
994 KnownZero = ~KnownOne & DemandedMask;
995 return false;
996 }
997
Zhou Sheng96704452007-03-14 03:21:24 +0000998 KnownZero.clear();
999 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001000 if (!V->hasOneUse()) { // Other users may use these bits.
1001 if (Depth != 0) { // Not at the root.
1002 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1003 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1004 return false;
1005 }
1006 // If this is the root being simplified, allow it to have multiple uses,
1007 // just set the DemandedMask to all bits.
1008 DemandedMask = APInt::getAllOnesValue(BitWidth);
1009 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1010 if (V != UndefValue::get(VTy))
1011 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1012 return false;
1013 } else if (Depth == 6) { // Limit search depth.
1014 return false;
1015 }
1016
1017 Instruction *I = dyn_cast<Instruction>(V);
1018 if (!I) return false; // Only analyze instructions.
1019
Reid Spencer8cb68342007-03-12 17:25:59 +00001020 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1021 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1022 switch (I->getOpcode()) {
1023 default: break;
1024 case Instruction::And:
1025 // If either the LHS or the RHS are Zero, the result is zero.
1026 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1027 RHSKnownZero, RHSKnownOne, Depth+1))
1028 return true;
1029 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1030 "Bits known to be one AND zero?");
1031
1032 // If something is known zero on the RHS, the bits aren't demanded on the
1033 // LHS.
1034 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1035 LHSKnownZero, LHSKnownOne, Depth+1))
1036 return true;
1037 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1038 "Bits known to be one AND zero?");
1039
1040 // If all of the demanded bits are known 1 on one side, return the other.
1041 // These bits cannot contribute to the result of the 'and'.
1042 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1043 (DemandedMask & ~LHSKnownZero))
1044 return UpdateValueUsesWith(I, I->getOperand(0));
1045 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1046 (DemandedMask & ~RHSKnownZero))
1047 return UpdateValueUsesWith(I, I->getOperand(1));
1048
1049 // If all of the demanded bits in the inputs are known zeros, return zero.
1050 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1051 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1052
1053 // If the RHS is a constant, see if we can simplify it.
1054 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1055 return UpdateValueUsesWith(I, I);
1056
1057 // Output known-1 bits are only known if set in both the LHS & RHS.
1058 RHSKnownOne &= LHSKnownOne;
1059 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1060 RHSKnownZero |= LHSKnownZero;
1061 break;
1062 case Instruction::Or:
1063 // If either the LHS or the RHS are One, the result is One.
1064 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1065 RHSKnownZero, RHSKnownOne, Depth+1))
1066 return true;
1067 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1068 "Bits known to be one AND zero?");
1069 // If something is known one on the RHS, the bits aren't demanded on the
1070 // LHS.
1071 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1072 LHSKnownZero, LHSKnownOne, Depth+1))
1073 return true;
1074 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1075 "Bits known to be one AND zero?");
1076
1077 // If all of the demanded bits are known zero on one side, return the other.
1078 // These bits cannot contribute to the result of the 'or'.
1079 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1080 (DemandedMask & ~LHSKnownOne))
1081 return UpdateValueUsesWith(I, I->getOperand(0));
1082 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1083 (DemandedMask & ~RHSKnownOne))
1084 return UpdateValueUsesWith(I, I->getOperand(1));
1085
1086 // If all of the potentially set bits on one side are known to be set on
1087 // the other side, just use the 'other' side.
1088 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1089 (DemandedMask & (~RHSKnownZero)))
1090 return UpdateValueUsesWith(I, I->getOperand(0));
1091 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1092 (DemandedMask & (~LHSKnownZero)))
1093 return UpdateValueUsesWith(I, I->getOperand(1));
1094
1095 // If the RHS is a constant, see if we can simplify it.
1096 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1097 return UpdateValueUsesWith(I, I);
1098
1099 // Output known-0 bits are only known if clear in both the LHS & RHS.
1100 RHSKnownZero &= LHSKnownZero;
1101 // Output known-1 are known to be set if set in either the LHS | RHS.
1102 RHSKnownOne |= LHSKnownOne;
1103 break;
1104 case Instruction::Xor: {
1105 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1106 RHSKnownZero, RHSKnownOne, Depth+1))
1107 return true;
1108 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1109 "Bits known to be one AND zero?");
1110 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1111 LHSKnownZero, LHSKnownOne, Depth+1))
1112 return true;
1113 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1114 "Bits known to be one AND zero?");
1115
1116 // If all of the demanded bits are known zero on one side, return the other.
1117 // These bits cannot contribute to the result of the 'xor'.
1118 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1119 return UpdateValueUsesWith(I, I->getOperand(0));
1120 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1121 return UpdateValueUsesWith(I, I->getOperand(1));
1122
1123 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1124 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1125 (RHSKnownOne & LHSKnownOne);
1126 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1127 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1128 (RHSKnownOne & LHSKnownZero);
1129
1130 // If all of the demanded bits are known to be zero on one side or the
1131 // other, turn this into an *inclusive* or.
1132 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1133 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1134 Instruction *Or =
1135 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1136 I->getName());
1137 InsertNewInstBefore(Or, *I);
1138 return UpdateValueUsesWith(I, Or);
1139 }
1140
1141 // If all of the demanded bits on one side are known, and all of the set
1142 // bits on that side are also known to be set on the other side, turn this
1143 // into an AND, as we know the bits will be cleared.
1144 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1145 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1146 // all known
1147 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1148 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1149 Instruction *And =
1150 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1151 InsertNewInstBefore(And, *I);
1152 return UpdateValueUsesWith(I, And);
1153 }
1154 }
1155
1156 // If the RHS is a constant, see if we can simplify it.
1157 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1158 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1159 return UpdateValueUsesWith(I, I);
1160
1161 RHSKnownZero = KnownZeroOut;
1162 RHSKnownOne = KnownOneOut;
1163 break;
1164 }
1165 case Instruction::Select:
1166 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1167 RHSKnownZero, RHSKnownOne, Depth+1))
1168 return true;
1169 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1170 LHSKnownZero, LHSKnownOne, Depth+1))
1171 return true;
1172 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1173 "Bits known to be one AND zero?");
1174 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1175 "Bits known to be one AND zero?");
1176
1177 // If the operands are constants, see if we can simplify them.
1178 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1179 return UpdateValueUsesWith(I, I);
1180 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1181 return UpdateValueUsesWith(I, I);
1182
1183 // Only known if known in both the LHS and RHS.
1184 RHSKnownOne &= LHSKnownOne;
1185 RHSKnownZero &= LHSKnownZero;
1186 break;
1187 case Instruction::Trunc: {
1188 uint32_t truncBf =
1189 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001190 DemandedMask.zext(truncBf);
1191 RHSKnownZero.zext(truncBf);
1192 RHSKnownOne.zext(truncBf);
1193 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1194 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001195 return true;
1196 DemandedMask.trunc(BitWidth);
1197 RHSKnownZero.trunc(BitWidth);
1198 RHSKnownOne.trunc(BitWidth);
1199 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1200 "Bits known to be one AND zero?");
1201 break;
1202 }
1203 case Instruction::BitCast:
1204 if (!I->getOperand(0)->getType()->isInteger())
1205 return false;
1206
1207 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1208 RHSKnownZero, RHSKnownOne, Depth+1))
1209 return true;
1210 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1211 "Bits known to be one AND zero?");
1212 break;
1213 case Instruction::ZExt: {
1214 // Compute the bits in the result that are not present in the input.
1215 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001216 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001217
Zhou Shengd48653a2007-03-29 04:45:55 +00001218 DemandedMask.trunc(SrcBitWidth);
1219 RHSKnownZero.trunc(SrcBitWidth);
1220 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001221 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1222 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001223 return true;
1224 DemandedMask.zext(BitWidth);
1225 RHSKnownZero.zext(BitWidth);
1226 RHSKnownOne.zext(BitWidth);
1227 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1228 "Bits known to be one AND zero?");
1229 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001230 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001231 break;
1232 }
1233 case Instruction::SExt: {
1234 // Compute the bits in the result that are not present in the input.
1235 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001236 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001237
Reid Spencer8cb68342007-03-12 17:25:59 +00001238 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001239 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001240
Zhou Sheng01542f32007-03-29 02:26:30 +00001241 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001242 // If any of the sign extended bits are demanded, we know that the sign
1243 // bit is demanded.
1244 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001245 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001246
Zhou Shengd48653a2007-03-29 04:45:55 +00001247 InputDemandedBits.trunc(SrcBitWidth);
1248 RHSKnownZero.trunc(SrcBitWidth);
1249 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001250 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1251 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001252 return true;
1253 InputDemandedBits.zext(BitWidth);
1254 RHSKnownZero.zext(BitWidth);
1255 RHSKnownOne.zext(BitWidth);
1256 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1257 "Bits known to be one AND zero?");
1258
1259 // If the sign bit of the input is known set or clear, then we know the
1260 // top bits of the result.
1261
1262 // If the input sign bit is known zero, or if the NewBits are not demanded
1263 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001264 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001265 {
1266 // Convert to ZExt cast
1267 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1268 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001269 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001270 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001271 }
1272 break;
1273 }
1274 case Instruction::Add: {
1275 // Figure out what the input bits are. If the top bits of the and result
1276 // are not demanded, then the add doesn't demand them from its input
1277 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001278 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001279
1280 // If there is a constant on the RHS, there are a variety of xformations
1281 // we can do.
1282 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1283 // If null, this should be simplified elsewhere. Some of the xforms here
1284 // won't work if the RHS is zero.
1285 if (RHS->isZero())
1286 break;
1287
1288 // If the top bit of the output is demanded, demand everything from the
1289 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001290 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001291
1292 // Find information about known zero/one bits in the input.
1293 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1294 LHSKnownZero, LHSKnownOne, Depth+1))
1295 return true;
1296
1297 // If the RHS of the add has bits set that can't affect the input, reduce
1298 // the constant.
1299 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1300 return UpdateValueUsesWith(I, I);
1301
1302 // Avoid excess work.
1303 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1304 break;
1305
1306 // Turn it into OR if input bits are zero.
1307 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1308 Instruction *Or =
1309 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1310 I->getName());
1311 InsertNewInstBefore(Or, *I);
1312 return UpdateValueUsesWith(I, Or);
1313 }
1314
1315 // We can say something about the output known-zero and known-one bits,
1316 // depending on potential carries from the input constant and the
1317 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1318 // bits set and the RHS constant is 0x01001, then we know we have a known
1319 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1320
1321 // To compute this, we first compute the potential carry bits. These are
1322 // the bits which may be modified. I'm not aware of a better way to do
1323 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001324 const APInt& RHSVal = RHS->getValue();
1325 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001326
1327 // Now that we know which bits have carries, compute the known-1/0 sets.
1328
1329 // Bits are known one if they are known zero in one operand and one in the
1330 // other, and there is no input carry.
1331 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1332 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1333
1334 // Bits are known zero if they are known zero in both operands and there
1335 // is no input carry.
1336 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1337 } else {
1338 // If the high-bits of this ADD are not demanded, then it does not demand
1339 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001340 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001341 // Right fill the mask of bits for this ADD to demand the most
1342 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001343 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001344 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1345 LHSKnownZero, LHSKnownOne, Depth+1))
1346 return true;
1347 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1348 LHSKnownZero, LHSKnownOne, Depth+1))
1349 return true;
1350 }
1351 }
1352 break;
1353 }
1354 case Instruction::Sub:
1355 // If the high-bits of this SUB are not demanded, then it does not demand
1356 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001357 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001358 // Right fill the mask of bits for this SUB to demand the most
1359 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001360 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001361 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001362 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1363 LHSKnownZero, LHSKnownOne, Depth+1))
1364 return true;
1365 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1366 LHSKnownZero, LHSKnownOne, Depth+1))
1367 return true;
1368 }
1369 break;
1370 case Instruction::Shl:
1371 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001372 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001373 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1374 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001375 RHSKnownZero, RHSKnownOne, Depth+1))
1376 return true;
1377 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1378 "Bits known to be one AND zero?");
1379 RHSKnownZero <<= ShiftAmt;
1380 RHSKnownOne <<= ShiftAmt;
1381 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001382 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001383 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001384 }
1385 break;
1386 case Instruction::LShr:
1387 // For a logical shift right
1388 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001389 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001390
Reid Spencer8cb68342007-03-12 17:25:59 +00001391 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001392 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1393 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001394 RHSKnownZero, RHSKnownOne, Depth+1))
1395 return true;
1396 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1397 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001398 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1399 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001400 if (ShiftAmt) {
1401 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001402 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001403 RHSKnownZero |= HighBits; // high bits known zero.
1404 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001405 }
1406 break;
1407 case Instruction::AShr:
1408 // If this is an arithmetic shift right and only the low-bit is set, we can
1409 // always convert this into a logical shr, even if the shift amount is
1410 // variable. The low bit of the shift cannot be an input sign bit unless
1411 // the shift amount is >= the size of the datatype, which is undefined.
1412 if (DemandedMask == 1) {
1413 // Perform the logical shift right.
1414 Value *NewVal = BinaryOperator::createLShr(
1415 I->getOperand(0), I->getOperand(1), I->getName());
1416 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1417 return UpdateValueUsesWith(I, NewVal);
1418 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001419
1420 // If the sign bit is the only bit demanded by this ashr, then there is no
1421 // need to do it, the shift doesn't change the high bit.
1422 if (DemandedMask.isSignBit())
1423 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001424
1425 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001426 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001427
Reid Spencer8cb68342007-03-12 17:25:59 +00001428 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001429 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001430 // If any of the "high bits" are demanded, we should set the sign bit as
1431 // demanded.
1432 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1433 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001434 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001435 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001436 RHSKnownZero, RHSKnownOne, Depth+1))
1437 return true;
1438 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1439 "Bits known to be one AND zero?");
1440 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001441 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001442 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1443 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1444
1445 // Handle the sign bits.
1446 APInt SignBit(APInt::getSignBit(BitWidth));
1447 // Adjust to where it is now in the mask.
1448 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1449
1450 // If the input sign bit is known to be zero, or if none of the top bits
1451 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001452 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001453 (HighBits & ~DemandedMask) == HighBits) {
1454 // Perform the logical shift right.
1455 Value *NewVal = BinaryOperator::createLShr(
1456 I->getOperand(0), SA, I->getName());
1457 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1458 return UpdateValueUsesWith(I, NewVal);
1459 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1460 RHSKnownOne |= HighBits;
1461 }
1462 }
1463 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001464 case Instruction::SRem:
1465 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1466 APInt RA = Rem->getValue();
1467 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1468 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) | RA : ~RA;
1469 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1470 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1471 LHSKnownZero, LHSKnownOne, Depth+1))
1472 return true;
1473
1474 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1475 LHSKnownZero |= ~LowBits;
1476 else if (LHSKnownOne[BitWidth-1])
1477 LHSKnownOne |= ~LowBits;
1478
1479 KnownZero |= LHSKnownZero & DemandedMask;
1480 KnownOne |= LHSKnownOne & DemandedMask;
1481
1482 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1483 }
1484 }
1485 break;
1486 case Instruction::URem:
1487 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1488 APInt RA = Rem->getValue();
1489 if (RA.isPowerOf2()) {
1490 APInt LowBits = (RA - 1) | RA;
1491 APInt Mask2 = LowBits & DemandedMask;
1492 KnownZero |= ~LowBits & DemandedMask;
1493 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1494 KnownZero, KnownOne, Depth+1))
1495 return true;
1496
1497 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1498 }
1499 } else {
1500 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1501 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1502 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1503 KnownZero2, KnownOne2, Depth+1))
1504 return true;
1505
1506 uint32_t Leaders = KnownZero2.countLeadingOnes();
1507 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1508 }
1509 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001510 }
1511
1512 // If the client is only demanding bits that we know, return the known
1513 // constant.
1514 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1515 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1516 return false;
1517}
1518
Chris Lattner867b99f2006-10-05 06:55:50 +00001519
1520/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1521/// 64 or fewer elements. DemandedElts contains the set of elements that are
1522/// actually used by the caller. This method analyzes which elements of the
1523/// operand are undef and returns that information in UndefElts.
1524///
1525/// If the information about demanded elements can be used to simplify the
1526/// operation, the operation is simplified, then the resultant value is
1527/// returned. This returns null if no change was made.
1528Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1529 uint64_t &UndefElts,
1530 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001531 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001532 assert(VWidth <= 64 && "Vector too wide to analyze!");
1533 uint64_t EltMask = ~0ULL >> (64-VWidth);
1534 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1535 "Invalid DemandedElts!");
1536
1537 if (isa<UndefValue>(V)) {
1538 // If the entire vector is undefined, just return this info.
1539 UndefElts = EltMask;
1540 return 0;
1541 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1542 UndefElts = EltMask;
1543 return UndefValue::get(V->getType());
1544 }
1545
1546 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001547 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1548 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001549 Constant *Undef = UndefValue::get(EltTy);
1550
1551 std::vector<Constant*> Elts;
1552 for (unsigned i = 0; i != VWidth; ++i)
1553 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1554 Elts.push_back(Undef);
1555 UndefElts |= (1ULL << i);
1556 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1557 Elts.push_back(Undef);
1558 UndefElts |= (1ULL << i);
1559 } else { // Otherwise, defined.
1560 Elts.push_back(CP->getOperand(i));
1561 }
1562
1563 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001564 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001565 return NewCP != CP ? NewCP : 0;
1566 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001567 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001568 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001569 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001570 Constant *Zero = Constant::getNullValue(EltTy);
1571 Constant *Undef = UndefValue::get(EltTy);
1572 std::vector<Constant*> Elts;
1573 for (unsigned i = 0; i != VWidth; ++i)
1574 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1575 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001576 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001577 }
1578
1579 if (!V->hasOneUse()) { // Other users may use these bits.
1580 if (Depth != 0) { // Not at the root.
1581 // TODO: Just compute the UndefElts information recursively.
1582 return false;
1583 }
1584 return false;
1585 } else if (Depth == 10) { // Limit search depth.
1586 return false;
1587 }
1588
1589 Instruction *I = dyn_cast<Instruction>(V);
1590 if (!I) return false; // Only analyze instructions.
1591
1592 bool MadeChange = false;
1593 uint64_t UndefElts2;
1594 Value *TmpV;
1595 switch (I->getOpcode()) {
1596 default: break;
1597
1598 case Instruction::InsertElement: {
1599 // If this is a variable index, we don't know which element it overwrites.
1600 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001601 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001602 if (Idx == 0) {
1603 // Note that we can't propagate undef elt info, because we don't know
1604 // which elt is getting updated.
1605 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1606 UndefElts2, Depth+1);
1607 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1608 break;
1609 }
1610
1611 // If this is inserting an element that isn't demanded, remove this
1612 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001613 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001614 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1615 return AddSoonDeadInstToWorklist(*I, 0);
1616
1617 // Otherwise, the element inserted overwrites whatever was there, so the
1618 // input demanded set is simpler than the output set.
1619 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1620 DemandedElts & ~(1ULL << IdxNo),
1621 UndefElts, Depth+1);
1622 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1623
1624 // The inserted element is defined.
1625 UndefElts |= 1ULL << IdxNo;
1626 break;
1627 }
Chris Lattner69878332007-04-14 22:29:23 +00001628 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001629 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001630 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1631 if (!VTy) break;
1632 unsigned InVWidth = VTy->getNumElements();
1633 uint64_t InputDemandedElts = 0;
1634 unsigned Ratio;
1635
1636 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001637 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001638 // elements as are demanded of us.
1639 Ratio = 1;
1640 InputDemandedElts = DemandedElts;
1641 } else if (VWidth > InVWidth) {
1642 // Untested so far.
1643 break;
1644
1645 // If there are more elements in the result than there are in the source,
1646 // then an input element is live if any of the corresponding output
1647 // elements are live.
1648 Ratio = VWidth/InVWidth;
1649 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1650 if (DemandedElts & (1ULL << OutIdx))
1651 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1652 }
1653 } else {
1654 // Untested so far.
1655 break;
1656
1657 // If there are more elements in the source than there are in the result,
1658 // then an input element is live if the corresponding output element is
1659 // live.
1660 Ratio = InVWidth/VWidth;
1661 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1662 if (DemandedElts & (1ULL << InIdx/Ratio))
1663 InputDemandedElts |= 1ULL << InIdx;
1664 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001665
Chris Lattner69878332007-04-14 22:29:23 +00001666 // div/rem demand all inputs, because they don't want divide by zero.
1667 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1668 UndefElts2, Depth+1);
1669 if (TmpV) {
1670 I->setOperand(0, TmpV);
1671 MadeChange = true;
1672 }
1673
1674 UndefElts = UndefElts2;
1675 if (VWidth > InVWidth) {
1676 assert(0 && "Unimp");
1677 // If there are more elements in the result than there are in the source,
1678 // then an output element is undef if the corresponding input element is
1679 // undef.
1680 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1681 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1682 UndefElts |= 1ULL << OutIdx;
1683 } else if (VWidth < InVWidth) {
1684 assert(0 && "Unimp");
1685 // If there are more elements in the source than there are in the result,
1686 // then a result element is undef if all of the corresponding input
1687 // elements are undef.
1688 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1689 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1690 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1691 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1692 }
1693 break;
1694 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001695 case Instruction::And:
1696 case Instruction::Or:
1697 case Instruction::Xor:
1698 case Instruction::Add:
1699 case Instruction::Sub:
1700 case Instruction::Mul:
1701 // div/rem demand all inputs, because they don't want divide by zero.
1702 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1703 UndefElts, Depth+1);
1704 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1705 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1706 UndefElts2, Depth+1);
1707 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1708
1709 // Output elements are undefined if both are undefined. Consider things
1710 // like undef&0. The result is known zero, not undef.
1711 UndefElts &= UndefElts2;
1712 break;
1713
1714 case Instruction::Call: {
1715 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1716 if (!II) break;
1717 switch (II->getIntrinsicID()) {
1718 default: break;
1719
1720 // Binary vector operations that work column-wise. A dest element is a
1721 // function of the corresponding input elements from the two inputs.
1722 case Intrinsic::x86_sse_sub_ss:
1723 case Intrinsic::x86_sse_mul_ss:
1724 case Intrinsic::x86_sse_min_ss:
1725 case Intrinsic::x86_sse_max_ss:
1726 case Intrinsic::x86_sse2_sub_sd:
1727 case Intrinsic::x86_sse2_mul_sd:
1728 case Intrinsic::x86_sse2_min_sd:
1729 case Intrinsic::x86_sse2_max_sd:
1730 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1731 UndefElts, Depth+1);
1732 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1733 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1734 UndefElts2, Depth+1);
1735 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1736
1737 // If only the low elt is demanded and this is a scalarizable intrinsic,
1738 // scalarize it now.
1739 if (DemandedElts == 1) {
1740 switch (II->getIntrinsicID()) {
1741 default: break;
1742 case Intrinsic::x86_sse_sub_ss:
1743 case Intrinsic::x86_sse_mul_ss:
1744 case Intrinsic::x86_sse2_sub_sd:
1745 case Intrinsic::x86_sse2_mul_sd:
1746 // TODO: Lower MIN/MAX/ABS/etc
1747 Value *LHS = II->getOperand(1);
1748 Value *RHS = II->getOperand(2);
1749 // Extract the element as scalars.
1750 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1751 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1752
1753 switch (II->getIntrinsicID()) {
1754 default: assert(0 && "Case stmts out of sync!");
1755 case Intrinsic::x86_sse_sub_ss:
1756 case Intrinsic::x86_sse2_sub_sd:
1757 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1758 II->getName()), *II);
1759 break;
1760 case Intrinsic::x86_sse_mul_ss:
1761 case Intrinsic::x86_sse2_mul_sd:
1762 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1763 II->getName()), *II);
1764 break;
1765 }
1766
1767 Instruction *New =
1768 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1769 II->getName());
1770 InsertNewInstBefore(New, *II);
1771 AddSoonDeadInstToWorklist(*II, 0);
1772 return New;
1773 }
1774 }
1775
1776 // Output elements are undefined if both are undefined. Consider things
1777 // like undef&0. The result is known zero, not undef.
1778 UndefElts &= UndefElts2;
1779 break;
1780 }
1781 break;
1782 }
1783 }
1784 return MadeChange ? I : 0;
1785}
1786
Nick Lewycky455e1762007-09-06 02:40:25 +00001787/// @returns true if the specified compare predicate is
Reid Spencere4d87aa2006-12-23 06:05:41 +00001788/// true when both operands are equal...
Nick Lewycky455e1762007-09-06 02:40:25 +00001789/// @brief Determine if the icmp Predicate is true when both operands are equal
1790static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001791 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1792 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1793 pred == ICmpInst::ICMP_SLE;
1794}
1795
Nick Lewycky455e1762007-09-06 02:40:25 +00001796/// @returns true if the specified compare instruction is
1797/// true when both operands are equal...
1798/// @brief Determine if the ICmpInst returns true when both operands are equal
1799static bool isTrueWhenEqual(ICmpInst &ICI) {
1800 return isTrueWhenEqual(ICI.getPredicate());
1801}
1802
Chris Lattner564a7272003-08-13 19:01:45 +00001803/// AssociativeOpt - Perform an optimization on an associative operator. This
1804/// function is designed to check a chain of associative operators for a
1805/// potential to apply a certain optimization. Since the optimization may be
1806/// applicable if the expression was reassociated, this checks the chain, then
1807/// reassociates the expression as necessary to expose the optimization
1808/// opportunity. This makes use of a special Functor, which must define
1809/// 'shouldApply' and 'apply' methods.
1810///
1811template<typename Functor>
1812Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1813 unsigned Opcode = Root.getOpcode();
1814 Value *LHS = Root.getOperand(0);
1815
1816 // Quick check, see if the immediate LHS matches...
1817 if (F.shouldApply(LHS))
1818 return F.apply(Root);
1819
1820 // Otherwise, if the LHS is not of the same opcode as the root, return.
1821 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001822 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001823 // Should we apply this transform to the RHS?
1824 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1825
1826 // If not to the RHS, check to see if we should apply to the LHS...
1827 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1828 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1829 ShouldApply = true;
1830 }
1831
1832 // If the functor wants to apply the optimization to the RHS of LHSI,
1833 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1834 if (ShouldApply) {
1835 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001836
Chris Lattner564a7272003-08-13 19:01:45 +00001837 // Now all of the instructions are in the current basic block, go ahead
1838 // and perform the reassociation.
1839 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1840
1841 // First move the selected RHS to the LHS of the root...
1842 Root.setOperand(0, LHSI->getOperand(1));
1843
1844 // Make what used to be the LHS of the root be the user of the root...
1845 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001846 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001847 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1848 return 0;
1849 }
Chris Lattner65725312004-04-16 18:08:07 +00001850 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001851 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001852 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1853 BasicBlock::iterator ARI = &Root; ++ARI;
1854 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1855 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001856
1857 // Now propagate the ExtraOperand down the chain of instructions until we
1858 // get to LHSI.
1859 while (TmpLHSI != LHSI) {
1860 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001861 // Move the instruction to immediately before the chain we are
1862 // constructing to avoid breaking dominance properties.
1863 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1864 BB->getInstList().insert(ARI, NextLHSI);
1865 ARI = NextLHSI;
1866
Chris Lattner564a7272003-08-13 19:01:45 +00001867 Value *NextOp = NextLHSI->getOperand(1);
1868 NextLHSI->setOperand(1, ExtraOperand);
1869 TmpLHSI = NextLHSI;
1870 ExtraOperand = NextOp;
1871 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001872
Chris Lattner564a7272003-08-13 19:01:45 +00001873 // Now that the instructions are reassociated, have the functor perform
1874 // the transformation...
1875 return F.apply(Root);
1876 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001877
Chris Lattner564a7272003-08-13 19:01:45 +00001878 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1879 }
1880 return 0;
1881}
1882
1883
1884// AddRHS - Implements: X + X --> X << 1
1885struct AddRHS {
1886 Value *RHS;
1887 AddRHS(Value *rhs) : RHS(rhs) {}
1888 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1889 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00001890 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00001891 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001892 }
1893};
1894
1895// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1896// iff C1&C2 == 0
1897struct AddMaskingAnd {
1898 Constant *C2;
1899 AddMaskingAnd(Constant *c) : C2(c) {}
1900 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001901 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001902 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001903 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001904 }
1905 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001906 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001907 }
1908};
1909
Chris Lattner6e7ba452005-01-01 16:22:27 +00001910static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001911 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001912 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001913 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001914 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001915
Reid Spencer3da59db2006-11-27 01:05:10 +00001916 return IC->InsertNewInstBefore(CastInst::create(
1917 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001918 }
1919
Chris Lattner2eefe512004-04-09 19:05:30 +00001920 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001921 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1922 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001923
Chris Lattner2eefe512004-04-09 19:05:30 +00001924 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1925 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001926 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1927 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001928 }
1929
1930 Value *Op0 = SO, *Op1 = ConstOperand;
1931 if (!ConstIsRHS)
1932 std::swap(Op0, Op1);
1933 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001934 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1935 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001936 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1937 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1938 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001939 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001940 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001941 abort();
1942 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001943 return IC->InsertNewInstBefore(New, I);
1944}
1945
1946// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1947// constant as the other operand, try to fold the binary operator into the
1948// select arguments. This also works for Cast instructions, which obviously do
1949// not have a second operand.
1950static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1951 InstCombiner *IC) {
1952 // Don't modify shared select instructions
1953 if (!SI->hasOneUse()) return 0;
1954 Value *TV = SI->getOperand(1);
1955 Value *FV = SI->getOperand(2);
1956
1957 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001958 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001959 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001960
Chris Lattner6e7ba452005-01-01 16:22:27 +00001961 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1962 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1963
1964 return new SelectInst(SI->getCondition(), SelectTrueVal,
1965 SelectFalseVal);
1966 }
1967 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001968}
1969
Chris Lattner4e998b22004-09-29 05:07:12 +00001970
1971/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1972/// node as operand #0, see if we can fold the instruction into the PHI (which
1973/// is only possible if all operands to the PHI are constants).
1974Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1975 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001976 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001977 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001978
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001979 // Check to see if all of the operands of the PHI are constants. If there is
1980 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001981 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001982 BasicBlock *NonConstBB = 0;
1983 for (unsigned i = 0; i != NumPHIValues; ++i)
1984 if (!isa<Constant>(PN->getIncomingValue(i))) {
1985 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001986 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001987 NonConstBB = PN->getIncomingBlock(i);
1988
1989 // If the incoming non-constant value is in I's block, we have an infinite
1990 // loop.
1991 if (NonConstBB == I.getParent())
1992 return 0;
1993 }
1994
1995 // If there is exactly one non-constant value, we can insert a copy of the
1996 // operation in that block. However, if this is a critical edge, we would be
1997 // inserting the computation one some other paths (e.g. inside a loop). Only
1998 // do this if the pred block is unconditionally branching into the phi block.
1999 if (NonConstBB) {
2000 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2001 if (!BI || !BI->isUnconditional()) return 0;
2002 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002003
2004 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6934a042007-02-11 01:23:03 +00002005 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002006 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002007 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002008 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002009
2010 // Next, add all of the operands to the PHI.
2011 if (I.getNumOperands() == 2) {
2012 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002013 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002014 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002015 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002016 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2017 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2018 else
2019 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002020 } else {
2021 assert(PN->getIncomingBlock(i) == NonConstBB);
2022 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2023 InV = BinaryOperator::create(BO->getOpcode(),
2024 PN->getIncomingValue(i), C, "phitmp",
2025 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002026 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2027 InV = CmpInst::create(CI->getOpcode(),
2028 CI->getPredicate(),
2029 PN->getIncomingValue(i), C, "phitmp",
2030 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002031 else
2032 assert(0 && "Unknown binop!");
2033
Chris Lattnerdbab3862007-03-02 21:28:56 +00002034 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002035 }
2036 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002037 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002038 } else {
2039 CastInst *CI = cast<CastInst>(&I);
2040 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002041 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002042 Value *InV;
2043 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002044 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002045 } else {
2046 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00002047 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2048 I.getType(), "phitmp",
2049 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002050 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002051 }
2052 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002053 }
2054 }
2055 return ReplaceInstUsesWith(I, NewPN);
2056}
2057
Chris Lattner2454a2e2008-01-29 06:52:45 +00002058
2059/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2060/// value is never equal to -0.0.
2061///
2062/// Note that this function will need to be revisited when we support nondefault
2063/// rounding modes!
2064///
2065static bool CannotBeNegativeZero(const Value *V) {
2066 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2067 return !CFP->getValueAPF().isNegZero();
2068
2069 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2070 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2071 if (I->getOpcode() == Instruction::Add &&
2072 isa<ConstantFP>(I->getOperand(1)) &&
2073 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2074 return true;
2075
2076 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2077 if (II->getIntrinsicID() == Intrinsic::sqrt)
2078 return CannotBeNegativeZero(II->getOperand(1));
2079
2080 if (const CallInst *CI = dyn_cast<CallInst>(I))
2081 if (const Function *F = CI->getCalledFunction()) {
2082 if (F->isDeclaration()) {
2083 switch (F->getNameLen()) {
2084 case 3: // abs(x) != -0.0
2085 if (!strcmp(F->getNameStart(), "abs")) return true;
2086 break;
2087 case 4: // abs[lf](x) != -0.0
2088 if (!strcmp(F->getNameStart(), "absf")) return true;
2089 if (!strcmp(F->getNameStart(), "absl")) return true;
2090 break;
2091 }
2092 }
2093 }
2094 }
2095
2096 return false;
2097}
2098
2099
Chris Lattner7e708292002-06-25 16:13:24 +00002100Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002101 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002102 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002103
Chris Lattner66331a42004-04-10 22:01:55 +00002104 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002105 // X + undef -> undef
2106 if (isa<UndefValue>(RHS))
2107 return ReplaceInstUsesWith(I, RHS);
2108
Chris Lattner66331a42004-04-10 22:01:55 +00002109 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002110 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002111 if (RHSC->isNullValue())
2112 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002113 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002114 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2115 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002116 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002117 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002118
Chris Lattner66331a42004-04-10 22:01:55 +00002119 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002120 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002121 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002122 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002123 if (Val == APInt::getSignBit(BitWidth))
Chris Lattner48595f12004-06-10 02:07:29 +00002124 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002125
2126 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2127 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002128 if (!isa<VectorType>(I.getType())) {
2129 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2130 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2131 KnownZero, KnownOne))
2132 return &I;
2133 }
Chris Lattner66331a42004-04-10 22:01:55 +00002134 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002135
2136 if (isa<PHINode>(LHS))
2137 if (Instruction *NV = FoldOpIntoPhi(I))
2138 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002139
Chris Lattner4f637d42006-01-06 17:59:59 +00002140 ConstantInt *XorRHS = 0;
2141 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002142 if (isa<ConstantInt>(RHSC) &&
2143 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002144 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002145 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002146
Zhou Sheng4351c642007-04-02 08:20:41 +00002147 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002148 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2149 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002150 do {
2151 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002152 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2153 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002154 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2155 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002156 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002157 if (!MaskedValueIsZero(XorLHS,
2158 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002159 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002160 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002161 }
2162 }
2163 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002164 C0080Val = APIntOps::lshr(C0080Val, Size);
2165 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2166 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002167
Reid Spencer35c38852007-03-28 01:36:16 +00002168 // FIXME: This shouldn't be necessary. When the backends can handle types
2169 // with funny bit widths then this whole cascade of if statements should
2170 // be removed. It is just here to get the size of the "middle" type back
2171 // up to something that the back ends can handle.
2172 const Type *MiddleType = 0;
2173 switch (Size) {
2174 default: break;
2175 case 32: MiddleType = Type::Int32Ty; break;
2176 case 16: MiddleType = Type::Int16Ty; break;
2177 case 8: MiddleType = Type::Int8Ty; break;
2178 }
2179 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002180 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002181 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002182 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002183 }
2184 }
Chris Lattner66331a42004-04-10 22:01:55 +00002185 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002186
Chris Lattner564a7272003-08-13 19:01:45 +00002187 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002188 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002189 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002190
2191 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2192 if (RHSI->getOpcode() == Instruction::Sub)
2193 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2194 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2195 }
2196 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2197 if (LHSI->getOpcode() == Instruction::Sub)
2198 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2199 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2200 }
Robert Bocchino71698282004-07-27 21:02:21 +00002201 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002202
Chris Lattner5c4afb92002-05-08 22:46:53 +00002203 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002204 // -A + -B --> -(A + B)
2205 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002206 if (LHS->getType()->isIntOrIntVector()) {
2207 if (Value *RHSV = dyn_castNegVal(RHS)) {
2208 Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2209 InsertNewInstBefore(NewAdd, I);
2210 return BinaryOperator::createNeg(NewAdd);
2211 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002212 }
2213
2214 return BinaryOperator::createSub(RHS, LHSV);
2215 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002216
2217 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002218 if (!isa<Constant>(RHS))
2219 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002220 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002221
Misha Brukmanfd939082005-04-21 23:48:37 +00002222
Chris Lattner50af16a2004-11-13 19:50:12 +00002223 ConstantInt *C2;
2224 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2225 if (X == RHS) // X*C + X --> X * (C+1)
2226 return BinaryOperator::createMul(RHS, AddOne(C2));
2227
2228 // X*C1 + X*C2 --> X * (C1+C2)
2229 ConstantInt *C1;
2230 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002231 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002232 }
2233
2234 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002235 if (dyn_castFoldableMul(RHS, C2) == LHS)
2236 return BinaryOperator::createMul(LHS, AddOne(C2));
2237
Chris Lattnere617c9e2007-01-05 02:17:46 +00002238 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002239 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2240 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002241
Chris Lattnerad3448c2003-02-18 19:57:07 +00002242
Chris Lattner564a7272003-08-13 19:01:45 +00002243 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002244 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002245 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2246 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002247
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002248 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002249 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002250 Value *W, *X, *Y, *Z;
2251 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2252 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2253 if (W != Y) {
2254 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002255 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002256 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002257 std::swap(W, X);
2258 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002259 std::swap(Y, Z);
2260 std::swap(W, X);
2261 }
2262 }
2263
2264 if (W == Y) {
2265 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2266 LHS->getName()), I);
2267 return BinaryOperator::createMul(W, NewAdd);
2268 }
2269 }
2270 }
2271
Chris Lattner6b032052003-10-02 15:11:26 +00002272 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002273 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002274 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2275 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002276
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002277 // (X & FF00) + xx00 -> (X+xx00) & FF00
2278 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002279 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002280 if (Anded == CRHS) {
2281 // See if all bits from the first bit set in the Add RHS up are included
2282 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002283 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002284
2285 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002286 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002287
2288 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002289 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002290
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002291 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2292 // Okay, the xform is safe. Insert the new add pronto.
2293 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2294 LHS->getName()), I);
2295 return BinaryOperator::createAnd(NewAdd, C2);
2296 }
2297 }
2298 }
2299
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002300 // Try to fold constant add into select arguments.
2301 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002302 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002303 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002304 }
2305
Reid Spencer1628cec2006-10-26 06:15:43 +00002306 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002307 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002308 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002309 CastInst *CI = dyn_cast<CastInst>(LHS);
2310 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002311 if (!CI) {
2312 CI = dyn_cast<CastInst>(RHS);
2313 Other = LHS;
2314 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002315 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002316 (CI->getType()->getPrimitiveSizeInBits() ==
2317 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002318 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002319 unsigned AS =
2320 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002321 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2322 PointerType::get(Type::Int8Ty, AS), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00002323 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002324 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002325 }
2326 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002327
Chris Lattner42790482007-12-20 01:56:58 +00002328 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002329 {
2330 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2331 Value *Other = RHS;
2332 if (!SI) {
2333 SI = dyn_cast<SelectInst>(RHS);
2334 Other = LHS;
2335 }
Chris Lattner42790482007-12-20 01:56:58 +00002336 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002337 Value *TV = SI->getTrueValue();
2338 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002339 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002340
2341 // Can we fold the add into the argument of the select?
2342 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002343 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2344 A == Other) // Fold the add into the true select value.
2345 return new SelectInst(SI->getCondition(), N, A);
2346 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2347 A == Other) // Fold the add into the false select value.
2348 return new SelectInst(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002349 }
2350 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002351
2352 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2353 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2354 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2355 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002356
Chris Lattner7e708292002-06-25 16:13:24 +00002357 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002358}
2359
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002360// isSignBit - Return true if the value represented by the constant only has the
2361// highest order bit set.
2362static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002363 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002364 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002365}
2366
Chris Lattner7e708292002-06-25 16:13:24 +00002367Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002368 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002369
Chris Lattner233f7dc2002-08-12 21:17:25 +00002370 if (Op0 == Op1) // sub X, X -> 0
2371 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002372
Chris Lattner233f7dc2002-08-12 21:17:25 +00002373 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002374 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002375 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002376
Chris Lattnere87597f2004-10-16 18:11:37 +00002377 if (isa<UndefValue>(Op0))
2378 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2379 if (isa<UndefValue>(Op1))
2380 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2381
Chris Lattnerd65460f2003-11-05 01:06:05 +00002382 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2383 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002384 if (C->isAllOnesValue())
2385 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002386
Chris Lattnerd65460f2003-11-05 01:06:05 +00002387 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002388 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002389 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002390 return BinaryOperator::createAdd(X, AddOne(C));
2391
Chris Lattner76b7a062007-01-15 07:02:54 +00002392 // -(X >>u 31) -> (X >>s 31)
2393 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002394 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002395 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002396 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002397 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002398 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002399 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002400 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002401 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002402 return BinaryOperator::create(Instruction::AShr,
2403 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002404 }
2405 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002406 }
2407 else if (SI->getOpcode() == Instruction::AShr) {
2408 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2409 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002410 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002411 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002412 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002413 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002414 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002415 }
2416 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002417 }
2418 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002419 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002420
2421 // Try to fold constant sub into select arguments.
2422 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002423 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002424 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002425
2426 if (isa<PHINode>(Op0))
2427 if (Instruction *NV = FoldOpIntoPhi(I))
2428 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002429 }
2430
Chris Lattner43d84d62005-04-07 16:15:25 +00002431 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2432 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002433 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002434 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002435 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002436 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002437 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002438 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2439 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2440 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002441 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002442 Op1I->getOperand(0));
2443 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002444 }
2445
Chris Lattnerfd059242003-10-15 16:48:29 +00002446 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002447 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2448 // is not used by anyone else...
2449 //
Chris Lattner0517e722004-02-02 20:09:56 +00002450 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002451 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002452 // Swap the two operands of the subexpr...
2453 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2454 Op1I->setOperand(0, IIOp1);
2455 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002456
Chris Lattnera2881962003-02-18 19:28:33 +00002457 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002458 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002459 }
2460
2461 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2462 //
2463 if (Op1I->getOpcode() == Instruction::And &&
2464 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2465 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2466
Chris Lattnerf523d062004-06-09 05:08:07 +00002467 Value *NewNot =
2468 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002469 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002470 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002471
Reid Spencerac5209e2006-10-16 23:08:08 +00002472 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002473 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002474 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002475 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002476 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002477 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002478 ConstantExpr::getNeg(DivRHS));
2479
Chris Lattnerad3448c2003-02-18 19:57:07 +00002480 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002481 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002482 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002483 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002484 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002485 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002486
2487 // X - ((X / Y) * Y) --> X % Y
2488 if (Op1I->getOpcode() == Instruction::Mul)
2489 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2490 if (Op0 == I->getOperand(0) &&
2491 Op1I->getOperand(1) == I->getOperand(1)) {
2492 if (I->getOpcode() == Instruction::SDiv)
2493 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2494 if (I->getOpcode() == Instruction::UDiv)
2495 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2496 }
Chris Lattner40371712002-05-09 01:29:19 +00002497 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002498 }
Chris Lattnera2881962003-02-18 19:28:33 +00002499
Chris Lattner9919e3d2006-12-02 00:13:08 +00002500 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002501 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002502 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002503 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2504 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2505 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2506 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002507 } else if (Op0I->getOpcode() == Instruction::Sub) {
2508 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2509 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002510 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002511 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002512
Chris Lattner50af16a2004-11-13 19:50:12 +00002513 ConstantInt *C1;
2514 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002515 if (X == Op1) // X*C - X --> X * (C-1)
2516 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002517
Chris Lattner50af16a2004-11-13 19:50:12 +00002518 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2519 if (X == dyn_castFoldableMul(Op1, C2))
Zhou Sheng58d13af2008-02-22 10:00:35 +00002520 return BinaryOperator::createMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002521 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002522 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002523}
2524
Chris Lattnera0141b92007-07-15 20:42:37 +00002525/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2526/// comparison only checks the sign bit. If it only checks the sign bit, set
2527/// TrueIfSigned if the result of the comparison is true when the input value is
2528/// signed.
2529static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2530 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002531 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002532 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2533 TrueIfSigned = true;
2534 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002535 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2536 TrueIfSigned = true;
2537 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002538 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2539 TrueIfSigned = false;
2540 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002541 case ICmpInst::ICMP_UGT:
2542 // True if LHS u> RHS and RHS == high-bit-mask - 1
2543 TrueIfSigned = true;
2544 return RHS->getValue() ==
2545 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2546 case ICmpInst::ICMP_UGE:
2547 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2548 TrueIfSigned = true;
2549 return RHS->getValue() ==
2550 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002551 default:
2552 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002553 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002554}
2555
Chris Lattner7e708292002-06-25 16:13:24 +00002556Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002557 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002558 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002559
Chris Lattnere87597f2004-10-16 18:11:37 +00002560 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2561 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2562
Chris Lattner233f7dc2002-08-12 21:17:25 +00002563 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002564 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2565 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002566
2567 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002568 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002569 if (SI->getOpcode() == Instruction::Shl)
2570 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002571 return BinaryOperator::createMul(SI->getOperand(0),
2572 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002573
Zhou Sheng843f07672007-04-19 05:39:12 +00002574 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002575 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2576 if (CI->equalsInt(1)) // X * 1 == X
2577 return ReplaceInstUsesWith(I, Op0);
2578 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002579 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002580
Zhou Sheng97b52c22007-03-29 01:57:21 +00002581 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002582 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002583 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002584 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002585 }
Robert Bocchino71698282004-07-27 21:02:21 +00002586 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002587 if (Op1F->isNullValue())
2588 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002589
Chris Lattnera2881962003-02-18 19:28:33 +00002590 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2591 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002592 // We need a better interface for long double here.
2593 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2594 if (Op1F->isExactlyValue(1.0))
2595 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002596 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002597
2598 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2599 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2600 isa<ConstantInt>(Op0I->getOperand(1))) {
2601 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2602 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2603 Op1, "tmp");
2604 InsertNewInstBefore(Add, I);
2605 Value *C1C2 = ConstantExpr::getMul(Op1,
2606 cast<Constant>(Op0I->getOperand(1)));
2607 return BinaryOperator::createAdd(Add, C1C2);
2608
2609 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002610
2611 // Try to fold constant mul into select arguments.
2612 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002613 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002614 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002615
2616 if (isa<PHINode>(Op0))
2617 if (Instruction *NV = FoldOpIntoPhi(I))
2618 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002619 }
2620
Chris Lattnera4f445b2003-03-10 23:23:04 +00002621 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2622 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002623 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002624
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002625 // If one of the operands of the multiply is a cast from a boolean value, then
2626 // we know the bool is either zero or one, so this is a 'masking' multiply.
2627 // See if we can simplify things based on how the boolean was originally
2628 // formed.
2629 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002630 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002631 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002632 BoolCast = CI;
2633 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002634 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002635 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002636 BoolCast = CI;
2637 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002638 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002639 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2640 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002641 bool TIS = false;
2642
Reid Spencere4d87aa2006-12-23 06:05:41 +00002643 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002644 // multiply into a shift/and combination.
2645 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002646 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2647 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002648 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002649 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002650 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002651 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002652 InsertNewInstBefore(
2653 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002654 BoolCast->getOperand(0)->getName()+
2655 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002656
2657 // If the multiply type is not the same as the source type, sign extend
2658 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002659 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002660 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2661 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002662 Instruction::CastOps opcode =
2663 (SrcBits == DstBits ? Instruction::BitCast :
2664 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2665 V = InsertCastBefore(opcode, V, I.getType(), I);
2666 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002667
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002668 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002669 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002670 }
2671 }
2672 }
2673
Chris Lattner7e708292002-06-25 16:13:24 +00002674 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002675}
2676
Reid Spencer1628cec2006-10-26 06:15:43 +00002677/// This function implements the transforms on div instructions that work
2678/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2679/// used by the visitors to those instructions.
2680/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002681Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002682 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002683
Chris Lattner50b2ca42008-02-19 06:12:18 +00002684 // undef / X -> 0 for integer.
2685 // undef / X -> undef for FP (the undef could be a snan).
2686 if (isa<UndefValue>(Op0)) {
2687 if (Op0->getType()->isFPOrFPVector())
2688 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002689 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002690 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002691
2692 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002693 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002694 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002695
Chris Lattner25feae52008-01-28 00:58:18 +00002696 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2697 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002698 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002699 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2700 // the same basic block, then we replace the select with Y, and the
2701 // condition of the select with false (if the cond value is in the same BB).
2702 // If the select has uses other than the div, this allows them to be
2703 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2704 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002705 if (ST->isNullValue()) {
2706 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2707 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002708 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002709 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2710 I.setOperand(1, SI->getOperand(2));
2711 else
2712 UpdateValueUsesWith(SI, SI->getOperand(2));
2713 return &I;
2714 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002715
Chris Lattner25feae52008-01-28 00:58:18 +00002716 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2717 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002718 if (ST->isNullValue()) {
2719 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2720 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002721 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002722 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2723 I.setOperand(1, SI->getOperand(1));
2724 else
2725 UpdateValueUsesWith(SI, SI->getOperand(1));
2726 return &I;
2727 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002728 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002729
Reid Spencer1628cec2006-10-26 06:15:43 +00002730 return 0;
2731}
Misha Brukmanfd939082005-04-21 23:48:37 +00002732
Reid Spencer1628cec2006-10-26 06:15:43 +00002733/// This function implements the transforms common to both integer division
2734/// instructions (udiv and sdiv). It is called by the visitors to those integer
2735/// division instructions.
2736/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002737Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002738 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2739
2740 if (Instruction *Common = commonDivTransforms(I))
2741 return Common;
2742
2743 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2744 // div X, 1 == X
2745 if (RHS->equalsInt(1))
2746 return ReplaceInstUsesWith(I, Op0);
2747
2748 // (X / C1) / C2 -> X / (C1*C2)
2749 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2750 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2751 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002752 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2753 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2754 else
2755 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2756 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002757 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002758
Reid Spencerbca0e382007-03-23 20:05:17 +00002759 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002760 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2761 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2762 return R;
2763 if (isa<PHINode>(Op0))
2764 if (Instruction *NV = FoldOpIntoPhi(I))
2765 return NV;
2766 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002767 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002768
Chris Lattnera2881962003-02-18 19:28:33 +00002769 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002770 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002771 if (LHS->equalsInt(0))
2772 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2773
Reid Spencer1628cec2006-10-26 06:15:43 +00002774 return 0;
2775}
2776
2777Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2778 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2779
2780 // Handle the integer div common cases
2781 if (Instruction *Common = commonIDivTransforms(I))
2782 return Common;
2783
2784 // X udiv C^2 -> X >> C
2785 // Check to see if this is an unsigned division with an exact power of 2,
2786 // if so, convert to a right shift.
2787 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002788 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00002789 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002790 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002791 }
2792
2793 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002794 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002795 if (RHSI->getOpcode() == Instruction::Shl &&
2796 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002797 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002798 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002799 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002800 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002801 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002802 Constant *C2V = ConstantInt::get(NTy, C2);
2803 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002804 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00002805 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002806 }
2807 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002808 }
2809
Reid Spencer1628cec2006-10-26 06:15:43 +00002810 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2811 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002812 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002813 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002814 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002815 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002816 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002817 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002818 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002819 // Construct the "on true" case of the select
2820 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2821 Instruction *TSI = BinaryOperator::createLShr(
2822 Op0, TC, SI->getName()+".t");
2823 TSI = InsertNewInstBefore(TSI, I);
2824
2825 // Construct the "on false" case of the select
2826 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2827 Instruction *FSI = BinaryOperator::createLShr(
2828 Op0, FC, SI->getName()+".f");
2829 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002830
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002831 // construct the select instruction and return it.
2832 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002833 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002834 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002835 return 0;
2836}
2837
Reid Spencer1628cec2006-10-26 06:15:43 +00002838Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2839 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2840
2841 // Handle the integer div common cases
2842 if (Instruction *Common = commonIDivTransforms(I))
2843 return Common;
2844
2845 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2846 // sdiv X, -1 == -X
2847 if (RHS->isAllOnesValue())
2848 return BinaryOperator::createNeg(Op0);
2849
2850 // -X/C -> X/-C
2851 if (Value *LHSNeg = dyn_castNegVal(Op0))
2852 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2853 }
2854
2855 // If the sign bits of both operands are zero (i.e. we can prove they are
2856 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002857 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002858 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002859 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002860 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Reid Spencer1628cec2006-10-26 06:15:43 +00002861 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2862 }
2863 }
2864
2865 return 0;
2866}
2867
2868Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2869 return commonDivTransforms(I);
2870}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002871
Reid Spencer0a783f72006-11-02 01:53:59 +00002872/// This function implements the transforms on rem instructions that work
2873/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2874/// is used by the visitors to those instructions.
2875/// @brief Transforms common to all three rem instructions
2876Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002877 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002878
Chris Lattner50b2ca42008-02-19 06:12:18 +00002879 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002880 if (Constant *LHS = dyn_cast<Constant>(Op0))
2881 if (LHS->isNullValue())
2882 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2883
Chris Lattner50b2ca42008-02-19 06:12:18 +00002884 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2885 if (I.getType()->isFPOrFPVector())
2886 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002887 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002888 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002889 if (isa<UndefValue>(Op1))
2890 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002891
2892 // Handle cases involving: rem X, (select Cond, Y, Z)
2893 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2894 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2895 // the same basic block, then we replace the select with Y, and the
2896 // condition of the select with false (if the cond value is in the same
2897 // BB). If the select has uses other than the div, this allows them to be
2898 // simplified also.
2899 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2900 if (ST->isNullValue()) {
2901 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2902 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002903 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002904 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2905 I.setOperand(1, SI->getOperand(2));
2906 else
2907 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002908 return &I;
2909 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002910 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2911 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2912 if (ST->isNullValue()) {
2913 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2914 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002915 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002916 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2917 I.setOperand(1, SI->getOperand(1));
2918 else
2919 UpdateValueUsesWith(SI, SI->getOperand(1));
2920 return &I;
2921 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002922 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002923
Reid Spencer0a783f72006-11-02 01:53:59 +00002924 return 0;
2925}
2926
2927/// This function implements the transforms common to both integer remainder
2928/// instructions (urem and srem). It is called by the visitors to those integer
2929/// remainder instructions.
2930/// @brief Common integer remainder transforms
2931Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2932 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2933
2934 if (Instruction *common = commonRemTransforms(I))
2935 return common;
2936
Chris Lattner857e8cd2004-12-12 21:48:58 +00002937 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002938 // X % 0 == undef, we don't need to preserve faults!
2939 if (RHS->equalsInt(0))
2940 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2941
Chris Lattnera2881962003-02-18 19:28:33 +00002942 if (RHS->equalsInt(1)) // X % 1 == 0
2943 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2944
Chris Lattner97943922006-02-28 05:49:21 +00002945 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2946 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2947 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2948 return R;
2949 } else if (isa<PHINode>(Op0I)) {
2950 if (Instruction *NV = FoldOpIntoPhi(I))
2951 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002952 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002953
2954 // See if we can fold away this rem instruction.
2955 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2956 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2957 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2958 KnownZero, KnownOne))
2959 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00002960 }
Chris Lattnera2881962003-02-18 19:28:33 +00002961 }
2962
Reid Spencer0a783f72006-11-02 01:53:59 +00002963 return 0;
2964}
2965
2966Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2967 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2968
2969 if (Instruction *common = commonIRemTransforms(I))
2970 return common;
2971
2972 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2973 // X urem C^2 -> X and C
2974 // Check to see if this is an unsigned remainder with an exact power of 2,
2975 // if so, convert to a bitwise and.
2976 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002977 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00002978 return BinaryOperator::createAnd(Op0, SubOne(C));
2979 }
2980
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002981 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002982 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2983 if (RHSI->getOpcode() == Instruction::Shl &&
2984 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002985 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002986 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2987 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2988 "tmp"), I);
2989 return BinaryOperator::createAnd(Op0, Add);
2990 }
2991 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002992 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002993
Reid Spencer0a783f72006-11-02 01:53:59 +00002994 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2995 // where C1&C2 are powers of two.
2996 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2997 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2998 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2999 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003000 if ((STO->getValue().isPowerOf2()) &&
3001 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003002 Value *TrueAnd = InsertNewInstBefore(
3003 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3004 Value *FalseAnd = InsertNewInstBefore(
3005 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3006 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
3007 }
3008 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003009 }
3010
Chris Lattner3f5b8772002-05-06 16:14:14 +00003011 return 0;
3012}
3013
Reid Spencer0a783f72006-11-02 01:53:59 +00003014Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3015 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3016
Dan Gohmancff55092007-11-05 23:16:33 +00003017 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003018 if (Instruction *common = commonIRemTransforms(I))
3019 return common;
3020
3021 if (Value *RHSNeg = dyn_castNegVal(Op1))
3022 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003023 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003024 // X % -Y -> X % Y
3025 AddUsesToWorkList(I);
3026 I.setOperand(1, RHSNeg);
3027 return &I;
3028 }
3029
Dan Gohmancff55092007-11-05 23:16:33 +00003030 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003031 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003032 if (I.getType()->isInteger()) {
3033 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3034 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3035 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3036 return BinaryOperator::createURem(Op0, Op1, I.getName());
3037 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003038 }
3039
3040 return 0;
3041}
3042
3043Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003044 return commonRemTransforms(I);
3045}
3046
Chris Lattner8b170942002-08-09 23:47:40 +00003047// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003048static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003049 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003050 if (!isSigned)
3051 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3052 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003053}
3054
3055// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003056static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003057 if (!isSigned)
3058 return C->getValue() == 1; // unsigned
3059
3060 // Calculate 1111111111000000000000
3061 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3062 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003063}
3064
Chris Lattner457dd822004-06-09 07:59:58 +00003065// isOneBitSet - Return true if there is exactly one bit set in the specified
3066// constant.
3067static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003068 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003069}
3070
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003071// isHighOnes - Return true if the constant is of the form 1+0+.
3072// This is the same as lowones(~X).
3073static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003074 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003075}
3076
Reid Spencere4d87aa2006-12-23 06:05:41 +00003077/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003078/// are carefully arranged to allow folding of expressions such as:
3079///
3080/// (A < B) | (A > B) --> (A != B)
3081///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003082/// Note that this is only valid if the first and second predicates have the
3083/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003084///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003085/// Three bits are used to represent the condition, as follows:
3086/// 0 A > B
3087/// 1 A == B
3088/// 2 A < B
3089///
3090/// <=> Value Definition
3091/// 000 0 Always false
3092/// 001 1 A > B
3093/// 010 2 A == B
3094/// 011 3 A >= B
3095/// 100 4 A < B
3096/// 101 5 A != B
3097/// 110 6 A <= B
3098/// 111 7 Always true
3099///
3100static unsigned getICmpCode(const ICmpInst *ICI) {
3101 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003102 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003103 case ICmpInst::ICMP_UGT: return 1; // 001
3104 case ICmpInst::ICMP_SGT: return 1; // 001
3105 case ICmpInst::ICMP_EQ: return 2; // 010
3106 case ICmpInst::ICMP_UGE: return 3; // 011
3107 case ICmpInst::ICMP_SGE: return 3; // 011
3108 case ICmpInst::ICMP_ULT: return 4; // 100
3109 case ICmpInst::ICMP_SLT: return 4; // 100
3110 case ICmpInst::ICMP_NE: return 5; // 101
3111 case ICmpInst::ICMP_ULE: return 6; // 110
3112 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003113 // True -> 7
3114 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003115 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003116 return 0;
3117 }
3118}
3119
Reid Spencere4d87aa2006-12-23 06:05:41 +00003120/// getICmpValue - This is the complement of getICmpCode, which turns an
3121/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003122/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003123/// of predicate to use in new icmp instructions.
3124static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3125 switch (code) {
3126 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003127 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003128 case 1:
3129 if (sign)
3130 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3131 else
3132 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3133 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3134 case 3:
3135 if (sign)
3136 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3137 else
3138 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3139 case 4:
3140 if (sign)
3141 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3142 else
3143 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3144 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3145 case 6:
3146 if (sign)
3147 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3148 else
3149 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003150 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003151 }
3152}
3153
Reid Spencere4d87aa2006-12-23 06:05:41 +00003154static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3155 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3156 (ICmpInst::isSignedPredicate(p1) &&
3157 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3158 (ICmpInst::isSignedPredicate(p2) &&
3159 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3160}
3161
3162namespace {
3163// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3164struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003165 InstCombiner &IC;
3166 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003167 ICmpInst::Predicate pred;
3168 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3169 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3170 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003171 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003172 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3173 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003174 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3175 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003176 return false;
3177 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003178 Instruction *apply(Instruction &Log) const {
3179 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3180 if (ICI->getOperand(0) != LHS) {
3181 assert(ICI->getOperand(1) == LHS);
3182 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003183 }
3184
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003185 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003186 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003187 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003188 unsigned Code;
3189 switch (Log.getOpcode()) {
3190 case Instruction::And: Code = LHSCode & RHSCode; break;
3191 case Instruction::Or: Code = LHSCode | RHSCode; break;
3192 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003193 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003194 }
3195
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003196 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3197 ICmpInst::isSignedPredicate(ICI->getPredicate());
3198
3199 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003200 if (Instruction *I = dyn_cast<Instruction>(RV))
3201 return I;
3202 // Otherwise, it's a constant boolean value...
3203 return IC.ReplaceInstUsesWith(Log, RV);
3204 }
3205};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003206} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003207
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003208// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3209// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003210// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003211Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003212 ConstantInt *OpRHS,
3213 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003214 BinaryOperator &TheAnd) {
3215 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003216 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003217 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003218 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003219
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003220 switch (Op->getOpcode()) {
3221 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003222 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003223 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003224 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003225 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003226 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003227 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003228 }
3229 break;
3230 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003231 if (Together == AndRHS) // (X | C) & C --> C
3232 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003233
Chris Lattner6e7ba452005-01-01 16:22:27 +00003234 if (Op->hasOneUse() && Together != OpRHS) {
3235 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003236 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003237 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003238 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003239 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003240 }
3241 break;
3242 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003243 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003244 // Adding a one to a single bit bit-field should be turned into an XOR
3245 // of the bit. First thing to check is to see if this AND is with a
3246 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003247 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003248
3249 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003250 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003251 // Ok, at this point, we know that we are masking the result of the
3252 // ADD down to exactly one bit. If the constant we are adding has
3253 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003254 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003255
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003256 // Check to see if any bits below the one bit set in AndRHSV are set.
3257 if ((AddRHS & (AndRHSV-1)) == 0) {
3258 // If not, the only thing that can effect the output of the AND is
3259 // the bit specified by AndRHSV. If that bit is set, the effect of
3260 // the XOR is to toggle the bit. If it is clear, then the ADD has
3261 // no effect.
3262 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3263 TheAnd.setOperand(0, X);
3264 return &TheAnd;
3265 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003266 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003267 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003268 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003269 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003270 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003271 }
3272 }
3273 }
3274 }
3275 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003276
3277 case Instruction::Shl: {
3278 // We know that the AND will not produce any of the bits shifted in, so if
3279 // the anded constant includes them, clear them now!
3280 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003281 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003282 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003283 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3284 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003285
Zhou Sheng290bec52007-03-29 08:15:12 +00003286 if (CI->getValue() == ShlMask) {
3287 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003288 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3289 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003290 TheAnd.setOperand(1, CI);
3291 return &TheAnd;
3292 }
3293 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003294 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003295 case Instruction::LShr:
3296 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003297 // We know that the AND will not produce any of the bits shifted in, so if
3298 // the anded constant includes them, clear them now! This only applies to
3299 // unsigned shifts, because a signed shr may bring in set bits!
3300 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003301 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003302 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003303 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3304 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003305
Zhou Sheng290bec52007-03-29 08:15:12 +00003306 if (CI->getValue() == ShrMask) {
3307 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003308 return ReplaceInstUsesWith(TheAnd, Op);
3309 } else if (CI != AndRHS) {
3310 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3311 return &TheAnd;
3312 }
3313 break;
3314 }
3315 case Instruction::AShr:
3316 // Signed shr.
3317 // See if this is shifting in some sign extension, then masking it out
3318 // with an and.
3319 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003320 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003321 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003322 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3323 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003324 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003325 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003326 // Make the argument unsigned.
3327 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003328 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003329 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003330 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003331 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003332 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003333 }
3334 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003335 }
3336 return 0;
3337}
3338
Chris Lattner8b170942002-08-09 23:47:40 +00003339
Chris Lattnera96879a2004-09-29 17:40:11 +00003340/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3341/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003342/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3343/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003344/// insert new instructions.
3345Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003346 bool isSigned, bool Inside,
3347 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003348 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003349 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003350 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003351
Chris Lattnera96879a2004-09-29 17:40:11 +00003352 if (Inside) {
3353 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003354 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003355
Reid Spencere4d87aa2006-12-23 06:05:41 +00003356 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003357 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003358 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003359 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3360 return new ICmpInst(pred, V, Hi);
3361 }
3362
3363 // Emit V-Lo <u Hi-Lo
3364 Constant *NegLo = ConstantExpr::getNeg(Lo);
3365 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003366 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003367 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3368 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003369 }
3370
3371 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003372 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003373
Reid Spencere4e40032007-03-21 23:19:50 +00003374 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003375 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003376 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003377 ICmpInst::Predicate pred = (isSigned ?
3378 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3379 return new ICmpInst(pred, V, Hi);
3380 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003381
Reid Spencere4e40032007-03-21 23:19:50 +00003382 // Emit V-Lo >u Hi-1-Lo
3383 // Note that Hi has already had one subtracted from it, above.
3384 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003385 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003386 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003387 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3388 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003389}
3390
Chris Lattner7203e152005-09-18 07:22:02 +00003391// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3392// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3393// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3394// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003395static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003396 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003397 uint32_t BitWidth = Val->getType()->getBitWidth();
3398 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003399
3400 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003401 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003402 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003403 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003404 return true;
3405}
3406
Chris Lattner7203e152005-09-18 07:22:02 +00003407/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3408/// where isSub determines whether the operator is a sub. If we can fold one of
3409/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003410///
3411/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3412/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3413/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3414///
3415/// return (A +/- B).
3416///
3417Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003418 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003419 Instruction &I) {
3420 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3421 if (!LHSI || LHSI->getNumOperands() != 2 ||
3422 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3423
3424 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3425
3426 switch (LHSI->getOpcode()) {
3427 default: return 0;
3428 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003429 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003430 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003431 if ((Mask->getValue().countLeadingZeros() +
3432 Mask->getValue().countPopulation()) ==
3433 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003434 break;
3435
3436 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3437 // part, we don't need any explicit masks to take them out of A. If that
3438 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003439 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003440 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003441 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003442 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003443 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003444 break;
3445 }
3446 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003447 return 0;
3448 case Instruction::Or:
3449 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003450 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003451 if ((Mask->getValue().countLeadingZeros() +
3452 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003453 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003454 break;
3455 return 0;
3456 }
3457
3458 Instruction *New;
3459 if (isSub)
3460 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3461 else
3462 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3463 return InsertNewInstBefore(New, I);
3464}
3465
Chris Lattner7e708292002-06-25 16:13:24 +00003466Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003467 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003468 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003469
Chris Lattnere87597f2004-10-16 18:11:37 +00003470 if (isa<UndefValue>(Op1)) // X & undef -> 0
3471 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3472
Chris Lattner6e7ba452005-01-01 16:22:27 +00003473 // and X, X = X
3474 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003475 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003476
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003477 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003478 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003479 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003480 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3481 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3482 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003483 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003484 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003485 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003486 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003487 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003488 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003489 } else if (isa<ConstantAggregateZero>(Op1)) {
3490 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003491 }
3492 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003493
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003494 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003495 const APInt& AndRHSMask = AndRHS->getValue();
3496 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003497
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003498 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003499 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003500 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003501 Value *Op0LHS = Op0I->getOperand(0);
3502 Value *Op0RHS = Op0I->getOperand(1);
3503 switch (Op0I->getOpcode()) {
3504 case Instruction::Xor:
3505 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003506 // If the mask is only needed on one incoming arm, push it up.
3507 if (Op0I->hasOneUse()) {
3508 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3509 // Not masking anything out for the LHS, move to RHS.
3510 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3511 Op0RHS->getName()+".masked");
3512 InsertNewInstBefore(NewRHS, I);
3513 return BinaryOperator::create(
3514 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003515 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003516 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003517 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3518 // Not masking anything out for the RHS, move to LHS.
3519 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3520 Op0LHS->getName()+".masked");
3521 InsertNewInstBefore(NewLHS, I);
3522 return BinaryOperator::create(
3523 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3524 }
3525 }
3526
Chris Lattner6e7ba452005-01-01 16:22:27 +00003527 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003528 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003529 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3530 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3531 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3532 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3533 return BinaryOperator::createAnd(V, AndRHS);
3534 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3535 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003536 break;
3537
3538 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003539 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3540 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3541 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3542 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3543 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003544 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003545 }
3546
Chris Lattner58403262003-07-23 19:25:52 +00003547 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003548 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003549 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003550 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003551 // If this is an integer truncation or change from signed-to-unsigned, and
3552 // if the source is an and/or with immediate, transform it. This
3553 // frequently occurs for bitfield accesses.
3554 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003555 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003556 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003557 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003558 if (CastOp->getOpcode() == Instruction::And) {
3559 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003560 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3561 // This will fold the two constants together, which may allow
3562 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003563 Instruction *NewCast = CastInst::createTruncOrBitCast(
3564 CastOp->getOperand(0), I.getType(),
3565 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003566 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003567 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003568 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003569 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003570 return BinaryOperator::createAnd(NewCast, C3);
3571 } else if (CastOp->getOpcode() == Instruction::Or) {
3572 // Change: and (cast (or X, C1) to T), C2
3573 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003574 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003575 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3576 return ReplaceInstUsesWith(I, AndRHS);
3577 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003578 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003579 }
Chris Lattner06782f82003-07-23 19:36:21 +00003580 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003581
3582 // Try to fold constant and into select arguments.
3583 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003584 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003585 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003586 if (isa<PHINode>(Op0))
3587 if (Instruction *NV = FoldOpIntoPhi(I))
3588 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003589 }
3590
Chris Lattner8d969642003-03-10 23:06:50 +00003591 Value *Op0NotVal = dyn_castNotVal(Op0);
3592 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003593
Chris Lattner5b62aa72004-06-18 06:07:51 +00003594 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3595 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3596
Misha Brukmancb6267b2004-07-30 12:50:08 +00003597 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003598 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003599 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3600 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003601 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003602 return BinaryOperator::createNot(Or);
3603 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003604
3605 {
Chris Lattner003b6202007-06-15 05:58:24 +00003606 Value *A = 0, *B = 0, *C = 0, *D = 0;
3607 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003608 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3609 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003610
3611 // (A|B) & ~(A&B) -> A^B
3612 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3613 if ((A == C && B == D) || (A == D && B == C))
3614 return BinaryOperator::createXor(A, B);
3615 }
3616 }
3617
3618 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003619 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3620 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003621
3622 // ~(A&B) & (A|B) -> A^B
3623 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3624 if ((A == C && B == D) || (A == D && B == C))
3625 return BinaryOperator::createXor(A, B);
3626 }
3627 }
Chris Lattner64daab52006-04-01 08:03:55 +00003628
3629 if (Op0->hasOneUse() &&
3630 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3631 if (A == Op1) { // (A^B)&A -> A&(A^B)
3632 I.swapOperands(); // Simplify below
3633 std::swap(Op0, Op1);
3634 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3635 cast<BinaryOperator>(Op0)->swapOperands();
3636 I.swapOperands(); // Simplify below
3637 std::swap(Op0, Op1);
3638 }
3639 }
3640 if (Op1->hasOneUse() &&
3641 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3642 if (B == Op0) { // B&(A^B) -> B&(B^A)
3643 cast<BinaryOperator>(Op1)->swapOperands();
3644 std::swap(A, B);
3645 }
3646 if (A == Op0) { // A&(A^B) -> A & ~B
3647 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3648 InsertNewInstBefore(NotB, I);
3649 return BinaryOperator::createAnd(A, NotB);
3650 }
3651 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003652 }
3653
Reid Spencere4d87aa2006-12-23 06:05:41 +00003654 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3655 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3656 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003657 return R;
3658
Chris Lattner955f3312004-09-28 21:48:02 +00003659 Value *LHSVal, *RHSVal;
3660 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003661 ICmpInst::Predicate LHSCC, RHSCC;
3662 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3663 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3664 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3665 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3666 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3667 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3668 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003669 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3670
3671 // Don't try to fold ICMP_SLT + ICMP_ULT.
3672 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3673 ICmpInst::isSignedPredicate(LHSCC) ==
3674 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003675 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003676 ICmpInst::Predicate GT;
3677 if (ICmpInst::isSignedPredicate(LHSCC) ||
3678 (ICmpInst::isEquality(LHSCC) &&
3679 ICmpInst::isSignedPredicate(RHSCC)))
3680 GT = ICmpInst::ICMP_SGT;
3681 else
3682 GT = ICmpInst::ICMP_UGT;
3683
Reid Spencere4d87aa2006-12-23 06:05:41 +00003684 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3685 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003686 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003687 std::swap(LHS, RHS);
3688 std::swap(LHSCst, RHSCst);
3689 std::swap(LHSCC, RHSCC);
3690 }
3691
Reid Spencere4d87aa2006-12-23 06:05:41 +00003692 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003693 // comparing a value against two constants and and'ing the result
3694 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003695 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3696 // (from the FoldICmpLogical check above), that the two constants
3697 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003698 assert(LHSCst != RHSCst && "Compares not folded above?");
3699
3700 switch (LHSCC) {
3701 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003702 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003703 switch (RHSCC) {
3704 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003705 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3706 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3707 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003708 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003709 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3710 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3711 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003712 return ReplaceInstUsesWith(I, LHS);
3713 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003714 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003715 switch (RHSCC) {
3716 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003717 case ICmpInst::ICMP_ULT:
3718 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3719 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3720 break; // (X != 13 & X u< 15) -> no change
3721 case ICmpInst::ICMP_SLT:
3722 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3723 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3724 break; // (X != 13 & X s< 15) -> no change
3725 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3726 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3727 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003728 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003729 case ICmpInst::ICMP_NE:
3730 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003731 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3732 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3733 LHSVal->getName()+".off");
3734 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003735 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3736 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003737 }
3738 break; // (X != 13 & X != 15) -> no change
3739 }
3740 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003741 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003742 switch (RHSCC) {
3743 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003744 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3745 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003746 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003747 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3748 break;
3749 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3750 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003751 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003752 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3753 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003754 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003755 break;
3756 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003757 switch (RHSCC) {
3758 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003759 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3760 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003761 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003762 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3763 break;
3764 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3765 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003766 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003767 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3768 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003769 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003770 break;
3771 case ICmpInst::ICMP_UGT:
3772 switch (RHSCC) {
3773 default: assert(0 && "Unknown integer condition code!");
3774 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3775 return ReplaceInstUsesWith(I, LHS);
3776 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3777 return ReplaceInstUsesWith(I, RHS);
3778 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3779 break;
3780 case ICmpInst::ICMP_NE:
3781 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3782 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3783 break; // (X u> 13 & X != 15) -> no change
3784 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3785 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3786 true, I);
3787 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3788 break;
3789 }
3790 break;
3791 case ICmpInst::ICMP_SGT:
3792 switch (RHSCC) {
3793 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003794 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003795 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3796 return ReplaceInstUsesWith(I, RHS);
3797 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3798 break;
3799 case ICmpInst::ICMP_NE:
3800 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3801 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3802 break; // (X s> 13 & X != 15) -> no change
3803 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3804 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3805 true, I);
3806 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3807 break;
3808 }
3809 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003810 }
3811 }
3812 }
3813
Chris Lattner6fc205f2006-05-05 06:39:07 +00003814 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003815 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3816 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3817 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3818 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003819 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003820 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003821 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3822 I.getType(), TD) &&
3823 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3824 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003825 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3826 Op1C->getOperand(0),
3827 I.getName());
3828 InsertNewInstBefore(NewOp, I);
3829 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3830 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003831 }
Chris Lattnere511b742006-11-14 07:46:50 +00003832
3833 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003834 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3835 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3836 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003837 SI0->getOperand(1) == SI1->getOperand(1) &&
3838 (SI0->hasOneUse() || SI1->hasOneUse())) {
3839 Instruction *NewOp =
3840 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3841 SI1->getOperand(0),
3842 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003843 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3844 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003845 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003846 }
3847
Chris Lattner99c65742007-10-24 05:38:08 +00003848 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3849 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3850 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3851 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3852 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3853 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3854 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3855 // If either of the constants are nans, then the whole thing returns
3856 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003857 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003858 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3859 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3860 RHS->getOperand(0));
3861 }
3862 }
3863 }
3864
Chris Lattner7e708292002-06-25 16:13:24 +00003865 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003866}
3867
Chris Lattnerafe91a52006-06-15 19:07:26 +00003868/// CollectBSwapParts - Look to see if the specified value defines a single byte
3869/// in the result. If it does, and if the specified byte hasn't been filled in
3870/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003871static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003872 Instruction *I = dyn_cast<Instruction>(V);
3873 if (I == 0) return true;
3874
3875 // If this is an or instruction, it is an inner node of the bswap.
3876 if (I->getOpcode() == Instruction::Or)
3877 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3878 CollectBSwapParts(I->getOperand(1), ByteValues);
3879
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003880 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003881 // If this is a shift by a constant int, and it is "24", then its operand
3882 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003883 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003884 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003885 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003886 8*(ByteValues.size()-1))
3887 return true;
3888
3889 unsigned DestNo;
3890 if (I->getOpcode() == Instruction::Shl) {
3891 // X << 24 defines the top byte with the lowest of the input bytes.
3892 DestNo = ByteValues.size()-1;
3893 } else {
3894 // X >>u 24 defines the low byte with the highest of the input bytes.
3895 DestNo = 0;
3896 }
3897
3898 // If the destination byte value is already defined, the values are or'd
3899 // together, which isn't a bswap (unless it's an or of the same bits).
3900 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3901 return true;
3902 ByteValues[DestNo] = I->getOperand(0);
3903 return false;
3904 }
3905
3906 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3907 // don't have this.
3908 Value *Shift = 0, *ShiftLHS = 0;
3909 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3910 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3911 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3912 return true;
3913 Instruction *SI = cast<Instruction>(Shift);
3914
3915 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003916 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3917 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003918 return true;
3919
3920 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3921 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003922 if (AndAmt->getValue().getActiveBits() > 64)
3923 return true;
3924 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003925 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003926 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003927 break;
3928 // Unknown mask for bswap.
3929 if (DestByte == ByteValues.size()) return true;
3930
Reid Spencerb83eb642006-10-20 07:07:24 +00003931 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003932 unsigned SrcByte;
3933 if (SI->getOpcode() == Instruction::Shl)
3934 SrcByte = DestByte - ShiftBytes;
3935 else
3936 SrcByte = DestByte + ShiftBytes;
3937
3938 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3939 if (SrcByte != ByteValues.size()-DestByte-1)
3940 return true;
3941
3942 // If the destination byte value is already defined, the values are or'd
3943 // together, which isn't a bswap (unless it's an or of the same bits).
3944 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3945 return true;
3946 ByteValues[DestByte] = SI->getOperand(0);
3947 return false;
3948}
3949
3950/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3951/// If so, insert the new bswap intrinsic and return it.
3952Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003953 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3954 if (!ITy || ITy->getBitWidth() % 16)
3955 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003956
3957 /// ByteValues - For each byte of the result, we keep track of which value
3958 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003959 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003960 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003961
3962 // Try to find all the pieces corresponding to the bswap.
3963 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3964 CollectBSwapParts(I.getOperand(1), ByteValues))
3965 return 0;
3966
3967 // Check to see if all of the bytes come from the same value.
3968 Value *V = ByteValues[0];
3969 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3970
3971 // Check to make sure that all of the bytes come from the same value.
3972 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3973 if (ByteValues[i] != V)
3974 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003975 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003976 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003977 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003978 return new CallInst(F, V);
3979}
3980
3981
Chris Lattner7e708292002-06-25 16:13:24 +00003982Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003983 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003984 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003985
Chris Lattner42593e62007-03-24 23:56:43 +00003986 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003987 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003988
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003989 // or X, X = X
3990 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003991 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003992
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003993 // See if we can simplify any instructions used by the instruction whose sole
3994 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003995 if (!isa<VectorType>(I.getType())) {
3996 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3997 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3998 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3999 KnownZero, KnownOne))
4000 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004001 } else if (isa<ConstantAggregateZero>(Op1)) {
4002 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4003 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4004 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4005 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004006 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004007
4008
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004009
Chris Lattner3f5b8772002-05-06 16:14:14 +00004010 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004011 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004012 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004013 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4014 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004015 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004016 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004017 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004018 return BinaryOperator::createAnd(Or,
4019 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004020 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004021
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004022 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4023 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004024 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004025 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004026 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004027 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004028 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004029 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004030
4031 // Try to fold constant and into select arguments.
4032 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004033 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004034 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004035 if (isa<PHINode>(Op0))
4036 if (Instruction *NV = FoldOpIntoPhi(I))
4037 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004038 }
4039
Chris Lattner4f637d42006-01-06 17:59:59 +00004040 Value *A = 0, *B = 0;
4041 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004042
4043 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4044 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4045 return ReplaceInstUsesWith(I, Op1);
4046 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4047 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4048 return ReplaceInstUsesWith(I, Op0);
4049
Chris Lattner6423d4c2006-07-10 20:25:24 +00004050 // (A | B) | C and A | (B | C) -> bswap if possible.
4051 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004052 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004053 match(Op1, m_Or(m_Value(), m_Value())) ||
4054 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4055 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004056 if (Instruction *BSwap = MatchBSwap(I))
4057 return BSwap;
4058 }
4059
Chris Lattner6e4c6492005-05-09 04:58:36 +00004060 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4061 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004062 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004063 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4064 InsertNewInstBefore(NOr, I);
4065 NOr->takeName(Op0);
4066 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004067 }
4068
4069 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4070 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004071 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004072 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4073 InsertNewInstBefore(NOr, I);
4074 NOr->takeName(Op0);
4075 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004076 }
4077
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004078 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004079 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004080 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4081 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004082 Value *V1 = 0, *V2 = 0, *V3 = 0;
4083 C1 = dyn_cast<ConstantInt>(C);
4084 C2 = dyn_cast<ConstantInt>(D);
4085 if (C1 && C2) { // (A & C1)|(B & C2)
4086 // If we have: ((V + N) & C1) | (V & C2)
4087 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4088 // replace with V+N.
4089 if (C1->getValue() == ~C2->getValue()) {
4090 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4091 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4092 // Add commutes, try both ways.
4093 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4094 return ReplaceInstUsesWith(I, A);
4095 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4096 return ReplaceInstUsesWith(I, A);
4097 }
4098 // Or commutes, try both ways.
4099 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4100 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4101 // Add commutes, try both ways.
4102 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4103 return ReplaceInstUsesWith(I, B);
4104 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4105 return ReplaceInstUsesWith(I, B);
4106 }
4107 }
Chris Lattner044e5332007-04-08 08:01:49 +00004108 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004109 }
4110
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004111 // Check to see if we have any common things being and'ed. If so, find the
4112 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004113 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4114 if (A == B) // (A & C)|(A & D) == A & (C|D)
4115 V1 = A, V2 = C, V3 = D;
4116 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4117 V1 = A, V2 = B, V3 = C;
4118 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4119 V1 = C, V2 = A, V3 = D;
4120 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4121 V1 = C, V2 = A, V3 = B;
4122
4123 if (V1) {
4124 Value *Or =
4125 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4126 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004127 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004128 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004129 }
Chris Lattnere511b742006-11-14 07:46:50 +00004130
4131 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004132 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4133 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4134 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004135 SI0->getOperand(1) == SI1->getOperand(1) &&
4136 (SI0->hasOneUse() || SI1->hasOneUse())) {
4137 Instruction *NewOp =
4138 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4139 SI1->getOperand(0),
4140 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004141 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4142 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004143 }
4144 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004145
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004146 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4147 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004148 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004149 } else {
4150 A = 0;
4151 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004152 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004153 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4154 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004155 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004156
Misha Brukmancb6267b2004-07-30 12:50:08 +00004157 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004158 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4159 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4160 I.getName()+".demorgan"), I);
4161 return BinaryOperator::createNot(And);
4162 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004163 }
Chris Lattnera2881962003-02-18 19:28:33 +00004164
Reid Spencere4d87aa2006-12-23 06:05:41 +00004165 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4166 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4167 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004168 return R;
4169
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004170 Value *LHSVal, *RHSVal;
4171 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004172 ICmpInst::Predicate LHSCC, RHSCC;
4173 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4174 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4175 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4176 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4177 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4178 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4179 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004180 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4181 // We can't fold (ugt x, C) | (sgt x, C2).
4182 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004183 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004184 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004185 bool NeedsSwap;
4186 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004187 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004188 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004189 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004190
4191 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004192 std::swap(LHS, RHS);
4193 std::swap(LHSCst, RHSCst);
4194 std::swap(LHSCC, RHSCC);
4195 }
4196
Reid Spencere4d87aa2006-12-23 06:05:41 +00004197 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004198 // comparing a value against two constants and or'ing the result
4199 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004200 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4201 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004202 // equal.
4203 assert(LHSCst != RHSCst && "Compares not folded above?");
4204
4205 switch (LHSCC) {
4206 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004207 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004208 switch (RHSCC) {
4209 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004210 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004211 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4212 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4213 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4214 LHSVal->getName()+".off");
4215 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004216 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004217 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004218 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004219 break; // (X == 13 | X == 15) -> no change
4220 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4221 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004222 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004223 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4224 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4225 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004226 return ReplaceInstUsesWith(I, RHS);
4227 }
4228 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004229 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004230 switch (RHSCC) {
4231 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004232 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4233 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4234 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004235 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004236 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4237 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4238 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004239 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004240 }
4241 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004242 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004243 switch (RHSCC) {
4244 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004245 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004246 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004247 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004248 // If RHSCst is [us]MAXINT, it is always false. Not handling
4249 // this can cause overflow.
4250 if (RHSCst->isMaxValue(false))
4251 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004252 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4253 false, I);
4254 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4255 break;
4256 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4257 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004258 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004259 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4260 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004261 }
4262 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004263 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004264 switch (RHSCC) {
4265 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004266 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4267 break;
4268 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004269 // If RHSCst is [us]MAXINT, it is always false. Not handling
4270 // this can cause overflow.
4271 if (RHSCst->isMaxValue(true))
4272 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004273 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4274 false, I);
4275 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4276 break;
4277 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4278 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4279 return ReplaceInstUsesWith(I, RHS);
4280 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4281 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004282 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004283 break;
4284 case ICmpInst::ICMP_UGT:
4285 switch (RHSCC) {
4286 default: assert(0 && "Unknown integer condition code!");
4287 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4288 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4289 return ReplaceInstUsesWith(I, LHS);
4290 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4291 break;
4292 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4293 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004294 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004295 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4296 break;
4297 }
4298 break;
4299 case ICmpInst::ICMP_SGT:
4300 switch (RHSCC) {
4301 default: assert(0 && "Unknown integer condition code!");
4302 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4303 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4304 return ReplaceInstUsesWith(I, LHS);
4305 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4306 break;
4307 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4308 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004309 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004310 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4311 break;
4312 }
4313 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004314 }
4315 }
4316 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004317
4318 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004319 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004320 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004321 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4322 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004323 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004324 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004325 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4326 I.getType(), TD) &&
4327 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4328 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004329 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4330 Op1C->getOperand(0),
4331 I.getName());
4332 InsertNewInstBefore(NewOp, I);
4333 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4334 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004335 }
Chris Lattner99c65742007-10-24 05:38:08 +00004336 }
4337
4338
4339 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4340 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4341 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4342 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004343 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4344 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004345 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4346 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4347 // If either of the constants are nans, then the whole thing returns
4348 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004349 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004350 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4351
4352 // Otherwise, no need to compare the two constants, compare the
4353 // rest.
4354 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4355 RHS->getOperand(0));
4356 }
4357 }
4358 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004359
Chris Lattner7e708292002-06-25 16:13:24 +00004360 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004361}
4362
Chris Lattnerc317d392004-02-16 01:20:27 +00004363// XorSelf - Implements: X ^ X --> 0
4364struct XorSelf {
4365 Value *RHS;
4366 XorSelf(Value *rhs) : RHS(rhs) {}
4367 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4368 Instruction *apply(BinaryOperator &Xor) const {
4369 return &Xor;
4370 }
4371};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004372
4373
Chris Lattner7e708292002-06-25 16:13:24 +00004374Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004375 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004376 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004377
Chris Lattnere87597f2004-10-16 18:11:37 +00004378 if (isa<UndefValue>(Op1))
4379 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4380
Chris Lattnerc317d392004-02-16 01:20:27 +00004381 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4382 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004383 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004384 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004385 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004386
4387 // See if we can simplify any instructions used by the instruction whose sole
4388 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004389 if (!isa<VectorType>(I.getType())) {
4390 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4391 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4392 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4393 KnownZero, KnownOne))
4394 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004395 } else if (isa<ConstantAggregateZero>(Op1)) {
4396 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004397 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004398
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004399 // Is this a ~ operation?
4400 if (Value *NotOp = dyn_castNotVal(&I)) {
4401 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4402 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4403 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4404 if (Op0I->getOpcode() == Instruction::And ||
4405 Op0I->getOpcode() == Instruction::Or) {
4406 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4407 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4408 Instruction *NotY =
4409 BinaryOperator::createNot(Op0I->getOperand(1),
4410 Op0I->getOperand(1)->getName()+".not");
4411 InsertNewInstBefore(NotY, I);
4412 if (Op0I->getOpcode() == Instruction::And)
4413 return BinaryOperator::createOr(Op0NotVal, NotY);
4414 else
4415 return BinaryOperator::createAnd(Op0NotVal, NotY);
4416 }
4417 }
4418 }
4419 }
4420
4421
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004422 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004423 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4424 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4425 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004426 return new ICmpInst(ICI->getInversePredicate(),
4427 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004428
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004429 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4430 return new FCmpInst(FCI->getInversePredicate(),
4431 FCI->getOperand(0), FCI->getOperand(1));
4432 }
4433
Reid Spencere4d87aa2006-12-23 06:05:41 +00004434 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004435 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004436 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4437 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004438 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4439 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004440 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004441 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004442 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004443
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004444 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004445 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004446 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004447 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004448 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4449 return BinaryOperator::createSub(
4450 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004451 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004452 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004453 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004454 // (X + C) ^ signbit -> (X + C + signbit)
4455 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4456 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004457
Chris Lattner7c4049c2004-01-12 19:35:11 +00004458 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004459 } else if (Op0I->getOpcode() == Instruction::Or) {
4460 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004461 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004462 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4463 // Anything in both C1 and C2 is known to be zero, remove it from
4464 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004465 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004466 NewRHS = ConstantExpr::getAnd(NewRHS,
4467 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004468 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004469 I.setOperand(0, Op0I->getOperand(0));
4470 I.setOperand(1, NewRHS);
4471 return &I;
4472 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004473 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004474 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004475 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004476
4477 // Try to fold constant and into select arguments.
4478 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004479 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004480 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004481 if (isa<PHINode>(Op0))
4482 if (Instruction *NV = FoldOpIntoPhi(I))
4483 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004484 }
4485
Chris Lattner8d969642003-03-10 23:06:50 +00004486 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004487 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004488 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004489
Chris Lattner8d969642003-03-10 23:06:50 +00004490 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004491 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004492 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004493
Chris Lattner318bf792007-03-18 22:51:34 +00004494
4495 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4496 if (Op1I) {
4497 Value *A, *B;
4498 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4499 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004500 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004501 I.swapOperands();
4502 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004503 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004504 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004505 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004506 }
Chris Lattner318bf792007-03-18 22:51:34 +00004507 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4508 if (Op0 == A) // A^(A^B) == B
4509 return ReplaceInstUsesWith(I, B);
4510 else if (Op0 == B) // A^(B^A) == B
4511 return ReplaceInstUsesWith(I, A);
4512 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004513 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004514 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004515 std::swap(A, B);
4516 }
Chris Lattner318bf792007-03-18 22:51:34 +00004517 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004518 I.swapOperands(); // Simplified below.
4519 std::swap(Op0, Op1);
4520 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004521 }
Chris Lattner318bf792007-03-18 22:51:34 +00004522 }
4523
4524 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4525 if (Op0I) {
4526 Value *A, *B;
4527 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4528 if (A == Op1) // (B|A)^B == (A|B)^B
4529 std::swap(A, B);
4530 if (B == Op1) { // (A|B)^B == A & ~B
4531 Instruction *NotB =
4532 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4533 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004534 }
Chris Lattner318bf792007-03-18 22:51:34 +00004535 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4536 if (Op1 == A) // (A^B)^A == B
4537 return ReplaceInstUsesWith(I, B);
4538 else if (Op1 == B) // (B^A)^A == B
4539 return ReplaceInstUsesWith(I, A);
4540 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4541 if (A == Op1) // (A&B)^A -> (B&A)^A
4542 std::swap(A, B);
4543 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004544 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004545 Instruction *N =
4546 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004547 return BinaryOperator::createAnd(N, Op1);
4548 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004549 }
Chris Lattner318bf792007-03-18 22:51:34 +00004550 }
4551
4552 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4553 if (Op0I && Op1I && Op0I->isShift() &&
4554 Op0I->getOpcode() == Op1I->getOpcode() &&
4555 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4556 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4557 Instruction *NewOp =
4558 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4559 Op1I->getOperand(0),
4560 Op0I->getName()), I);
4561 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4562 Op1I->getOperand(1));
4563 }
4564
4565 if (Op0I && Op1I) {
4566 Value *A, *B, *C, *D;
4567 // (A & B)^(A | B) -> A ^ B
4568 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4569 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4570 if ((A == C && B == D) || (A == D && B == C))
4571 return BinaryOperator::createXor(A, B);
4572 }
4573 // (A | B)^(A & B) -> A ^ B
4574 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4575 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4576 if ((A == C && B == D) || (A == D && B == C))
4577 return BinaryOperator::createXor(A, B);
4578 }
4579
4580 // (A & B)^(C & D)
4581 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4582 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4583 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4584 // (X & Y)^(X & Y) -> (Y^Z) & X
4585 Value *X = 0, *Y = 0, *Z = 0;
4586 if (A == C)
4587 X = A, Y = B, Z = D;
4588 else if (A == D)
4589 X = A, Y = B, Z = C;
4590 else if (B == C)
4591 X = B, Y = A, Z = D;
4592 else if (B == D)
4593 X = B, Y = A, Z = C;
4594
4595 if (X) {
4596 Instruction *NewOp =
4597 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4598 return BinaryOperator::createAnd(NewOp, X);
4599 }
4600 }
4601 }
4602
Reid Spencere4d87aa2006-12-23 06:05:41 +00004603 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4604 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4605 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004606 return R;
4607
Chris Lattner6fc205f2006-05-05 06:39:07 +00004608 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004609 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004610 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004611 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4612 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004613 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004614 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004615 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4616 I.getType(), TD) &&
4617 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4618 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004619 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4620 Op1C->getOperand(0),
4621 I.getName());
4622 InsertNewInstBefore(NewOp, I);
4623 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4624 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004625 }
Chris Lattner99c65742007-10-24 05:38:08 +00004626 }
Chris Lattner7e708292002-06-25 16:13:24 +00004627 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004628}
4629
Chris Lattnera96879a2004-09-29 17:40:11 +00004630/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4631/// overflowed for this type.
4632static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004633 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004634 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004635
Reid Spencere4e40032007-03-21 23:19:50 +00004636 if (IsSigned)
4637 if (In2->getValue().isNegative())
4638 return Result->getValue().sgt(In1->getValue());
4639 else
4640 return Result->getValue().slt(In1->getValue());
4641 else
4642 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004643}
4644
Chris Lattner574da9b2005-01-13 20:14:25 +00004645/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4646/// code necessary to compute the offset from the base pointer (without adding
4647/// in the base pointer). Return the result as a signed integer of intptr size.
4648static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4649 TargetData &TD = IC.getTargetData();
4650 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004651 const Type *IntPtrTy = TD.getIntPtrType();
4652 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004653
4654 // Build a mask for high order bits.
Chris Lattnere62f0212007-04-28 04:52:43 +00004655 unsigned IntPtrWidth = TD.getPointerSize()*8;
4656 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004657
Chris Lattner574da9b2005-01-13 20:14:25 +00004658 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4659 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004660 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004661 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4662 if (OpC->isZero()) continue;
4663
4664 // Handle a struct index, which adds its field offset to the pointer.
4665 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4666 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4667
4668 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4669 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004670 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004671 Result = IC.InsertNewInstBefore(
4672 BinaryOperator::createAdd(Result,
4673 ConstantInt::get(IntPtrTy, Size),
4674 GEP->getName()+".offs"), I);
4675 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004676 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004677
4678 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4679 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4680 Scale = ConstantExpr::getMul(OC, Scale);
4681 if (Constant *RC = dyn_cast<Constant>(Result))
4682 Result = ConstantExpr::getAdd(RC, Scale);
4683 else {
4684 // Emit an add instruction.
4685 Result = IC.InsertNewInstBefore(
4686 BinaryOperator::createAdd(Result, Scale,
4687 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004688 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004689 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004690 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004691 // Convert to correct type.
4692 if (Op->getType() != IntPtrTy) {
4693 if (Constant *OpC = dyn_cast<Constant>(Op))
4694 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4695 else
4696 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4697 Op->getName()+".c"), I);
4698 }
4699 if (Size != 1) {
4700 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4701 if (Constant *OpC = dyn_cast<Constant>(Op))
4702 Op = ConstantExpr::getMul(OpC, Scale);
4703 else // We'll let instcombine(mul) convert this to a shl if possible.
4704 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4705 GEP->getName()+".idx"), I);
4706 }
4707
4708 // Emit an add instruction.
4709 if (isa<Constant>(Op) && isa<Constant>(Result))
4710 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4711 cast<Constant>(Result));
4712 else
4713 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4714 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004715 }
4716 return Result;
4717}
4718
Reid Spencere4d87aa2006-12-23 06:05:41 +00004719/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004720/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004721Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4722 ICmpInst::Predicate Cond,
4723 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004724 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004725
4726 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4727 if (isa<PointerType>(CI->getOperand(0)->getType()))
4728 RHS = CI->getOperand(0);
4729
Chris Lattner574da9b2005-01-13 20:14:25 +00004730 Value *PtrBase = GEPLHS->getOperand(0);
4731 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004732 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4733 // This transformation is valid because we know pointers can't overflow.
4734 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4735 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4736 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004737 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004738 // If the base pointers are different, but the indices are the same, just
4739 // compare the base pointer.
4740 if (PtrBase != GEPRHS->getOperand(0)) {
4741 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004742 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004743 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004744 if (IndicesTheSame)
4745 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4746 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4747 IndicesTheSame = false;
4748 break;
4749 }
4750
4751 // If all indices are the same, just compare the base pointers.
4752 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004753 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4754 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004755
4756 // Otherwise, the base pointers are different and the indices are
4757 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004758 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004759 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004760
Chris Lattnere9d782b2005-01-13 22:25:21 +00004761 // If one of the GEPs has all zero indices, recurse.
4762 bool AllZeros = true;
4763 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4764 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4765 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4766 AllZeros = false;
4767 break;
4768 }
4769 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004770 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4771 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004772
4773 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004774 AllZeros = true;
4775 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4776 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4777 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4778 AllZeros = false;
4779 break;
4780 }
4781 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004782 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004783
Chris Lattner4401c9c2005-01-14 00:20:05 +00004784 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4785 // If the GEPs only differ by one index, compare it.
4786 unsigned NumDifferences = 0; // Keep track of # differences.
4787 unsigned DiffOperand = 0; // The operand that differs.
4788 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4789 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004790 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4791 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004792 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004793 NumDifferences = 2;
4794 break;
4795 } else {
4796 if (NumDifferences++) break;
4797 DiffOperand = i;
4798 }
4799 }
4800
4801 if (NumDifferences == 0) // SAME GEP?
4802 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004803 ConstantInt::get(Type::Int1Ty,
4804 isTrueWhenEqual(Cond)));
4805
Chris Lattner4401c9c2005-01-14 00:20:05 +00004806 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004807 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4808 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004809 // Make sure we do a signed comparison here.
4810 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004811 }
4812 }
4813
Reid Spencere4d87aa2006-12-23 06:05:41 +00004814 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004815 // the result to fold to a constant!
4816 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4817 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4818 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4819 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4820 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004821 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004822 }
4823 }
4824 return 0;
4825}
4826
Reid Spencere4d87aa2006-12-23 06:05:41 +00004827Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4828 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004829 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004830
Chris Lattner58e97462007-01-14 19:42:17 +00004831 // Fold trivial predicates.
4832 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4833 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4834 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4835 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4836
4837 // Simplify 'fcmp pred X, X'
4838 if (Op0 == Op1) {
4839 switch (I.getPredicate()) {
4840 default: assert(0 && "Unknown predicate!");
4841 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4842 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4843 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4844 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4845 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4846 case FCmpInst::FCMP_OLT: // True if ordered and less than
4847 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4848 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4849
4850 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4851 case FCmpInst::FCMP_ULT: // True if unordered or less than
4852 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4853 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4854 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4855 I.setPredicate(FCmpInst::FCMP_UNO);
4856 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4857 return &I;
4858
4859 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4860 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4861 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4862 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4863 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4864 I.setPredicate(FCmpInst::FCMP_ORD);
4865 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4866 return &I;
4867 }
4868 }
4869
Reid Spencere4d87aa2006-12-23 06:05:41 +00004870 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004871 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00004872
Reid Spencere4d87aa2006-12-23 06:05:41 +00004873 // Handle fcmp with constant RHS
4874 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4875 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4876 switch (LHSI->getOpcode()) {
4877 case Instruction::PHI:
4878 if (Instruction *NV = FoldOpIntoPhi(I))
4879 return NV;
4880 break;
4881 case Instruction::Select:
4882 // If either operand of the select is a constant, we can fold the
4883 // comparison into the select arms, which will cause one to be
4884 // constant folded and the select turned into a bitwise or.
4885 Value *Op1 = 0, *Op2 = 0;
4886 if (LHSI->hasOneUse()) {
4887 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4888 // Fold the known value into the constant operand.
4889 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4890 // Insert a new FCmp of the other select operand.
4891 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4892 LHSI->getOperand(2), RHSC,
4893 I.getName()), I);
4894 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4895 // Fold the known value into the constant operand.
4896 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4897 // Insert a new FCmp of the other select operand.
4898 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4899 LHSI->getOperand(1), RHSC,
4900 I.getName()), I);
4901 }
4902 }
4903
4904 if (Op1)
4905 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4906 break;
4907 }
4908 }
4909
4910 return Changed ? &I : 0;
4911}
4912
4913Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4914 bool Changed = SimplifyCompare(I);
4915 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4916 const Type *Ty = Op0->getType();
4917
4918 // icmp X, X
4919 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00004920 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4921 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004922
4923 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004924 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00004925
Reid Spencere4d87aa2006-12-23 06:05:41 +00004926 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004927 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004928 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4929 isa<ConstantPointerNull>(Op0)) &&
4930 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004931 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00004932 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4933 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00004934
Reid Spencere4d87aa2006-12-23 06:05:41 +00004935 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00004936 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004937 switch (I.getPredicate()) {
4938 default: assert(0 && "Invalid icmp instruction!");
4939 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004940 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004941 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004942 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004943 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004944 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00004945 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004946
Reid Spencere4d87aa2006-12-23 06:05:41 +00004947 case ICmpInst::ICMP_UGT:
4948 case ICmpInst::ICMP_SGT:
4949 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00004950 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004951 case ICmpInst::ICMP_ULT:
4952 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00004953 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4954 InsertNewInstBefore(Not, I);
4955 return BinaryOperator::createAnd(Not, Op1);
4956 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004957 case ICmpInst::ICMP_UGE:
4958 case ICmpInst::ICMP_SGE:
4959 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00004960 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004961 case ICmpInst::ICMP_ULE:
4962 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00004963 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4964 InsertNewInstBefore(Not, I);
4965 return BinaryOperator::createOr(Not, Op1);
4966 }
4967 }
Chris Lattner8b170942002-08-09 23:47:40 +00004968 }
4969
Chris Lattner2be51ae2004-06-09 04:24:29 +00004970 // See if we are doing a comparison between a constant and an instruction that
4971 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00004972 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00004973 Value *A, *B;
4974
Chris Lattnerb6566012008-01-05 01:18:20 +00004975 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4976 if (I.isEquality() && CI->isNullValue() &&
4977 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4978 // (icmp cond A B) if cond is equality
4979 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00004980 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00004981
Reid Spencere4d87aa2006-12-23 06:05:41 +00004982 switch (I.getPredicate()) {
4983 default: break;
4984 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4985 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004986 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004987 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4988 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4989 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4990 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004991 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4992 if (CI->isMinValue(true))
4993 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4994 ConstantInt::getAllOnesValue(Op0->getType()));
4995
Reid Spencere4d87aa2006-12-23 06:05:41 +00004996 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004997
Reid Spencere4d87aa2006-12-23 06:05:41 +00004998 case ICmpInst::ICMP_SLT:
4999 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005000 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005001 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5002 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5003 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5004 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5005 break;
5006
5007 case ICmpInst::ICMP_UGT:
5008 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005009 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005010 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5011 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5012 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5013 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005014
5015 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5016 if (CI->isMaxValue(true))
5017 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5018 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005019 break;
5020
5021 case ICmpInst::ICMP_SGT:
5022 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005023 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005024 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5025 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5026 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5027 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5028 break;
5029
5030 case ICmpInst::ICMP_ULE:
5031 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005032 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005033 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5034 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5035 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5036 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5037 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005038
Reid Spencere4d87aa2006-12-23 06:05:41 +00005039 case ICmpInst::ICMP_SLE:
5040 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005041 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005042 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5043 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5044 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5045 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5046 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005047
Reid Spencere4d87aa2006-12-23 06:05:41 +00005048 case ICmpInst::ICMP_UGE:
5049 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005050 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005051 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5052 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5053 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5054 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5055 break;
5056
5057 case ICmpInst::ICMP_SGE:
5058 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005059 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005060 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5061 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5062 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5063 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5064 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005065 }
5066
Reid Spencere4d87aa2006-12-23 06:05:41 +00005067 // If we still have a icmp le or icmp ge instruction, turn it into the
5068 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005069 // already been handled above, this requires little checking.
5070 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005071 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005072 default: break;
5073 case ICmpInst::ICMP_ULE:
5074 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5075 case ICmpInst::ICMP_SLE:
5076 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5077 case ICmpInst::ICMP_UGE:
5078 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5079 case ICmpInst::ICMP_SGE:
5080 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005081 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005082
5083 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005084 // in the input. If this comparison is a normal comparison, it demands all
5085 // bits, if it is a sign bit comparison, it only demands the sign bit.
5086
5087 bool UnusedBit;
5088 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5089
Reid Spencer0460fb32007-03-22 20:36:03 +00005090 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5091 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005092 if (SimplifyDemandedBits(Op0,
5093 isSignBit ? APInt::getSignBit(BitWidth)
5094 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005095 KnownZero, KnownOne, 0))
5096 return &I;
5097
5098 // Given the known and unknown bits, compute a range that the LHS could be
5099 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005100 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005101 // Compute the Min, Max and RHS values based on the known bits. For the
5102 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005103 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5104 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005105 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005106 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5107 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005108 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005109 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5110 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005111 }
5112 switch (I.getPredicate()) { // LE/GE have been folded already.
5113 default: assert(0 && "Unknown icmp opcode!");
5114 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005115 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005116 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005117 break;
5118 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005119 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005120 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005121 break;
5122 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005123 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005124 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005125 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005126 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005127 break;
5128 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005129 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005130 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005131 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005132 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005133 break;
5134 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005135 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005136 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005137 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005138 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005139 break;
5140 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005141 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005142 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005143 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005144 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005145 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005146 }
5147 }
5148
Reid Spencere4d87aa2006-12-23 06:05:41 +00005149 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005150 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005151 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005152 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005153 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5154 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005155 }
5156
Chris Lattner01deb9d2007-04-03 17:43:25 +00005157 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005158 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5159 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5160 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005161 case Instruction::GetElementPtr:
5162 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005163 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005164 bool isAllZeros = true;
5165 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5166 if (!isa<Constant>(LHSI->getOperand(i)) ||
5167 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5168 isAllZeros = false;
5169 break;
5170 }
5171 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005172 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005173 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5174 }
5175 break;
5176
Chris Lattner6970b662005-04-23 15:31:55 +00005177 case Instruction::PHI:
5178 if (Instruction *NV = FoldOpIntoPhi(I))
5179 return NV;
5180 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005181 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005182 // If either operand of the select is a constant, we can fold the
5183 // comparison into the select arms, which will cause one to be
5184 // constant folded and the select turned into a bitwise or.
5185 Value *Op1 = 0, *Op2 = 0;
5186 if (LHSI->hasOneUse()) {
5187 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5188 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005189 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5190 // Insert a new ICmp of the other select operand.
5191 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5192 LHSI->getOperand(2), RHSC,
5193 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005194 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5195 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005196 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5197 // Insert a new ICmp of the other select operand.
5198 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5199 LHSI->getOperand(1), RHSC,
5200 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005201 }
5202 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005203
Chris Lattner6970b662005-04-23 15:31:55 +00005204 if (Op1)
5205 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5206 break;
5207 }
Chris Lattner4802d902007-04-06 18:57:34 +00005208 case Instruction::Malloc:
5209 // If we have (malloc != null), and if the malloc has a single use, we
5210 // can assume it is successful and remove the malloc.
5211 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5212 AddToWorkList(LHSI);
5213 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5214 !isTrueWhenEqual(I)));
5215 }
5216 break;
5217 }
Chris Lattner6970b662005-04-23 15:31:55 +00005218 }
5219
Reid Spencere4d87aa2006-12-23 06:05:41 +00005220 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005221 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005222 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005223 return NI;
5224 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005225 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5226 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005227 return NI;
5228
Reid Spencere4d87aa2006-12-23 06:05:41 +00005229 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005230 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5231 // now.
5232 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5233 if (isa<PointerType>(Op0->getType()) &&
5234 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005235 // We keep moving the cast from the left operand over to the right
5236 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005237 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005238
Chris Lattner57d86372007-01-06 01:45:59 +00005239 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5240 // so eliminate it as well.
5241 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5242 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005243
Chris Lattnerde90b762003-11-03 04:25:02 +00005244 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005245 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005246 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005247 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005248 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005249 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005250 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005251 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005252 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005253 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005254 }
Chris Lattner57d86372007-01-06 01:45:59 +00005255 }
5256
5257 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005258 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005259 // This comes up when you have code like
5260 // int X = A < B;
5261 // if (X) ...
5262 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005263 // with a constant or another cast from the same type.
5264 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005265 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005266 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005267 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005268
Chris Lattner65b72ba2006-09-18 04:22:48 +00005269 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005270 Value *A, *B, *C, *D;
5271 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5272 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5273 Value *OtherVal = A == Op1 ? B : A;
5274 return new ICmpInst(I.getPredicate(), OtherVal,
5275 Constant::getNullValue(A->getType()));
5276 }
5277
5278 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5279 // A^c1 == C^c2 --> A == C^(c1^c2)
5280 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5281 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5282 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005283 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005284 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5285 return new ICmpInst(I.getPredicate(), A,
5286 InsertNewInstBefore(Xor, I));
5287 }
5288
5289 // A^B == A^D -> B == D
5290 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5291 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5292 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5293 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5294 }
5295 }
5296
5297 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5298 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005299 // A == (A^B) -> B == 0
5300 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005301 return new ICmpInst(I.getPredicate(), OtherVal,
5302 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005303 }
5304 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005305 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005306 return new ICmpInst(I.getPredicate(), B,
5307 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005308 }
5309 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005310 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005311 return new ICmpInst(I.getPredicate(), B,
5312 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005313 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005314
Chris Lattner9c2328e2006-11-14 06:06:06 +00005315 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5316 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5317 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5318 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5319 Value *X = 0, *Y = 0, *Z = 0;
5320
5321 if (A == C) {
5322 X = B; Y = D; Z = A;
5323 } else if (A == D) {
5324 X = B; Y = C; Z = A;
5325 } else if (B == C) {
5326 X = A; Y = D; Z = B;
5327 } else if (B == D) {
5328 X = A; Y = C; Z = B;
5329 }
5330
5331 if (X) { // Build (X^Y) & Z
5332 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5333 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5334 I.setOperand(0, Op1);
5335 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5336 return &I;
5337 }
5338 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005339 }
Chris Lattner7e708292002-06-25 16:13:24 +00005340 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005341}
5342
Chris Lattner562ef782007-06-20 23:46:26 +00005343
5344/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5345/// and CmpRHS are both known to be integer constants.
5346Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5347 ConstantInt *DivRHS) {
5348 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5349 const APInt &CmpRHSV = CmpRHS->getValue();
5350
5351 // FIXME: If the operand types don't match the type of the divide
5352 // then don't attempt this transform. The code below doesn't have the
5353 // logic to deal with a signed divide and an unsigned compare (and
5354 // vice versa). This is because (x /s C1) <s C2 produces different
5355 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5356 // (x /u C1) <u C2. Simply casting the operands and result won't
5357 // work. :( The if statement below tests that condition and bails
5358 // if it finds it.
5359 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5360 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5361 return 0;
5362 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005363 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005364
5365 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5366 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5367 // C2 (CI). By solving for X we can turn this into a range check
5368 // instead of computing a divide.
5369 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5370
5371 // Determine if the product overflows by seeing if the product is
5372 // not equal to the divide. Make sure we do the same kind of divide
5373 // as in the LHS instruction that we're folding.
5374 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5375 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5376
5377 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005378 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005379
Chris Lattner1dbfd482007-06-21 18:11:19 +00005380 // Figure out the interval that is being checked. For example, a comparison
5381 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5382 // Compute this interval based on the constants involved and the signedness of
5383 // the compare/divide. This computes a half-open interval, keeping track of
5384 // whether either value in the interval overflows. After analysis each
5385 // overflow variable is set to 0 if it's corresponding bound variable is valid
5386 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5387 int LoOverflow = 0, HiOverflow = 0;
5388 ConstantInt *LoBound = 0, *HiBound = 0;
5389
5390
Chris Lattner562ef782007-06-20 23:46:26 +00005391 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005392 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005393 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005394 HiOverflow = LoOverflow = ProdOV;
5395 if (!HiOverflow)
5396 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005397 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005398 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005399 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005400 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5401 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005402 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005403 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5404 HiOverflow = LoOverflow = ProdOV;
5405 if (!HiOverflow)
5406 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005407 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005408 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005409 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5410 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005411 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005412 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005413 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005414 }
Dan Gohman76491272008-02-13 22:09:18 +00005415 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005416 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005417 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005418 LoBound = AddOne(DivRHS);
5419 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005420 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5421 HiOverflow = 1; // [INTMIN+1, overflow)
5422 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5423 }
Dan Gohman76491272008-02-13 22:09:18 +00005424 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005425 // e.g. X/-5 op 3 --> [-19, -14)
5426 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005427 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005428 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005429 HiBound = AddOne(Prod);
5430 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005431 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005432 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005433 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005434 HiBound = Subtract(Prod, DivRHS);
5435 }
5436
Chris Lattner1dbfd482007-06-21 18:11:19 +00005437 // Dividing by a negative swaps the condition. LT <-> GT
5438 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005439 }
5440
5441 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005442 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005443 default: assert(0 && "Unhandled icmp opcode!");
5444 case ICmpInst::ICMP_EQ:
5445 if (LoOverflow && HiOverflow)
5446 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5447 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005448 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005449 ICmpInst::ICMP_UGE, X, LoBound);
5450 else if (LoOverflow)
5451 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5452 ICmpInst::ICMP_ULT, X, HiBound);
5453 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005454 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005455 case ICmpInst::ICMP_NE:
5456 if (LoOverflow && HiOverflow)
5457 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5458 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005459 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005460 ICmpInst::ICMP_ULT, X, LoBound);
5461 else if (LoOverflow)
5462 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5463 ICmpInst::ICMP_UGE, X, HiBound);
5464 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005465 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005466 case ICmpInst::ICMP_ULT:
5467 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005468 if (LoOverflow == +1) // Low bound is greater than input range.
5469 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5470 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005471 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005472 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005473 case ICmpInst::ICMP_UGT:
5474 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005475 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005476 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005477 else if (HiOverflow == -1) // High bound less than input range.
5478 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5479 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005480 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5481 else
5482 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5483 }
5484}
5485
5486
Chris Lattner01deb9d2007-04-03 17:43:25 +00005487/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5488///
5489Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5490 Instruction *LHSI,
5491 ConstantInt *RHS) {
5492 const APInt &RHSV = RHS->getValue();
5493
5494 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005495 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005496 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5497 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5498 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005499 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5500 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005501 Value *CompareVal = LHSI->getOperand(0);
5502
5503 // If the sign bit of the XorCST is not set, there is no change to
5504 // the operation, just stop using the Xor.
5505 if (!XorCST->getValue().isNegative()) {
5506 ICI.setOperand(0, CompareVal);
5507 AddToWorkList(LHSI);
5508 return &ICI;
5509 }
5510
5511 // Was the old condition true if the operand is positive?
5512 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5513
5514 // If so, the new one isn't.
5515 isTrueIfPositive ^= true;
5516
5517 if (isTrueIfPositive)
5518 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5519 else
5520 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5521 }
5522 }
5523 break;
5524 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5525 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5526 LHSI->getOperand(0)->hasOneUse()) {
5527 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5528
5529 // If the LHS is an AND of a truncating cast, we can widen the
5530 // and/compare to be the input width without changing the value
5531 // produced, eliminating a cast.
5532 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5533 // We can do this transformation if either the AND constant does not
5534 // have its sign bit set or if it is an equality comparison.
5535 // Extending a relational comparison when we're checking the sign
5536 // bit would not work.
5537 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005538 (ICI.isEquality() ||
5539 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005540 uint32_t BitWidth =
5541 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5542 APInt NewCST = AndCST->getValue();
5543 NewCST.zext(BitWidth);
5544 APInt NewCI = RHSV;
5545 NewCI.zext(BitWidth);
5546 Instruction *NewAnd =
5547 BinaryOperator::createAnd(Cast->getOperand(0),
5548 ConstantInt::get(NewCST),LHSI->getName());
5549 InsertNewInstBefore(NewAnd, ICI);
5550 return new ICmpInst(ICI.getPredicate(), NewAnd,
5551 ConstantInt::get(NewCI));
5552 }
5553 }
5554
5555 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5556 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5557 // happens a LOT in code produced by the C front-end, for bitfield
5558 // access.
5559 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5560 if (Shift && !Shift->isShift())
5561 Shift = 0;
5562
5563 ConstantInt *ShAmt;
5564 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5565 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5566 const Type *AndTy = AndCST->getType(); // Type of the and.
5567
5568 // We can fold this as long as we can't shift unknown bits
5569 // into the mask. This can only happen with signed shift
5570 // rights, as they sign-extend.
5571 if (ShAmt) {
5572 bool CanFold = Shift->isLogicalShift();
5573 if (!CanFold) {
5574 // To test for the bad case of the signed shr, see if any
5575 // of the bits shifted in could be tested after the mask.
5576 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5577 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5578
5579 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5580 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5581 AndCST->getValue()) == 0)
5582 CanFold = true;
5583 }
5584
5585 if (CanFold) {
5586 Constant *NewCst;
5587 if (Shift->getOpcode() == Instruction::Shl)
5588 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5589 else
5590 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5591
5592 // Check to see if we are shifting out any of the bits being
5593 // compared.
5594 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5595 // If we shifted bits out, the fold is not going to work out.
5596 // As a special case, check to see if this means that the
5597 // result is always true or false now.
5598 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5599 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5600 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5601 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5602 } else {
5603 ICI.setOperand(1, NewCst);
5604 Constant *NewAndCST;
5605 if (Shift->getOpcode() == Instruction::Shl)
5606 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5607 else
5608 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5609 LHSI->setOperand(1, NewAndCST);
5610 LHSI->setOperand(0, Shift->getOperand(0));
5611 AddToWorkList(Shift); // Shift is dead.
5612 AddUsesToWorkList(ICI);
5613 return &ICI;
5614 }
5615 }
5616 }
5617
5618 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5619 // preferable because it allows the C<<Y expression to be hoisted out
5620 // of a loop if Y is invariant and X is not.
5621 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5622 ICI.isEquality() && !Shift->isArithmeticShift() &&
5623 isa<Instruction>(Shift->getOperand(0))) {
5624 // Compute C << Y.
5625 Value *NS;
5626 if (Shift->getOpcode() == Instruction::LShr) {
5627 NS = BinaryOperator::createShl(AndCST,
5628 Shift->getOperand(1), "tmp");
5629 } else {
5630 // Insert a logical shift.
5631 NS = BinaryOperator::createLShr(AndCST,
5632 Shift->getOperand(1), "tmp");
5633 }
5634 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5635
5636 // Compute X & (C << Y).
5637 Instruction *NewAnd =
5638 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5639 InsertNewInstBefore(NewAnd, ICI);
5640
5641 ICI.setOperand(0, NewAnd);
5642 return &ICI;
5643 }
5644 }
5645 break;
5646
Chris Lattnera0141b92007-07-15 20:42:37 +00005647 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5648 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5649 if (!ShAmt) break;
5650
5651 uint32_t TypeBits = RHSV.getBitWidth();
5652
5653 // Check that the shift amount is in range. If not, don't perform
5654 // undefined shifts. When the shift is visited it will be
5655 // simplified.
5656 if (ShAmt->uge(TypeBits))
5657 break;
5658
5659 if (ICI.isEquality()) {
5660 // If we are comparing against bits always shifted out, the
5661 // comparison cannot succeed.
5662 Constant *Comp =
5663 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5664 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5665 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5666 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5667 return ReplaceInstUsesWith(ICI, Cst);
5668 }
5669
5670 if (LHSI->hasOneUse()) {
5671 // Otherwise strength reduce the shift into an and.
5672 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5673 Constant *Mask =
5674 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005675
Chris Lattnera0141b92007-07-15 20:42:37 +00005676 Instruction *AndI =
5677 BinaryOperator::createAnd(LHSI->getOperand(0),
5678 Mask, LHSI->getName()+".mask");
5679 Value *And = InsertNewInstBefore(AndI, ICI);
5680 return new ICmpInst(ICI.getPredicate(), And,
5681 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005682 }
5683 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005684
5685 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5686 bool TrueIfSigned = false;
5687 if (LHSI->hasOneUse() &&
5688 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5689 // (X << 31) <s 0 --> (X&1) != 0
5690 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5691 (TypeBits-ShAmt->getZExtValue()-1));
5692 Instruction *AndI =
5693 BinaryOperator::createAnd(LHSI->getOperand(0),
5694 Mask, LHSI->getName()+".mask");
5695 Value *And = InsertNewInstBefore(AndI, ICI);
5696
5697 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5698 And, Constant::getNullValue(And->getType()));
5699 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005700 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005701 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005702
5703 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005704 case Instruction::AShr: {
5705 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5706 if (!ShAmt) break;
5707
5708 if (ICI.isEquality()) {
5709 // Check that the shift amount is in range. If not, don't perform
5710 // undefined shifts. When the shift is visited it will be
5711 // simplified.
5712 uint32_t TypeBits = RHSV.getBitWidth();
5713 if (ShAmt->uge(TypeBits))
5714 break;
5715 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5716
5717 // If we are comparing against bits always shifted out, the
5718 // comparison cannot succeed.
5719 APInt Comp = RHSV << ShAmtVal;
5720 if (LHSI->getOpcode() == Instruction::LShr)
5721 Comp = Comp.lshr(ShAmtVal);
5722 else
5723 Comp = Comp.ashr(ShAmtVal);
5724
5725 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5726 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5727 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5728 return ReplaceInstUsesWith(ICI, Cst);
5729 }
5730
5731 if (LHSI->hasOneUse() || RHSV == 0) {
5732 // Otherwise strength reduce the shift into an and.
5733 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5734 Constant *Mask = ConstantInt::get(Val);
Chris Lattner01deb9d2007-04-03 17:43:25 +00005735
Chris Lattnera0141b92007-07-15 20:42:37 +00005736 Instruction *AndI =
5737 BinaryOperator::createAnd(LHSI->getOperand(0),
5738 Mask, LHSI->getName()+".mask");
5739 Value *And = InsertNewInstBefore(AndI, ICI);
5740 return new ICmpInst(ICI.getPredicate(), And,
5741 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005742 }
5743 }
5744 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005745 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005746
5747 case Instruction::SDiv:
5748 case Instruction::UDiv:
5749 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5750 // Fold this div into the comparison, producing a range check.
5751 // Determine, based on the divide type, what the range is being
5752 // checked. If there is an overflow on the low or high side, remember
5753 // it, otherwise compute the range [low, hi) bounding the new value.
5754 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005755 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5756 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5757 DivRHS))
5758 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005759 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00005760
5761 case Instruction::Add:
5762 // Fold: icmp pred (add, X, C1), C2
5763
5764 if (!ICI.isEquality()) {
5765 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5766 if (!LHSC) break;
5767 const APInt &LHSV = LHSC->getValue();
5768
5769 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5770 .subtract(LHSV);
5771
5772 if (ICI.isSignedPredicate()) {
5773 if (CR.getLower().isSignBit()) {
5774 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5775 ConstantInt::get(CR.getUpper()));
5776 } else if (CR.getUpper().isSignBit()) {
5777 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5778 ConstantInt::get(CR.getLower()));
5779 }
5780 } else {
5781 if (CR.getLower().isMinValue()) {
5782 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5783 ConstantInt::get(CR.getUpper()));
5784 } else if (CR.getUpper().isMinValue()) {
5785 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5786 ConstantInt::get(CR.getLower()));
5787 }
5788 }
5789 }
5790 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005791 }
5792
5793 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5794 if (ICI.isEquality()) {
5795 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5796
5797 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5798 // the second operand is a constant, simplify a bit.
5799 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5800 switch (BO->getOpcode()) {
5801 case Instruction::SRem:
5802 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5803 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5804 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5805 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5806 Instruction *NewRem =
5807 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5808 BO->getName());
5809 InsertNewInstBefore(NewRem, ICI);
5810 return new ICmpInst(ICI.getPredicate(), NewRem,
5811 Constant::getNullValue(BO->getType()));
5812 }
5813 }
5814 break;
5815 case Instruction::Add:
5816 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5817 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5818 if (BO->hasOneUse())
5819 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5820 Subtract(RHS, BOp1C));
5821 } else if (RHSV == 0) {
5822 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5823 // efficiently invertible, or if the add has just this one use.
5824 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5825
5826 if (Value *NegVal = dyn_castNegVal(BOp1))
5827 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5828 else if (Value *NegVal = dyn_castNegVal(BOp0))
5829 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5830 else if (BO->hasOneUse()) {
5831 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5832 InsertNewInstBefore(Neg, ICI);
5833 Neg->takeName(BO);
5834 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5835 }
5836 }
5837 break;
5838 case Instruction::Xor:
5839 // For the xor case, we can xor two constants together, eliminating
5840 // the explicit xor.
5841 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5842 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5843 ConstantExpr::getXor(RHS, BOC));
5844
5845 // FALLTHROUGH
5846 case Instruction::Sub:
5847 // Replace (([sub|xor] A, B) != 0) with (A != B)
5848 if (RHSV == 0)
5849 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5850 BO->getOperand(1));
5851 break;
5852
5853 case Instruction::Or:
5854 // If bits are being or'd in that are not present in the constant we
5855 // are comparing against, then the comparison could never succeed!
5856 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5857 Constant *NotCI = ConstantExpr::getNot(RHS);
5858 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5859 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5860 isICMP_NE));
5861 }
5862 break;
5863
5864 case Instruction::And:
5865 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5866 // If bits are being compared against that are and'd out, then the
5867 // comparison can never succeed!
5868 if ((RHSV & ~BOC->getValue()) != 0)
5869 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5870 isICMP_NE));
5871
5872 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5873 if (RHS == BOC && RHSV.isPowerOf2())
5874 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5875 ICmpInst::ICMP_NE, LHSI,
5876 Constant::getNullValue(RHS->getType()));
5877
5878 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5879 if (isSignBit(BOC)) {
5880 Value *X = BO->getOperand(0);
5881 Constant *Zero = Constant::getNullValue(X->getType());
5882 ICmpInst::Predicate pred = isICMP_NE ?
5883 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5884 return new ICmpInst(pred, X, Zero);
5885 }
5886
5887 // ((X & ~7) == 0) --> X < 8
5888 if (RHSV == 0 && isHighOnes(BOC)) {
5889 Value *X = BO->getOperand(0);
5890 Constant *NegX = ConstantExpr::getNeg(BOC);
5891 ICmpInst::Predicate pred = isICMP_NE ?
5892 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5893 return new ICmpInst(pred, X, NegX);
5894 }
5895 }
5896 default: break;
5897 }
5898 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5899 // Handle icmp {eq|ne} <intrinsic>, intcst.
5900 if (II->getIntrinsicID() == Intrinsic::bswap) {
5901 AddToWorkList(II);
5902 ICI.setOperand(0, II->getOperand(1));
5903 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5904 return &ICI;
5905 }
5906 }
5907 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00005908 // If the LHS is a cast from an integral value of the same size,
5909 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00005910 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5911 Value *CastOp = Cast->getOperand(0);
5912 const Type *SrcTy = CastOp->getType();
5913 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5914 if (SrcTy->isInteger() &&
5915 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5916 // If this is an unsigned comparison, try to make the comparison use
5917 // smaller constant values.
5918 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5919 // X u< 128 => X s> -1
5920 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5921 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5922 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5923 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5924 // X u> 127 => X s< 0
5925 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5926 Constant::getNullValue(SrcTy));
5927 }
5928 }
5929 }
5930 }
5931 return 0;
5932}
5933
5934/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5935/// We only handle extending casts so far.
5936///
Reid Spencere4d87aa2006-12-23 06:05:41 +00005937Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5938 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00005939 Value *LHSCIOp = LHSCI->getOperand(0);
5940 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005941 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005942 Value *RHSCIOp;
5943
Chris Lattner8c756c12007-05-05 22:41:33 +00005944 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5945 // integer type is the same size as the pointer type.
5946 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5947 getTargetData().getPointerSizeInBits() ==
5948 cast<IntegerType>(DestTy)->getBitWidth()) {
5949 Value *RHSOp = 0;
5950 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00005951 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00005952 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5953 RHSOp = RHSC->getOperand(0);
5954 // If the pointer types don't match, insert a bitcast.
5955 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00005956 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00005957 }
5958
5959 if (RHSOp)
5960 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5961 }
5962
5963 // The code below only handles extension cast instructions, so far.
5964 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005965 if (LHSCI->getOpcode() != Instruction::ZExt &&
5966 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00005967 return 0;
5968
Reid Spencere4d87aa2006-12-23 06:05:41 +00005969 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5970 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005971
Reid Spencere4d87aa2006-12-23 06:05:41 +00005972 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005973 // Not an extension from the same type?
5974 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005975 if (RHSCIOp->getType() != LHSCIOp->getType())
5976 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00005977
Nick Lewycky4189a532008-01-28 03:48:02 +00005978 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00005979 // and the other is a zext), then we can't handle this.
5980 if (CI->getOpcode() != LHSCI->getOpcode())
5981 return 0;
5982
Nick Lewycky4189a532008-01-28 03:48:02 +00005983 // Deal with equality cases early.
5984 if (ICI.isEquality())
5985 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5986
5987 // A signed comparison of sign extended values simplifies into a
5988 // signed comparison.
5989 if (isSignedCmp && isSignedExt)
5990 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5991
5992 // The other three cases all fold into an unsigned comparison.
5993 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00005994 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005995
Reid Spencere4d87aa2006-12-23 06:05:41 +00005996 // If we aren't dealing with a constant on the RHS, exit early
5997 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5998 if (!CI)
5999 return 0;
6000
6001 // Compute the constant that would happen if we truncated to SrcTy then
6002 // reextended to DestTy.
6003 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6004 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6005
6006 // If the re-extended constant didn't change...
6007 if (Res2 == CI) {
6008 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6009 // For example, we might have:
6010 // %A = sext short %X to uint
6011 // %B = icmp ugt uint %A, 1330
6012 // It is incorrect to transform this into
6013 // %B = icmp ugt short %X, 1330
6014 // because %A may have negative value.
6015 //
6016 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6017 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006018 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006019 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6020 else
6021 return 0;
6022 }
6023
6024 // The re-extended constant changed so the constant cannot be represented
6025 // in the shorter type. Consequently, we cannot emit a simple comparison.
6026
6027 // First, handle some easy cases. We know the result cannot be equal at this
6028 // point so handle the ICI.isEquality() cases
6029 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006030 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006031 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006032 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006033
6034 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6035 // should have been folded away previously and not enter in here.
6036 Value *Result;
6037 if (isSignedCmp) {
6038 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006039 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006040 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006041 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006042 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006043 } else {
6044 // We're performing an unsigned comparison.
6045 if (isSignedExt) {
6046 // We're performing an unsigned comp with a sign extended value.
6047 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006048 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006049 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6050 NegOne, ICI.getName()), ICI);
6051 } else {
6052 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006053 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006054 }
6055 }
6056
6057 // Finally, return the value computed.
6058 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6059 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6060 return ReplaceInstUsesWith(ICI, Result);
6061 } else {
6062 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6063 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6064 "ICmp should be folded!");
6065 if (Constant *CI = dyn_cast<Constant>(Result))
6066 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6067 else
6068 return BinaryOperator::createNot(Result);
6069 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006070}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006071
Reid Spencer832254e2007-02-02 02:16:23 +00006072Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6073 return commonShiftTransforms(I);
6074}
6075
6076Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6077 return commonShiftTransforms(I);
6078}
6079
6080Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006081 if (Instruction *R = commonShiftTransforms(I))
6082 return R;
6083
6084 Value *Op0 = I.getOperand(0);
6085
6086 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6087 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6088 if (CSI->isAllOnesValue())
6089 return ReplaceInstUsesWith(I, CSI);
6090
6091 // See if we can turn a signed shr into an unsigned shr.
6092 if (MaskedValueIsZero(Op0,
6093 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6094 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6095
6096 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006097}
6098
6099Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6100 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006101 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006102
6103 // shl X, 0 == X and shr X, 0 == X
6104 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006105 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006106 Op0 == Constant::getNullValue(Op0->getType()))
6107 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006108
Reid Spencere4d87aa2006-12-23 06:05:41 +00006109 if (isa<UndefValue>(Op0)) {
6110 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006111 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006112 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006113 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6114 }
6115 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006116 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6117 return ReplaceInstUsesWith(I, Op0);
6118 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006119 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006120 }
6121
Chris Lattner2eefe512004-04-09 19:05:30 +00006122 // Try to fold constant and into select arguments.
6123 if (isa<Constant>(Op0))
6124 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006125 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006126 return R;
6127
Reid Spencerb83eb642006-10-20 07:07:24 +00006128 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006129 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6130 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006131 return 0;
6132}
6133
Reid Spencerb83eb642006-10-20 07:07:24 +00006134Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006135 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006136 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006137
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006138 // See if we can simplify any instructions used by the instruction whose sole
6139 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006140 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6141 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6142 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006143 KnownZero, KnownOne))
6144 return &I;
6145
Chris Lattner4d5542c2006-01-06 07:12:35 +00006146 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6147 // of a signed value.
6148 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006149 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006150 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006151 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6152 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006153 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006154 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006155 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006156 }
6157
6158 // ((X*C1) << C2) == (X * (C1 << C2))
6159 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6160 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6161 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6162 return BinaryOperator::createMul(BO->getOperand(0),
6163 ConstantExpr::getShl(BOOp, Op1));
6164
6165 // Try to fold constant and into select arguments.
6166 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6167 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6168 return R;
6169 if (isa<PHINode>(Op0))
6170 if (Instruction *NV = FoldOpIntoPhi(I))
6171 return NV;
6172
Chris Lattner8999dd32007-12-22 09:07:47 +00006173 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6174 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6175 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6176 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6177 // place. Don't try to do this transformation in this case. Also, we
6178 // require that the input operand is a shift-by-constant so that we have
6179 // confidence that the shifts will get folded together. We could do this
6180 // xform in more cases, but it is unlikely to be profitable.
6181 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6182 isa<ConstantInt>(TrOp->getOperand(1))) {
6183 // Okay, we'll do this xform. Make the shift of shift.
6184 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6185 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6186 I.getName());
6187 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6188
6189 // For logical shifts, the truncation has the effect of making the high
6190 // part of the register be zeros. Emulate this by inserting an AND to
6191 // clear the top bits as needed. This 'and' will usually be zapped by
6192 // other xforms later if dead.
6193 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6194 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6195 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6196
6197 // The mask we constructed says what the trunc would do if occurring
6198 // between the shifts. We want to know the effect *after* the second
6199 // shift. We know that it is a logical shift by a constant, so adjust the
6200 // mask as appropriate.
6201 if (I.getOpcode() == Instruction::Shl)
6202 MaskV <<= Op1->getZExtValue();
6203 else {
6204 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6205 MaskV = MaskV.lshr(Op1->getZExtValue());
6206 }
6207
6208 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6209 TI->getName());
6210 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6211
6212 // Return the value truncated to the interesting size.
6213 return new TruncInst(And, I.getType());
6214 }
6215 }
6216
Chris Lattner4d5542c2006-01-06 07:12:35 +00006217 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006218 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6219 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6220 Value *V1, *V2;
6221 ConstantInt *CC;
6222 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006223 default: break;
6224 case Instruction::Add:
6225 case Instruction::And:
6226 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006227 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006228 // These operators commute.
6229 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006230 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6231 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006232 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006233 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006234 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006235 Op0BO->getName());
6236 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006237 Instruction *X =
6238 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6239 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006240 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006241 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006242 return BinaryOperator::createAnd(X, ConstantInt::get(
6243 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006244 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006245
Chris Lattner150f12a2005-09-18 06:30:59 +00006246 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006247 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006248 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006249 match(Op0BOOp1,
6250 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006251 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6252 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006253 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006254 Op0BO->getOperand(0), Op1,
6255 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006256 InsertNewInstBefore(YS, I); // (Y << C)
6257 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006258 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006259 V1->getName()+".mask");
6260 InsertNewInstBefore(XM, I); // X & (CC << C)
6261
6262 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6263 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006264 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006265
Reid Spencera07cb7d2007-02-02 14:41:37 +00006266 // FALL THROUGH.
6267 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006268 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006269 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6270 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006271 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006272 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006273 Op0BO->getOperand(1), Op1,
6274 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006275 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006276 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00006277 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006278 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006279 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006280 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006281 return BinaryOperator::createAnd(X, ConstantInt::get(
6282 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006283 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006284
Chris Lattner13d4ab42006-05-31 21:14:00 +00006285 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006286 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6287 match(Op0BO->getOperand(0),
6288 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006289 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006290 cast<BinaryOperator>(Op0BO->getOperand(0))
6291 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006292 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006293 Op0BO->getOperand(1), Op1,
6294 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006295 InsertNewInstBefore(YS, I); // (Y << C)
6296 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006297 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006298 V1->getName()+".mask");
6299 InsertNewInstBefore(XM, I); // X & (CC << C)
6300
Chris Lattner13d4ab42006-05-31 21:14:00 +00006301 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006302 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006303
Chris Lattner11021cb2005-09-18 05:12:10 +00006304 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006305 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006306 }
6307
6308
6309 // If the operand is an bitwise operator with a constant RHS, and the
6310 // shift is the only use, we can pull it out of the shift.
6311 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6312 bool isValid = true; // Valid only for And, Or, Xor
6313 bool highBitSet = false; // Transform if high bit of constant set?
6314
6315 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006316 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006317 case Instruction::Add:
6318 isValid = isLeftShift;
6319 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006320 case Instruction::Or:
6321 case Instruction::Xor:
6322 highBitSet = false;
6323 break;
6324 case Instruction::And:
6325 highBitSet = true;
6326 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006327 }
6328
6329 // If this is a signed shift right, and the high bit is modified
6330 // by the logical operation, do not perform the transformation.
6331 // The highBitSet boolean indicates the value of the high bit of
6332 // the constant which would cause it to be modified for this
6333 // operation.
6334 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006335 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006336 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006337
6338 if (isValid) {
6339 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6340
6341 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00006342 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006343 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006344 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006345
6346 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6347 NewRHS);
6348 }
6349 }
6350 }
6351 }
6352
Chris Lattnerad0124c2006-01-06 07:52:12 +00006353 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006354 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6355 if (ShiftOp && !ShiftOp->isShift())
6356 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006357
Reid Spencerb83eb642006-10-20 07:07:24 +00006358 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006359 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006360 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6361 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006362 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6363 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6364 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006365
Zhou Sheng4351c642007-04-02 08:20:41 +00006366 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006367 if (AmtSum > TypeBits)
6368 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006369
6370 const IntegerType *Ty = cast<IntegerType>(I.getType());
6371
6372 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006373 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006374 return BinaryOperator::create(I.getOpcode(), X,
6375 ConstantInt::get(Ty, AmtSum));
6376 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6377 I.getOpcode() == Instruction::AShr) {
6378 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6379 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6380 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6381 I.getOpcode() == Instruction::LShr) {
6382 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6383 Instruction *Shift =
6384 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6385 InsertNewInstBefore(Shift, I);
6386
Zhou Shenge9e03f62007-03-28 15:02:20 +00006387 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006388 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006389 }
6390
Chris Lattnerb87056f2007-02-05 00:57:54 +00006391 // Okay, if we get here, one shift must be left, and the other shift must be
6392 // right. See if the amounts are equal.
6393 if (ShiftAmt1 == ShiftAmt2) {
6394 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6395 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006396 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006397 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006398 }
6399 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6400 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006401 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006402 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006403 }
6404 // We can simplify ((X << C) >>s C) into a trunc + sext.
6405 // NOTE: we could do this for any C, but that would make 'unusual' integer
6406 // types. For now, just stick to ones well-supported by the code
6407 // generators.
6408 const Type *SExtType = 0;
6409 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006410 case 1 :
6411 case 8 :
6412 case 16 :
6413 case 32 :
6414 case 64 :
6415 case 128:
6416 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6417 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006418 default: break;
6419 }
6420 if (SExtType) {
6421 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6422 InsertNewInstBefore(NewTrunc, I);
6423 return new SExtInst(NewTrunc, Ty);
6424 }
6425 // Otherwise, we can't handle it yet.
6426 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006427 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006428
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006429 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006430 if (I.getOpcode() == Instruction::Shl) {
6431 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6432 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006433 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006434 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006435 InsertNewInstBefore(Shift, I);
6436
Reid Spencer55702aa2007-03-25 21:11:44 +00006437 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6438 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006439 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006440
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006441 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006442 if (I.getOpcode() == Instruction::LShr) {
6443 assert(ShiftOp->getOpcode() == Instruction::Shl);
6444 Instruction *Shift =
6445 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6446 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006447
Reid Spencerd5e30f02007-03-26 17:18:58 +00006448 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006449 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006450 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006451
6452 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6453 } else {
6454 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006455 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006456
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006457 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006458 if (I.getOpcode() == Instruction::Shl) {
6459 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6460 ShiftOp->getOpcode() == Instruction::AShr);
6461 Instruction *Shift =
6462 BinaryOperator::create(ShiftOp->getOpcode(), X,
6463 ConstantInt::get(Ty, ShiftDiff));
6464 InsertNewInstBefore(Shift, I);
6465
Reid Spencer55702aa2007-03-25 21:11:44 +00006466 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006467 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006468 }
6469
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006470 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006471 if (I.getOpcode() == Instruction::LShr) {
6472 assert(ShiftOp->getOpcode() == Instruction::Shl);
6473 Instruction *Shift =
6474 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6475 InsertNewInstBefore(Shift, I);
6476
Reid Spencer68d27cf2007-03-26 23:45:51 +00006477 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006478 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006479 }
6480
6481 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006482 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006483 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006484 return 0;
6485}
6486
Chris Lattnera1be5662002-05-02 17:06:02 +00006487
Chris Lattnercfd65102005-10-29 04:36:15 +00006488/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6489/// expression. If so, decompose it, returning some value X, such that Val is
6490/// X*Scale+Offset.
6491///
6492static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006493 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006494 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006495 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006496 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006497 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006498 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006499 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6500 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6501 if (I->getOpcode() == Instruction::Shl) {
6502 // This is a value scaled by '1 << the shift amt'.
6503 Scale = 1U << RHS->getZExtValue();
6504 Offset = 0;
6505 return I->getOperand(0);
6506 } else if (I->getOpcode() == Instruction::Mul) {
6507 // This value is scaled by 'RHS'.
6508 Scale = RHS->getZExtValue();
6509 Offset = 0;
6510 return I->getOperand(0);
6511 } else if (I->getOpcode() == Instruction::Add) {
6512 // We have X+C. Check to see if we really have (X*C2)+C1,
6513 // where C1 is divisible by C2.
6514 unsigned SubScale;
6515 Value *SubVal =
6516 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6517 Offset += RHS->getZExtValue();
6518 Scale = SubScale;
6519 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006520 }
6521 }
6522 }
6523
6524 // Otherwise, we can't look past this.
6525 Scale = 1;
6526 Offset = 0;
6527 return Val;
6528}
6529
6530
Chris Lattnerb3f83972005-10-24 06:03:58 +00006531/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6532/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006533Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006534 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006535 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006536
Chris Lattnerb53c2382005-10-24 06:22:12 +00006537 // Remove any uses of AI that are dead.
6538 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006539
Chris Lattnerb53c2382005-10-24 06:22:12 +00006540 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6541 Instruction *User = cast<Instruction>(*UI++);
6542 if (isInstructionTriviallyDead(User)) {
6543 while (UI != E && *UI == User)
6544 ++UI; // If this instruction uses AI more than once, don't break UI.
6545
Chris Lattnerb53c2382005-10-24 06:22:12 +00006546 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006547 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006548 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006549 }
6550 }
6551
Chris Lattnerb3f83972005-10-24 06:03:58 +00006552 // Get the type really allocated and the type casted to.
6553 const Type *AllocElTy = AI.getAllocatedType();
6554 const Type *CastElTy = PTy->getElementType();
6555 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006556
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006557 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6558 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006559 if (CastElTyAlign < AllocElTyAlign) return 0;
6560
Chris Lattner39387a52005-10-24 06:35:18 +00006561 // If the allocation has multiple uses, only promote it if we are strictly
6562 // increasing the alignment of the resultant allocation. If we keep it the
6563 // same, we open the door to infinite loops of various kinds.
6564 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6565
Duncan Sands514ab342007-11-01 20:53:16 +00006566 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6567 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006568 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006569
Chris Lattner455fcc82005-10-29 03:19:53 +00006570 // See if we can satisfy the modulus by pulling a scale out of the array
6571 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006572 unsigned ArraySizeScale;
6573 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006574 Value *NumElements = // See if the array size is a decomposable linear expr.
6575 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6576
Chris Lattner455fcc82005-10-29 03:19:53 +00006577 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6578 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006579 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6580 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006581
Chris Lattner455fcc82005-10-29 03:19:53 +00006582 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6583 Value *Amt = 0;
6584 if (Scale == 1) {
6585 Amt = NumElements;
6586 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006587 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006588 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6589 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006590 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006591 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006592 else if (Scale != 1) {
6593 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6594 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006595 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006596 }
6597
Jeff Cohen86796be2007-04-04 16:58:57 +00006598 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6599 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00006600 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6601 Amt = InsertNewInstBefore(Tmp, AI);
6602 }
6603
Chris Lattnerb3f83972005-10-24 06:03:58 +00006604 AllocationInst *New;
6605 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006606 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006607 else
Chris Lattner6934a042007-02-11 01:23:03 +00006608 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006609 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006610 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006611
6612 // If the allocation has multiple uses, insert a cast and change all things
6613 // that used it to use the new cast. This will also hack on CI, but it will
6614 // die soon.
6615 if (!AI.hasOneUse()) {
6616 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006617 // New is the allocation instruction, pointer typed. AI is the original
6618 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6619 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006620 InsertNewInstBefore(NewCast, AI);
6621 AI.replaceAllUsesWith(NewCast);
6622 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006623 return ReplaceInstUsesWith(CI, New);
6624}
6625
Chris Lattner70074e02006-05-13 02:06:03 +00006626/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006627/// and return it as type Ty without inserting any new casts and without
6628/// changing the computed value. This is used by code that tries to decide
6629/// whether promoting or shrinking integer operations to wider or smaller types
6630/// will allow us to eliminate a truncate or extend.
6631///
6632/// This is a truncation operation if Ty is smaller than V->getType(), or an
6633/// extension operation if Ty is larger.
6634static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner951626b2007-08-02 06:11:14 +00006635 unsigned CastOpc, int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006636 // We can always evaluate constants in another type.
6637 if (isa<ConstantInt>(V))
6638 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006639
6640 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006641 if (!I) return false;
6642
6643 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006644
Chris Lattner951626b2007-08-02 06:11:14 +00006645 // If this is an extension or truncate, we can often eliminate it.
6646 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6647 // If this is a cast from the destination type, we can trivially eliminate
6648 // it, and this will remove a cast overall.
6649 if (I->getOperand(0)->getType() == Ty) {
6650 // If the first operand is itself a cast, and is eliminable, do not count
6651 // this as an eliminable cast. We would prefer to eliminate those two
6652 // casts first.
6653 if (!isa<CastInst>(I->getOperand(0)))
6654 ++NumCastsRemoved;
6655 return true;
6656 }
6657 }
6658
6659 // We can't extend or shrink something that has multiple uses: doing so would
6660 // require duplicating the instruction in general, which isn't profitable.
6661 if (!I->hasOneUse()) return false;
6662
Chris Lattner70074e02006-05-13 02:06:03 +00006663 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006664 case Instruction::Add:
6665 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006666 case Instruction::And:
6667 case Instruction::Or:
6668 case Instruction::Xor:
6669 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006670 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6671 NumCastsRemoved) &&
6672 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6673 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006674
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006675 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006676 // A multiply can be truncated by truncating its operands.
6677 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6678 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6679 NumCastsRemoved) &&
6680 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6681 NumCastsRemoved);
6682
Chris Lattner46b96052006-11-29 07:18:39 +00006683 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006684 // If we are truncating the result of this SHL, and if it's a shift of a
6685 // constant amount, we can always perform a SHL in a smaller type.
6686 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006687 uint32_t BitWidth = Ty->getBitWidth();
6688 if (BitWidth < OrigTy->getBitWidth() &&
6689 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006690 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6691 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006692 }
6693 break;
6694 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006695 // If this is a truncate of a logical shr, we can truncate it to a smaller
6696 // lshr iff we know that the bits we would otherwise be shifting in are
6697 // already zeros.
6698 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006699 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6700 uint32_t BitWidth = Ty->getBitWidth();
6701 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006702 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006703 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6704 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006705 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6706 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006707 }
6708 }
Chris Lattner46b96052006-11-29 07:18:39 +00006709 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006710 case Instruction::ZExt:
6711 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006712 case Instruction::Trunc:
6713 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006714 // can safely replace it. Note that replacing it does not reduce the number
6715 // of casts in the input.
6716 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006717 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006718
Reid Spencer3da59db2006-11-27 01:05:10 +00006719 break;
6720 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006721 // TODO: Can handle more cases here.
6722 break;
6723 }
6724
6725 return false;
6726}
6727
6728/// EvaluateInDifferentType - Given an expression that
6729/// CanEvaluateInDifferentType returns true for, actually insert the code to
6730/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006731Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006732 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006733 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006734 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006735
6736 // Otherwise, it must be an instruction.
6737 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006738 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006739 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006740 case Instruction::Add:
6741 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006742 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006743 case Instruction::And:
6744 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006745 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006746 case Instruction::AShr:
6747 case Instruction::LShr:
6748 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006749 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006750 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6751 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6752 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006753 break;
6754 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006755 case Instruction::Trunc:
6756 case Instruction::ZExt:
6757 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006758 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006759 // just return the source. There's no need to insert it because it is not
6760 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006761 if (I->getOperand(0)->getType() == Ty)
6762 return I->getOperand(0);
6763
Chris Lattner951626b2007-08-02 06:11:14 +00006764 // Otherwise, must be the same type of case, so just reinsert a new one.
6765 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6766 Ty, I->getName());
6767 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006768 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006769 // TODO: Can handle more cases here.
6770 assert(0 && "Unreachable!");
6771 break;
6772 }
6773
6774 return InsertNewInstBefore(Res, *I);
6775}
6776
Reid Spencer3da59db2006-11-27 01:05:10 +00006777/// @brief Implement the transforms common to all CastInst visitors.
6778Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006779 Value *Src = CI.getOperand(0);
6780
Dan Gohman23d9d272007-05-11 21:10:54 +00006781 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00006782 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006783 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006784 if (Instruction::CastOps opc =
6785 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6786 // The first cast (CSrc) is eliminable so we need to fix up or replace
6787 // the second cast (CI). CSrc will then have a good chance of being dead.
6788 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006789 }
6790 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006791
Reid Spencer3da59db2006-11-27 01:05:10 +00006792 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006793 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6794 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6795 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006796
6797 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006798 if (isa<PHINode>(Src))
6799 if (Instruction *NV = FoldOpIntoPhi(CI))
6800 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006801
Reid Spencer3da59db2006-11-27 01:05:10 +00006802 return 0;
6803}
6804
Chris Lattnerd3e28342007-04-27 17:44:50 +00006805/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6806Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6807 Value *Src = CI.getOperand(0);
6808
Chris Lattnerd3e28342007-04-27 17:44:50 +00006809 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00006810 // If casting the result of a getelementptr instruction with no offset, turn
6811 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00006812 if (GEP->hasAllZeroIndices()) {
6813 // Changing the cast operand is usually not a good idea but it is safe
6814 // here because the pointer operand is being replaced with another
6815 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00006816 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00006817 CI.setOperand(0, GEP->getOperand(0));
6818 return &CI;
6819 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006820
6821 // If the GEP has a single use, and the base pointer is a bitcast, and the
6822 // GEP computes a constant offset, see if we can convert these three
6823 // instructions into fewer. This typically happens with unions and other
6824 // non-type-safe code.
6825 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6826 if (GEP->hasAllConstantIndices()) {
6827 // We are guaranteed to get a constant from EmitGEPOffset.
6828 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6829 int64_t Offset = OffsetV->getSExtValue();
6830
6831 // Get the base pointer input of the bitcast, and the type it points to.
6832 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6833 const Type *GEPIdxTy =
6834 cast<PointerType>(OrigBase->getType())->getElementType();
6835 if (GEPIdxTy->isSized()) {
6836 SmallVector<Value*, 8> NewIndices;
6837
Chris Lattnerc42e2262007-05-05 01:59:31 +00006838 // Start with the index over the outer type. Note that the type size
6839 // might be zero (even if the offset isn't zero) if the indexed type
6840 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00006841 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00006842 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00006843 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00006844 FirstIdx = Offset/TySize;
6845 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00006846
Chris Lattnerc42e2262007-05-05 01:59:31 +00006847 // Handle silly modulus not returning values values [0..TySize).
6848 if (Offset < 0) {
6849 --FirstIdx;
6850 Offset += TySize;
6851 assert(Offset >= 0);
6852 }
Chris Lattnerd717c182007-05-05 22:32:24 +00006853 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00006854 }
6855
6856 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00006857
6858 // Index into the types. If we fail, set OrigBase to null.
6859 while (Offset) {
6860 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6861 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006862 if (Offset < (int64_t)SL->getSizeInBytes()) {
6863 unsigned Elt = SL->getElementContainingOffset(Offset);
6864 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00006865
Chris Lattner6b6aef82007-05-15 00:16:00 +00006866 Offset -= SL->getElementOffset(Elt);
6867 GEPIdxTy = STy->getElementType(Elt);
6868 } else {
6869 // Otherwise, we can't index into this, bail out.
6870 Offset = 0;
6871 OrigBase = 0;
6872 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006873 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6874 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00006875 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00006876 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6877 Offset %= EltSize;
6878 } else {
6879 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6880 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006881 GEPIdxTy = STy->getElementType();
6882 } else {
6883 // Otherwise, we can't index into this, bail out.
6884 Offset = 0;
6885 OrigBase = 0;
6886 }
6887 }
6888 if (OrigBase) {
6889 // If we were able to index down into an element, create the GEP
6890 // and bitcast the result. This eliminates one bitcast, potentially
6891 // two.
David Greeneb8f74792007-09-04 15:46:09 +00006892 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6893 NewIndices.begin(),
6894 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00006895 InsertNewInstBefore(NGEP, CI);
6896 NGEP->takeName(GEP);
6897
Chris Lattner9bc14642007-04-28 00:57:34 +00006898 if (isa<BitCastInst>(CI))
6899 return new BitCastInst(NGEP, CI.getType());
6900 assert(isa<PtrToIntInst>(CI));
6901 return new PtrToIntInst(NGEP, CI.getType());
6902 }
6903 }
6904 }
6905 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00006906 }
6907
6908 return commonCastTransforms(CI);
6909}
6910
6911
6912
Chris Lattnerc739cd62007-03-03 05:27:34 +00006913/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6914/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006915/// cases.
6916/// @brief Implement the transforms common to CastInst with integer operands
6917Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6918 if (Instruction *Result = commonCastTransforms(CI))
6919 return Result;
6920
6921 Value *Src = CI.getOperand(0);
6922 const Type *SrcTy = Src->getType();
6923 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006924 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6925 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006926
Reid Spencer3da59db2006-11-27 01:05:10 +00006927 // See if we can simplify any instructions used by the LHS whose sole
6928 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00006929 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6930 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00006931 KnownZero, KnownOne))
6932 return &CI;
6933
6934 // If the source isn't an instruction or has more than one use then we
6935 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006936 Instruction *SrcI = dyn_cast<Instruction>(Src);
6937 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006938 return 0;
6939
Chris Lattnerc739cd62007-03-03 05:27:34 +00006940 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00006941 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00006942 if (!isa<BitCastInst>(CI) &&
6943 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00006944 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006945 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00006946 // eliminates the cast, so it is always a win. If this is a zero-extension,
6947 // we need to do an AND to maintain the clear top-part of the computation,
6948 // so we require that the input have eliminated at least one cast. If this
6949 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00006950 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00006951 bool DoXForm;
6952 switch (CI.getOpcode()) {
6953 default:
6954 // All the others use floating point so we shouldn't actually
6955 // get here because of the check above.
6956 assert(0 && "Unknown cast type");
6957 case Instruction::Trunc:
6958 DoXForm = true;
6959 break;
6960 case Instruction::ZExt:
6961 DoXForm = NumCastsRemoved >= 1;
6962 break;
6963 case Instruction::SExt:
6964 DoXForm = NumCastsRemoved >= 2;
6965 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006966 }
6967
6968 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00006969 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6970 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00006971 assert(Res->getType() == DestTy);
6972 switch (CI.getOpcode()) {
6973 default: assert(0 && "Unknown cast type!");
6974 case Instruction::Trunc:
6975 case Instruction::BitCast:
6976 // Just replace this cast with the result.
6977 return ReplaceInstUsesWith(CI, Res);
6978 case Instruction::ZExt: {
6979 // We need to emit an AND to clear the high bits.
6980 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00006981 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6982 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00006983 return BinaryOperator::createAnd(Res, C);
6984 }
6985 case Instruction::SExt:
6986 // We need to emit a cast to truncate, then a cast to sext.
6987 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00006988 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6989 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00006990 }
6991 }
6992 }
6993
6994 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6995 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6996
6997 switch (SrcI->getOpcode()) {
6998 case Instruction::Add:
6999 case Instruction::Mul:
7000 case Instruction::And:
7001 case Instruction::Or:
7002 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007003 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007004 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7005 // Don't insert two casts if they cannot be eliminated. We allow
7006 // two casts to be inserted if the sizes are the same. This could
7007 // only be converting signedness, which is a noop.
7008 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007009 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7010 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007011 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007012 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7013 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7014 return BinaryOperator::create(
7015 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007016 }
7017 }
7018
7019 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7020 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7021 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007022 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007023 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007024 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007025 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7026 }
7027 break;
7028 case Instruction::SDiv:
7029 case Instruction::UDiv:
7030 case Instruction::SRem:
7031 case Instruction::URem:
7032 // If we are just changing the sign, rewrite.
7033 if (DestBitSize == SrcBitSize) {
7034 // Don't insert two casts if they cannot be eliminated. We allow
7035 // two casts to be inserted if the sizes are the same. This could
7036 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007037 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7038 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007039 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7040 Op0, DestTy, SrcI);
7041 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7042 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007043 return BinaryOperator::create(
7044 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7045 }
7046 }
7047 break;
7048
7049 case Instruction::Shl:
7050 // Allow changing the sign of the source operand. Do not allow
7051 // changing the size of the shift, UNLESS the shift amount is a
7052 // constant. We must not change variable sized shifts to a smaller
7053 // size, because it is undefined to shift more bits out than exist
7054 // in the value.
7055 if (DestBitSize == SrcBitSize ||
7056 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007057 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7058 Instruction::BitCast : Instruction::Trunc);
7059 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007060 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007061 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007062 }
7063 break;
7064 case Instruction::AShr:
7065 // If this is a signed shr, and if all bits shifted in are about to be
7066 // truncated off, turn it into an unsigned shr to allow greater
7067 // simplifications.
7068 if (DestBitSize < SrcBitSize &&
7069 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007070 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007071 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7072 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00007073 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007074 }
7075 }
7076 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007077 }
7078 return 0;
7079}
7080
Chris Lattner8a9f5712007-04-11 06:57:46 +00007081Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007082 if (Instruction *Result = commonIntCastTransforms(CI))
7083 return Result;
7084
7085 Value *Src = CI.getOperand(0);
7086 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007087 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7088 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007089
7090 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7091 switch (SrcI->getOpcode()) {
7092 default: break;
7093 case Instruction::LShr:
7094 // We can shrink lshr to something smaller if we know the bits shifted in
7095 // are already zeros.
7096 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007097 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007098
7099 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007100 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007101 Value* SrcIOp0 = SrcI->getOperand(0);
7102 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007103 if (ShAmt >= DestBitWidth) // All zeros.
7104 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7105
7106 // Okay, we can shrink this. Truncate the input, then return a new
7107 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007108 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7109 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7110 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007111 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007112 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007113 } else { // This is a variable shr.
7114
7115 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7116 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7117 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007118 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007119 Value *One = ConstantInt::get(SrcI->getType(), 1);
7120
Reid Spencer832254e2007-02-02 02:16:23 +00007121 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00007122 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007123 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007124 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7125 SrcI->getOperand(0),
7126 "tmp"), CI);
7127 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007128 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007129 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007130 }
7131 break;
7132 }
7133 }
7134
7135 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007136}
7137
Chris Lattner8a9f5712007-04-11 06:57:46 +00007138Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007139 // If one of the common conversion will work ..
7140 if (Instruction *Result = commonIntCastTransforms(CI))
7141 return Result;
7142
7143 Value *Src = CI.getOperand(0);
7144
7145 // If this is a cast of a cast
7146 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007147 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7148 // types and if the sizes are just right we can convert this into a logical
7149 // 'and' which will be much cheaper than the pair of casts.
7150 if (isa<TruncInst>(CSrc)) {
7151 // Get the sizes of the types involved
7152 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007153 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7154 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7155 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007156 // If we're actually extending zero bits and the trunc is a no-op
7157 if (MidSize < DstSize && SrcSize == DstSize) {
7158 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007159 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007160 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007161 Instruction *And =
7162 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7163 // Unfortunately, if the type changed, we need to cast it back.
7164 if (And->getType() != CI.getType()) {
7165 And->setName(CSrc->getName()+".mask");
7166 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00007167 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007168 }
7169 return And;
7170 }
7171 }
7172 }
7173
Chris Lattner66bc3252007-04-11 05:45:39 +00007174 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7175 // If we are just checking for a icmp eq of a single bit and zext'ing it
7176 // to an integer, then shift the bit to the appropriate place and then
7177 // cast to integer to avoid the comparison.
7178 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007179 const APInt &Op1CV = Op1C->getValue();
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007180
7181 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7182 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7183 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7184 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7185 Value *In = ICI->getOperand(0);
7186 Value *Sh = ConstantInt::get(In->getType(),
7187 In->getType()->getPrimitiveSizeInBits()-1);
7188 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007189 In->getName()+".lobit"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007190 CI);
7191 if (In->getType() != CI.getType())
7192 In = CastInst::createIntegerCast(In, CI.getType(),
7193 false/*ZExt*/, "tmp", &CI);
7194
7195 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7196 Constant *One = ConstantInt::get(In->getType(), 1);
7197 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007198 In->getName()+".not"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007199 CI);
7200 }
7201
7202 return ReplaceInstUsesWith(CI, In);
7203 }
7204
7205
7206
Chris Lattnerba417832007-04-11 06:12:58 +00007207 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7208 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7209 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7210 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7211 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7212 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7213 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7214 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Chris Lattner66bc3252007-04-11 05:45:39 +00007215 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7216 // This only works for EQ and NE
7217 ICI->isEquality()) {
7218 // If Op1C some other power of two, convert:
7219 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7220 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7221 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7222 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7223
7224 APInt KnownZeroMask(~KnownZero);
7225 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7226 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7227 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7228 // (X&4) == 2 --> false
7229 // (X&4) != 2 --> true
7230 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7231 Res = ConstantExpr::getZExt(Res, CI.getType());
7232 return ReplaceInstUsesWith(CI, Res);
7233 }
7234
7235 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7236 Value *In = ICI->getOperand(0);
7237 if (ShiftAmt) {
7238 // Perform a logical shr by shiftamt.
7239 // Insert the shift to put the result in the low bit.
7240 In = InsertNewInstBefore(
7241 BinaryOperator::createLShr(In,
7242 ConstantInt::get(In->getType(), ShiftAmt),
7243 In->getName()+".lobit"), CI);
7244 }
7245
7246 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7247 Constant *One = ConstantInt::get(In->getType(), 1);
7248 In = BinaryOperator::createXor(In, One, "tmp");
7249 InsertNewInstBefore(cast<Instruction>(In), CI);
7250 }
7251
7252 if (CI.getType() == In->getType())
7253 return ReplaceInstUsesWith(CI, In);
7254 else
7255 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7256 }
7257 }
7258 }
7259 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007260 return 0;
7261}
7262
Chris Lattner8a9f5712007-04-11 06:57:46 +00007263Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007264 if (Instruction *I = commonIntCastTransforms(CI))
7265 return I;
7266
Chris Lattner8a9f5712007-04-11 06:57:46 +00007267 Value *Src = CI.getOperand(0);
7268
7269 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7270 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7271 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7272 // If we are just checking for a icmp eq of a single bit and zext'ing it
7273 // to an integer, then shift the bit to the appropriate place and then
7274 // cast to integer to avoid the comparison.
7275 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7276 const APInt &Op1CV = Op1C->getValue();
7277
7278 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7279 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7280 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7281 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7282 Value *In = ICI->getOperand(0);
7283 Value *Sh = ConstantInt::get(In->getType(),
7284 In->getType()->getPrimitiveSizeInBits()-1);
7285 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007286 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007287 CI);
7288 if (In->getType() != CI.getType())
7289 In = CastInst::createIntegerCast(In, CI.getType(),
7290 true/*SExt*/, "tmp", &CI);
7291
7292 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7293 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7294 In->getName()+".not"), CI);
7295
7296 return ReplaceInstUsesWith(CI, In);
7297 }
7298 }
7299 }
7300
Chris Lattnerba417832007-04-11 06:12:58 +00007301 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007302}
7303
Chris Lattnerb7530652008-01-27 05:29:54 +00007304/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7305/// in the specified FP type without changing its value.
7306static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy,
7307 const fltSemantics &Sem) {
7308 APFloat F = CFP->getValueAPF();
7309 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7310 return ConstantFP::get(FPTy, F);
7311 return 0;
7312}
7313
7314/// LookThroughFPExtensions - If this is an fp extension instruction, look
7315/// through it until we get the source value.
7316static Value *LookThroughFPExtensions(Value *V) {
7317 if (Instruction *I = dyn_cast<Instruction>(V))
7318 if (I->getOpcode() == Instruction::FPExt)
7319 return LookThroughFPExtensions(I->getOperand(0));
7320
7321 // If this value is a constant, return the constant in the smallest FP type
7322 // that can accurately represent it. This allows us to turn
7323 // (float)((double)X+2.0) into x+2.0f.
7324 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7325 if (CFP->getType() == Type::PPC_FP128Ty)
7326 return V; // No constant folding of this.
7327 // See if the value can be truncated to float and then reextended.
7328 if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7329 return V;
7330 if (CFP->getType() == Type::DoubleTy)
7331 return V; // Won't shrink.
7332 if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7333 return V;
7334 // Don't try to shrink to various long double types.
7335 }
7336
7337 return V;
7338}
7339
7340Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7341 if (Instruction *I = commonCastTransforms(CI))
7342 return I;
7343
7344 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7345 // smaller than the destination type, we can eliminate the truncate by doing
7346 // the add as the smaller type. This applies to add/sub/mul/div as well as
7347 // many builtins (sqrt, etc).
7348 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7349 if (OpI && OpI->hasOneUse()) {
7350 switch (OpI->getOpcode()) {
7351 default: break;
7352 case Instruction::Add:
7353 case Instruction::Sub:
7354 case Instruction::Mul:
7355 case Instruction::FDiv:
7356 case Instruction::FRem:
7357 const Type *SrcTy = OpI->getType();
7358 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7359 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7360 if (LHSTrunc->getType() != SrcTy &&
7361 RHSTrunc->getType() != SrcTy) {
7362 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7363 // If the source types were both smaller than the destination type of
7364 // the cast, do this xform.
7365 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7366 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7367 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7368 CI.getType(), CI);
7369 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7370 CI.getType(), CI);
7371 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7372 }
7373 }
7374 break;
7375 }
7376 }
7377 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007378}
7379
7380Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7381 return commonCastTransforms(CI);
7382}
7383
7384Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007385 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007386}
7387
7388Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007389 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007390}
7391
7392Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7393 return commonCastTransforms(CI);
7394}
7395
7396Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7397 return commonCastTransforms(CI);
7398}
7399
7400Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007401 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007402}
7403
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007404Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7405 if (Instruction *I = commonCastTransforms(CI))
7406 return I;
7407
7408 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7409 if (!DestPointee->isSized()) return 0;
7410
7411 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7412 ConstantInt *Cst;
7413 Value *X;
7414 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7415 m_ConstantInt(Cst)))) {
7416 // If the source and destination operands have the same type, see if this
7417 // is a single-index GEP.
7418 if (X->getType() == CI.getType()) {
7419 // Get the size of the pointee type.
7420 uint64_t Size = TD->getABITypeSizeInBits(DestPointee);
7421
7422 // Convert the constant to intptr type.
7423 APInt Offset = Cst->getValue();
7424 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7425
7426 // If Offset is evenly divisible by Size, we can do this xform.
7427 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7428 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7429 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7430 }
7431 }
7432 // TODO: Could handle other cases, e.g. where add is indexing into field of
7433 // struct etc.
7434 } else if (CI.getOperand(0)->hasOneUse() &&
7435 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7436 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7437 // "inttoptr+GEP" instead of "add+intptr".
7438
7439 // Get the size of the pointee type.
7440 uint64_t Size = TD->getABITypeSize(DestPointee);
7441
7442 // Convert the constant to intptr type.
7443 APInt Offset = Cst->getValue();
7444 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7445
7446 // If Offset is evenly divisible by Size, we can do this xform.
7447 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7448 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7449
7450 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7451 "tmp"), CI);
7452 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7453 }
7454 }
7455 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007456}
7457
Chris Lattnerd3e28342007-04-27 17:44:50 +00007458Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007459 // If the operands are integer typed then apply the integer transforms,
7460 // otherwise just apply the common ones.
7461 Value *Src = CI.getOperand(0);
7462 const Type *SrcTy = Src->getType();
7463 const Type *DestTy = CI.getType();
7464
Chris Lattner42a75512007-01-15 02:27:26 +00007465 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007466 if (Instruction *Result = commonIntCastTransforms(CI))
7467 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007468 } else if (isa<PointerType>(SrcTy)) {
7469 if (Instruction *I = commonPointerCastTransforms(CI))
7470 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007471 } else {
7472 if (Instruction *Result = commonCastTransforms(CI))
7473 return Result;
7474 }
7475
7476
7477 // Get rid of casts from one type to the same type. These are useless and can
7478 // be replaced by the operand.
7479 if (DestTy == Src->getType())
7480 return ReplaceInstUsesWith(CI, Src);
7481
Reid Spencer3da59db2006-11-27 01:05:10 +00007482 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007483 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7484 const Type *DstElTy = DstPTy->getElementType();
7485 const Type *SrcElTy = SrcPTy->getElementType();
7486
7487 // If we are casting a malloc or alloca to a pointer to a type of the same
7488 // size, rewrite the allocation instruction to allocate the "right" type.
7489 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7490 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7491 return V;
7492
Chris Lattnerd717c182007-05-05 22:32:24 +00007493 // If the source and destination are pointers, and this cast is equivalent
7494 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007495 // This can enhance SROA and other transforms that want type-safe pointers.
7496 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7497 unsigned NumZeros = 0;
7498 while (SrcElTy != DstElTy &&
7499 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7500 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7501 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7502 ++NumZeros;
7503 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007504
Chris Lattnerd3e28342007-04-27 17:44:50 +00007505 // If we found a path from the src to dest, create the getelementptr now.
7506 if (SrcElTy == DstElTy) {
7507 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose IIIc331d302007-09-05 20:36:41 +00007508 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7509 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007510 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007511 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007512
Reid Spencer3da59db2006-11-27 01:05:10 +00007513 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7514 if (SVI->hasOneUse()) {
7515 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7516 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007517 if (isa<VectorType>(DestTy) &&
7518 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007519 SVI->getType()->getNumElements()) {
7520 CastInst *Tmp;
7521 // If either of the operands is a cast from CI.getType(), then
7522 // evaluating the shuffle in the casted destination's type will allow
7523 // us to eliminate at least one cast.
7524 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7525 Tmp->getOperand(0)->getType() == DestTy) ||
7526 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7527 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007528 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7529 SVI->getOperand(0), DestTy, &CI);
7530 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7531 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007532 // Return a new shuffle vector. Use the same element ID's, as we
7533 // know the vector types match #elts.
7534 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007535 }
7536 }
7537 }
7538 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007539 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007540}
7541
Chris Lattnere576b912004-04-09 23:46:01 +00007542/// GetSelectFoldableOperands - We want to turn code that looks like this:
7543/// %C = or %A, %B
7544/// %D = select %cond, %C, %A
7545/// into:
7546/// %C = select %cond, %B, 0
7547/// %D = or %A, %C
7548///
7549/// Assuming that the specified instruction is an operand to the select, return
7550/// a bitmask indicating which operands of this instruction are foldable if they
7551/// equal the other incoming value of the select.
7552///
7553static unsigned GetSelectFoldableOperands(Instruction *I) {
7554 switch (I->getOpcode()) {
7555 case Instruction::Add:
7556 case Instruction::Mul:
7557 case Instruction::And:
7558 case Instruction::Or:
7559 case Instruction::Xor:
7560 return 3; // Can fold through either operand.
7561 case Instruction::Sub: // Can only fold on the amount subtracted.
7562 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007563 case Instruction::LShr:
7564 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007565 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007566 default:
7567 return 0; // Cannot fold
7568 }
7569}
7570
7571/// GetSelectFoldableConstant - For the same transformation as the previous
7572/// function, return the identity constant that goes into the select.
7573static Constant *GetSelectFoldableConstant(Instruction *I) {
7574 switch (I->getOpcode()) {
7575 default: assert(0 && "This cannot happen!"); abort();
7576 case Instruction::Add:
7577 case Instruction::Sub:
7578 case Instruction::Or:
7579 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007580 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007581 case Instruction::LShr:
7582 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007583 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007584 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007585 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007586 case Instruction::Mul:
7587 return ConstantInt::get(I->getType(), 1);
7588 }
7589}
7590
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007591/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7592/// have the same opcode and only one use each. Try to simplify this.
7593Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7594 Instruction *FI) {
7595 if (TI->getNumOperands() == 1) {
7596 // If this is a non-volatile load or a cast from the same type,
7597 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007598 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007599 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7600 return 0;
7601 } else {
7602 return 0; // unknown unary op.
7603 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007604
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007605 // Fold this by inserting a select from the input values.
7606 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7607 FI->getOperand(0), SI.getName()+".v");
7608 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007609 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7610 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007611 }
7612
Reid Spencer832254e2007-02-02 02:16:23 +00007613 // Only handle binary operators here.
7614 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007615 return 0;
7616
7617 // Figure out if the operations have any operands in common.
7618 Value *MatchOp, *OtherOpT, *OtherOpF;
7619 bool MatchIsOpZero;
7620 if (TI->getOperand(0) == FI->getOperand(0)) {
7621 MatchOp = TI->getOperand(0);
7622 OtherOpT = TI->getOperand(1);
7623 OtherOpF = FI->getOperand(1);
7624 MatchIsOpZero = true;
7625 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7626 MatchOp = TI->getOperand(1);
7627 OtherOpT = TI->getOperand(0);
7628 OtherOpF = FI->getOperand(0);
7629 MatchIsOpZero = false;
7630 } else if (!TI->isCommutative()) {
7631 return 0;
7632 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7633 MatchOp = TI->getOperand(0);
7634 OtherOpT = TI->getOperand(1);
7635 OtherOpF = FI->getOperand(0);
7636 MatchIsOpZero = true;
7637 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7638 MatchOp = TI->getOperand(1);
7639 OtherOpT = TI->getOperand(0);
7640 OtherOpF = FI->getOperand(1);
7641 MatchIsOpZero = true;
7642 } else {
7643 return 0;
7644 }
7645
7646 // If we reach here, they do have operations in common.
7647 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7648 OtherOpF, SI.getName()+".v");
7649 InsertNewInstBefore(NewSI, SI);
7650
7651 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7652 if (MatchIsOpZero)
7653 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7654 else
7655 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007656 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007657 assert(0 && "Shouldn't get here");
7658 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007659}
7660
Chris Lattner3d69f462004-03-12 05:52:32 +00007661Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007662 Value *CondVal = SI.getCondition();
7663 Value *TrueVal = SI.getTrueValue();
7664 Value *FalseVal = SI.getFalseValue();
7665
7666 // select true, X, Y -> X
7667 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007668 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007669 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007670
7671 // select C, X, X -> X
7672 if (TrueVal == FalseVal)
7673 return ReplaceInstUsesWith(SI, TrueVal);
7674
Chris Lattnere87597f2004-10-16 18:11:37 +00007675 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7676 return ReplaceInstUsesWith(SI, FalseVal);
7677 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7678 return ReplaceInstUsesWith(SI, TrueVal);
7679 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7680 if (isa<Constant>(TrueVal))
7681 return ReplaceInstUsesWith(SI, TrueVal);
7682 else
7683 return ReplaceInstUsesWith(SI, FalseVal);
7684 }
7685
Reid Spencer4fe16d62007-01-11 18:21:29 +00007686 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007687 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007688 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007689 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007690 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007691 } else {
7692 // Change: A = select B, false, C --> A = and !B, C
7693 Value *NotCond =
7694 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7695 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007696 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007697 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007698 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007699 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007700 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007701 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007702 } else {
7703 // Change: A = select B, C, true --> A = or !B, C
7704 Value *NotCond =
7705 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7706 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007707 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007708 }
7709 }
Chris Lattnercfa59752007-11-25 21:27:53 +00007710
7711 // select a, b, a -> a&b
7712 // select a, a, b -> a|b
7713 if (CondVal == TrueVal)
7714 return BinaryOperator::createOr(CondVal, FalseVal);
7715 else if (CondVal == FalseVal)
7716 return BinaryOperator::createAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007717 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007718
Chris Lattner2eefe512004-04-09 19:05:30 +00007719 // Selecting between two integer constants?
7720 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7721 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00007722 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00007723 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007724 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00007725 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00007726 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00007727 Value *NotCond =
7728 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007729 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007730 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007731 }
Chris Lattnerba417832007-04-11 06:12:58 +00007732
7733 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00007734
Reid Spencere4d87aa2006-12-23 06:05:41 +00007735 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007736
Reid Spencere4d87aa2006-12-23 06:05:41 +00007737 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00007738 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00007739 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007740 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007741 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00007742 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00007743 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007744 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00007745 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7746 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7747 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00007748 InsertNewInstBefore(SRA, SI);
7749
Reid Spencer3da59db2006-11-27 01:05:10 +00007750 // Finally, convert to the type of the select RHS. We figure out
7751 // if this requires a SExt, Trunc or BitCast based on the sizes.
7752 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00007753 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7754 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007755 if (SRASize < SISize)
7756 opc = Instruction::SExt;
7757 else if (SRASize > SISize)
7758 opc = Instruction::Trunc;
7759 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00007760 }
7761 }
7762
7763
7764 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00007765 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00007766 // non-constant value, eliminate this whole mess. This corresponds to
7767 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00007768 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00007769 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007770 cast<Constant>(IC->getOperand(1))->isNullValue())
7771 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7772 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007773 isa<ConstantInt>(ICA->getOperand(1)) &&
7774 (ICA->getOperand(1) == TrueValC ||
7775 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007776 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7777 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00007778 // know whether we have a icmp_ne or icmp_eq and whether the
7779 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00007780 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007781 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00007782 Value *V = ICA;
7783 if (ShouldNotVal)
7784 V = InsertNewInstBefore(BinaryOperator::create(
7785 Instruction::Xor, V, ICA->getOperand(1)), SI);
7786 return ReplaceInstUsesWith(SI, V);
7787 }
Chris Lattnerb8456462006-09-20 04:44:59 +00007788 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007789 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007790
7791 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007792 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7793 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00007794 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007795 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7796 // This is not safe in general for floating point:
7797 // consider X== -0, Y== +0.
7798 // It becomes safe if either operand is a nonzero constant.
7799 ConstantFP *CFPt, *CFPf;
7800 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7801 !CFPt->getValueAPF().isZero()) ||
7802 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7803 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00007804 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007805 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007806 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007807 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007808 return ReplaceInstUsesWith(SI, TrueVal);
7809 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7810
Reid Spencere4d87aa2006-12-23 06:05:41 +00007811 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00007812 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007813 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7814 // This is not safe in general for floating point:
7815 // consider X== -0, Y== +0.
7816 // It becomes safe if either operand is a nonzero constant.
7817 ConstantFP *CFPt, *CFPf;
7818 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7819 !CFPt->getValueAPF().isZero()) ||
7820 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7821 !CFPf->getValueAPF().isZero()))
7822 return ReplaceInstUsesWith(SI, FalseVal);
7823 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007824 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007825 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7826 return ReplaceInstUsesWith(SI, TrueVal);
7827 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7828 }
7829 }
7830
7831 // See if we are selecting two values based on a comparison of the two values.
7832 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7833 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7834 // Transform (X == Y) ? X : Y -> Y
7835 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7836 return ReplaceInstUsesWith(SI, FalseVal);
7837 // Transform (X != Y) ? X : Y -> X
7838 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7839 return ReplaceInstUsesWith(SI, TrueVal);
7840 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7841
7842 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7843 // Transform (X == Y) ? Y : X -> X
7844 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7845 return ReplaceInstUsesWith(SI, FalseVal);
7846 // Transform (X != Y) ? Y : X -> Y
7847 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00007848 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007849 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7850 }
7851 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007852
Chris Lattner87875da2005-01-13 22:52:24 +00007853 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7854 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7855 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00007856 Instruction *AddOp = 0, *SubOp = 0;
7857
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007858 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7859 if (TI->getOpcode() == FI->getOpcode())
7860 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7861 return IV;
7862
7863 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7864 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00007865 if (TI->getOpcode() == Instruction::Sub &&
7866 FI->getOpcode() == Instruction::Add) {
7867 AddOp = FI; SubOp = TI;
7868 } else if (FI->getOpcode() == Instruction::Sub &&
7869 TI->getOpcode() == Instruction::Add) {
7870 AddOp = TI; SubOp = FI;
7871 }
7872
7873 if (AddOp) {
7874 Value *OtherAddOp = 0;
7875 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7876 OtherAddOp = AddOp->getOperand(1);
7877 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7878 OtherAddOp = AddOp->getOperand(0);
7879 }
7880
7881 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00007882 // So at this point we know we have (Y -> OtherAddOp):
7883 // select C, (add X, Y), (sub X, Z)
7884 Value *NegVal; // Compute -Z
7885 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7886 NegVal = ConstantExpr::getNeg(C);
7887 } else {
7888 NegVal = InsertNewInstBefore(
7889 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00007890 }
Chris Lattner97f37a42006-02-24 18:05:58 +00007891
7892 Value *NewTrueOp = OtherAddOp;
7893 Value *NewFalseOp = NegVal;
7894 if (AddOp != TI)
7895 std::swap(NewTrueOp, NewFalseOp);
7896 Instruction *NewSel =
7897 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7898
7899 NewSel = InsertNewInstBefore(NewSel, SI);
7900 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00007901 }
7902 }
7903 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007904
Chris Lattnere576b912004-04-09 23:46:01 +00007905 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00007906 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00007907 // See the comment above GetSelectFoldableOperands for a description of the
7908 // transformation we are doing here.
7909 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7910 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7911 !isa<Constant>(FalseVal))
7912 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7913 unsigned OpToFold = 0;
7914 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7915 OpToFold = 1;
7916 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7917 OpToFold = 2;
7918 }
7919
7920 if (OpToFold) {
7921 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007922 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007923 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00007924 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007925 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007926 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7927 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00007928 else {
7929 assert(0 && "Unknown instruction!!");
7930 }
7931 }
7932 }
Chris Lattnera96879a2004-09-29 17:40:11 +00007933
Chris Lattnere576b912004-04-09 23:46:01 +00007934 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7935 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7936 !isa<Constant>(TrueVal))
7937 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7938 unsigned OpToFold = 0;
7939 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7940 OpToFold = 1;
7941 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7942 OpToFold = 2;
7943 }
7944
7945 if (OpToFold) {
7946 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007947 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007948 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00007949 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007950 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007951 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7952 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00007953 else
Chris Lattnere576b912004-04-09 23:46:01 +00007954 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00007955 }
7956 }
7957 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00007958
7959 if (BinaryOperator::isNot(CondVal)) {
7960 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7961 SI.setOperand(1, FalseVal);
7962 SI.setOperand(2, TrueVal);
7963 return &SI;
7964 }
7965
Chris Lattner3d69f462004-03-12 05:52:32 +00007966 return 0;
7967}
7968
Chris Lattnerf2369f22007-08-09 19:05:49 +00007969/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7970/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
7971/// and it is more than the alignment of the ultimate object, see if we can
7972/// increase the alignment of the ultimate object, making this check succeed.
7973static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7974 unsigned PrefAlign = 0) {
Chris Lattner95a959d2006-03-06 20:18:44 +00007975 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7976 unsigned Align = GV->getAlignment();
Andrew Lenharthb410df92007-11-08 18:45:15 +00007977 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007978 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattnerf2369f22007-08-09 19:05:49 +00007979
7980 // If there is a large requested alignment and we can, bump up the alignment
7981 // of the global.
7982 if (PrefAlign > Align && GV->hasInitializer()) {
7983 GV->setAlignment(PrefAlign);
7984 Align = PrefAlign;
7985 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007986 return Align;
7987 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7988 unsigned Align = AI->getAlignment();
7989 if (Align == 0 && TD) {
7990 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007991 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007992 else if (isa<MallocInst>(AI)) {
7993 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007994 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00007995 Align =
7996 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007997 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00007998 Align =
7999 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008000 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00008001 }
8002 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008003
8004 // If there is a requested alignment and if this is an alloca, round up. We
8005 // don't do this for malloc, because some systems can't respect the request.
8006 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
8007 AI->setAlignment(PrefAlign);
8008 Align = PrefAlign;
8009 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008010 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00008011 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00008012 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00008013 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008014 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
8015 TD, PrefAlign);
Chris Lattner9bc14642007-04-28 00:57:34 +00008016 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008017 // If all indexes are zero, it is just the alignment of the base pointer.
8018 bool AllZeroOperands = true;
8019 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
8020 if (!isa<Constant>(GEPI->getOperand(i)) ||
8021 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
8022 AllZeroOperands = false;
8023 break;
8024 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008025
8026 if (AllZeroOperands) {
8027 // Treat this like a bitcast.
8028 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
8029 }
8030
8031 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
8032 if (BaseAlignment == 0) return 0;
8033
Chris Lattner95a959d2006-03-06 20:18:44 +00008034 // Otherwise, if the base alignment is >= the alignment we expect for the
8035 // base pointer type, then we know that the resultant pointer is aligned at
8036 // least as much as its type requires.
8037 if (!TD) return 0;
8038
8039 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00008040 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00008041 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
8042 if (Align <= BaseAlignment) {
Chris Lattner51c26e92006-03-07 01:28:57 +00008043 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00008044 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00008045 Align = std::min(Align, (unsigned)
8046 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
8047 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00008048 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008049 return 0;
8050 }
8051 return 0;
8052}
8053
Chris Lattnerf497b022008-01-13 23:50:23 +00008054Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8055 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
8056 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
8057 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8058 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8059
8060 if (CopyAlign < MinAlign) {
8061 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8062 return MI;
8063 }
8064
8065 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8066 // load/store.
8067 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8068 if (MemOpLength == 0) return 0;
8069
Chris Lattner37ac6082008-01-14 00:28:35 +00008070 // Source and destination pointer types are always "i8*" for intrinsic. See
8071 // if the size is something we can handle with a single primitive load/store.
8072 // A single load+store correctly handles overlapping memory in the memmove
8073 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008074 unsigned Size = MemOpLength->getZExtValue();
8075 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008076 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008077
Chris Lattner37ac6082008-01-14 00:28:35 +00008078 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008079 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008080
8081 // Memcpy forces the use of i8* for the source and destination. That means
8082 // that if you're using memcpy to move one double around, you'll get a cast
8083 // from double* to i8*. We'd much rather use a double load+store rather than
8084 // an i64 load+store, here because this improves the odds that the source or
8085 // dest address will be promotable. See if we can find a better type than the
8086 // integer datatype.
8087 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8088 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8089 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8090 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8091 // down through these levels if so.
8092 while (!SrcETy->isFirstClassType()) {
8093 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8094 if (STy->getNumElements() == 1)
8095 SrcETy = STy->getElementType(0);
8096 else
8097 break;
8098 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8099 if (ATy->getNumElements() == 1)
8100 SrcETy = ATy->getElementType();
8101 else
8102 break;
8103 } else
8104 break;
8105 }
8106
8107 if (SrcETy->isFirstClassType())
8108 NewPtrTy = PointerType::getUnqual(SrcETy);
8109 }
8110 }
8111
8112
Chris Lattnerf497b022008-01-13 23:50:23 +00008113 // If the memcpy/memmove provides better alignment info than we can
8114 // infer, use it.
8115 SrcAlign = std::max(SrcAlign, CopyAlign);
8116 DstAlign = std::max(DstAlign, CopyAlign);
8117
8118 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8119 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008120 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8121 InsertNewInstBefore(L, *MI);
8122 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8123
8124 // Set the size of the copy to 0, it will be deleted on the next iteration.
8125 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8126 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008127}
Chris Lattner3d69f462004-03-12 05:52:32 +00008128
Chris Lattner8b0ea312006-01-13 20:11:04 +00008129/// visitCallInst - CallInst simplification. This mostly only handles folding
8130/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8131/// the heavy lifting.
8132///
Chris Lattner9fe38862003-06-19 17:00:31 +00008133Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008134 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8135 if (!II) return visitCallSite(&CI);
8136
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008137 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8138 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008139 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008140 bool Changed = false;
8141
8142 // memmove/cpy/set of zero bytes is a noop.
8143 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8144 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8145
Chris Lattner35b9e482004-10-12 04:52:52 +00008146 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008147 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008148 // Replace the instruction with just byte operations. We would
8149 // transform other cases to loads/stores, but we don't know if
8150 // alignment is sufficient.
8151 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008152 }
8153
Chris Lattner35b9e482004-10-12 04:52:52 +00008154 // If we have a memmove and the source operation is a constant global,
8155 // then the source and dest pointers can't alias, so we can change this
8156 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008157 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008158 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8159 if (GVSrc->isConstant()) {
8160 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008161 Intrinsic::ID MemCpyID;
8162 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8163 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008164 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008165 MemCpyID = Intrinsic::memcpy_i64;
8166 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008167 Changed = true;
8168 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008169 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008170
Chris Lattner95a959d2006-03-06 20:18:44 +00008171 // If we can determine a pointer alignment that is bigger than currently
8172 // set, update the alignment.
8173 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008174 if (Instruction *I = SimplifyMemTransfer(MI))
8175 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008176 } else if (isa<MemSetInst>(MI)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008177 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00008178 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008179 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00008180 Changed = true;
8181 }
8182 }
8183
Chris Lattner8b0ea312006-01-13 20:11:04 +00008184 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008185 } else {
8186 switch (II->getIntrinsicID()) {
8187 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008188 case Intrinsic::ppc_altivec_lvx:
8189 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008190 case Intrinsic::x86_sse_loadu_ps:
8191 case Intrinsic::x86_sse2_loadu_pd:
8192 case Intrinsic::x86_sse2_loadu_dq:
8193 // Turn PPC lvx -> load if the pointer is known aligned.
8194 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008195 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008196 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8197 PointerType::getUnqual(II->getType()),
8198 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008199 return new LoadInst(Ptr);
8200 }
8201 break;
8202 case Intrinsic::ppc_altivec_stvx:
8203 case Intrinsic::ppc_altivec_stvxl:
8204 // Turn stvx -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008205 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008206 const Type *OpPtrTy =
8207 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008208 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008209 return new StoreInst(II->getOperand(1), Ptr);
8210 }
8211 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008212 case Intrinsic::x86_sse_storeu_ps:
8213 case Intrinsic::x86_sse2_storeu_pd:
8214 case Intrinsic::x86_sse2_storeu_dq:
8215 case Intrinsic::x86_sse2_storel_dq:
8216 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008217 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008218 const Type *OpPtrTy =
8219 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008220 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008221 return new StoreInst(II->getOperand(2), Ptr);
8222 }
8223 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008224
8225 case Intrinsic::x86_sse_cvttss2si: {
8226 // These intrinsics only demands the 0th element of its input vector. If
8227 // we can simplify the input based on that, do so now.
8228 uint64_t UndefElts;
8229 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8230 UndefElts)) {
8231 II->setOperand(1, V);
8232 return II;
8233 }
8234 break;
8235 }
8236
Chris Lattnere2ed0572006-04-06 19:19:17 +00008237 case Intrinsic::ppc_altivec_vperm:
8238 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008239 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008240 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8241
8242 // Check that all of the elements are integer constants or undefs.
8243 bool AllEltsOk = true;
8244 for (unsigned i = 0; i != 16; ++i) {
8245 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8246 !isa<UndefValue>(Mask->getOperand(i))) {
8247 AllEltsOk = false;
8248 break;
8249 }
8250 }
8251
8252 if (AllEltsOk) {
8253 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008254 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8255 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008256 Value *Result = UndefValue::get(Op0->getType());
8257
8258 // Only extract each element once.
8259 Value *ExtractedElts[32];
8260 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8261
8262 for (unsigned i = 0; i != 16; ++i) {
8263 if (isa<UndefValue>(Mask->getOperand(i)))
8264 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008265 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008266 Idx &= 31; // Match the hardware behavior.
8267
8268 if (ExtractedElts[Idx] == 0) {
8269 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008270 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008271 InsertNewInstBefore(Elt, CI);
8272 ExtractedElts[Idx] = Elt;
8273 }
8274
8275 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00008276 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008277 InsertNewInstBefore(cast<Instruction>(Result), CI);
8278 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008279 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008280 }
8281 }
8282 break;
8283
Chris Lattnera728ddc2006-01-13 21:28:09 +00008284 case Intrinsic::stackrestore: {
8285 // If the save is right next to the restore, remove the restore. This can
8286 // happen when variable allocas are DCE'd.
8287 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8288 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8289 BasicBlock::iterator BI = SS;
8290 if (&*++BI == II)
8291 return EraseInstFromFunction(CI);
8292 }
8293 }
8294
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008295 // Scan down this block to see if there is another stack restore in the
8296 // same block without an intervening call/alloca.
8297 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008298 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008299 bool CannotRemove = false;
8300 for (++BI; &*BI != TI; ++BI) {
8301 if (isa<AllocaInst>(BI)) {
8302 CannotRemove = true;
8303 break;
8304 }
8305 if (isa<CallInst>(BI)) {
8306 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008307 CannotRemove = true;
8308 break;
8309 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008310 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008311 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008312 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008313 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008314
8315 // If the stack restore is in a return/unwind block and if there are no
8316 // allocas or calls between the restore and the return, nuke the restore.
8317 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8318 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008319 break;
8320 }
8321 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008322 }
8323
Chris Lattner8b0ea312006-01-13 20:11:04 +00008324 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008325}
8326
8327// InvokeInst simplification
8328//
8329Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008330 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008331}
8332
Chris Lattnera44d8a22003-10-07 22:32:43 +00008333// visitCallSite - Improvements for call and invoke instructions.
8334//
8335Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008336 bool Changed = false;
8337
8338 // If the callee is a constexpr cast of a function, attempt to move the cast
8339 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008340 if (transformConstExprCastCall(CS)) return 0;
8341
Chris Lattner6c266db2003-10-07 22:54:13 +00008342 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008343
Chris Lattner08b22ec2005-05-13 07:09:09 +00008344 if (Function *CalleeF = dyn_cast<Function>(Callee))
8345 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8346 Instruction *OldCall = CS.getInstruction();
8347 // If the call and callee calling conventions don't match, this call must
8348 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008349 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008350 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8351 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008352 if (!OldCall->use_empty())
8353 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8354 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8355 return EraseInstFromFunction(*OldCall);
8356 return 0;
8357 }
8358
Chris Lattner17be6352004-10-18 02:59:09 +00008359 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8360 // This instruction is not reachable, just remove it. We insert a store to
8361 // undef so that we know that this code is not reachable, despite the fact
8362 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008363 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008364 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008365 CS.getInstruction());
8366
8367 if (!CS.getInstruction()->use_empty())
8368 CS.getInstruction()->
8369 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8370
8371 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8372 // Don't break the CFG, insert a dummy cond branch.
8373 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008374 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008375 }
Chris Lattner17be6352004-10-18 02:59:09 +00008376 return EraseInstFromFunction(*CS.getInstruction());
8377 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008378
Duncan Sandscdb6d922007-09-17 10:26:40 +00008379 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8380 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8381 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8382 return transformCallThroughTrampoline(CS);
8383
Chris Lattner6c266db2003-10-07 22:54:13 +00008384 const PointerType *PTy = cast<PointerType>(Callee->getType());
8385 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8386 if (FTy->isVarArg()) {
8387 // See if we can optimize any arguments passed through the varargs area of
8388 // the call.
8389 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8390 E = CS.arg_end(); I != E; ++I)
8391 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8392 // If this cast does not effect the value passed through the varargs
8393 // area, we can eliminate the use of the cast.
8394 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00008395 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008396 *I = Op;
8397 Changed = true;
8398 }
8399 }
8400 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008401
Duncan Sandsf0c33542007-12-19 21:13:37 +00008402 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008403 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008404 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008405 Changed = true;
8406 }
8407
Chris Lattner6c266db2003-10-07 22:54:13 +00008408 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008409}
8410
Chris Lattner9fe38862003-06-19 17:00:31 +00008411// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8412// attempt to move the cast to the arguments of the call/invoke.
8413//
8414bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8415 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8416 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008417 if (CE->getOpcode() != Instruction::BitCast ||
8418 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008419 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008420 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008421 Instruction *Caller = CS.getInstruction();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008422 const ParamAttrsList* CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008423
8424 // Okay, this is a cast from a function to a different type. Unless doing so
8425 // would cause a type conversion of one of our arguments, change this call to
8426 // be a direct call with arguments casted to the appropriate types.
8427 //
8428 const FunctionType *FT = Callee->getFunctionType();
8429 const Type *OldRetTy = Caller->getType();
8430
Chris Lattnerf78616b2004-01-14 06:06:08 +00008431 // Check to see if we are changing the return type...
8432 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00008433 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008434 // Conversion is ok if changing from pointer to int of same size.
8435 !(isa<PointerType>(FT->getReturnType()) &&
8436 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008437 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008438
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008439 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008440 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008441 FT->getReturnType() != Type::VoidTy &&
8442 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008443 return false; // Cannot transform this return value.
8444
Duncan Sands6c3470e2008-01-07 17:16:06 +00008445 if (CallerPAL && !Caller->use_empty()) {
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008446 ParameterAttributes RAttrs = CallerPAL->getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00008447 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8448 return false; // Attribute not compatible with transformed value.
8449 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008450
Chris Lattnerf78616b2004-01-14 06:06:08 +00008451 // If the callsite is an invoke instruction, and the return value is used by
8452 // a PHI node in a successor, we cannot change the return type of the call
8453 // because there is no place to put the cast instruction (without breaking
8454 // the critical edge). Bail out in this case.
8455 if (!Caller->use_empty())
8456 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8457 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8458 UI != E; ++UI)
8459 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8460 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008461 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008462 return false;
8463 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008464
8465 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8466 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008467
Chris Lattner9fe38862003-06-19 17:00:31 +00008468 CallSite::arg_iterator AI = CS.arg_begin();
8469 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8470 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008471 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008472
8473 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008474 return false; // Cannot transform this parameter value.
8475
Duncan Sands6c3470e2008-01-07 17:16:06 +00008476 if (CallerPAL) {
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008477 ParameterAttributes PAttrs = CallerPAL->getParamAttrs(i + 1);
Duncan Sands6c3470e2008-01-07 17:16:06 +00008478 if (PAttrs & ParamAttr::typeIncompatible(ParamTy))
8479 return false; // Attribute not compatible with transformed value.
8480 }
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008481
Reid Spencer3da59db2006-11-27 01:05:10 +00008482 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008483 // Some conversions are safe even if we do not have a body.
8484 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00008485 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00008486 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00008487 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008488 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8489 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00008490 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00008491 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008492 }
8493
8494 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008495 Callee->isDeclaration())
Chris Lattner9fe38862003-06-19 17:00:31 +00008496 return false; // Do not delete arguments unless we have a function body...
8497
Duncan Sandse1e520f2008-01-13 08:02:44 +00008498 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && CallerPAL)
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008499 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008500 // won't be dropping them. Check that these extra arguments have attributes
8501 // that are compatible with being a vararg call argument.
8502 for (unsigned i = CallerPAL->size(); i; --i) {
8503 if (CallerPAL->getParamIndex(i - 1) <= FT->getNumParams())
8504 break;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008505 ParameterAttributes PAttrs = CallerPAL->getParamAttrsAtIndex(i - 1);
Duncan Sandse1e520f2008-01-13 08:02:44 +00008506 if (PAttrs & ParamAttr::VarArgsIncompatible)
8507 return false;
8508 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008509
Chris Lattner9fe38862003-06-19 17:00:31 +00008510 // Okay, we decided that this is a safe thing to do: go ahead and start
8511 // inserting cast instructions as necessary...
8512 std::vector<Value*> Args;
8513 Args.reserve(NumActualArgs);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008514 ParamAttrsVector attrVec;
8515 attrVec.reserve(NumCommonArgs);
8516
8517 // Get any return attributes.
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008518 ParameterAttributes RAttrs = CallerPAL ? CallerPAL->getParamAttrs(0) :
8519 ParamAttr::None;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008520
8521 // If the return value is not being used, the type may not be compatible
8522 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00008523 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008524
8525 // Add the new return attributes.
8526 if (RAttrs)
8527 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008528
8529 AI = CS.arg_begin();
8530 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8531 const Type *ParamTy = FT->getParamType(i);
8532 if ((*AI)->getType() == ParamTy) {
8533 Args.push_back(*AI);
8534 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008535 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008536 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008537 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008538 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008539 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008540
8541 // Add any parameter attributes.
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008542 ParameterAttributes PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) :
8543 ParamAttr::None;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008544 if (PAttrs)
8545 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008546 }
8547
8548 // If the function takes more arguments than the call was taking, add them
8549 // now...
8550 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8551 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8552
8553 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008554 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008555 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008556 cerr << "WARNING: While resolving call to function '"
8557 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008558 } else {
8559 // Add all of the arguments in their promoted form to the arg list...
8560 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8561 const Type *PTy = getPromotedType((*AI)->getType());
8562 if (PTy != (*AI)->getType()) {
8563 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008564 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8565 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008566 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008567 InsertNewInstBefore(Cast, *Caller);
8568 Args.push_back(Cast);
8569 } else {
8570 Args.push_back(*AI);
8571 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008572
Duncan Sandse1e520f2008-01-13 08:02:44 +00008573 // Add any parameter attributes.
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008574 ParameterAttributes PAttrs = CallerPAL ?
8575 CallerPAL->getParamAttrs(i + 1) :
8576 ParamAttr::None;
Duncan Sandse1e520f2008-01-13 08:02:44 +00008577 if (PAttrs)
8578 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8579 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008580 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008581 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008582
8583 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008584 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008585
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008586 const ParamAttrsList* NewCallerPAL = ParamAttrsList::get(attrVec);
8587
Chris Lattner9fe38862003-06-19 17:00:31 +00008588 Instruction *NC;
8589 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008590 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greenef1355a52007-08-27 19:04:21 +00008591 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008592 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008593 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008594 } else {
Chris Lattner684b22d2007-08-02 16:53:43 +00008595 NC = new CallInst(Callee, Args.begin(), Args.end(),
8596 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008597 CallInst *CI = cast<CallInst>(Caller);
8598 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008599 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008600 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008601 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008602 }
8603
Chris Lattner6934a042007-02-11 01:23:03 +00008604 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008605 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008606 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008607 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008608 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008609 OldRetTy, false);
8610 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008611
8612 // If this is an invoke instruction, we should insert it after the first
8613 // non-phi, instruction in the normal successor block.
8614 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8615 BasicBlock::iterator I = II->getNormalDest()->begin();
8616 while (isa<PHINode>(I)) ++I;
8617 InsertNewInstBefore(NC, *I);
8618 } else {
8619 // Otherwise, it's a call, just insert cast right after the call instr
8620 InsertNewInstBefore(NC, *Caller);
8621 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008622 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008623 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008624 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008625 }
8626 }
8627
8628 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8629 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008630 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008631 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008632 return true;
8633}
8634
Duncan Sandscdb6d922007-09-17 10:26:40 +00008635// transformCallThroughTrampoline - Turn a call to a function created by the
8636// init_trampoline intrinsic into a direct call to the underlying function.
8637//
8638Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8639 Value *Callee = CS.getCalledValue();
8640 const PointerType *PTy = cast<PointerType>(Callee->getType());
8641 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008642 const ParamAttrsList *Attrs = CS.getParamAttrs();
8643
8644 // If the call already has the 'nest' attribute somewhere then give up -
8645 // otherwise 'nest' would occur twice after splicing in the chain.
8646 if (Attrs && Attrs->hasAttrSomewhere(ParamAttr::Nest))
8647 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008648
8649 IntrinsicInst *Tramp =
8650 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8651
8652 Function *NestF =
8653 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8654 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8655 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8656
Duncan Sandsdc024672007-11-27 13:23:08 +00008657 if (const ParamAttrsList *NestAttrs = NestF->getParamAttrs()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008658 unsigned NestIdx = 1;
8659 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008660 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008661
8662 // Look for a parameter marked with the 'nest' attribute.
8663 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8664 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8665 if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8666 // Record the parameter type and any other attributes.
8667 NestTy = *I;
8668 NestAttr = NestAttrs->getParamAttrs(NestIdx);
8669 break;
8670 }
8671
8672 if (NestTy) {
8673 Instruction *Caller = CS.getInstruction();
8674 std::vector<Value*> NewArgs;
8675 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8676
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008677 ParamAttrsVector NewAttrs;
8678 NewAttrs.reserve(Attrs ? Attrs->size() + 1 : 1);
8679
Duncan Sandscdb6d922007-09-17 10:26:40 +00008680 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008681 // mean appending it. Likewise for attributes.
8682
8683 // Add any function result attributes.
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008684 ParameterAttributes Attr = Attrs ? Attrs->getParamAttrs(0) :
8685 ParamAttr::None;
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008686 if (Attr)
8687 NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8688
Duncan Sandscdb6d922007-09-17 10:26:40 +00008689 {
8690 unsigned Idx = 1;
8691 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8692 do {
8693 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008694 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008695 Value *NestVal = Tramp->getOperand(3);
8696 if (NestVal->getType() != NestTy)
8697 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8698 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008699 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008700 }
8701
8702 if (I == E)
8703 break;
8704
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008705 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008706 NewArgs.push_back(*I);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008707 Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8708 if (Attr)
8709 NewAttrs.push_back
8710 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008711
8712 ++Idx, ++I;
8713 } while (1);
8714 }
8715
8716 // The trampoline may have been bitcast to a bogus type (FTy).
8717 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008718 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008719
Duncan Sandscdb6d922007-09-17 10:26:40 +00008720 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008721 NewTypes.reserve(FTy->getNumParams()+1);
8722
Duncan Sandscdb6d922007-09-17 10:26:40 +00008723 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008724 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008725 {
8726 unsigned Idx = 1;
8727 FunctionType::param_iterator I = FTy->param_begin(),
8728 E = FTy->param_end();
8729
8730 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008731 if (Idx == NestIdx)
8732 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008733 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008734
8735 if (I == E)
8736 break;
8737
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008738 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008739 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008740
8741 ++Idx, ++I;
8742 } while (1);
8743 }
8744
8745 // Replace the trampoline call with a direct call. Let the generic
8746 // code sort out any function type mismatches.
8747 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00008748 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008749 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8750 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Duncan Sandsdc024672007-11-27 13:23:08 +00008751 const ParamAttrsList *NewPAL = ParamAttrsList::get(NewAttrs);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008752
8753 Instruction *NewCaller;
8754 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8755 NewCaller = new InvokeInst(NewCallee,
8756 II->getNormalDest(), II->getUnwindDest(),
8757 NewArgs.begin(), NewArgs.end(),
8758 Caller->getName(), Caller);
8759 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008760 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008761 } else {
8762 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8763 Caller->getName(), Caller);
8764 if (cast<CallInst>(Caller)->isTailCall())
8765 cast<CallInst>(NewCaller)->setTailCall();
8766 cast<CallInst>(NewCaller)->
8767 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008768 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008769 }
8770 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8771 Caller->replaceAllUsesWith(NewCaller);
8772 Caller->eraseFromParent();
8773 RemoveFromWorkList(Caller);
8774 return 0;
8775 }
8776 }
8777
8778 // Replace the trampoline call with a direct call. Since there is no 'nest'
8779 // parameter, there is no need to adjust the argument list. Let the generic
8780 // code sort out any function type mismatches.
8781 Constant *NewCallee =
8782 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8783 CS.setCalledFunction(NewCallee);
8784 return CS.getInstruction();
8785}
8786
Chris Lattner7da52b22006-11-01 04:51:18 +00008787/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8788/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8789/// and a single binop.
8790Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8791 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00008792 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8793 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00008794 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008795 Value *LHSVal = FirstInst->getOperand(0);
8796 Value *RHSVal = FirstInst->getOperand(1);
8797
8798 const Type *LHSType = LHSVal->getType();
8799 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00008800
8801 // Scan to see if all operands are the same opcode, all have one use, and all
8802 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00008803 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00008804 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00008805 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008806 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00008807 // types or GEP's with different index types.
8808 I->getOperand(0)->getType() != LHSType ||
8809 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00008810 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008811
8812 // If they are CmpInst instructions, check their predicates
8813 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8814 if (cast<CmpInst>(I)->getPredicate() !=
8815 cast<CmpInst>(FirstInst)->getPredicate())
8816 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008817
8818 // Keep track of which operand needs a phi node.
8819 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8820 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00008821 }
8822
Chris Lattner53738a42006-11-08 19:42:28 +00008823 // Otherwise, this is safe to transform, determine if it is profitable.
8824
8825 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8826 // Indexes are often folded into load/store instructions, so we don't want to
8827 // hide them behind a phi.
8828 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8829 return 0;
8830
Chris Lattner7da52b22006-11-01 04:51:18 +00008831 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00008832 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00008833 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008834 if (LHSVal == 0) {
8835 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8836 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8837 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008838 InsertNewInstBefore(NewLHS, PN);
8839 LHSVal = NewLHS;
8840 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008841
8842 if (RHSVal == 0) {
8843 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8844 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8845 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008846 InsertNewInstBefore(NewRHS, PN);
8847 RHSVal = NewRHS;
8848 }
8849
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008850 // Add all operands to the new PHIs.
8851 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8852 if (NewLHS) {
8853 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8854 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8855 }
8856 if (NewRHS) {
8857 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8858 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8859 }
8860 }
8861
Chris Lattner7da52b22006-11-01 04:51:18 +00008862 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00008863 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008864 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8865 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8866 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00008867 else {
8868 assert(isa<GetElementPtrInst>(FirstInst));
8869 return new GetElementPtrInst(LHSVal, RHSVal);
8870 }
Chris Lattner7da52b22006-11-01 04:51:18 +00008871}
8872
Chris Lattner76c73142006-11-01 07:13:54 +00008873/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8874/// of the block that defines it. This means that it must be obvious the value
8875/// of the load is not changed from the point of the load to the end of the
8876/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008877///
8878/// Finally, it is safe, but not profitable, to sink a load targetting a
8879/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8880/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00008881static bool isSafeToSinkLoad(LoadInst *L) {
8882 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8883
8884 for (++BBI; BBI != E; ++BBI)
8885 if (BBI->mayWriteToMemory())
8886 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008887
8888 // Check for non-address taken alloca. If not address-taken already, it isn't
8889 // profitable to do this xform.
8890 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8891 bool isAddressTaken = false;
8892 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8893 UI != E; ++UI) {
8894 if (isa<LoadInst>(UI)) continue;
8895 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8896 // If storing TO the alloca, then the address isn't taken.
8897 if (SI->getOperand(1) == AI) continue;
8898 }
8899 isAddressTaken = true;
8900 break;
8901 }
8902
8903 if (!isAddressTaken)
8904 return false;
8905 }
8906
Chris Lattner76c73142006-11-01 07:13:54 +00008907 return true;
8908}
8909
Chris Lattner9fe38862003-06-19 17:00:31 +00008910
Chris Lattnerbac32862004-11-14 19:13:23 +00008911// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8912// operator and they all are only used by the PHI, PHI together their
8913// inputs, and do the operation once, to the result of the PHI.
8914Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8915 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8916
8917 // Scan the instruction, looking for input operations that can be folded away.
8918 // If all input operands to the phi are the same instruction (e.g. a cast from
8919 // the same type or "+42") we can pull the operation through the PHI, reducing
8920 // code size and simplifying code.
8921 Constant *ConstantOp = 0;
8922 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00008923 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00008924 if (isa<CastInst>(FirstInst)) {
8925 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00008926 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008927 // Can fold binop, compare or shift here if the RHS is a constant,
8928 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00008929 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00008930 if (ConstantOp == 0)
8931 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00008932 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8933 isVolatile = LI->isVolatile();
8934 // We can't sink the load if the loaded value could be modified between the
8935 // load and the PHI.
8936 if (LI->getParent() != PN.getIncomingBlock(0) ||
8937 !isSafeToSinkLoad(LI))
8938 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00008939 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00008940 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00008941 return FoldPHIArgBinOpIntoPHI(PN);
8942 // Can't handle general GEPs yet.
8943 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008944 } else {
8945 return 0; // Cannot fold this operation.
8946 }
8947
8948 // Check to see if all arguments are the same operation.
8949 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8950 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8951 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00008952 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00008953 return 0;
8954 if (CastSrcTy) {
8955 if (I->getOperand(0)->getType() != CastSrcTy)
8956 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00008957 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008958 // We can't sink the load if the loaded value could be modified between
8959 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00008960 if (LI->isVolatile() != isVolatile ||
8961 LI->getParent() != PN.getIncomingBlock(i) ||
8962 !isSafeToSinkLoad(LI))
8963 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008964 } else if (I->getOperand(1) != ConstantOp) {
8965 return 0;
8966 }
8967 }
8968
8969 // Okay, they are all the same operation. Create a new PHI node of the
8970 // correct type, and PHI together all of the LHS's of the instructions.
8971 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8972 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00008973 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00008974
8975 Value *InVal = FirstInst->getOperand(0);
8976 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00008977
8978 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00008979 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8980 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8981 if (NewInVal != InVal)
8982 InVal = 0;
8983 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8984 }
8985
8986 Value *PhiVal;
8987 if (InVal) {
8988 // The new PHI unions all of the same values together. This is really
8989 // common, so we handle it intelligently here for compile-time speed.
8990 PhiVal = InVal;
8991 delete NewPN;
8992 } else {
8993 InsertNewInstBefore(NewPN, PN);
8994 PhiVal = NewPN;
8995 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008996
Chris Lattnerbac32862004-11-14 19:13:23 +00008997 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00008998 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8999 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00009000 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00009001 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009002 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00009003 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009004 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9005 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
9006 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00009007 else
Reid Spencer832254e2007-02-02 02:16:23 +00009008 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00009009 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009010}
Chris Lattnera1be5662002-05-02 17:06:02 +00009011
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009012/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9013/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009014static bool DeadPHICycle(PHINode *PN,
9015 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009016 if (PN->use_empty()) return true;
9017 if (!PN->hasOneUse()) return false;
9018
9019 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009020 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009021 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009022
9023 // Don't scan crazily complex things.
9024 if (PotentiallyDeadPHIs.size() == 16)
9025 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009026
9027 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9028 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009029
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009030 return false;
9031}
9032
Chris Lattnercf5008a2007-11-06 21:52:06 +00009033/// PHIsEqualValue - Return true if this phi node is always equal to
9034/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9035/// z = some value; x = phi (y, z); y = phi (x, z)
9036static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9037 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9038 // See if we already saw this PHI node.
9039 if (!ValueEqualPHIs.insert(PN))
9040 return true;
9041
9042 // Don't scan crazily complex things.
9043 if (ValueEqualPHIs.size() == 16)
9044 return false;
9045
9046 // Scan the operands to see if they are either phi nodes or are equal to
9047 // the value.
9048 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9049 Value *Op = PN->getIncomingValue(i);
9050 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9051 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9052 return false;
9053 } else if (Op != NonPhiInVal)
9054 return false;
9055 }
9056
9057 return true;
9058}
9059
9060
Chris Lattner473945d2002-05-06 18:06:38 +00009061// PHINode simplification
9062//
Chris Lattner7e708292002-06-25 16:13:24 +00009063Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009064 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009065 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009066
Owen Anderson7e057142006-07-10 22:03:18 +00009067 if (Value *V = PN.hasConstantValue())
9068 return ReplaceInstUsesWith(PN, V);
9069
Owen Anderson7e057142006-07-10 22:03:18 +00009070 // If all PHI operands are the same operation, pull them through the PHI,
9071 // reducing code size.
9072 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9073 PN.getIncomingValue(0)->hasOneUse())
9074 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9075 return Result;
9076
9077 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9078 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9079 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009080 if (PN.hasOneUse()) {
9081 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9082 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009083 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009084 PotentiallyDeadPHIs.insert(&PN);
9085 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9086 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9087 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009088
9089 // If this phi has a single use, and if that use just computes a value for
9090 // the next iteration of a loop, delete the phi. This occurs with unused
9091 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9092 // common case here is good because the only other things that catch this
9093 // are induction variable analysis (sometimes) and ADCE, which is only run
9094 // late.
9095 if (PHIUser->hasOneUse() &&
9096 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9097 PHIUser->use_back() == &PN) {
9098 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9099 }
9100 }
Owen Anderson7e057142006-07-10 22:03:18 +00009101
Chris Lattnercf5008a2007-11-06 21:52:06 +00009102 // We sometimes end up with phi cycles that non-obviously end up being the
9103 // same value, for example:
9104 // z = some value; x = phi (y, z); y = phi (x, z)
9105 // where the phi nodes don't necessarily need to be in the same block. Do a
9106 // quick check to see if the PHI node only contains a single non-phi value, if
9107 // so, scan to see if the phi cycle is actually equal to that value.
9108 {
9109 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9110 // Scan for the first non-phi operand.
9111 while (InValNo != NumOperandVals &&
9112 isa<PHINode>(PN.getIncomingValue(InValNo)))
9113 ++InValNo;
9114
9115 if (InValNo != NumOperandVals) {
9116 Value *NonPhiInVal = PN.getOperand(InValNo);
9117
9118 // Scan the rest of the operands to see if there are any conflicts, if so
9119 // there is no need to recursively scan other phis.
9120 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9121 Value *OpVal = PN.getIncomingValue(InValNo);
9122 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9123 break;
9124 }
9125
9126 // If we scanned over all operands, then we have one unique value plus
9127 // phi values. Scan PHI nodes to see if they all merge in each other or
9128 // the value.
9129 if (InValNo == NumOperandVals) {
9130 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9131 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9132 return ReplaceInstUsesWith(PN, NonPhiInVal);
9133 }
9134 }
9135 }
Chris Lattner60921c92003-12-19 05:58:40 +00009136 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009137}
9138
Reid Spencer17212df2006-12-12 09:18:51 +00009139static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9140 Instruction *InsertPoint,
9141 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009142 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9143 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009144 // We must cast correctly to the pointer type. Ensure that we
9145 // sign extend the integer value if it is smaller as this is
9146 // used for address computation.
9147 Instruction::CastOps opcode =
9148 (VTySize < PtrSize ? Instruction::SExt :
9149 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9150 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009151}
9152
Chris Lattnera1be5662002-05-02 17:06:02 +00009153
Chris Lattner7e708292002-06-25 16:13:24 +00009154Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009155 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009156 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009157 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009158 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009159 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009160
Chris Lattnere87597f2004-10-16 18:11:37 +00009161 if (isa<UndefValue>(GEP.getOperand(0)))
9162 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9163
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009164 bool HasZeroPointerIndex = false;
9165 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9166 HasZeroPointerIndex = C->isNullValue();
9167
9168 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009169 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009170
Chris Lattner28977af2004-04-05 01:30:19 +00009171 // Eliminate unneeded casts for indices.
9172 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009173
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009174 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009175 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009176 if (isa<SequentialType>(*GTI)) {
9177 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009178 if (CI->getOpcode() == Instruction::ZExt ||
9179 CI->getOpcode() == Instruction::SExt) {
9180 const Type *SrcTy = CI->getOperand(0)->getType();
9181 // We can eliminate a cast from i32 to i64 iff the target
9182 // is a 32-bit pointer target.
9183 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9184 MadeChange = true;
9185 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009186 }
9187 }
9188 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009189 // If we are using a wider index than needed for this platform, shrink it
9190 // to what we need. If the incoming value needs a cast instruction,
9191 // insert it. This explicit cast can make subsequent optimizations more
9192 // obvious.
9193 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009194 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009195 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009196 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009197 MadeChange = true;
9198 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009199 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9200 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009201 GEP.setOperand(i, Op);
9202 MadeChange = true;
9203 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009204 }
Chris Lattner28977af2004-04-05 01:30:19 +00009205 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009206 }
Chris Lattner28977af2004-04-05 01:30:19 +00009207 if (MadeChange) return &GEP;
9208
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009209 // If this GEP instruction doesn't move the pointer, and if the input operand
9210 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9211 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009212 if (GEP.hasAllZeroIndices()) {
9213 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9214 // If the bitcast is of an allocation, and the allocation will be
9215 // converted to match the type of the cast, don't touch this.
9216 if (isa<AllocationInst>(BCI->getOperand(0))) {
9217 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009218 if (Instruction *I = visitBitCast(*BCI)) {
9219 if (I != BCI) {
9220 I->takeName(BCI);
9221 BCI->getParent()->getInstList().insert(BCI, I);
9222 ReplaceInstUsesWith(*BCI, I);
9223 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009224 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009225 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009226 }
9227 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9228 }
9229 }
9230
Chris Lattner90ac28c2002-08-02 19:29:35 +00009231 // Combine Indices - If the source pointer to this getelementptr instruction
9232 // is a getelementptr instruction, combine the indices of the two
9233 // getelementptr instructions into a single instruction.
9234 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009235 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009236 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009237 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009238
9239 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009240 // Note that if our source is a gep chain itself that we wait for that
9241 // chain to be resolved before we perform this transformation. This
9242 // avoids us creating a TON of code in some cases.
9243 //
9244 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9245 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9246 return 0; // Wait until our source is folded to completion.
9247
Chris Lattner72588fc2007-02-15 22:48:32 +00009248 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009249
9250 // Find out whether the last index in the source GEP is a sequential idx.
9251 bool EndsWithSequential = false;
9252 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9253 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009254 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009255
Chris Lattner90ac28c2002-08-02 19:29:35 +00009256 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009257 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009258 // Replace: gep (gep %P, long B), long A, ...
9259 // With: T = long A+B; gep %P, T, ...
9260 //
Chris Lattner620ce142004-05-07 22:09:22 +00009261 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009262 if (SO1 == Constant::getNullValue(SO1->getType())) {
9263 Sum = GO1;
9264 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9265 Sum = SO1;
9266 } else {
9267 // If they aren't the same type, convert both to an integer of the
9268 // target's pointer size.
9269 if (SO1->getType() != GO1->getType()) {
9270 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009271 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009272 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009273 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009274 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009275 unsigned PS = TD->getPointerSizeInBits();
9276 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009277 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009278 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009279
Duncan Sands514ab342007-11-01 20:53:16 +00009280 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009281 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009282 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009283 } else {
9284 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009285 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9286 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009287 }
9288 }
9289 }
Chris Lattner620ce142004-05-07 22:09:22 +00009290 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9291 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9292 else {
Chris Lattner48595f12004-06-10 02:07:29 +00009293 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9294 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009295 }
Chris Lattner28977af2004-04-05 01:30:19 +00009296 }
Chris Lattner620ce142004-05-07 22:09:22 +00009297
9298 // Recycle the GEP we already have if possible.
9299 if (SrcGEPOperands.size() == 2) {
9300 GEP.setOperand(0, SrcGEPOperands[0]);
9301 GEP.setOperand(1, Sum);
9302 return &GEP;
9303 } else {
9304 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9305 SrcGEPOperands.end()-1);
9306 Indices.push_back(Sum);
9307 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9308 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009309 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009310 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009311 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009312 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009313 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9314 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009315 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9316 }
9317
9318 if (!Indices.empty())
David Greeneb8f74792007-09-04 15:46:09 +00009319 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9320 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009321
Chris Lattner620ce142004-05-07 22:09:22 +00009322 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009323 // GEP of global variable. If all of the indices for this GEP are
9324 // constants, we can promote this to a constexpr instead of an instruction.
9325
9326 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009327 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009328 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9329 for (; I != E && isa<Constant>(*I); ++I)
9330 Indices.push_back(cast<Constant>(*I));
9331
9332 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009333 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9334 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009335
9336 // Replace all uses of the GEP with the new constexpr...
9337 return ReplaceInstUsesWith(GEP, CE);
9338 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009339 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009340 if (!isa<PointerType>(X->getType())) {
9341 // Not interesting. Source pointer must be a cast from pointer.
9342 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009343 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9344 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009345 //
9346 // This occurs when the program declares an array extern like "int X[];"
9347 //
9348 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9349 const PointerType *XTy = cast<PointerType>(X->getType());
9350 if (const ArrayType *XATy =
9351 dyn_cast<ArrayType>(XTy->getElementType()))
9352 if (const ArrayType *CATy =
9353 dyn_cast<ArrayType>(CPTy->getElementType()))
9354 if (CATy->getElementType() == XATy->getElementType()) {
9355 // At this point, we know that the cast source type is a pointer
9356 // to an array of the same type as the destination pointer
9357 // array. Because the array type is never stepped over (there
9358 // is a leading zero) we can fold the cast into this GEP.
9359 GEP.setOperand(0, X);
9360 return &GEP;
9361 }
9362 } else if (GEP.getNumOperands() == 2) {
9363 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009364 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9365 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009366 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9367 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9368 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009369 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9370 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009371 Value *Idx[2];
9372 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9373 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009374 Value *V = InsertNewInstBefore(
David Greeneb8f74792007-09-04 15:46:09 +00009375 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009376 // V and GEP are both pointer types --> BitCast
9377 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009378 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009379
9380 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009381 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009382 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009383 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009384
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009385 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009386 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009387 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009388
9389 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9390 // allow either a mul, shift, or constant here.
9391 Value *NewIdx = 0;
9392 ConstantInt *Scale = 0;
9393 if (ArrayEltSize == 1) {
9394 NewIdx = GEP.getOperand(1);
9395 Scale = ConstantInt::get(NewIdx->getType(), 1);
9396 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009397 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009398 Scale = CI;
9399 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9400 if (Inst->getOpcode() == Instruction::Shl &&
9401 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009402 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9403 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9404 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009405 NewIdx = Inst->getOperand(0);
9406 } else if (Inst->getOpcode() == Instruction::Mul &&
9407 isa<ConstantInt>(Inst->getOperand(1))) {
9408 Scale = cast<ConstantInt>(Inst->getOperand(1));
9409 NewIdx = Inst->getOperand(0);
9410 }
9411 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009412
Chris Lattner7835cdd2005-09-13 18:36:04 +00009413 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009414 // out, perform the transformation. Note, we don't know whether Scale is
9415 // signed or not. We'll use unsigned version of division/modulo
9416 // operation after making sure Scale doesn't have the sign bit set.
9417 if (Scale && Scale->getSExtValue() >= 0LL &&
9418 Scale->getZExtValue() % ArrayEltSize == 0) {
9419 Scale = ConstantInt::get(Scale->getType(),
9420 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009421 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009422 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009423 false /*ZExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009424 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9425 NewIdx = InsertNewInstBefore(Sc, GEP);
9426 }
9427
9428 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009429 Value *Idx[2];
9430 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9431 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009432 Instruction *NewGEP =
David Greeneb8f74792007-09-04 15:46:09 +00009433 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009434 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9435 // The NewGEP must be pointer typed, so must the old one -> BitCast
9436 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009437 }
9438 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009439 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009440 }
9441
Chris Lattner8a2a3112001-12-14 16:52:21 +00009442 return 0;
9443}
9444
Chris Lattner0864acf2002-11-04 16:18:53 +00009445Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9446 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009447 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009448 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9449 const Type *NewTy =
9450 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009451 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009452
9453 // Create and insert the replacement instruction...
9454 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009455 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009456 else {
9457 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009458 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009459 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009460
9461 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009462
Chris Lattner0864acf2002-11-04 16:18:53 +00009463 // Scan to the end of the allocation instructions, to skip over a block of
9464 // allocas if possible...
9465 //
9466 BasicBlock::iterator It = New;
9467 while (isa<AllocationInst>(*It)) ++It;
9468
9469 // Now that I is pointing to the first non-allocation-inst in the block,
9470 // insert our getelementptr instruction...
9471 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009472 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009473 Value *Idx[2];
9474 Idx[0] = NullIdx;
9475 Idx[1] = NullIdx;
9476 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Chris Lattner693787a2005-05-04 19:10:26 +00009477 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009478
9479 // Now make everything use the getelementptr instead of the original
9480 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009481 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009482 } else if (isa<UndefValue>(AI.getArraySize())) {
9483 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009484 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009485 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009486
9487 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9488 // Note that we only do this for alloca's, because malloc should allocate and
9489 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009490 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009491 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009492 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9493
Chris Lattner0864acf2002-11-04 16:18:53 +00009494 return 0;
9495}
9496
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009497Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9498 Value *Op = FI.getOperand(0);
9499
Chris Lattner17be6352004-10-18 02:59:09 +00009500 // free undef -> unreachable.
9501 if (isa<UndefValue>(Op)) {
9502 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009503 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009504 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009505 return EraseInstFromFunction(FI);
9506 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009507
Chris Lattner6160e852004-02-28 04:57:37 +00009508 // If we have 'free null' delete the instruction. This can happen in stl code
9509 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009510 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009511 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009512
9513 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9514 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9515 FI.setOperand(0, CI->getOperand(0));
9516 return &FI;
9517 }
9518
9519 // Change free (gep X, 0,0,0,0) into free(X)
9520 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9521 if (GEPI->hasAllZeroIndices()) {
9522 AddToWorkList(GEPI);
9523 FI.setOperand(0, GEPI->getOperand(0));
9524 return &FI;
9525 }
9526 }
9527
9528 // Change free(malloc) into nothing, if the malloc has a single use.
9529 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9530 if (MI->hasOneUse()) {
9531 EraseInstFromFunction(FI);
9532 return EraseInstFromFunction(*MI);
9533 }
Chris Lattner6160e852004-02-28 04:57:37 +00009534
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009535 return 0;
9536}
9537
9538
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009539/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009540static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +00009541 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009542 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009543 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009544
Devang Patel99db6ad2007-10-18 19:52:32 +00009545 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9546 // Instead of loading constant c string, use corresponding integer value
9547 // directly if string length is small enough.
9548 const std::string &Str = CE->getOperand(0)->getStringValue();
9549 if (!Str.empty()) {
9550 unsigned len = Str.length();
9551 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9552 unsigned numBits = Ty->getPrimitiveSizeInBits();
9553 // Replace LI with immediate integer store.
9554 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +00009555 APInt StrVal(numBits, 0);
9556 APInt SingleChar(numBits, 0);
9557 if (TD->isLittleEndian()) {
9558 for (signed i = len-1; i >= 0; i--) {
9559 SingleChar = (uint64_t) Str[i];
9560 StrVal = (StrVal << 8) | SingleChar;
9561 }
9562 } else {
9563 for (unsigned i = 0; i < len; i++) {
9564 SingleChar = (uint64_t) Str[i];
9565 StrVal = (StrVal << 8) | SingleChar;
9566 }
9567 // Append NULL at the end.
9568 SingleChar = 0;
9569 StrVal = (StrVal << 8) | SingleChar;
9570 }
9571 Value *NL = ConstantInt::get(StrVal);
9572 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +00009573 }
9574 }
9575 }
9576
Chris Lattnerb89e0712004-07-13 01:49:43 +00009577 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009578 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009579 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009580
Reid Spencer42230162007-01-22 05:51:25 +00009581 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009582 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009583 // If the source is an array, the code below will not succeed. Check to
9584 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9585 // constants.
9586 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9587 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9588 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009589 Value *Idxs[2];
9590 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9591 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009592 SrcTy = cast<PointerType>(CastOp->getType());
9593 SrcPTy = SrcTy->getElementType();
9594 }
9595
Reid Spencer42230162007-01-22 05:51:25 +00009596 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009597 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009598 // Do not allow turning this into a load of an integer, which is then
9599 // casted to a pointer, this pessimizes pointer analysis a lot.
9600 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009601 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9602 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009603
Chris Lattnerf9527852005-01-31 04:50:46 +00009604 // Okay, we are casting from one integer or pointer type to another of
9605 // the same size. Instead of casting the pointer before the load, cast
9606 // the result of the loaded value.
9607 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9608 CI->getName(),
9609 LI.isVolatile()),LI);
9610 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009611 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009612 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009613 }
9614 }
9615 return 0;
9616}
9617
Chris Lattnerc10aced2004-09-19 18:43:46 +00009618/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009619/// from this value cannot trap. If it is not obviously safe to load from the
9620/// specified pointer, we do a quick local scan of the basic block containing
9621/// ScanFrom, to determine if the address is already accessed.
9622static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009623 // If it is an alloca it is always safe to load from.
9624 if (isa<AllocaInst>(V)) return true;
9625
Duncan Sands46318cd2007-09-19 10:25:38 +00009626 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009627 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009628 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009629 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009630
9631 // Otherwise, be a little bit agressive by scanning the local block where we
9632 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009633 // from/to. If so, the previous load or store would have already trapped,
9634 // so there is no harm doing an extra load (also, CSE will later eliminate
9635 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00009636 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9637
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009638 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00009639 --BBI;
9640
9641 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9642 if (LI->getOperand(0) == V) return true;
9643 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9644 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00009645
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009646 }
Chris Lattner8a375202004-09-19 19:18:10 +00009647 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00009648}
9649
Chris Lattner8d2e8882007-08-11 18:48:48 +00009650/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9651/// until we find the underlying object a pointer is referring to or something
9652/// we don't understand. Note that the returned pointer may be offset from the
9653/// input, because we ignore GEP indices.
9654static Value *GetUnderlyingObject(Value *Ptr) {
9655 while (1) {
9656 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9657 if (CE->getOpcode() == Instruction::BitCast ||
9658 CE->getOpcode() == Instruction::GetElementPtr)
9659 Ptr = CE->getOperand(0);
9660 else
9661 return Ptr;
9662 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9663 Ptr = BCI->getOperand(0);
9664 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9665 Ptr = GEP->getOperand(0);
9666 } else {
9667 return Ptr;
9668 }
9669 }
9670}
9671
Chris Lattner833b8a42003-06-26 05:06:25 +00009672Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9673 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00009674
Dan Gohman9941f742007-07-20 16:34:21 +00009675 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009676 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009677 if (KnownAlign > LI.getAlignment())
9678 LI.setAlignment(KnownAlign);
9679
Chris Lattner37366c12005-05-01 04:24:53 +00009680 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00009681 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +00009682 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +00009683 return Res;
9684
9685 // None of the following transforms are legal for volatile loads.
9686 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00009687
Chris Lattner62f254d2005-09-12 22:00:15 +00009688 if (&LI.getParent()->front() != &LI) {
9689 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009690 // If the instruction immediately before this is a store to the same
9691 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00009692 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9693 if (SI->getOperand(1) == LI.getOperand(0))
9694 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009695 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9696 if (LIB->getOperand(0) == LI.getOperand(0))
9697 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00009698 }
Chris Lattner37366c12005-05-01 04:24:53 +00009699
Christopher Lambb15147e2007-12-29 07:56:53 +00009700 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9701 const Value *GEPI0 = GEPI->getOperand(0);
9702 // TODO: Consider a target hook for valid address spaces for this xform.
9703 if (isa<ConstantPointerNull>(GEPI0) &&
9704 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +00009705 // Insert a new store to null instruction before the load to indicate
9706 // that this code is not reachable. We do this instead of inserting
9707 // an unreachable instruction directly because we cannot modify the
9708 // CFG.
9709 new StoreInst(UndefValue::get(LI.getType()),
9710 Constant::getNullValue(Op->getType()), &LI);
9711 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9712 }
Christopher Lambb15147e2007-12-29 07:56:53 +00009713 }
Chris Lattner37366c12005-05-01 04:24:53 +00009714
Chris Lattnere87597f2004-10-16 18:11:37 +00009715 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00009716 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +00009717 // TODO: Consider a target hook for valid address spaces for this xform.
9718 if (isa<UndefValue>(C) || (C->isNullValue() &&
9719 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +00009720 // Insert a new store to null instruction before the load to indicate that
9721 // this code is not reachable. We do this instead of inserting an
9722 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00009723 new StoreInst(UndefValue::get(LI.getType()),
9724 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00009725 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009726 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009727
Chris Lattnere87597f2004-10-16 18:11:37 +00009728 // Instcombine load (constant global) into the value loaded.
9729 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009730 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00009731 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00009732
Chris Lattnere87597f2004-10-16 18:11:37 +00009733 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009734 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00009735 if (CE->getOpcode() == Instruction::GetElementPtr) {
9736 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009737 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00009738 if (Constant *V =
9739 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00009740 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00009741 if (CE->getOperand(0)->isNullValue()) {
9742 // Insert a new store to null instruction before the load to indicate
9743 // that this code is not reachable. We do this instead of inserting
9744 // an unreachable instruction directly because we cannot modify the
9745 // CFG.
9746 new StoreInst(UndefValue::get(LI.getType()),
9747 Constant::getNullValue(Op->getType()), &LI);
9748 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9749 }
9750
Reid Spencer3da59db2006-11-27 01:05:10 +00009751 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +00009752 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +00009753 return Res;
9754 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009755 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009756 }
Chris Lattner8d2e8882007-08-11 18:48:48 +00009757
9758 // If this load comes from anywhere in a constant global, and if the global
9759 // is all undef or zero, we know what it loads.
9760 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9761 if (GV->isConstant() && GV->hasInitializer()) {
9762 if (GV->getInitializer()->isNullValue())
9763 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9764 else if (isa<UndefValue>(GV->getInitializer()))
9765 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9766 }
9767 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00009768
Chris Lattner37366c12005-05-01 04:24:53 +00009769 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009770 // Change select and PHI nodes to select values instead of addresses: this
9771 // helps alias analysis out a lot, allows many others simplifications, and
9772 // exposes redundancy in the code.
9773 //
9774 // Note that we cannot do the transformation unless we know that the
9775 // introduced loads cannot trap! Something like this is valid as long as
9776 // the condition is always false: load (select bool %C, int* null, int* %G),
9777 // but it would not be valid if we transformed it to load from null
9778 // unconditionally.
9779 //
9780 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9781 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00009782 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9783 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009784 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009785 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009786 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009787 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009788 return new SelectInst(SI->getCondition(), V1, V2);
9789 }
9790
Chris Lattner684fe212004-09-23 15:46:00 +00009791 // load (select (cond, null, P)) -> load P
9792 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9793 if (C->isNullValue()) {
9794 LI.setOperand(0, SI->getOperand(2));
9795 return &LI;
9796 }
9797
9798 // load (select (cond, P, null)) -> load P
9799 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9800 if (C->isNullValue()) {
9801 LI.setOperand(0, SI->getOperand(1));
9802 return &LI;
9803 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00009804 }
9805 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009806 return 0;
9807}
9808
Reid Spencer55af2b52007-01-19 21:20:31 +00009809/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009810/// when possible.
9811static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9812 User *CI = cast<User>(SI.getOperand(1));
9813 Value *CastOp = CI->getOperand(0);
9814
9815 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9816 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9817 const Type *SrcPTy = SrcTy->getElementType();
9818
Reid Spencer42230162007-01-22 05:51:25 +00009819 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009820 // If the source is an array, the code below will not succeed. Check to
9821 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9822 // constants.
9823 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9824 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9825 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009826 Value* Idxs[2];
9827 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9828 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009829 SrcTy = cast<PointerType>(CastOp->getType());
9830 SrcPTy = SrcTy->getElementType();
9831 }
9832
Reid Spencer67f827c2007-01-20 23:35:48 +00009833 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9834 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9835 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009836
9837 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00009838 // the same size. Instead of casting the pointer before
9839 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009840 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00009841 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00009842 Instruction::CastOps opcode = Instruction::BitCast;
9843 const Type* CastSrcTy = SIOp0->getType();
9844 const Type* CastDstTy = SrcPTy;
9845 if (isa<PointerType>(CastDstTy)) {
9846 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00009847 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00009848 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00009849 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00009850 opcode = Instruction::PtrToInt;
9851 }
9852 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00009853 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009854 else
Reid Spencer3da59db2006-11-27 01:05:10 +00009855 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00009856 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9857 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009858 return new StoreInst(NewCast, CastOp);
9859 }
9860 }
9861 }
9862 return 0;
9863}
9864
Chris Lattner2f503e62005-01-31 05:36:43 +00009865Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9866 Value *Val = SI.getOperand(0);
9867 Value *Ptr = SI.getOperand(1);
9868
9869 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00009870 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009871 ++NumCombined;
9872 return 0;
9873 }
Chris Lattner836692d2007-01-15 06:51:56 +00009874
9875 // If the RHS is an alloca with a single use, zapify the store, making the
9876 // alloca dead.
9877 if (Ptr->hasOneUse()) {
9878 if (isa<AllocaInst>(Ptr)) {
9879 EraseInstFromFunction(SI);
9880 ++NumCombined;
9881 return 0;
9882 }
9883
9884 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9885 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9886 GEP->getOperand(0)->hasOneUse()) {
9887 EraseInstFromFunction(SI);
9888 ++NumCombined;
9889 return 0;
9890 }
9891 }
Chris Lattner2f503e62005-01-31 05:36:43 +00009892
Dan Gohman9941f742007-07-20 16:34:21 +00009893 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009894 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009895 if (KnownAlign > SI.getAlignment())
9896 SI.setAlignment(KnownAlign);
9897
Chris Lattner9ca96412006-02-08 03:25:32 +00009898 // Do really simple DSE, to catch cases where there are several consequtive
9899 // stores to the same location, separated by a few arithmetic operations. This
9900 // situation often occurs with bitfield accesses.
9901 BasicBlock::iterator BBI = &SI;
9902 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9903 --ScanInsts) {
9904 --BBI;
9905
9906 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9907 // Prev store isn't volatile, and stores to the same location?
9908 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9909 ++NumDeadStore;
9910 ++BBI;
9911 EraseInstFromFunction(*PrevSI);
9912 continue;
9913 }
9914 break;
9915 }
9916
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009917 // If this is a load, we have to stop. However, if the loaded value is from
9918 // the pointer we're loading and is producing the pointer we're storing,
9919 // then *this* store is dead (X = load P; store X -> P).
9920 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +00009921 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009922 EraseInstFromFunction(SI);
9923 ++NumCombined;
9924 return 0;
9925 }
9926 // Otherwise, this is a load from some other location. Stores before it
9927 // may not be dead.
9928 break;
9929 }
9930
Chris Lattner9ca96412006-02-08 03:25:32 +00009931 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009932 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00009933 break;
9934 }
9935
9936
9937 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00009938
9939 // store X, null -> turns into 'unreachable' in SimplifyCFG
9940 if (isa<ConstantPointerNull>(Ptr)) {
9941 if (!isa<UndefValue>(Val)) {
9942 SI.setOperand(0, UndefValue::get(Val->getType()));
9943 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +00009944 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00009945 ++NumCombined;
9946 }
9947 return 0; // Do not modify these!
9948 }
9949
9950 // store undef, Ptr -> noop
9951 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00009952 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009953 ++NumCombined;
9954 return 0;
9955 }
9956
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009957 // If the pointer destination is a cast, see if we can fold the cast into the
9958 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00009959 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009960 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9961 return Res;
9962 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00009963 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009964 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9965 return Res;
9966
Chris Lattner408902b2005-09-12 23:23:25 +00009967
9968 // If this store is the last instruction in the basic block, and if the block
9969 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00009970 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00009971 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009972 if (BI->isUnconditional())
9973 if (SimplifyStoreAtEndOfBlock(SI))
9974 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +00009975
Chris Lattner2f503e62005-01-31 05:36:43 +00009976 return 0;
9977}
9978
Chris Lattner3284d1f2007-04-15 00:07:55 +00009979/// SimplifyStoreAtEndOfBlock - Turn things like:
9980/// if () { *P = v1; } else { *P = v2 }
9981/// into a phi node with a store in the successor.
9982///
Chris Lattner31755a02007-04-15 01:02:18 +00009983/// Simplify things like:
9984/// *P = v1; if () { *P = v2; }
9985/// into a phi node with a store in the successor.
9986///
Chris Lattner3284d1f2007-04-15 00:07:55 +00009987bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9988 BasicBlock *StoreBB = SI.getParent();
9989
9990 // Check to see if the successor block has exactly two incoming edges. If
9991 // so, see if the other predecessor contains a store to the same location.
9992 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +00009993 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +00009994
9995 // Determine whether Dest has exactly two predecessors and, if so, compute
9996 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +00009997 pred_iterator PI = pred_begin(DestBB);
9998 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009999 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010000 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010001 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010002 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010003 return false;
10004
10005 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010006 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010007 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010008 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010009 }
Chris Lattner31755a02007-04-15 01:02:18 +000010010 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010011 return false;
10012
10013
Chris Lattner31755a02007-04-15 01:02:18 +000010014 // Verify that the other block ends in a branch and is not otherwise empty.
10015 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010016 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010017 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010018 return false;
10019
Chris Lattner31755a02007-04-15 01:02:18 +000010020 // If the other block ends in an unconditional branch, check for the 'if then
10021 // else' case. there is an instruction before the branch.
10022 StoreInst *OtherStore = 0;
10023 if (OtherBr->isUnconditional()) {
10024 // If this isn't a store, or isn't a store to the same location, bail out.
10025 --BBI;
10026 OtherStore = dyn_cast<StoreInst>(BBI);
10027 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10028 return false;
10029 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010030 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010031 // destinations is StoreBB, then we have the if/then case.
10032 if (OtherBr->getSuccessor(0) != StoreBB &&
10033 OtherBr->getSuccessor(1) != StoreBB)
10034 return false;
10035
10036 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010037 // if/then triangle. See if there is a store to the same ptr as SI that
10038 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010039 for (;; --BBI) {
10040 // Check to see if we find the matching store.
10041 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10042 if (OtherStore->getOperand(1) != SI.getOperand(1))
10043 return false;
10044 break;
10045 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010046 // If we find something that may be using the stored value, or if we run
10047 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010048 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10049 BBI == OtherBB->begin())
10050 return false;
10051 }
10052
10053 // In order to eliminate the store in OtherBr, we have to
10054 // make sure nothing reads the stored value in StoreBB.
10055 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10056 // FIXME: This should really be AA driven.
10057 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10058 return false;
10059 }
10060 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010061
Chris Lattner31755a02007-04-15 01:02:18 +000010062 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010063 Value *MergedVal = OtherStore->getOperand(0);
10064 if (MergedVal != SI.getOperand(0)) {
10065 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
10066 PN->reserveOperandSpace(2);
10067 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010068 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10069 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010070 }
10071
10072 // Advance to a place where it is safe to insert the new store and
10073 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010074 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010075 while (isa<PHINode>(BBI)) ++BBI;
10076 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10077 OtherStore->isVolatile()), *BBI);
10078
10079 // Nuke the old stores.
10080 EraseInstFromFunction(SI);
10081 EraseInstFromFunction(*OtherStore);
10082 ++NumCombined;
10083 return true;
10084}
10085
Chris Lattner2f503e62005-01-31 05:36:43 +000010086
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010087Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10088 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010089 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010090 BasicBlock *TrueDest;
10091 BasicBlock *FalseDest;
10092 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10093 !isa<Constant>(X)) {
10094 // Swap Destinations and condition...
10095 BI.setCondition(X);
10096 BI.setSuccessor(0, FalseDest);
10097 BI.setSuccessor(1, TrueDest);
10098 return &BI;
10099 }
10100
Reid Spencere4d87aa2006-12-23 06:05:41 +000010101 // Cannonicalize fcmp_one -> fcmp_oeq
10102 FCmpInst::Predicate FPred; Value *Y;
10103 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10104 TrueDest, FalseDest)))
10105 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10106 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10107 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010108 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010109 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10110 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010111 // Swap Destinations and condition...
10112 BI.setCondition(NewSCC);
10113 BI.setSuccessor(0, FalseDest);
10114 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010115 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010116 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010117 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010118 return &BI;
10119 }
10120
10121 // Cannonicalize icmp_ne -> icmp_eq
10122 ICmpInst::Predicate IPred;
10123 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10124 TrueDest, FalseDest)))
10125 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10126 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10127 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10128 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010129 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010130 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10131 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010132 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010133 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010134 BI.setSuccessor(0, FalseDest);
10135 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010136 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010137 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010138 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010139 return &BI;
10140 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010141
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010142 return 0;
10143}
Chris Lattner0864acf2002-11-04 16:18:53 +000010144
Chris Lattner46238a62004-07-03 00:26:11 +000010145Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10146 Value *Cond = SI.getCondition();
10147 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10148 if (I->getOpcode() == Instruction::Add)
10149 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10150 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10151 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010152 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010153 AddRHS));
10154 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010155 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010156 return &SI;
10157 }
10158 }
10159 return 0;
10160}
10161
Chris Lattner220b0cf2006-03-05 00:22:33 +000010162/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10163/// is to leave as a vector operation.
10164static bool CheapToScalarize(Value *V, bool isConstant) {
10165 if (isa<ConstantAggregateZero>(V))
10166 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010167 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010168 if (isConstant) return true;
10169 // If all elts are the same, we can extract.
10170 Constant *Op0 = C->getOperand(0);
10171 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10172 if (C->getOperand(i) != Op0)
10173 return false;
10174 return true;
10175 }
10176 Instruction *I = dyn_cast<Instruction>(V);
10177 if (!I) return false;
10178
10179 // Insert element gets simplified to the inserted element or is deleted if
10180 // this is constant idx extract element and its a constant idx insertelt.
10181 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10182 isa<ConstantInt>(I->getOperand(2)))
10183 return true;
10184 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10185 return true;
10186 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10187 if (BO->hasOneUse() &&
10188 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10189 CheapToScalarize(BO->getOperand(1), isConstant)))
10190 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010191 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10192 if (CI->hasOneUse() &&
10193 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10194 CheapToScalarize(CI->getOperand(1), isConstant)))
10195 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010196
10197 return false;
10198}
10199
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010200/// Read and decode a shufflevector mask.
10201///
10202/// It turns undef elements into values that are larger than the number of
10203/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010204static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10205 unsigned NElts = SVI->getType()->getNumElements();
10206 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10207 return std::vector<unsigned>(NElts, 0);
10208 if (isa<UndefValue>(SVI->getOperand(2)))
10209 return std::vector<unsigned>(NElts, 2*NElts);
10210
10211 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010212 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010213 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10214 if (isa<UndefValue>(CP->getOperand(i)))
10215 Result.push_back(NElts*2); // undef -> 8
10216 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010217 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010218 return Result;
10219}
10220
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010221/// FindScalarElement - Given a vector and an element number, see if the scalar
10222/// value is already around as a register, for example if it were inserted then
10223/// extracted from the vector.
10224static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010225 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10226 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010227 unsigned Width = PTy->getNumElements();
10228 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010229 return UndefValue::get(PTy->getElementType());
10230
10231 if (isa<UndefValue>(V))
10232 return UndefValue::get(PTy->getElementType());
10233 else if (isa<ConstantAggregateZero>(V))
10234 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010235 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010236 return CP->getOperand(EltNo);
10237 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10238 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010239 if (!isa<ConstantInt>(III->getOperand(2)))
10240 return 0;
10241 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010242
10243 // If this is an insert to the element we are looking for, return the
10244 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010245 if (EltNo == IIElt)
10246 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010247
10248 // Otherwise, the insertelement doesn't modify the value, recurse on its
10249 // vector input.
10250 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010251 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010252 unsigned InEl = getShuffleMask(SVI)[EltNo];
10253 if (InEl < Width)
10254 return FindScalarElement(SVI->getOperand(0), InEl);
10255 else if (InEl < Width*2)
10256 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10257 else
10258 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010259 }
10260
10261 // Otherwise, we don't know.
10262 return 0;
10263}
10264
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010265Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010266
Dan Gohman07a96762007-07-16 14:29:03 +000010267 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010268 if (isa<UndefValue>(EI.getOperand(0)))
10269 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10270
Dan Gohman07a96762007-07-16 14:29:03 +000010271 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010272 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10273 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10274
Reid Spencer9d6565a2007-02-15 02:26:10 +000010275 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010276 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010277 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010278 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010279 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010280 if (C->getOperand(i) != op0) {
10281 op0 = 0;
10282 break;
10283 }
10284 if (op0)
10285 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010286 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010287
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010288 // If extracting a specified index from the vector, see if we can recursively
10289 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010290 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010291 unsigned IndexVal = IdxC->getZExtValue();
10292 unsigned VectorWidth =
10293 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10294
10295 // If this is extracting an invalid index, turn this into undef, to avoid
10296 // crashing the code below.
10297 if (IndexVal >= VectorWidth)
10298 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10299
Chris Lattner867b99f2006-10-05 06:55:50 +000010300 // This instruction only demands the single element from the input vector.
10301 // If the input vector has a single use, simplify it based on this use
10302 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010303 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010304 uint64_t UndefElts;
10305 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010306 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010307 UndefElts)) {
10308 EI.setOperand(0, V);
10309 return &EI;
10310 }
10311 }
10312
Reid Spencerb83eb642006-10-20 07:07:24 +000010313 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010314 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010315
10316 // If the this extractelement is directly using a bitcast from a vector of
10317 // the same number of elements, see if we can find the source element from
10318 // it. In this case, we will end up needing to bitcast the scalars.
10319 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10320 if (const VectorType *VT =
10321 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10322 if (VT->getNumElements() == VectorWidth)
10323 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10324 return new BitCastInst(Elt, EI.getType());
10325 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010326 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010327
Chris Lattner73fa49d2006-05-25 22:53:38 +000010328 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010329 if (I->hasOneUse()) {
10330 // Push extractelement into predecessor operation if legal and
10331 // profitable to do so
10332 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010333 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10334 if (CheapToScalarize(BO, isConstantElt)) {
10335 ExtractElementInst *newEI0 =
10336 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10337 EI.getName()+".lhs");
10338 ExtractElementInst *newEI1 =
10339 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10340 EI.getName()+".rhs");
10341 InsertNewInstBefore(newEI0, EI);
10342 InsertNewInstBefore(newEI1, EI);
10343 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10344 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010345 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010346 unsigned AS =
10347 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010348 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10349 PointerType::get(EI.getType(), AS),EI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010350 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +000010351 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010352 InsertNewInstBefore(GEP, EI);
10353 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010354 }
10355 }
10356 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10357 // Extracting the inserted element?
10358 if (IE->getOperand(2) == EI.getOperand(1))
10359 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10360 // If the inserted and extracted elements are constants, they must not
10361 // be the same value, extract from the pre-inserted value instead.
10362 if (isa<Constant>(IE->getOperand(2)) &&
10363 isa<Constant>(EI.getOperand(1))) {
10364 AddUsesToWorkList(EI);
10365 EI.setOperand(0, IE->getOperand(0));
10366 return &EI;
10367 }
10368 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10369 // If this is extracting an element from a shufflevector, figure out where
10370 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010371 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10372 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010373 Value *Src;
10374 if (SrcIdx < SVI->getType()->getNumElements())
10375 Src = SVI->getOperand(0);
10376 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10377 SrcIdx -= SVI->getType()->getNumElements();
10378 Src = SVI->getOperand(1);
10379 } else {
10380 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010381 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010382 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010383 }
10384 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010385 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010386 return 0;
10387}
10388
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010389/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10390/// elements from either LHS or RHS, return the shuffle mask and true.
10391/// Otherwise, return false.
10392static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10393 std::vector<Constant*> &Mask) {
10394 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10395 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010396 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010397
10398 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010399 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010400 return true;
10401 } else if (V == LHS) {
10402 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010403 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010404 return true;
10405 } else if (V == RHS) {
10406 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010407 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010408 return true;
10409 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10410 // If this is an insert of an extract from some other vector, include it.
10411 Value *VecOp = IEI->getOperand(0);
10412 Value *ScalarOp = IEI->getOperand(1);
10413 Value *IdxOp = IEI->getOperand(2);
10414
Chris Lattnerd929f062006-04-27 21:14:21 +000010415 if (!isa<ConstantInt>(IdxOp))
10416 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010417 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010418
10419 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10420 // Okay, we can handle this if the vector we are insertinting into is
10421 // transitively ok.
10422 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10423 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010424 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010425 return true;
10426 }
10427 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10428 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010429 EI->getOperand(0)->getType() == V->getType()) {
10430 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010431 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010432
10433 // This must be extracting from either LHS or RHS.
10434 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10435 // Okay, we can handle this if the vector we are insertinting into is
10436 // transitively ok.
10437 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10438 // If so, update the mask to reflect the inserted value.
10439 if (EI->getOperand(0) == LHS) {
10440 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010441 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010442 } else {
10443 assert(EI->getOperand(0) == RHS);
10444 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010445 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010446
10447 }
10448 return true;
10449 }
10450 }
10451 }
10452 }
10453 }
10454 // TODO: Handle shufflevector here!
10455
10456 return false;
10457}
10458
10459/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10460/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10461/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010462static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010463 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010464 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010465 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010466 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010467 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010468
10469 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010470 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010471 return V;
10472 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010473 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010474 return V;
10475 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10476 // If this is an insert of an extract from some other vector, include it.
10477 Value *VecOp = IEI->getOperand(0);
10478 Value *ScalarOp = IEI->getOperand(1);
10479 Value *IdxOp = IEI->getOperand(2);
10480
10481 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10482 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10483 EI->getOperand(0)->getType() == V->getType()) {
10484 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010485 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10486 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010487
10488 // Either the extracted from or inserted into vector must be RHSVec,
10489 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010490 if (EI->getOperand(0) == RHS || RHS == 0) {
10491 RHS = EI->getOperand(0);
10492 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010493 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010494 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010495 return V;
10496 }
10497
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010498 if (VecOp == RHS) {
10499 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010500 // Everything but the extracted element is replaced with the RHS.
10501 for (unsigned i = 0; i != NumElts; ++i) {
10502 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010503 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010504 }
10505 return V;
10506 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010507
10508 // If this insertelement is a chain that comes from exactly these two
10509 // vectors, return the vector and the effective shuffle.
10510 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10511 return EI->getOperand(0);
10512
Chris Lattnerefb47352006-04-15 01:39:45 +000010513 }
10514 }
10515 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010516 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010517
10518 // Otherwise, can't do anything fancy. Return an identity vector.
10519 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010520 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010521 return V;
10522}
10523
10524Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10525 Value *VecOp = IE.getOperand(0);
10526 Value *ScalarOp = IE.getOperand(1);
10527 Value *IdxOp = IE.getOperand(2);
10528
Chris Lattner599ded12007-04-09 01:11:16 +000010529 // Inserting an undef or into an undefined place, remove this.
10530 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10531 ReplaceInstUsesWith(IE, VecOp);
10532
Chris Lattnerefb47352006-04-15 01:39:45 +000010533 // If the inserted element was extracted from some other vector, and if the
10534 // indexes are constant, try to turn this into a shufflevector operation.
10535 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10536 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10537 EI->getOperand(0)->getType() == IE.getType()) {
10538 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010539 unsigned ExtractedIdx =
10540 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010541 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010542
10543 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10544 return ReplaceInstUsesWith(IE, VecOp);
10545
10546 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10547 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10548
10549 // If we are extracting a value from a vector, then inserting it right
10550 // back into the same place, just use the input vector.
10551 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10552 return ReplaceInstUsesWith(IE, VecOp);
10553
10554 // We could theoretically do this for ANY input. However, doing so could
10555 // turn chains of insertelement instructions into a chain of shufflevector
10556 // instructions, and right now we do not merge shufflevectors. As such,
10557 // only do this in a situation where it is clear that there is benefit.
10558 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10559 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10560 // the values of VecOp, except then one read from EIOp0.
10561 // Build a new shuffle mask.
10562 std::vector<Constant*> Mask;
10563 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000010564 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010565 else {
10566 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000010567 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000010568 NumVectorElts));
10569 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000010570 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010571 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000010572 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010573 }
10574
10575 // If this insertelement isn't used by some other insertelement, turn it
10576 // (and any insertelements it points to), into one big shuffle.
10577 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10578 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010579 Value *RHS = 0;
10580 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10581 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10582 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000010583 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010584 }
10585 }
10586 }
10587
10588 return 0;
10589}
10590
10591
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010592Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10593 Value *LHS = SVI.getOperand(0);
10594 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000010595 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010596
10597 bool MadeChange = false;
10598
Chris Lattner867b99f2006-10-05 06:55:50 +000010599 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000010600 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010601 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10602
Chris Lattnere4929dd2007-01-05 07:36:08 +000010603 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000010604 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000010605 if (isa<UndefValue>(SVI.getOperand(1))) {
10606 // Scan to see if there are any references to the RHS. If so, replace them
10607 // with undef element refs and set MadeChange to true.
10608 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10609 if (Mask[i] >= e && Mask[i] != 2*e) {
10610 Mask[i] = 2*e;
10611 MadeChange = true;
10612 }
10613 }
10614
10615 if (MadeChange) {
10616 // Remap any references to RHS to use LHS.
10617 std::vector<Constant*> Elts;
10618 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10619 if (Mask[i] == 2*e)
10620 Elts.push_back(UndefValue::get(Type::Int32Ty));
10621 else
10622 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10623 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000010624 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000010625 }
10626 }
Chris Lattnerefb47352006-04-15 01:39:45 +000010627
Chris Lattner863bcff2006-05-25 23:48:38 +000010628 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10629 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10630 if (LHS == RHS || isa<UndefValue>(LHS)) {
10631 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010632 // shuffle(undef,undef,mask) -> undef.
10633 return ReplaceInstUsesWith(SVI, LHS);
10634 }
10635
Chris Lattner863bcff2006-05-25 23:48:38 +000010636 // Remap any references to RHS to use LHS.
10637 std::vector<Constant*> Elts;
10638 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000010639 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010640 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010641 else {
10642 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10643 (Mask[i] < e && isa<UndefValue>(LHS)))
10644 Mask[i] = 2*e; // Turn into undef.
10645 else
10646 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010647 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010648 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010649 }
Chris Lattner863bcff2006-05-25 23:48:38 +000010650 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010651 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000010652 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010653 LHS = SVI.getOperand(0);
10654 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010655 MadeChange = true;
10656 }
10657
Chris Lattner7b2e27922006-05-26 00:29:06 +000010658 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000010659 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000010660
Chris Lattner863bcff2006-05-25 23:48:38 +000010661 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10662 if (Mask[i] >= e*2) continue; // Ignore undef values.
10663 // Is this an identity shuffle of the LHS value?
10664 isLHSID &= (Mask[i] == i);
10665
10666 // Is this an identity shuffle of the RHS value?
10667 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000010668 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010669
Chris Lattner863bcff2006-05-25 23:48:38 +000010670 // Eliminate identity shuffles.
10671 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10672 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010673
Chris Lattner7b2e27922006-05-26 00:29:06 +000010674 // If the LHS is a shufflevector itself, see if we can combine it with this
10675 // one without producing an unusual shuffle. Here we are really conservative:
10676 // we are absolutely afraid of producing a shuffle mask not in the input
10677 // program, because the code gen may not be smart enough to turn a merged
10678 // shuffle into two specific shuffles: it may produce worse code. As such,
10679 // we only merge two shuffles if the result is one of the two input shuffle
10680 // masks. In this case, merging the shuffles just removes one instruction,
10681 // which we know is safe. This is good for things like turning:
10682 // (splat(splat)) -> splat.
10683 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10684 if (isa<UndefValue>(RHS)) {
10685 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10686
10687 std::vector<unsigned> NewMask;
10688 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10689 if (Mask[i] >= 2*e)
10690 NewMask.push_back(2*e);
10691 else
10692 NewMask.push_back(LHSMask[Mask[i]]);
10693
10694 // If the result mask is equal to the src shuffle or this shuffle mask, do
10695 // the replacement.
10696 if (NewMask == LHSMask || NewMask == Mask) {
10697 std::vector<Constant*> Elts;
10698 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10699 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010700 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010701 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010702 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010703 }
10704 }
10705 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10706 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000010707 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010708 }
10709 }
10710 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000010711
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010712 return MadeChange ? &SVI : 0;
10713}
10714
10715
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010716
Chris Lattnerea1c4542004-12-08 23:43:58 +000010717
10718/// TryToSinkInstruction - Try to move the specified instruction from its
10719/// current block into the beginning of DestBlock, which can only happen if it's
10720/// safe to move the instruction past all of the instructions between it and the
10721/// end of its block.
10722static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10723 assert(I->hasOneUse() && "Invariants didn't hold!");
10724
Chris Lattner108e9022005-10-27 17:13:11 +000010725 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10726 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000010727
Chris Lattnerea1c4542004-12-08 23:43:58 +000010728 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000010729 if (isa<AllocaInst>(I) && I->getParent() ==
10730 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000010731 return false;
10732
Chris Lattner96a52a62004-12-09 07:14:34 +000010733 // We can only sink load instructions if there is nothing between the load and
10734 // the end of block that could change the value.
10735 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +000010736 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10737 Scan != E; ++Scan)
10738 if (Scan->mayWriteToMemory())
10739 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000010740 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000010741
10742 BasicBlock::iterator InsertPos = DestBlock->begin();
10743 while (isa<PHINode>(InsertPos)) ++InsertPos;
10744
Chris Lattner4bc5f802005-08-08 19:11:57 +000010745 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000010746 ++NumSunkInst;
10747 return true;
10748}
10749
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010750
10751/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10752/// all reachable code to the worklist.
10753///
10754/// This has a couple of tricks to make the code faster and more powerful. In
10755/// particular, we constant fold and DCE instructions as we go, to avoid adding
10756/// them to the worklist (this significantly speeds up instcombine on code where
10757/// many instructions are dead or constant). Additionally, if we find a branch
10758/// whose condition is a known constant, we only visit the reachable successors.
10759///
10760static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000010761 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000010762 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010763 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000010764 std::vector<BasicBlock*> Worklist;
10765 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010766
Chris Lattner2c7718a2007-03-23 19:17:18 +000010767 while (!Worklist.empty()) {
10768 BB = Worklist.back();
10769 Worklist.pop_back();
10770
10771 // We have now visited this block! If we've already been here, ignore it.
10772 if (!Visited.insert(BB)) continue;
10773
10774 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10775 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010776
Chris Lattner2c7718a2007-03-23 19:17:18 +000010777 // DCE instruction if trivially dead.
10778 if (isInstructionTriviallyDead(Inst)) {
10779 ++NumDeadInst;
10780 DOUT << "IC: DCE: " << *Inst;
10781 Inst->eraseFromParent();
10782 continue;
10783 }
10784
10785 // ConstantProp instruction if trivially constant.
10786 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10787 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10788 Inst->replaceAllUsesWith(C);
10789 ++NumConstProp;
10790 Inst->eraseFromParent();
10791 continue;
10792 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000010793
Chris Lattner2c7718a2007-03-23 19:17:18 +000010794 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010795 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000010796
10797 // Recursively visit successors. If this is a branch or switch on a
10798 // constant, only visit the reachable successor.
10799 TerminatorInst *TI = BB->getTerminator();
10800 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10801 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10802 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10803 Worklist.push_back(BI->getSuccessor(!CondVal));
10804 continue;
10805 }
10806 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10807 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10808 // See if this is an explicit destination.
10809 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10810 if (SI->getCaseValue(i) == Cond) {
10811 Worklist.push_back(SI->getSuccessor(i));
10812 continue;
10813 }
10814
10815 // Otherwise it is the default destination.
10816 Worklist.push_back(SI->getSuccessor(0));
10817 continue;
10818 }
10819 }
10820
10821 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10822 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010823 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010824}
10825
Chris Lattnerec9c3582007-03-03 02:04:50 +000010826bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010827 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000010828 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000010829
10830 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10831 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000010832
Chris Lattnerb3d59702005-07-07 20:40:38 +000010833 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010834 // Do a depth-first traversal of the function, populate the worklist with
10835 // the reachable instructions. Ignore blocks that are not reachable. Keep
10836 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000010837 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010838 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000010839
Chris Lattnerb3d59702005-07-07 20:40:38 +000010840 // Do a quick scan over the function. If we find any blocks that are
10841 // unreachable, remove any instructions inside of them. This prevents
10842 // the instcombine code from having to deal with some bad special cases.
10843 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10844 if (!Visited.count(BB)) {
10845 Instruction *Term = BB->getTerminator();
10846 while (Term != BB->begin()) { // Remove instrs bottom-up
10847 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000010848
Bill Wendlingb7427032006-11-26 09:46:52 +000010849 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000010850 ++NumDeadInst;
10851
10852 if (!I->use_empty())
10853 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10854 I->eraseFromParent();
10855 }
10856 }
10857 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010858
Chris Lattnerdbab3862007-03-02 21:28:56 +000010859 while (!Worklist.empty()) {
10860 Instruction *I = RemoveOneFromWorkList();
10861 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000010862
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010863 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000010864 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010865 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000010866 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010867 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000010868 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000010869
Bill Wendlingb7427032006-11-26 09:46:52 +000010870 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010871
10872 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010873 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010874 continue;
10875 }
Chris Lattner62b14df2002-09-02 04:59:56 +000010876
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010877 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000010878 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010879 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010880
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010881 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010882 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000010883 ReplaceInstUsesWith(*I, C);
10884
Chris Lattner62b14df2002-09-02 04:59:56 +000010885 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010886 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010887 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010888 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000010889 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000010890
Chris Lattnerea1c4542004-12-08 23:43:58 +000010891 // See if we can trivially sink this instruction to a successor basic block.
10892 if (I->hasOneUse()) {
10893 BasicBlock *BB = I->getParent();
10894 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10895 if (UserParent != BB) {
10896 bool UserIsSuccessor = false;
10897 // See if the user is one of our successors.
10898 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10899 if (*SI == UserParent) {
10900 UserIsSuccessor = true;
10901 break;
10902 }
10903
10904 // If the user is one of our immediate successors, and if that successor
10905 // only has us as a predecessors (we'd have to split the critical edge
10906 // otherwise), we can keep going.
10907 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10908 next(pred_begin(UserParent)) == pred_end(UserParent))
10909 // Okay, the CFG is simple enough, try to sink this instruction.
10910 Changed |= TryToSinkInstruction(I, UserParent);
10911 }
10912 }
10913
Chris Lattner8a2a3112001-12-14 16:52:21 +000010914 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000010915#ifndef NDEBUG
10916 std::string OrigI;
10917#endif
10918 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000010919 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000010920 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010921 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010922 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010923 DOUT << "IC: Old = " << *I
10924 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000010925
Chris Lattnerf523d062004-06-09 05:08:07 +000010926 // Everything uses the new instruction now.
10927 I->replaceAllUsesWith(Result);
10928
10929 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010930 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000010931 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010932
Chris Lattner6934a042007-02-11 01:23:03 +000010933 // Move the name to the new instruction first.
10934 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010935
10936 // Insert the new instruction into the basic block...
10937 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000010938 BasicBlock::iterator InsertPos = I;
10939
10940 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10941 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10942 ++InsertPos;
10943
10944 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010945
Chris Lattner00d51312004-05-01 23:27:23 +000010946 // Make sure that we reprocess all operands now that we reduced their
10947 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010948 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000010949
Chris Lattnerf523d062004-06-09 05:08:07 +000010950 // Instructions can end up on the worklist more than once. Make sure
10951 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010952 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010953
10954 // Erase the old instruction.
10955 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000010956 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000010957#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000010958 DOUT << "IC: Mod = " << OrigI
10959 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000010960#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000010961
Chris Lattner90ac28c2002-08-02 19:29:35 +000010962 // If the instruction was modified, it's possible that it is now dead.
10963 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000010964 if (isInstructionTriviallyDead(I)) {
10965 // Make sure we process all operands now that we are reducing their
10966 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000010967 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010968
Chris Lattner00d51312004-05-01 23:27:23 +000010969 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010970 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010971 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000010972 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000010973 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000010974 AddToWorkList(I);
10975 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000010976 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010977 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010978 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000010979 }
10980 }
10981
Chris Lattnerec9c3582007-03-03 02:04:50 +000010982 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000010983
10984 // Do an explicit clear, this shrinks the map if needed.
10985 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010986 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010987}
10988
Chris Lattnerec9c3582007-03-03 02:04:50 +000010989
10990bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000010991 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10992
Chris Lattnerec9c3582007-03-03 02:04:50 +000010993 bool EverMadeChange = false;
10994
10995 // Iterate while there is work to do.
10996 unsigned Iteration = 0;
10997 while (DoOneIteration(F, Iteration++))
10998 EverMadeChange = true;
10999 return EverMadeChange;
11000}
11001
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011002FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011003 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011004}
Brian Gaeked0fde302003-11-11 22:41:34 +000011005