blob: f89d1f2aeeecc2f9163fa558385ba693189ab7d6 [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"
Duncan Sandsb84abcd2007-09-11 14:35:41 +000042#include "llvm/ParameterAttributes.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}
608
Chris Lattner68d5ff22006-02-09 07:38:58 +0000609/// ComputeMaskedBits - Determine which of the bits specified in Mask are
610/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000611/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
612/// processing.
613/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
614/// we cannot optimize based on the assumption that it is zero without changing
615/// it to be an explicit zero. If we don't change it to zero, other code could
616/// optimized based on the contradictory assumption that it is non-zero.
617/// Because instcombine aggressively folds operations with undef args anyway,
618/// this won't lose us code quality.
Reid Spencer55702aa2007-03-25 21:11:44 +0000619static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spencer3e7594f2007-03-08 01:46:38 +0000620 APInt& KnownOne, unsigned Depth = 0) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000621 assert(V && "No Value?");
622 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000623 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000624 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000625 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000626 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000627 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000628 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
629 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000630 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000631 KnownZero = ~KnownOne & Mask;
632 return;
633 }
634
Reid Spencer3e7594f2007-03-08 01:46:38 +0000635 if (Depth == 6 || Mask == 0)
636 return; // Limit search depth.
637
638 Instruction *I = dyn_cast<Instruction>(V);
639 if (!I) return;
640
Zhou Sheng771dbf72007-03-13 02:23:10 +0000641 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000642 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000643
644 switch (I->getOpcode()) {
Reid Spencer2b812072007-03-25 02:03:12 +0000645 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000646 // If either the LHS or the RHS are Zero, the result is zero.
647 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000648 APInt Mask2(Mask & ~KnownZero);
649 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000650 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
651 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
652
653 // Output known-1 bits are only known if set in both the LHS & RHS.
654 KnownOne &= KnownOne2;
655 // Output known-0 are known to be clear if zero in either the LHS | RHS.
656 KnownZero |= KnownZero2;
657 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000658 }
659 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000660 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000661 APInt Mask2(Mask & ~KnownOne);
662 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000663 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
664 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
665
666 // Output known-0 bits are only known if clear in both the LHS & RHS.
667 KnownZero &= KnownZero2;
668 // Output known-1 are known to be set if set in either the LHS | RHS.
669 KnownOne |= KnownOne2;
670 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000671 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000672 case Instruction::Xor: {
673 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
674 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
675 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
676 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
677
678 // Output known-0 bits are known if clear or set in both the LHS & RHS.
679 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
680 // Output known-1 are known to be set if set in only one of the LHS, RHS.
681 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
682 KnownZero = KnownZeroOut;
683 return;
684 }
685 case Instruction::Select:
686 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
687 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
688 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
689 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
690
691 // Only known if known in both the LHS and RHS.
692 KnownOne &= KnownOne2;
693 KnownZero &= KnownZero2;
694 return;
695 case Instruction::FPTrunc:
696 case Instruction::FPExt:
697 case Instruction::FPToUI:
698 case Instruction::FPToSI:
699 case Instruction::SIToFP:
700 case Instruction::PtrToInt:
701 case Instruction::UIToFP:
702 case Instruction::IntToPtr:
703 return; // Can't work with floating point or pointers
Zhou Sheng771dbf72007-03-13 02:23:10 +0000704 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000705 // All these have integer operands
Zhou Sheng771dbf72007-03-13 02:23:10 +0000706 uint32_t SrcBitWidth =
707 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000708 APInt MaskIn(Mask);
709 MaskIn.zext(SrcBitWidth);
710 KnownZero.zext(SrcBitWidth);
711 KnownOne.zext(SrcBitWidth);
712 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Sheng771dbf72007-03-13 02:23:10 +0000713 KnownZero.trunc(BitWidth);
714 KnownOne.trunc(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000715 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000716 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000717 case Instruction::BitCast: {
718 const Type *SrcTy = I->getOperand(0)->getType();
719 if (SrcTy->isInteger()) {
720 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
721 return;
722 }
723 break;
724 }
725 case Instruction::ZExt: {
726 // Compute the bits in the result that are not present in the input.
727 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000728 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000729
Zhou Shengaa305ab2007-03-28 02:19:03 +0000730 APInt MaskIn(Mask);
731 MaskIn.trunc(SrcBitWidth);
732 KnownZero.trunc(SrcBitWidth);
733 KnownOne.trunc(SrcBitWidth);
734 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000735 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
736 // The top bits are known to be zero.
Zhou Sheng771dbf72007-03-13 02:23:10 +0000737 KnownZero.zext(BitWidth);
738 KnownOne.zext(BitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000739 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000740 return;
741 }
742 case Instruction::SExt: {
743 // Compute the bits in the result that are not present in the input.
744 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000745 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000746
Zhou Shengaa305ab2007-03-28 02:19:03 +0000747 APInt MaskIn(Mask);
748 MaskIn.trunc(SrcBitWidth);
749 KnownZero.trunc(SrcBitWidth);
750 KnownOne.trunc(SrcBitWidth);
751 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000752 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000753 KnownZero.zext(BitWidth);
754 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000755
756 // If the sign bit of the input is known set or clear, then we know the
757 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000758 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000759 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000760 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000761 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000762 return;
763 }
764 case Instruction::Shl:
765 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
766 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000767 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000768 APInt Mask2(Mask.lshr(ShiftAmt));
769 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000770 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000771 KnownZero <<= ShiftAmt;
772 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000773 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000774 return;
775 }
776 break;
777 case Instruction::LShr:
778 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
779 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
780 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000781 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000782
783 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000784 APInt Mask2(Mask.shl(ShiftAmt));
785 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000786 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
787 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
788 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000789 // high bits known zero.
790 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000791 return;
792 }
793 break;
794 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000795 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000796 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
797 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000798 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000799
800 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000801 APInt Mask2(Mask.shl(ShiftAmt));
802 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000803 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
804 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
805 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
806
Zhou Shengaa305ab2007-03-28 02:19:03 +0000807 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
808 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000809 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000810 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000811 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000812 return;
813 }
814 break;
815 }
816}
817
Reid Spencere7816b52007-03-08 01:52:58 +0000818/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
819/// this predicate to simplify operations downstream. Mask is known to be zero
820/// for bits that V cannot have.
821static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengedd089c2007-03-12 16:54:56 +0000822 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +0000823 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
824 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
825 return (KnownZero & Mask) == Mask;
826}
827
Chris Lattner255d8912006-02-11 09:31:47 +0000828/// ShrinkDemandedConstant - Check to see if the specified operand of the
829/// specified instruction is a constant integer. If so, check to see if there
830/// are any bits set in the constant that are not demanded. If so, shrink the
831/// constant and return true.
832static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000833 APInt Demanded) {
834 assert(I && "No instruction?");
835 assert(OpNo < I->getNumOperands() && "Operand index too large");
836
837 // If the operand is not a constant integer, nothing to do.
838 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
839 if (!OpC) return false;
840
841 // If there are no bits set that aren't demanded, nothing to do.
842 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
843 if ((~Demanded & OpC->getValue()) == 0)
844 return false;
845
846 // This instruction is producing bits that are not demanded. Shrink the RHS.
847 Demanded &= OpC->getValue();
848 I->setOperand(OpNo, ConstantInt::get(Demanded));
849 return true;
850}
851
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000852// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
853// set of known zero and one bits, compute the maximum and minimum values that
854// could have the specified known zero and known one bits, returning them in
855// min/max.
856static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000857 const APInt& KnownZero,
858 const APInt& KnownOne,
859 APInt& Min, APInt& Max) {
860 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
861 assert(KnownZero.getBitWidth() == BitWidth &&
862 KnownOne.getBitWidth() == BitWidth &&
863 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
864 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000865 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000866
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000867 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
868 // bit if it is unknown.
869 Min = KnownOne;
870 Max = KnownOne|UnknownBits;
871
Zhou Sheng4acf1552007-03-28 05:15:57 +0000872 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000873 Min.set(BitWidth-1);
874 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000875 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000876}
877
878// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
879// a set of known zero and one bits, compute the maximum and minimum values that
880// could have the specified known zero and known one bits, returning them in
881// min/max.
882static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000883 const APInt &KnownZero,
884 const APInt &KnownOne,
885 APInt &Min, APInt &Max) {
886 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000887 assert(KnownZero.getBitWidth() == BitWidth &&
888 KnownOne.getBitWidth() == BitWidth &&
889 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
890 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000891 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000892
893 // The minimum value is when the unknown bits are all zeros.
894 Min = KnownOne;
895 // The maximum value is when the unknown bits are all ones.
896 Max = KnownOne|UnknownBits;
897}
Chris Lattner255d8912006-02-11 09:31:47 +0000898
Reid Spencer8cb68342007-03-12 17:25:59 +0000899/// SimplifyDemandedBits - This function attempts to replace V with a simpler
900/// value based on the demanded bits. When this function is called, it is known
901/// that only the bits set in DemandedMask of the result of V are ever used
902/// downstream. Consequently, depending on the mask and V, it may be possible
903/// to replace V with a constant or one of its operands. In such cases, this
904/// function does the replacement and returns true. In all other cases, it
905/// returns false after analyzing the expression and setting KnownOne and known
906/// to be one in the expression. KnownZero contains all the bits that are known
907/// to be zero in the expression. These are provided to potentially allow the
908/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
909/// the expression. KnownOne and KnownZero always follow the invariant that
910/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
911/// the bits in KnownOne and KnownZero may only be accurate for those bits set
912/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
913/// and KnownOne must all be the same.
914bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
915 APInt& KnownZero, APInt& KnownOne,
916 unsigned Depth) {
917 assert(V != 0 && "Null pointer of Value???");
918 assert(Depth <= 6 && "Limit Search Depth");
919 uint32_t BitWidth = DemandedMask.getBitWidth();
920 const IntegerType *VTy = cast<IntegerType>(V->getType());
921 assert(VTy->getBitWidth() == BitWidth &&
922 KnownZero.getBitWidth() == BitWidth &&
923 KnownOne.getBitWidth() == BitWidth &&
924 "Value *V, DemandedMask, KnownZero and KnownOne \
925 must have same BitWidth");
926 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
927 // We know all of the bits for a constant!
928 KnownOne = CI->getValue() & DemandedMask;
929 KnownZero = ~KnownOne & DemandedMask;
930 return false;
931 }
932
Zhou Sheng96704452007-03-14 03:21:24 +0000933 KnownZero.clear();
934 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +0000935 if (!V->hasOneUse()) { // Other users may use these bits.
936 if (Depth != 0) { // Not at the root.
937 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
938 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
939 return false;
940 }
941 // If this is the root being simplified, allow it to have multiple uses,
942 // just set the DemandedMask to all bits.
943 DemandedMask = APInt::getAllOnesValue(BitWidth);
944 } else if (DemandedMask == 0) { // Not demanding any bits from V.
945 if (V != UndefValue::get(VTy))
946 return UpdateValueUsesWith(V, UndefValue::get(VTy));
947 return false;
948 } else if (Depth == 6) { // Limit search depth.
949 return false;
950 }
951
952 Instruction *I = dyn_cast<Instruction>(V);
953 if (!I) return false; // Only analyze instructions.
954
Reid Spencer8cb68342007-03-12 17:25:59 +0000955 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
956 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
957 switch (I->getOpcode()) {
958 default: break;
959 case Instruction::And:
960 // If either the LHS or the RHS are Zero, the result is zero.
961 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
962 RHSKnownZero, RHSKnownOne, Depth+1))
963 return true;
964 assert((RHSKnownZero & RHSKnownOne) == 0 &&
965 "Bits known to be one AND zero?");
966
967 // If something is known zero on the RHS, the bits aren't demanded on the
968 // LHS.
969 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
970 LHSKnownZero, LHSKnownOne, Depth+1))
971 return true;
972 assert((LHSKnownZero & LHSKnownOne) == 0 &&
973 "Bits known to be one AND zero?");
974
975 // If all of the demanded bits are known 1 on one side, return the other.
976 // These bits cannot contribute to the result of the 'and'.
977 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
978 (DemandedMask & ~LHSKnownZero))
979 return UpdateValueUsesWith(I, I->getOperand(0));
980 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
981 (DemandedMask & ~RHSKnownZero))
982 return UpdateValueUsesWith(I, I->getOperand(1));
983
984 // If all of the demanded bits in the inputs are known zeros, return zero.
985 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
986 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
987
988 // If the RHS is a constant, see if we can simplify it.
989 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
990 return UpdateValueUsesWith(I, I);
991
992 // Output known-1 bits are only known if set in both the LHS & RHS.
993 RHSKnownOne &= LHSKnownOne;
994 // Output known-0 are known to be clear if zero in either the LHS | RHS.
995 RHSKnownZero |= LHSKnownZero;
996 break;
997 case Instruction::Or:
998 // If either the LHS or the RHS are One, the result is One.
999 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1000 RHSKnownZero, RHSKnownOne, Depth+1))
1001 return true;
1002 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1003 "Bits known to be one AND zero?");
1004 // If something is known one on the RHS, the bits aren't demanded on the
1005 // LHS.
1006 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1007 LHSKnownZero, LHSKnownOne, Depth+1))
1008 return true;
1009 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1010 "Bits known to be one AND zero?");
1011
1012 // If all of the demanded bits are known zero on one side, return the other.
1013 // These bits cannot contribute to the result of the 'or'.
1014 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1015 (DemandedMask & ~LHSKnownOne))
1016 return UpdateValueUsesWith(I, I->getOperand(0));
1017 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1018 (DemandedMask & ~RHSKnownOne))
1019 return UpdateValueUsesWith(I, I->getOperand(1));
1020
1021 // If all of the potentially set bits on one side are known to be set on
1022 // the other side, just use the 'other' side.
1023 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1024 (DemandedMask & (~RHSKnownZero)))
1025 return UpdateValueUsesWith(I, I->getOperand(0));
1026 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1027 (DemandedMask & (~LHSKnownZero)))
1028 return UpdateValueUsesWith(I, I->getOperand(1));
1029
1030 // If the RHS is a constant, see if we can simplify it.
1031 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1032 return UpdateValueUsesWith(I, I);
1033
1034 // Output known-0 bits are only known if clear in both the LHS & RHS.
1035 RHSKnownZero &= LHSKnownZero;
1036 // Output known-1 are known to be set if set in either the LHS | RHS.
1037 RHSKnownOne |= LHSKnownOne;
1038 break;
1039 case Instruction::Xor: {
1040 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1041 RHSKnownZero, RHSKnownOne, Depth+1))
1042 return true;
1043 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1044 "Bits known to be one AND zero?");
1045 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1046 LHSKnownZero, LHSKnownOne, Depth+1))
1047 return true;
1048 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1049 "Bits known to be one AND zero?");
1050
1051 // If all of the demanded bits are known zero on one side, return the other.
1052 // These bits cannot contribute to the result of the 'xor'.
1053 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1054 return UpdateValueUsesWith(I, I->getOperand(0));
1055 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1056 return UpdateValueUsesWith(I, I->getOperand(1));
1057
1058 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1059 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1060 (RHSKnownOne & LHSKnownOne);
1061 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1062 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1063 (RHSKnownOne & LHSKnownZero);
1064
1065 // If all of the demanded bits are known to be zero on one side or the
1066 // other, turn this into an *inclusive* or.
1067 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1068 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1069 Instruction *Or =
1070 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1071 I->getName());
1072 InsertNewInstBefore(Or, *I);
1073 return UpdateValueUsesWith(I, Or);
1074 }
1075
1076 // If all of the demanded bits on one side are known, and all of the set
1077 // bits on that side are also known to be set on the other side, turn this
1078 // into an AND, as we know the bits will be cleared.
1079 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1080 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1081 // all known
1082 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1083 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1084 Instruction *And =
1085 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1086 InsertNewInstBefore(And, *I);
1087 return UpdateValueUsesWith(I, And);
1088 }
1089 }
1090
1091 // If the RHS is a constant, see if we can simplify it.
1092 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1093 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1094 return UpdateValueUsesWith(I, I);
1095
1096 RHSKnownZero = KnownZeroOut;
1097 RHSKnownOne = KnownOneOut;
1098 break;
1099 }
1100 case Instruction::Select:
1101 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1102 RHSKnownZero, RHSKnownOne, Depth+1))
1103 return true;
1104 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1105 LHSKnownZero, LHSKnownOne, Depth+1))
1106 return true;
1107 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1108 "Bits known to be one AND zero?");
1109 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1110 "Bits known to be one AND zero?");
1111
1112 // If the operands are constants, see if we can simplify them.
1113 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1114 return UpdateValueUsesWith(I, I);
1115 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1116 return UpdateValueUsesWith(I, I);
1117
1118 // Only known if known in both the LHS and RHS.
1119 RHSKnownOne &= LHSKnownOne;
1120 RHSKnownZero &= LHSKnownZero;
1121 break;
1122 case Instruction::Trunc: {
1123 uint32_t truncBf =
1124 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001125 DemandedMask.zext(truncBf);
1126 RHSKnownZero.zext(truncBf);
1127 RHSKnownOne.zext(truncBf);
1128 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1129 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001130 return true;
1131 DemandedMask.trunc(BitWidth);
1132 RHSKnownZero.trunc(BitWidth);
1133 RHSKnownOne.trunc(BitWidth);
1134 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1135 "Bits known to be one AND zero?");
1136 break;
1137 }
1138 case Instruction::BitCast:
1139 if (!I->getOperand(0)->getType()->isInteger())
1140 return false;
1141
1142 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1143 RHSKnownZero, RHSKnownOne, Depth+1))
1144 return true;
1145 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1146 "Bits known to be one AND zero?");
1147 break;
1148 case Instruction::ZExt: {
1149 // Compute the bits in the result that are not present in the input.
1150 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001151 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001152
Zhou Shengd48653a2007-03-29 04:45:55 +00001153 DemandedMask.trunc(SrcBitWidth);
1154 RHSKnownZero.trunc(SrcBitWidth);
1155 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001156 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1157 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001158 return true;
1159 DemandedMask.zext(BitWidth);
1160 RHSKnownZero.zext(BitWidth);
1161 RHSKnownOne.zext(BitWidth);
1162 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1163 "Bits known to be one AND zero?");
1164 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001165 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001166 break;
1167 }
1168 case Instruction::SExt: {
1169 // Compute the bits in the result that are not present in the input.
1170 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001171 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001172
Reid Spencer8cb68342007-03-12 17:25:59 +00001173 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001174 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001175
Zhou Sheng01542f32007-03-29 02:26:30 +00001176 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001177 // If any of the sign extended bits are demanded, we know that the sign
1178 // bit is demanded.
1179 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001180 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001181
Zhou Shengd48653a2007-03-29 04:45:55 +00001182 InputDemandedBits.trunc(SrcBitWidth);
1183 RHSKnownZero.trunc(SrcBitWidth);
1184 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001185 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1186 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001187 return true;
1188 InputDemandedBits.zext(BitWidth);
1189 RHSKnownZero.zext(BitWidth);
1190 RHSKnownOne.zext(BitWidth);
1191 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1192 "Bits known to be one AND zero?");
1193
1194 // If the sign bit of the input is known set or clear, then we know the
1195 // top bits of the result.
1196
1197 // If the input sign bit is known zero, or if the NewBits are not demanded
1198 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001199 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001200 {
1201 // Convert to ZExt cast
1202 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1203 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001204 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001205 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001206 }
1207 break;
1208 }
1209 case Instruction::Add: {
1210 // Figure out what the input bits are. If the top bits of the and result
1211 // are not demanded, then the add doesn't demand them from its input
1212 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001213 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001214
1215 // If there is a constant on the RHS, there are a variety of xformations
1216 // we can do.
1217 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1218 // If null, this should be simplified elsewhere. Some of the xforms here
1219 // won't work if the RHS is zero.
1220 if (RHS->isZero())
1221 break;
1222
1223 // If the top bit of the output is demanded, demand everything from the
1224 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001225 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001226
1227 // Find information about known zero/one bits in the input.
1228 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1229 LHSKnownZero, LHSKnownOne, Depth+1))
1230 return true;
1231
1232 // If the RHS of the add has bits set that can't affect the input, reduce
1233 // the constant.
1234 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1235 return UpdateValueUsesWith(I, I);
1236
1237 // Avoid excess work.
1238 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1239 break;
1240
1241 // Turn it into OR if input bits are zero.
1242 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1243 Instruction *Or =
1244 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1245 I->getName());
1246 InsertNewInstBefore(Or, *I);
1247 return UpdateValueUsesWith(I, Or);
1248 }
1249
1250 // We can say something about the output known-zero and known-one bits,
1251 // depending on potential carries from the input constant and the
1252 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1253 // bits set and the RHS constant is 0x01001, then we know we have a known
1254 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1255
1256 // To compute this, we first compute the potential carry bits. These are
1257 // the bits which may be modified. I'm not aware of a better way to do
1258 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001259 const APInt& RHSVal = RHS->getValue();
1260 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001261
1262 // Now that we know which bits have carries, compute the known-1/0 sets.
1263
1264 // Bits are known one if they are known zero in one operand and one in the
1265 // other, and there is no input carry.
1266 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1267 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1268
1269 // Bits are known zero if they are known zero in both operands and there
1270 // is no input carry.
1271 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1272 } else {
1273 // If the high-bits of this ADD are not demanded, then it does not demand
1274 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001275 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001276 // Right fill the mask of bits for this ADD to demand the most
1277 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001278 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001279 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1280 LHSKnownZero, LHSKnownOne, Depth+1))
1281 return true;
1282 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1283 LHSKnownZero, LHSKnownOne, Depth+1))
1284 return true;
1285 }
1286 }
1287 break;
1288 }
1289 case Instruction::Sub:
1290 // If the high-bits of this SUB are not demanded, then it does not demand
1291 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001292 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001293 // Right fill the mask of bits for this SUB to demand the most
1294 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001295 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001296 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001297 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1298 LHSKnownZero, LHSKnownOne, Depth+1))
1299 return true;
1300 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1301 LHSKnownZero, LHSKnownOne, Depth+1))
1302 return true;
1303 }
1304 break;
1305 case Instruction::Shl:
1306 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001307 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001308 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1309 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001310 RHSKnownZero, RHSKnownOne, Depth+1))
1311 return true;
1312 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1313 "Bits known to be one AND zero?");
1314 RHSKnownZero <<= ShiftAmt;
1315 RHSKnownOne <<= ShiftAmt;
1316 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001317 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001318 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001319 }
1320 break;
1321 case Instruction::LShr:
1322 // For a logical shift right
1323 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001324 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001325
Reid Spencer8cb68342007-03-12 17:25:59 +00001326 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001327 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1328 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001329 RHSKnownZero, RHSKnownOne, Depth+1))
1330 return true;
1331 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1332 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001333 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1334 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001335 if (ShiftAmt) {
1336 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001337 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001338 RHSKnownZero |= HighBits; // high bits known zero.
1339 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001340 }
1341 break;
1342 case Instruction::AShr:
1343 // If this is an arithmetic shift right and only the low-bit is set, we can
1344 // always convert this into a logical shr, even if the shift amount is
1345 // variable. The low bit of the shift cannot be an input sign bit unless
1346 // the shift amount is >= the size of the datatype, which is undefined.
1347 if (DemandedMask == 1) {
1348 // Perform the logical shift right.
1349 Value *NewVal = BinaryOperator::createLShr(
1350 I->getOperand(0), I->getOperand(1), I->getName());
1351 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1352 return UpdateValueUsesWith(I, NewVal);
1353 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001354
1355 // If the sign bit is the only bit demanded by this ashr, then there is no
1356 // need to do it, the shift doesn't change the high bit.
1357 if (DemandedMask.isSignBit())
1358 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001359
1360 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001361 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001362
Reid Spencer8cb68342007-03-12 17:25:59 +00001363 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001364 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001365 // If any of the "high bits" are demanded, we should set the sign bit as
1366 // demanded.
1367 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1368 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001369 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001370 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001371 RHSKnownZero, RHSKnownOne, Depth+1))
1372 return true;
1373 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1374 "Bits known to be one AND zero?");
1375 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001376 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001377 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1378 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1379
1380 // Handle the sign bits.
1381 APInt SignBit(APInt::getSignBit(BitWidth));
1382 // Adjust to where it is now in the mask.
1383 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1384
1385 // If the input sign bit is known to be zero, or if none of the top bits
1386 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001387 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001388 (HighBits & ~DemandedMask) == HighBits) {
1389 // Perform the logical shift right.
1390 Value *NewVal = BinaryOperator::createLShr(
1391 I->getOperand(0), SA, I->getName());
1392 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1393 return UpdateValueUsesWith(I, NewVal);
1394 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1395 RHSKnownOne |= HighBits;
1396 }
1397 }
1398 break;
1399 }
1400
1401 // If the client is only demanding bits that we know, return the known
1402 // constant.
1403 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1404 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1405 return false;
1406}
1407
Chris Lattner867b99f2006-10-05 06:55:50 +00001408
1409/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1410/// 64 or fewer elements. DemandedElts contains the set of elements that are
1411/// actually used by the caller. This method analyzes which elements of the
1412/// operand are undef and returns that information in UndefElts.
1413///
1414/// If the information about demanded elements can be used to simplify the
1415/// operation, the operation is simplified, then the resultant value is
1416/// returned. This returns null if no change was made.
1417Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1418 uint64_t &UndefElts,
1419 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001420 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001421 assert(VWidth <= 64 && "Vector too wide to analyze!");
1422 uint64_t EltMask = ~0ULL >> (64-VWidth);
1423 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1424 "Invalid DemandedElts!");
1425
1426 if (isa<UndefValue>(V)) {
1427 // If the entire vector is undefined, just return this info.
1428 UndefElts = EltMask;
1429 return 0;
1430 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1431 UndefElts = EltMask;
1432 return UndefValue::get(V->getType());
1433 }
1434
1435 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001436 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1437 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001438 Constant *Undef = UndefValue::get(EltTy);
1439
1440 std::vector<Constant*> Elts;
1441 for (unsigned i = 0; i != VWidth; ++i)
1442 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1443 Elts.push_back(Undef);
1444 UndefElts |= (1ULL << i);
1445 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1446 Elts.push_back(Undef);
1447 UndefElts |= (1ULL << i);
1448 } else { // Otherwise, defined.
1449 Elts.push_back(CP->getOperand(i));
1450 }
1451
1452 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001453 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001454 return NewCP != CP ? NewCP : 0;
1455 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001456 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001457 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001458 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001459 Constant *Zero = Constant::getNullValue(EltTy);
1460 Constant *Undef = UndefValue::get(EltTy);
1461 std::vector<Constant*> Elts;
1462 for (unsigned i = 0; i != VWidth; ++i)
1463 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1464 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001465 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001466 }
1467
1468 if (!V->hasOneUse()) { // Other users may use these bits.
1469 if (Depth != 0) { // Not at the root.
1470 // TODO: Just compute the UndefElts information recursively.
1471 return false;
1472 }
1473 return false;
1474 } else if (Depth == 10) { // Limit search depth.
1475 return false;
1476 }
1477
1478 Instruction *I = dyn_cast<Instruction>(V);
1479 if (!I) return false; // Only analyze instructions.
1480
1481 bool MadeChange = false;
1482 uint64_t UndefElts2;
1483 Value *TmpV;
1484 switch (I->getOpcode()) {
1485 default: break;
1486
1487 case Instruction::InsertElement: {
1488 // If this is a variable index, we don't know which element it overwrites.
1489 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001490 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001491 if (Idx == 0) {
1492 // Note that we can't propagate undef elt info, because we don't know
1493 // which elt is getting updated.
1494 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1495 UndefElts2, Depth+1);
1496 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1497 break;
1498 }
1499
1500 // If this is inserting an element that isn't demanded, remove this
1501 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001502 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001503 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1504 return AddSoonDeadInstToWorklist(*I, 0);
1505
1506 // Otherwise, the element inserted overwrites whatever was there, so the
1507 // input demanded set is simpler than the output set.
1508 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1509 DemandedElts & ~(1ULL << IdxNo),
1510 UndefElts, Depth+1);
1511 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1512
1513 // The inserted element is defined.
1514 UndefElts |= 1ULL << IdxNo;
1515 break;
1516 }
Chris Lattner69878332007-04-14 22:29:23 +00001517 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001518 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001519 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1520 if (!VTy) break;
1521 unsigned InVWidth = VTy->getNumElements();
1522 uint64_t InputDemandedElts = 0;
1523 unsigned Ratio;
1524
1525 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001526 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001527 // elements as are demanded of us.
1528 Ratio = 1;
1529 InputDemandedElts = DemandedElts;
1530 } else if (VWidth > InVWidth) {
1531 // Untested so far.
1532 break;
1533
1534 // If there are more elements in the result than there are in the source,
1535 // then an input element is live if any of the corresponding output
1536 // elements are live.
1537 Ratio = VWidth/InVWidth;
1538 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1539 if (DemandedElts & (1ULL << OutIdx))
1540 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1541 }
1542 } else {
1543 // Untested so far.
1544 break;
1545
1546 // If there are more elements in the source than there are in the result,
1547 // then an input element is live if the corresponding output element is
1548 // live.
1549 Ratio = InVWidth/VWidth;
1550 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1551 if (DemandedElts & (1ULL << InIdx/Ratio))
1552 InputDemandedElts |= 1ULL << InIdx;
1553 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001554
Chris Lattner69878332007-04-14 22:29:23 +00001555 // div/rem demand all inputs, because they don't want divide by zero.
1556 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1557 UndefElts2, Depth+1);
1558 if (TmpV) {
1559 I->setOperand(0, TmpV);
1560 MadeChange = true;
1561 }
1562
1563 UndefElts = UndefElts2;
1564 if (VWidth > InVWidth) {
1565 assert(0 && "Unimp");
1566 // If there are more elements in the result than there are in the source,
1567 // then an output element is undef if the corresponding input element is
1568 // undef.
1569 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1570 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1571 UndefElts |= 1ULL << OutIdx;
1572 } else if (VWidth < InVWidth) {
1573 assert(0 && "Unimp");
1574 // If there are more elements in the source than there are in the result,
1575 // then a result element is undef if all of the corresponding input
1576 // elements are undef.
1577 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1578 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1579 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1580 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1581 }
1582 break;
1583 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001584 case Instruction::And:
1585 case Instruction::Or:
1586 case Instruction::Xor:
1587 case Instruction::Add:
1588 case Instruction::Sub:
1589 case Instruction::Mul:
1590 // div/rem demand all inputs, because they don't want divide by zero.
1591 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1592 UndefElts, Depth+1);
1593 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1594 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1595 UndefElts2, Depth+1);
1596 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1597
1598 // Output elements are undefined if both are undefined. Consider things
1599 // like undef&0. The result is known zero, not undef.
1600 UndefElts &= UndefElts2;
1601 break;
1602
1603 case Instruction::Call: {
1604 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1605 if (!II) break;
1606 switch (II->getIntrinsicID()) {
1607 default: break;
1608
1609 // Binary vector operations that work column-wise. A dest element is a
1610 // function of the corresponding input elements from the two inputs.
1611 case Intrinsic::x86_sse_sub_ss:
1612 case Intrinsic::x86_sse_mul_ss:
1613 case Intrinsic::x86_sse_min_ss:
1614 case Intrinsic::x86_sse_max_ss:
1615 case Intrinsic::x86_sse2_sub_sd:
1616 case Intrinsic::x86_sse2_mul_sd:
1617 case Intrinsic::x86_sse2_min_sd:
1618 case Intrinsic::x86_sse2_max_sd:
1619 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1620 UndefElts, Depth+1);
1621 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1622 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1623 UndefElts2, Depth+1);
1624 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1625
1626 // If only the low elt is demanded and this is a scalarizable intrinsic,
1627 // scalarize it now.
1628 if (DemandedElts == 1) {
1629 switch (II->getIntrinsicID()) {
1630 default: break;
1631 case Intrinsic::x86_sse_sub_ss:
1632 case Intrinsic::x86_sse_mul_ss:
1633 case Intrinsic::x86_sse2_sub_sd:
1634 case Intrinsic::x86_sse2_mul_sd:
1635 // TODO: Lower MIN/MAX/ABS/etc
1636 Value *LHS = II->getOperand(1);
1637 Value *RHS = II->getOperand(2);
1638 // Extract the element as scalars.
1639 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1640 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1641
1642 switch (II->getIntrinsicID()) {
1643 default: assert(0 && "Case stmts out of sync!");
1644 case Intrinsic::x86_sse_sub_ss:
1645 case Intrinsic::x86_sse2_sub_sd:
1646 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1647 II->getName()), *II);
1648 break;
1649 case Intrinsic::x86_sse_mul_ss:
1650 case Intrinsic::x86_sse2_mul_sd:
1651 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1652 II->getName()), *II);
1653 break;
1654 }
1655
1656 Instruction *New =
1657 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1658 II->getName());
1659 InsertNewInstBefore(New, *II);
1660 AddSoonDeadInstToWorklist(*II, 0);
1661 return New;
1662 }
1663 }
1664
1665 // Output elements are undefined if both are undefined. Consider things
1666 // like undef&0. The result is known zero, not undef.
1667 UndefElts &= UndefElts2;
1668 break;
1669 }
1670 break;
1671 }
1672 }
1673 return MadeChange ? I : 0;
1674}
1675
Nick Lewycky455e1762007-09-06 02:40:25 +00001676/// @returns true if the specified compare predicate is
Reid Spencere4d87aa2006-12-23 06:05:41 +00001677/// true when both operands are equal...
Nick Lewycky455e1762007-09-06 02:40:25 +00001678/// @brief Determine if the icmp Predicate is true when both operands are equal
1679static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001680 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1681 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1682 pred == ICmpInst::ICMP_SLE;
1683}
1684
Nick Lewycky455e1762007-09-06 02:40:25 +00001685/// @returns true if the specified compare instruction is
1686/// true when both operands are equal...
1687/// @brief Determine if the ICmpInst returns true when both operands are equal
1688static bool isTrueWhenEqual(ICmpInst &ICI) {
1689 return isTrueWhenEqual(ICI.getPredicate());
1690}
1691
Chris Lattner564a7272003-08-13 19:01:45 +00001692/// AssociativeOpt - Perform an optimization on an associative operator. This
1693/// function is designed to check a chain of associative operators for a
1694/// potential to apply a certain optimization. Since the optimization may be
1695/// applicable if the expression was reassociated, this checks the chain, then
1696/// reassociates the expression as necessary to expose the optimization
1697/// opportunity. This makes use of a special Functor, which must define
1698/// 'shouldApply' and 'apply' methods.
1699///
1700template<typename Functor>
1701Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1702 unsigned Opcode = Root.getOpcode();
1703 Value *LHS = Root.getOperand(0);
1704
1705 // Quick check, see if the immediate LHS matches...
1706 if (F.shouldApply(LHS))
1707 return F.apply(Root);
1708
1709 // Otherwise, if the LHS is not of the same opcode as the root, return.
1710 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001711 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001712 // Should we apply this transform to the RHS?
1713 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1714
1715 // If not to the RHS, check to see if we should apply to the LHS...
1716 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1717 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1718 ShouldApply = true;
1719 }
1720
1721 // If the functor wants to apply the optimization to the RHS of LHSI,
1722 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1723 if (ShouldApply) {
1724 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001725
Chris Lattner564a7272003-08-13 19:01:45 +00001726 // Now all of the instructions are in the current basic block, go ahead
1727 // and perform the reassociation.
1728 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1729
1730 // First move the selected RHS to the LHS of the root...
1731 Root.setOperand(0, LHSI->getOperand(1));
1732
1733 // Make what used to be the LHS of the root be the user of the root...
1734 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001735 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001736 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1737 return 0;
1738 }
Chris Lattner65725312004-04-16 18:08:07 +00001739 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001740 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001741 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1742 BasicBlock::iterator ARI = &Root; ++ARI;
1743 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1744 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001745
1746 // Now propagate the ExtraOperand down the chain of instructions until we
1747 // get to LHSI.
1748 while (TmpLHSI != LHSI) {
1749 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001750 // Move the instruction to immediately before the chain we are
1751 // constructing to avoid breaking dominance properties.
1752 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1753 BB->getInstList().insert(ARI, NextLHSI);
1754 ARI = NextLHSI;
1755
Chris Lattner564a7272003-08-13 19:01:45 +00001756 Value *NextOp = NextLHSI->getOperand(1);
1757 NextLHSI->setOperand(1, ExtraOperand);
1758 TmpLHSI = NextLHSI;
1759 ExtraOperand = NextOp;
1760 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001761
Chris Lattner564a7272003-08-13 19:01:45 +00001762 // Now that the instructions are reassociated, have the functor perform
1763 // the transformation...
1764 return F.apply(Root);
1765 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001766
Chris Lattner564a7272003-08-13 19:01:45 +00001767 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1768 }
1769 return 0;
1770}
1771
1772
1773// AddRHS - Implements: X + X --> X << 1
1774struct AddRHS {
1775 Value *RHS;
1776 AddRHS(Value *rhs) : RHS(rhs) {}
1777 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1778 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00001779 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00001780 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001781 }
1782};
1783
1784// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1785// iff C1&C2 == 0
1786struct AddMaskingAnd {
1787 Constant *C2;
1788 AddMaskingAnd(Constant *c) : C2(c) {}
1789 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001790 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001791 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001792 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001793 }
1794 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001795 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001796 }
1797};
1798
Chris Lattner6e7ba452005-01-01 16:22:27 +00001799static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001800 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001801 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001802 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001803 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001804
Reid Spencer3da59db2006-11-27 01:05:10 +00001805 return IC->InsertNewInstBefore(CastInst::create(
1806 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001807 }
1808
Chris Lattner2eefe512004-04-09 19:05:30 +00001809 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001810 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1811 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001812
Chris Lattner2eefe512004-04-09 19:05:30 +00001813 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1814 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001815 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1816 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001817 }
1818
1819 Value *Op0 = SO, *Op1 = ConstOperand;
1820 if (!ConstIsRHS)
1821 std::swap(Op0, Op1);
1822 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001823 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1824 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001825 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1826 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1827 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001828 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001829 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001830 abort();
1831 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001832 return IC->InsertNewInstBefore(New, I);
1833}
1834
1835// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1836// constant as the other operand, try to fold the binary operator into the
1837// select arguments. This also works for Cast instructions, which obviously do
1838// not have a second operand.
1839static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1840 InstCombiner *IC) {
1841 // Don't modify shared select instructions
1842 if (!SI->hasOneUse()) return 0;
1843 Value *TV = SI->getOperand(1);
1844 Value *FV = SI->getOperand(2);
1845
1846 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001847 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001848 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001849
Chris Lattner6e7ba452005-01-01 16:22:27 +00001850 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1851 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1852
1853 return new SelectInst(SI->getCondition(), SelectTrueVal,
1854 SelectFalseVal);
1855 }
1856 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001857}
1858
Chris Lattner4e998b22004-09-29 05:07:12 +00001859
1860/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1861/// node as operand #0, see if we can fold the instruction into the PHI (which
1862/// is only possible if all operands to the PHI are constants).
1863Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1864 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001865 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001866 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001867
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001868 // Check to see if all of the operands of the PHI are constants. If there is
1869 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001870 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001871 BasicBlock *NonConstBB = 0;
1872 for (unsigned i = 0; i != NumPHIValues; ++i)
1873 if (!isa<Constant>(PN->getIncomingValue(i))) {
1874 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001875 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001876 NonConstBB = PN->getIncomingBlock(i);
1877
1878 // If the incoming non-constant value is in I's block, we have an infinite
1879 // loop.
1880 if (NonConstBB == I.getParent())
1881 return 0;
1882 }
1883
1884 // If there is exactly one non-constant value, we can insert a copy of the
1885 // operation in that block. However, if this is a critical edge, we would be
1886 // inserting the computation one some other paths (e.g. inside a loop). Only
1887 // do this if the pred block is unconditionally branching into the phi block.
1888 if (NonConstBB) {
1889 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1890 if (!BI || !BI->isUnconditional()) return 0;
1891 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001892
1893 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6934a042007-02-11 01:23:03 +00001894 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001895 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001896 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001897 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001898
1899 // Next, add all of the operands to the PHI.
1900 if (I.getNumOperands() == 2) {
1901 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001902 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001903 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001904 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001905 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1906 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1907 else
1908 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001909 } else {
1910 assert(PN->getIncomingBlock(i) == NonConstBB);
1911 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1912 InV = BinaryOperator::create(BO->getOpcode(),
1913 PN->getIncomingValue(i), C, "phitmp",
1914 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001915 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1916 InV = CmpInst::create(CI->getOpcode(),
1917 CI->getPredicate(),
1918 PN->getIncomingValue(i), C, "phitmp",
1919 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001920 else
1921 assert(0 && "Unknown binop!");
1922
Chris Lattnerdbab3862007-03-02 21:28:56 +00001923 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001924 }
1925 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001926 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001927 } else {
1928 CastInst *CI = cast<CastInst>(&I);
1929 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001930 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001931 Value *InV;
1932 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001933 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001934 } else {
1935 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00001936 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1937 I.getType(), "phitmp",
1938 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001939 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001940 }
1941 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001942 }
1943 }
1944 return ReplaceInstUsesWith(I, NewPN);
1945}
1946
Chris Lattner2454a2e2008-01-29 06:52:45 +00001947
1948/// CannotBeNegativeZero - Return true if we can prove that the specified FP
1949/// value is never equal to -0.0.
1950///
1951/// Note that this function will need to be revisited when we support nondefault
1952/// rounding modes!
1953///
1954static bool CannotBeNegativeZero(const Value *V) {
1955 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1956 return !CFP->getValueAPF().isNegZero();
1957
1958 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
1959 if (const Instruction *I = dyn_cast<Instruction>(V)) {
1960 if (I->getOpcode() == Instruction::Add &&
1961 isa<ConstantFP>(I->getOperand(1)) &&
1962 cast<ConstantFP>(I->getOperand(1))->isNullValue())
1963 return true;
1964
1965 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1966 if (II->getIntrinsicID() == Intrinsic::sqrt)
1967 return CannotBeNegativeZero(II->getOperand(1));
1968
1969 if (const CallInst *CI = dyn_cast<CallInst>(I))
1970 if (const Function *F = CI->getCalledFunction()) {
1971 if (F->isDeclaration()) {
1972 switch (F->getNameLen()) {
1973 case 3: // abs(x) != -0.0
1974 if (!strcmp(F->getNameStart(), "abs")) return true;
1975 break;
1976 case 4: // abs[lf](x) != -0.0
1977 if (!strcmp(F->getNameStart(), "absf")) return true;
1978 if (!strcmp(F->getNameStart(), "absl")) return true;
1979 break;
1980 }
1981 }
1982 }
1983 }
1984
1985 return false;
1986}
1987
1988
Chris Lattner7e708292002-06-25 16:13:24 +00001989Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001990 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001991 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001992
Chris Lattner66331a42004-04-10 22:01:55 +00001993 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001994 // X + undef -> undef
1995 if (isa<UndefValue>(RHS))
1996 return ReplaceInstUsesWith(I, RHS);
1997
Chris Lattner66331a42004-04-10 22:01:55 +00001998 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00001999 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002000 if (RHSC->isNullValue())
2001 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002002 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002003 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2004 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002005 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002006 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002007
Chris Lattner66331a42004-04-10 22:01:55 +00002008 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002009 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002010 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002011 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002012 if (Val == APInt::getSignBit(BitWidth))
Chris Lattner48595f12004-06-10 02:07:29 +00002013 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002014
2015 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2016 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002017 if (!isa<VectorType>(I.getType())) {
2018 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2019 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2020 KnownZero, KnownOne))
2021 return &I;
2022 }
Chris Lattner66331a42004-04-10 22:01:55 +00002023 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002024
2025 if (isa<PHINode>(LHS))
2026 if (Instruction *NV = FoldOpIntoPhi(I))
2027 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002028
Chris Lattner4f637d42006-01-06 17:59:59 +00002029 ConstantInt *XorRHS = 0;
2030 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002031 if (isa<ConstantInt>(RHSC) &&
2032 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002033 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002034 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002035
Zhou Sheng4351c642007-04-02 08:20:41 +00002036 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002037 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2038 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002039 do {
2040 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002041 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2042 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002043 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2044 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002045 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002046 if (!MaskedValueIsZero(XorLHS,
2047 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002048 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002049 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002050 }
2051 }
2052 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002053 C0080Val = APIntOps::lshr(C0080Val, Size);
2054 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2055 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002056
Reid Spencer35c38852007-03-28 01:36:16 +00002057 // FIXME: This shouldn't be necessary. When the backends can handle types
2058 // with funny bit widths then this whole cascade of if statements should
2059 // be removed. It is just here to get the size of the "middle" type back
2060 // up to something that the back ends can handle.
2061 const Type *MiddleType = 0;
2062 switch (Size) {
2063 default: break;
2064 case 32: MiddleType = Type::Int32Ty; break;
2065 case 16: MiddleType = Type::Int16Ty; break;
2066 case 8: MiddleType = Type::Int8Ty; break;
2067 }
2068 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002069 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002070 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002071 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002072 }
2073 }
Chris Lattner66331a42004-04-10 22:01:55 +00002074 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002075
Chris Lattner564a7272003-08-13 19:01:45 +00002076 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002077 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002078 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002079
2080 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2081 if (RHSI->getOpcode() == Instruction::Sub)
2082 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2083 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2084 }
2085 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2086 if (LHSI->getOpcode() == Instruction::Sub)
2087 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2088 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2089 }
Robert Bocchino71698282004-07-27 21:02:21 +00002090 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002091
Chris Lattner5c4afb92002-05-08 22:46:53 +00002092 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002093 // -A + -B --> -(A + B)
2094 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002095 if (LHS->getType()->isIntOrIntVector()) {
2096 if (Value *RHSV = dyn_castNegVal(RHS)) {
2097 Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2098 InsertNewInstBefore(NewAdd, I);
2099 return BinaryOperator::createNeg(NewAdd);
2100 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002101 }
2102
2103 return BinaryOperator::createSub(RHS, LHSV);
2104 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002105
2106 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002107 if (!isa<Constant>(RHS))
2108 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002109 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002110
Misha Brukmanfd939082005-04-21 23:48:37 +00002111
Chris Lattner50af16a2004-11-13 19:50:12 +00002112 ConstantInt *C2;
2113 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2114 if (X == RHS) // X*C + X --> X * (C+1)
2115 return BinaryOperator::createMul(RHS, AddOne(C2));
2116
2117 // X*C1 + X*C2 --> X * (C1+C2)
2118 ConstantInt *C1;
2119 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002120 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002121 }
2122
2123 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002124 if (dyn_castFoldableMul(RHS, C2) == LHS)
2125 return BinaryOperator::createMul(LHS, AddOne(C2));
2126
Chris Lattnere617c9e2007-01-05 02:17:46 +00002127 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002128 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2129 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002130
Chris Lattnerad3448c2003-02-18 19:57:07 +00002131
Chris Lattner564a7272003-08-13 19:01:45 +00002132 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002133 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002134 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2135 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002136
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002137 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002138 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002139 Value *W, *X, *Y, *Z;
2140 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2141 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2142 if (W != Y) {
2143 if (W == Z) {
2144 std::swap(Y, Z);
2145 } else if (Y == X) {
2146 std::swap(W, X);
2147 } else if (X == Z) {
2148 std::swap(Y, Z);
2149 std::swap(W, X);
2150 }
2151 }
2152
2153 if (W == Y) {
2154 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2155 LHS->getName()), I);
2156 return BinaryOperator::createMul(W, NewAdd);
2157 }
2158 }
2159 }
2160
Chris Lattner6b032052003-10-02 15:11:26 +00002161 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002162 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002163 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2164 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002165
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002166 // (X & FF00) + xx00 -> (X+xx00) & FF00
2167 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002168 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002169 if (Anded == CRHS) {
2170 // See if all bits from the first bit set in the Add RHS up are included
2171 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002172 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002173
2174 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002175 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002176
2177 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002178 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002179
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002180 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2181 // Okay, the xform is safe. Insert the new add pronto.
2182 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2183 LHS->getName()), I);
2184 return BinaryOperator::createAnd(NewAdd, C2);
2185 }
2186 }
2187 }
2188
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002189 // Try to fold constant add into select arguments.
2190 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002191 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002192 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002193 }
2194
Reid Spencer1628cec2006-10-26 06:15:43 +00002195 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002196 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002197 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002198 CastInst *CI = dyn_cast<CastInst>(LHS);
2199 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002200 if (!CI) {
2201 CI = dyn_cast<CastInst>(RHS);
2202 Other = LHS;
2203 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002204 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002205 (CI->getType()->getPrimitiveSizeInBits() ==
2206 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002207 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002208 unsigned AS =
2209 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002210 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2211 PointerType::get(Type::Int8Ty, AS), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00002212 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002213 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002214 }
2215 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002216
Chris Lattner42790482007-12-20 01:56:58 +00002217 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002218 {
2219 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2220 Value *Other = RHS;
2221 if (!SI) {
2222 SI = dyn_cast<SelectInst>(RHS);
2223 Other = LHS;
2224 }
Chris Lattner42790482007-12-20 01:56:58 +00002225 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002226 Value *TV = SI->getTrueValue();
2227 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002228 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002229
2230 // Can we fold the add into the argument of the select?
2231 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002232 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2233 A == Other) // Fold the add into the true select value.
2234 return new SelectInst(SI->getCondition(), N, A);
2235 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2236 A == Other) // Fold the add into the false select value.
2237 return new SelectInst(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002238 }
2239 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002240
2241 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2242 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2243 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2244 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002245
Chris Lattner7e708292002-06-25 16:13:24 +00002246 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002247}
2248
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002249// isSignBit - Return true if the value represented by the constant only has the
2250// highest order bit set.
2251static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002252 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002253 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002254}
2255
Chris Lattner7e708292002-06-25 16:13:24 +00002256Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002257 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002258
Chris Lattner233f7dc2002-08-12 21:17:25 +00002259 if (Op0 == Op1) // sub X, X -> 0
2260 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002261
Chris Lattner233f7dc2002-08-12 21:17:25 +00002262 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002263 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002264 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002265
Chris Lattnere87597f2004-10-16 18:11:37 +00002266 if (isa<UndefValue>(Op0))
2267 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2268 if (isa<UndefValue>(Op1))
2269 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2270
Chris Lattnerd65460f2003-11-05 01:06:05 +00002271 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2272 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002273 if (C->isAllOnesValue())
2274 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002275
Chris Lattnerd65460f2003-11-05 01:06:05 +00002276 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002277 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002278 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002279 return BinaryOperator::createAdd(X, AddOne(C));
2280
Chris Lattner76b7a062007-01-15 07:02:54 +00002281 // -(X >>u 31) -> (X >>s 31)
2282 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002283 if (C->isZero()) {
Reid Spencer832254e2007-02-02 02:16:23 +00002284 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
Reid Spencer3822ff52006-11-08 06:47:33 +00002285 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002286 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002287 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002288 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002289 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002290 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002291 return BinaryOperator::create(Instruction::AShr,
2292 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002293 }
2294 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002295 }
2296 else if (SI->getOpcode() == Instruction::AShr) {
2297 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2298 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002299 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002300 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002301 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002302 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002303 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002304 }
2305 }
2306 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002307 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002308
2309 // Try to fold constant sub into select arguments.
2310 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002311 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002312 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002313
2314 if (isa<PHINode>(Op0))
2315 if (Instruction *NV = FoldOpIntoPhi(I))
2316 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002317 }
2318
Chris Lattner43d84d62005-04-07 16:15:25 +00002319 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2320 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002321 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002322 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002323 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002324 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002325 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002326 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2327 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2328 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002329 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002330 Op1I->getOperand(0));
2331 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002332 }
2333
Chris Lattnerfd059242003-10-15 16:48:29 +00002334 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002335 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2336 // is not used by anyone else...
2337 //
Chris Lattner0517e722004-02-02 20:09:56 +00002338 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002339 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002340 // Swap the two operands of the subexpr...
2341 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2342 Op1I->setOperand(0, IIOp1);
2343 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002344
Chris Lattnera2881962003-02-18 19:28:33 +00002345 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002346 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002347 }
2348
2349 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2350 //
2351 if (Op1I->getOpcode() == Instruction::And &&
2352 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2353 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2354
Chris Lattnerf523d062004-06-09 05:08:07 +00002355 Value *NewNot =
2356 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002357 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002358 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002359
Reid Spencerac5209e2006-10-16 23:08:08 +00002360 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002361 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002362 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002363 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002364 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002365 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002366 ConstantExpr::getNeg(DivRHS));
2367
Chris Lattnerad3448c2003-02-18 19:57:07 +00002368 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002369 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002370 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002371 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002372 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002373 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002374
2375 // X - ((X / Y) * Y) --> X % Y
2376 if (Op1I->getOpcode() == Instruction::Mul)
2377 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2378 if (Op0 == I->getOperand(0) &&
2379 Op1I->getOperand(1) == I->getOperand(1)) {
2380 if (I->getOpcode() == Instruction::SDiv)
2381 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2382 if (I->getOpcode() == Instruction::UDiv)
2383 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2384 }
Chris Lattner40371712002-05-09 01:29:19 +00002385 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002386 }
Chris Lattnera2881962003-02-18 19:28:33 +00002387
Chris Lattner9919e3d2006-12-02 00:13:08 +00002388 if (!Op0->getType()->isFPOrFPVector())
Chris Lattner7edc8c22005-04-07 17:14:51 +00002389 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2390 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002391 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2392 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2393 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2394 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002395 } else if (Op0I->getOpcode() == Instruction::Sub) {
2396 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2397 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002398 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002399
Chris Lattner50af16a2004-11-13 19:50:12 +00002400 ConstantInt *C1;
2401 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002402 if (X == Op1) // X*C - X --> X * (C-1)
2403 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002404
Chris Lattner50af16a2004-11-13 19:50:12 +00002405 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2406 if (X == dyn_castFoldableMul(Op1, C2))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002407 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002408 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002409 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002410}
2411
Chris Lattnera0141b92007-07-15 20:42:37 +00002412/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2413/// comparison only checks the sign bit. If it only checks the sign bit, set
2414/// TrueIfSigned if the result of the comparison is true when the input value is
2415/// signed.
2416static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2417 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002418 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002419 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2420 TrueIfSigned = true;
2421 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002422 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2423 TrueIfSigned = true;
2424 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002425 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2426 TrueIfSigned = false;
2427 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002428 case ICmpInst::ICMP_UGT:
2429 // True if LHS u> RHS and RHS == high-bit-mask - 1
2430 TrueIfSigned = true;
2431 return RHS->getValue() ==
2432 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2433 case ICmpInst::ICMP_UGE:
2434 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2435 TrueIfSigned = true;
2436 return RHS->getValue() ==
2437 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002438 default:
2439 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002440 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002441}
2442
Chris Lattner7e708292002-06-25 16:13:24 +00002443Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002444 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002445 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002446
Chris Lattnere87597f2004-10-16 18:11:37 +00002447 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2448 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2449
Chris Lattner233f7dc2002-08-12 21:17:25 +00002450 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002451 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2452 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002453
2454 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002455 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002456 if (SI->getOpcode() == Instruction::Shl)
2457 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002458 return BinaryOperator::createMul(SI->getOperand(0),
2459 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002460
Zhou Sheng843f07672007-04-19 05:39:12 +00002461 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002462 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2463 if (CI->equalsInt(1)) // X * 1 == X
2464 return ReplaceInstUsesWith(I, Op0);
2465 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002466 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002467
Zhou Sheng97b52c22007-03-29 01:57:21 +00002468 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002469 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002470 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002471 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002472 }
Robert Bocchino71698282004-07-27 21:02:21 +00002473 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002474 if (Op1F->isNullValue())
2475 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002476
Chris Lattnera2881962003-02-18 19:28:33 +00002477 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2478 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002479 // We need a better interface for long double here.
2480 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2481 if (Op1F->isExactlyValue(1.0))
2482 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002483 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002484
2485 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2486 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2487 isa<ConstantInt>(Op0I->getOperand(1))) {
2488 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2489 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2490 Op1, "tmp");
2491 InsertNewInstBefore(Add, I);
2492 Value *C1C2 = ConstantExpr::getMul(Op1,
2493 cast<Constant>(Op0I->getOperand(1)));
2494 return BinaryOperator::createAdd(Add, C1C2);
2495
2496 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002497
2498 // Try to fold constant mul into select arguments.
2499 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002500 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002501 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002502
2503 if (isa<PHINode>(Op0))
2504 if (Instruction *NV = FoldOpIntoPhi(I))
2505 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002506 }
2507
Chris Lattnera4f445b2003-03-10 23:23:04 +00002508 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2509 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002510 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002511
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002512 // If one of the operands of the multiply is a cast from a boolean value, then
2513 // we know the bool is either zero or one, so this is a 'masking' multiply.
2514 // See if we can simplify things based on how the boolean was originally
2515 // formed.
2516 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002517 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002518 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002519 BoolCast = CI;
2520 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002521 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002522 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002523 BoolCast = CI;
2524 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002525 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002526 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2527 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002528 bool TIS = false;
2529
Reid Spencere4d87aa2006-12-23 06:05:41 +00002530 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002531 // multiply into a shift/and combination.
2532 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002533 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2534 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002535 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002536 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002537 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002538 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002539 InsertNewInstBefore(
2540 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002541 BoolCast->getOperand(0)->getName()+
2542 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002543
2544 // If the multiply type is not the same as the source type, sign extend
2545 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002546 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002547 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2548 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002549 Instruction::CastOps opcode =
2550 (SrcBits == DstBits ? Instruction::BitCast :
2551 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2552 V = InsertCastBefore(opcode, V, I.getType(), I);
2553 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002554
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002555 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002556 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002557 }
2558 }
2559 }
2560
Chris Lattner7e708292002-06-25 16:13:24 +00002561 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002562}
2563
Reid Spencer1628cec2006-10-26 06:15:43 +00002564/// This function implements the transforms on div instructions that work
2565/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2566/// used by the visitors to those instructions.
2567/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002568Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002569 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002570
Reid Spencer1628cec2006-10-26 06:15:43 +00002571 // undef / X -> 0
2572 if (isa<UndefValue>(Op0))
Chris Lattner857e8cd2004-12-12 21:48:58 +00002573 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002574
2575 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002576 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002577 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002578
Chris Lattner25feae52008-01-28 00:58:18 +00002579 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2580 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002581 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002582 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2583 // the same basic block, then we replace the select with Y, and the
2584 // condition of the select with false (if the cond value is in the same BB).
2585 // If the select has uses other than the div, this allows them to be
2586 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2587 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002588 if (ST->isNullValue()) {
2589 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2590 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002591 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002592 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2593 I.setOperand(1, SI->getOperand(2));
2594 else
2595 UpdateValueUsesWith(SI, SI->getOperand(2));
2596 return &I;
2597 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002598
Chris Lattner25feae52008-01-28 00:58:18 +00002599 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2600 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002601 if (ST->isNullValue()) {
2602 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2603 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002604 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002605 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2606 I.setOperand(1, SI->getOperand(1));
2607 else
2608 UpdateValueUsesWith(SI, SI->getOperand(1));
2609 return &I;
2610 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002611 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002612
Reid Spencer1628cec2006-10-26 06:15:43 +00002613 return 0;
2614}
Misha Brukmanfd939082005-04-21 23:48:37 +00002615
Reid Spencer1628cec2006-10-26 06:15:43 +00002616/// This function implements the transforms common to both integer division
2617/// instructions (udiv and sdiv). It is called by the visitors to those integer
2618/// division instructions.
2619/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002620Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002621 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2622
2623 if (Instruction *Common = commonDivTransforms(I))
2624 return Common;
2625
2626 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2627 // div X, 1 == X
2628 if (RHS->equalsInt(1))
2629 return ReplaceInstUsesWith(I, Op0);
2630
2631 // (X / C1) / C2 -> X / (C1*C2)
2632 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2633 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2634 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2635 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
Reid Spencer7177c3a2007-03-25 05:33:51 +00002636 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002637 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002638
Reid Spencerbca0e382007-03-23 20:05:17 +00002639 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002640 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2641 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2642 return R;
2643 if (isa<PHINode>(Op0))
2644 if (Instruction *NV = FoldOpIntoPhi(I))
2645 return NV;
2646 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002647 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002648
Chris Lattnera2881962003-02-18 19:28:33 +00002649 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002650 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002651 if (LHS->equalsInt(0))
2652 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2653
Reid Spencer1628cec2006-10-26 06:15:43 +00002654 return 0;
2655}
2656
2657Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2658 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2659
2660 // Handle the integer div common cases
2661 if (Instruction *Common = commonIDivTransforms(I))
2662 return Common;
2663
2664 // X udiv C^2 -> X >> C
2665 // Check to see if this is an unsigned division with an exact power of 2,
2666 // if so, convert to a right shift.
2667 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002668 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00002669 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002670 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002671 }
2672
2673 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002674 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002675 if (RHSI->getOpcode() == Instruction::Shl &&
2676 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002677 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002678 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002679 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002680 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002681 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002682 Constant *C2V = ConstantInt::get(NTy, C2);
2683 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002684 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00002685 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002686 }
2687 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002688 }
2689
Reid Spencer1628cec2006-10-26 06:15:43 +00002690 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2691 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002692 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002693 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002694 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002695 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002696 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002697 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002698 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002699 // Construct the "on true" case of the select
2700 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2701 Instruction *TSI = BinaryOperator::createLShr(
2702 Op0, TC, SI->getName()+".t");
2703 TSI = InsertNewInstBefore(TSI, I);
2704
2705 // Construct the "on false" case of the select
2706 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2707 Instruction *FSI = BinaryOperator::createLShr(
2708 Op0, FC, SI->getName()+".f");
2709 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002710
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002711 // construct the select instruction and return it.
2712 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002713 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002714 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002715 return 0;
2716}
2717
Reid Spencer1628cec2006-10-26 06:15:43 +00002718Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2719 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2720
2721 // Handle the integer div common cases
2722 if (Instruction *Common = commonIDivTransforms(I))
2723 return Common;
2724
2725 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2726 // sdiv X, -1 == -X
2727 if (RHS->isAllOnesValue())
2728 return BinaryOperator::createNeg(Op0);
2729
2730 // -X/C -> X/-C
2731 if (Value *LHSNeg = dyn_castNegVal(Op0))
2732 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2733 }
2734
2735 // If the sign bits of both operands are zero (i.e. we can prove they are
2736 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002737 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002738 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002739 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002740 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Reid Spencer1628cec2006-10-26 06:15:43 +00002741 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2742 }
2743 }
2744
2745 return 0;
2746}
2747
2748Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2749 return commonDivTransforms(I);
2750}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002751
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002752/// GetFactor - If we can prove that the specified value is at least a multiple
2753/// of some factor, return that factor.
2754static Constant *GetFactor(Value *V) {
2755 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2756 return CI;
2757
2758 // Unless we can be tricky, we know this is a multiple of 1.
2759 Constant *Result = ConstantInt::get(V->getType(), 1);
2760
2761 Instruction *I = dyn_cast<Instruction>(V);
2762 if (!I) return Result;
2763
2764 if (I->getOpcode() == Instruction::Mul) {
2765 // Handle multiplies by a constant, etc.
2766 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2767 GetFactor(I->getOperand(1)));
2768 } else if (I->getOpcode() == Instruction::Shl) {
2769 // (X<<C) -> X * (1 << C)
2770 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2771 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2772 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2773 }
2774 } else if (I->getOpcode() == Instruction::And) {
2775 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2776 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencerf2442522007-03-24 00:42:08 +00002777 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattner148083a2007-11-23 22:35:18 +00002778 if (Zeros != V->getType()->getPrimitiveSizeInBits())// don't shift by "32"
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002779 return ConstantExpr::getShl(Result,
Reid Spencer832254e2007-02-02 02:16:23 +00002780 ConstantInt::get(Result->getType(), Zeros));
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002781 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002782 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002783 // Only handle int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00002784 if (!CI->isIntegerCast())
2785 return Result;
2786 Value *Op = CI->getOperand(0);
2787 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002788 }
2789 return Result;
2790}
2791
Reid Spencer0a783f72006-11-02 01:53:59 +00002792/// This function implements the transforms on rem instructions that work
2793/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2794/// is used by the visitors to those instructions.
2795/// @brief Transforms common to all three rem instructions
2796Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002797 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002798
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002799 // 0 % X == 0, we don't need to preserve faults!
2800 if (Constant *LHS = dyn_cast<Constant>(Op0))
2801 if (LHS->isNullValue())
2802 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2803
2804 if (isa<UndefValue>(Op0)) // undef % X -> 0
2805 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2806 if (isa<UndefValue>(Op1))
2807 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002808
2809 // Handle cases involving: rem X, (select Cond, Y, Z)
2810 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2811 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2812 // the same basic block, then we replace the select with Y, and the
2813 // condition of the select with false (if the cond value is in the same
2814 // BB). If the select has uses other than the div, this allows them to be
2815 // simplified also.
2816 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2817 if (ST->isNullValue()) {
2818 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2819 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002820 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002821 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2822 I.setOperand(1, SI->getOperand(2));
2823 else
2824 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002825 return &I;
2826 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002827 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2828 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2829 if (ST->isNullValue()) {
2830 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2831 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002832 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002833 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2834 I.setOperand(1, SI->getOperand(1));
2835 else
2836 UpdateValueUsesWith(SI, SI->getOperand(1));
2837 return &I;
2838 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002839 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002840
Reid Spencer0a783f72006-11-02 01:53:59 +00002841 return 0;
2842}
2843
2844/// This function implements the transforms common to both integer remainder
2845/// instructions (urem and srem). It is called by the visitors to those integer
2846/// remainder instructions.
2847/// @brief Common integer remainder transforms
2848Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2849 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2850
2851 if (Instruction *common = commonRemTransforms(I))
2852 return common;
2853
Chris Lattner857e8cd2004-12-12 21:48:58 +00002854 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002855 // X % 0 == undef, we don't need to preserve faults!
2856 if (RHS->equalsInt(0))
2857 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2858
Chris Lattnera2881962003-02-18 19:28:33 +00002859 if (RHS->equalsInt(1)) // X % 1 == 0
2860 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2861
Chris Lattner97943922006-02-28 05:49:21 +00002862 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2863 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2864 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2865 return R;
2866 } else if (isa<PHINode>(Op0I)) {
2867 if (Instruction *NV = FoldOpIntoPhi(I))
2868 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002869 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002870 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2871 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002872 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002873 }
Chris Lattnera2881962003-02-18 19:28:33 +00002874 }
2875
Reid Spencer0a783f72006-11-02 01:53:59 +00002876 return 0;
2877}
2878
2879Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2880 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2881
2882 if (Instruction *common = commonIRemTransforms(I))
2883 return common;
2884
2885 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2886 // X urem C^2 -> X and C
2887 // Check to see if this is an unsigned remainder with an exact power of 2,
2888 // if so, convert to a bitwise and.
2889 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002890 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00002891 return BinaryOperator::createAnd(Op0, SubOne(C));
2892 }
2893
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002894 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002895 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2896 if (RHSI->getOpcode() == Instruction::Shl &&
2897 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002898 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002899 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2900 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2901 "tmp"), I);
2902 return BinaryOperator::createAnd(Op0, Add);
2903 }
2904 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002905 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002906
Reid Spencer0a783f72006-11-02 01:53:59 +00002907 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2908 // where C1&C2 are powers of two.
2909 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2910 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2911 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2912 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002913 if ((STO->getValue().isPowerOf2()) &&
2914 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002915 Value *TrueAnd = InsertNewInstBefore(
2916 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2917 Value *FalseAnd = InsertNewInstBefore(
2918 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2919 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2920 }
2921 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002922 }
2923
Chris Lattner3f5b8772002-05-06 16:14:14 +00002924 return 0;
2925}
2926
Reid Spencer0a783f72006-11-02 01:53:59 +00002927Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2928 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2929
Dan Gohmancff55092007-11-05 23:16:33 +00002930 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00002931 if (Instruction *common = commonIRemTransforms(I))
2932 return common;
2933
2934 if (Value *RHSNeg = dyn_castNegVal(Op1))
2935 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00002936 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002937 // X % -Y -> X % Y
2938 AddUsesToWorkList(I);
2939 I.setOperand(1, RHSNeg);
2940 return &I;
2941 }
2942
Dan Gohmancff55092007-11-05 23:16:33 +00002943 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00002944 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00002945 if (I.getType()->isInteger()) {
2946 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2947 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2948 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2949 return BinaryOperator::createURem(Op0, Op1, I.getName());
2950 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002951 }
2952
2953 return 0;
2954}
2955
2956Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002957 return commonRemTransforms(I);
2958}
2959
Chris Lattner8b170942002-08-09 23:47:40 +00002960// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002961static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002962 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00002963 if (!isSigned)
2964 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2965 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002966}
2967
2968// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002969static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002970 if (!isSigned)
2971 return C->getValue() == 1; // unsigned
2972
2973 // Calculate 1111111111000000000000
2974 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2975 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00002976}
2977
Chris Lattner457dd822004-06-09 07:59:58 +00002978// isOneBitSet - Return true if there is exactly one bit set in the specified
2979// constant.
2980static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00002981 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00002982}
2983
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002984// isHighOnes - Return true if the constant is of the form 1+0+.
2985// This is the same as lowones(~X).
2986static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00002987 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002988}
2989
Reid Spencere4d87aa2006-12-23 06:05:41 +00002990/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002991/// are carefully arranged to allow folding of expressions such as:
2992///
2993/// (A < B) | (A > B) --> (A != B)
2994///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002995/// Note that this is only valid if the first and second predicates have the
2996/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002997///
Reid Spencere4d87aa2006-12-23 06:05:41 +00002998/// Three bits are used to represent the condition, as follows:
2999/// 0 A > B
3000/// 1 A == B
3001/// 2 A < B
3002///
3003/// <=> Value Definition
3004/// 000 0 Always false
3005/// 001 1 A > B
3006/// 010 2 A == B
3007/// 011 3 A >= B
3008/// 100 4 A < B
3009/// 101 5 A != B
3010/// 110 6 A <= B
3011/// 111 7 Always true
3012///
3013static unsigned getICmpCode(const ICmpInst *ICI) {
3014 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003015 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003016 case ICmpInst::ICMP_UGT: return 1; // 001
3017 case ICmpInst::ICMP_SGT: return 1; // 001
3018 case ICmpInst::ICMP_EQ: return 2; // 010
3019 case ICmpInst::ICMP_UGE: return 3; // 011
3020 case ICmpInst::ICMP_SGE: return 3; // 011
3021 case ICmpInst::ICMP_ULT: return 4; // 100
3022 case ICmpInst::ICMP_SLT: return 4; // 100
3023 case ICmpInst::ICMP_NE: return 5; // 101
3024 case ICmpInst::ICMP_ULE: return 6; // 110
3025 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003026 // True -> 7
3027 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003028 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003029 return 0;
3030 }
3031}
3032
Reid Spencere4d87aa2006-12-23 06:05:41 +00003033/// getICmpValue - This is the complement of getICmpCode, which turns an
3034/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003035/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003036/// of predicate to use in new icmp instructions.
3037static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3038 switch (code) {
3039 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003040 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003041 case 1:
3042 if (sign)
3043 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3044 else
3045 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3046 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3047 case 3:
3048 if (sign)
3049 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3050 else
3051 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3052 case 4:
3053 if (sign)
3054 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3055 else
3056 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3057 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3058 case 6:
3059 if (sign)
3060 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3061 else
3062 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003063 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003064 }
3065}
3066
Reid Spencere4d87aa2006-12-23 06:05:41 +00003067static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3068 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3069 (ICmpInst::isSignedPredicate(p1) &&
3070 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3071 (ICmpInst::isSignedPredicate(p2) &&
3072 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3073}
3074
3075namespace {
3076// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3077struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003078 InstCombiner &IC;
3079 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003080 ICmpInst::Predicate pred;
3081 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3082 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3083 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003084 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003085 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3086 if (PredicatesFoldable(pred, ICI->getPredicate()))
3087 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3088 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003089 return false;
3090 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003091 Instruction *apply(Instruction &Log) const {
3092 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3093 if (ICI->getOperand(0) != LHS) {
3094 assert(ICI->getOperand(1) == LHS);
3095 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003096 }
3097
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003098 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003099 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003100 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003101 unsigned Code;
3102 switch (Log.getOpcode()) {
3103 case Instruction::And: Code = LHSCode & RHSCode; break;
3104 case Instruction::Or: Code = LHSCode | RHSCode; break;
3105 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003106 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003107 }
3108
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003109 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3110 ICmpInst::isSignedPredicate(ICI->getPredicate());
3111
3112 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003113 if (Instruction *I = dyn_cast<Instruction>(RV))
3114 return I;
3115 // Otherwise, it's a constant boolean value...
3116 return IC.ReplaceInstUsesWith(Log, RV);
3117 }
3118};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003119} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003120
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003121// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3122// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003123// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003124Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003125 ConstantInt *OpRHS,
3126 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003127 BinaryOperator &TheAnd) {
3128 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003129 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003130 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003131 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003132
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003133 switch (Op->getOpcode()) {
3134 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003135 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003136 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003137 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003138 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003139 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003140 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003141 }
3142 break;
3143 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003144 if (Together == AndRHS) // (X | C) & C --> C
3145 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003146
Chris Lattner6e7ba452005-01-01 16:22:27 +00003147 if (Op->hasOneUse() && Together != OpRHS) {
3148 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003149 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003150 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003151 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003152 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003153 }
3154 break;
3155 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003156 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003157 // Adding a one to a single bit bit-field should be turned into an XOR
3158 // of the bit. First thing to check is to see if this AND is with a
3159 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003160 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003161
3162 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003163 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003164 // Ok, at this point, we know that we are masking the result of the
3165 // ADD down to exactly one bit. If the constant we are adding has
3166 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003167 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003168
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003169 // Check to see if any bits below the one bit set in AndRHSV are set.
3170 if ((AddRHS & (AndRHSV-1)) == 0) {
3171 // If not, the only thing that can effect the output of the AND is
3172 // the bit specified by AndRHSV. If that bit is set, the effect of
3173 // the XOR is to toggle the bit. If it is clear, then the ADD has
3174 // no effect.
3175 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3176 TheAnd.setOperand(0, X);
3177 return &TheAnd;
3178 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003179 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003180 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003181 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003182 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003183 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003184 }
3185 }
3186 }
3187 }
3188 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003189
3190 case Instruction::Shl: {
3191 // We know that the AND will not produce any of the bits shifted in, so if
3192 // the anded constant includes them, clear them now!
3193 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003194 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003195 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003196 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3197 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003198
Zhou Sheng290bec52007-03-29 08:15:12 +00003199 if (CI->getValue() == ShlMask) {
3200 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003201 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3202 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003203 TheAnd.setOperand(1, CI);
3204 return &TheAnd;
3205 }
3206 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003207 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003208 case Instruction::LShr:
3209 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003210 // We know that the AND will not produce any of the bits shifted in, so if
3211 // the anded constant includes them, clear them now! This only applies to
3212 // unsigned shifts, because a signed shr may bring in set bits!
3213 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003214 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003215 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003216 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3217 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003218
Zhou Sheng290bec52007-03-29 08:15:12 +00003219 if (CI->getValue() == ShrMask) {
3220 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003221 return ReplaceInstUsesWith(TheAnd, Op);
3222 } else if (CI != AndRHS) {
3223 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3224 return &TheAnd;
3225 }
3226 break;
3227 }
3228 case Instruction::AShr:
3229 // Signed shr.
3230 // See if this is shifting in some sign extension, then masking it out
3231 // with an and.
3232 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003233 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003234 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003235 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3236 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003237 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003238 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003239 // Make the argument unsigned.
3240 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003241 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003242 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003243 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003244 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003245 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003246 }
3247 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003248 }
3249 return 0;
3250}
3251
Chris Lattner8b170942002-08-09 23:47:40 +00003252
Chris Lattnera96879a2004-09-29 17:40:11 +00003253/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3254/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003255/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3256/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003257/// insert new instructions.
3258Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003259 bool isSigned, bool Inside,
3260 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003261 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003262 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003263 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003264
Chris Lattnera96879a2004-09-29 17:40:11 +00003265 if (Inside) {
3266 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003267 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003268
Reid Spencere4d87aa2006-12-23 06:05:41 +00003269 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003270 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003271 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003272 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3273 return new ICmpInst(pred, V, Hi);
3274 }
3275
3276 // Emit V-Lo <u Hi-Lo
3277 Constant *NegLo = ConstantExpr::getNeg(Lo);
3278 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003279 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003280 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3281 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003282 }
3283
3284 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003285 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003286
Reid Spencere4e40032007-03-21 23:19:50 +00003287 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003288 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003289 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003290 ICmpInst::Predicate pred = (isSigned ?
3291 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3292 return new ICmpInst(pred, V, Hi);
3293 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003294
Reid Spencere4e40032007-03-21 23:19:50 +00003295 // Emit V-Lo >u Hi-1-Lo
3296 // Note that Hi has already had one subtracted from it, above.
3297 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003298 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003299 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003300 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3301 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003302}
3303
Chris Lattner7203e152005-09-18 07:22:02 +00003304// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3305// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3306// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3307// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003308static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003309 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003310 uint32_t BitWidth = Val->getType()->getBitWidth();
3311 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003312
3313 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003314 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003315 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003316 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003317 return true;
3318}
3319
Chris Lattner7203e152005-09-18 07:22:02 +00003320/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3321/// where isSub determines whether the operator is a sub. If we can fold one of
3322/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003323///
3324/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3325/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3326/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3327///
3328/// return (A +/- B).
3329///
3330Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003331 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003332 Instruction &I) {
3333 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3334 if (!LHSI || LHSI->getNumOperands() != 2 ||
3335 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3336
3337 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3338
3339 switch (LHSI->getOpcode()) {
3340 default: return 0;
3341 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003342 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003343 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003344 if ((Mask->getValue().countLeadingZeros() +
3345 Mask->getValue().countPopulation()) ==
3346 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003347 break;
3348
3349 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3350 // part, we don't need any explicit masks to take them out of A. If that
3351 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003352 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003353 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003354 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003355 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003356 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003357 break;
3358 }
3359 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003360 return 0;
3361 case Instruction::Or:
3362 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003363 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003364 if ((Mask->getValue().countLeadingZeros() +
3365 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003366 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003367 break;
3368 return 0;
3369 }
3370
3371 Instruction *New;
3372 if (isSub)
3373 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3374 else
3375 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3376 return InsertNewInstBefore(New, I);
3377}
3378
Chris Lattner7e708292002-06-25 16:13:24 +00003379Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003380 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003381 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003382
Chris Lattnere87597f2004-10-16 18:11:37 +00003383 if (isa<UndefValue>(Op1)) // X & undef -> 0
3384 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3385
Chris Lattner6e7ba452005-01-01 16:22:27 +00003386 // and X, X = X
3387 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003388 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003389
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003390 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003391 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003392 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003393 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3394 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3395 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003396 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003397 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003398 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003399 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003400 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003401 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003402 } else if (isa<ConstantAggregateZero>(Op1)) {
3403 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003404 }
3405 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003406
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003407 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003408 const APInt& AndRHSMask = AndRHS->getValue();
3409 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003410
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003411 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003412 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003413 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003414 Value *Op0LHS = Op0I->getOperand(0);
3415 Value *Op0RHS = Op0I->getOperand(1);
3416 switch (Op0I->getOpcode()) {
3417 case Instruction::Xor:
3418 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003419 // If the mask is only needed on one incoming arm, push it up.
3420 if (Op0I->hasOneUse()) {
3421 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3422 // Not masking anything out for the LHS, move to RHS.
3423 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3424 Op0RHS->getName()+".masked");
3425 InsertNewInstBefore(NewRHS, I);
3426 return BinaryOperator::create(
3427 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003428 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003429 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003430 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3431 // Not masking anything out for the RHS, move to LHS.
3432 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3433 Op0LHS->getName()+".masked");
3434 InsertNewInstBefore(NewLHS, I);
3435 return BinaryOperator::create(
3436 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3437 }
3438 }
3439
Chris Lattner6e7ba452005-01-01 16:22:27 +00003440 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003441 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003442 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3443 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3444 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3445 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3446 return BinaryOperator::createAnd(V, AndRHS);
3447 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3448 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003449 break;
3450
3451 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003452 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3453 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3454 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3455 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3456 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003457 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003458 }
3459
Chris Lattner58403262003-07-23 19:25:52 +00003460 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003461 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003462 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003463 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003464 // If this is an integer truncation or change from signed-to-unsigned, and
3465 // if the source is an and/or with immediate, transform it. This
3466 // frequently occurs for bitfield accesses.
3467 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003468 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003469 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00003470 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00003471 if (CastOp->getOpcode() == Instruction::And) {
3472 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003473 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3474 // This will fold the two constants together, which may allow
3475 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003476 Instruction *NewCast = CastInst::createTruncOrBitCast(
3477 CastOp->getOperand(0), I.getType(),
3478 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003479 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003480 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003481 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003482 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003483 return BinaryOperator::createAnd(NewCast, C3);
3484 } else if (CastOp->getOpcode() == Instruction::Or) {
3485 // Change: and (cast (or X, C1) to T), C2
3486 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003487 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003488 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3489 return ReplaceInstUsesWith(I, AndRHS);
3490 }
3491 }
Chris Lattner06782f82003-07-23 19:36:21 +00003492 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003493
3494 // Try to fold constant and into select arguments.
3495 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003496 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003497 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003498 if (isa<PHINode>(Op0))
3499 if (Instruction *NV = FoldOpIntoPhi(I))
3500 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003501 }
3502
Chris Lattner8d969642003-03-10 23:06:50 +00003503 Value *Op0NotVal = dyn_castNotVal(Op0);
3504 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003505
Chris Lattner5b62aa72004-06-18 06:07:51 +00003506 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3507 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3508
Misha Brukmancb6267b2004-07-30 12:50:08 +00003509 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003510 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003511 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3512 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003513 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003514 return BinaryOperator::createNot(Or);
3515 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003516
3517 {
Chris Lattner003b6202007-06-15 05:58:24 +00003518 Value *A = 0, *B = 0, *C = 0, *D = 0;
3519 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003520 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3521 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003522
3523 // (A|B) & ~(A&B) -> A^B
3524 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3525 if ((A == C && B == D) || (A == D && B == C))
3526 return BinaryOperator::createXor(A, B);
3527 }
3528 }
3529
3530 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003531 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3532 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003533
3534 // ~(A&B) & (A|B) -> A^B
3535 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3536 if ((A == C && B == D) || (A == D && B == C))
3537 return BinaryOperator::createXor(A, B);
3538 }
3539 }
Chris Lattner64daab52006-04-01 08:03:55 +00003540
3541 if (Op0->hasOneUse() &&
3542 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3543 if (A == Op1) { // (A^B)&A -> A&(A^B)
3544 I.swapOperands(); // Simplify below
3545 std::swap(Op0, Op1);
3546 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3547 cast<BinaryOperator>(Op0)->swapOperands();
3548 I.swapOperands(); // Simplify below
3549 std::swap(Op0, Op1);
3550 }
3551 }
3552 if (Op1->hasOneUse() &&
3553 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3554 if (B == Op0) { // B&(A^B) -> B&(B^A)
3555 cast<BinaryOperator>(Op1)->swapOperands();
3556 std::swap(A, B);
3557 }
3558 if (A == Op0) { // A&(A^B) -> A & ~B
3559 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3560 InsertNewInstBefore(NotB, I);
3561 return BinaryOperator::createAnd(A, NotB);
3562 }
3563 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003564 }
3565
Reid Spencere4d87aa2006-12-23 06:05:41 +00003566 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3567 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3568 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003569 return R;
3570
Chris Lattner955f3312004-09-28 21:48:02 +00003571 Value *LHSVal, *RHSVal;
3572 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003573 ICmpInst::Predicate LHSCC, RHSCC;
3574 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3575 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3576 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3577 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3578 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3579 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3580 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003581 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3582
3583 // Don't try to fold ICMP_SLT + ICMP_ULT.
3584 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3585 ICmpInst::isSignedPredicate(LHSCC) ==
3586 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003587 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003588 ICmpInst::Predicate GT;
3589 if (ICmpInst::isSignedPredicate(LHSCC) ||
3590 (ICmpInst::isEquality(LHSCC) &&
3591 ICmpInst::isSignedPredicate(RHSCC)))
3592 GT = ICmpInst::ICMP_SGT;
3593 else
3594 GT = ICmpInst::ICMP_UGT;
3595
Reid Spencere4d87aa2006-12-23 06:05:41 +00003596 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3597 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003598 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003599 std::swap(LHS, RHS);
3600 std::swap(LHSCst, RHSCst);
3601 std::swap(LHSCC, RHSCC);
3602 }
3603
Reid Spencere4d87aa2006-12-23 06:05:41 +00003604 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003605 // comparing a value against two constants and and'ing the result
3606 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003607 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3608 // (from the FoldICmpLogical check above), that the two constants
3609 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003610 assert(LHSCst != RHSCst && "Compares not folded above?");
3611
3612 switch (LHSCC) {
3613 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003614 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003615 switch (RHSCC) {
3616 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003617 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3618 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3619 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003620 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003621 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3622 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3623 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003624 return ReplaceInstUsesWith(I, LHS);
3625 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003626 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003627 switch (RHSCC) {
3628 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003629 case ICmpInst::ICMP_ULT:
3630 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3631 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3632 break; // (X != 13 & X u< 15) -> no change
3633 case ICmpInst::ICMP_SLT:
3634 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3635 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3636 break; // (X != 13 & X s< 15) -> no change
3637 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3638 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3639 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003640 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003641 case ICmpInst::ICMP_NE:
3642 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003643 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3644 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3645 LHSVal->getName()+".off");
3646 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003647 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3648 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003649 }
3650 break; // (X != 13 & X != 15) -> no change
3651 }
3652 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003653 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003654 switch (RHSCC) {
3655 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003656 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3657 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003658 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003659 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3660 break;
3661 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3662 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003663 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003664 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3665 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003666 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003667 break;
3668 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003669 switch (RHSCC) {
3670 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003671 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3672 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003673 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003674 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3675 break;
3676 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3677 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003678 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003679 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3680 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003681 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003682 break;
3683 case ICmpInst::ICMP_UGT:
3684 switch (RHSCC) {
3685 default: assert(0 && "Unknown integer condition code!");
3686 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3687 return ReplaceInstUsesWith(I, LHS);
3688 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3689 return ReplaceInstUsesWith(I, RHS);
3690 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3691 break;
3692 case ICmpInst::ICMP_NE:
3693 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3694 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3695 break; // (X u> 13 & X != 15) -> no change
3696 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3697 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3698 true, I);
3699 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3700 break;
3701 }
3702 break;
3703 case ICmpInst::ICMP_SGT:
3704 switch (RHSCC) {
3705 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003706 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003707 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3708 return ReplaceInstUsesWith(I, RHS);
3709 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3710 break;
3711 case ICmpInst::ICMP_NE:
3712 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3713 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3714 break; // (X s> 13 & X != 15) -> no change
3715 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3716 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3717 true, I);
3718 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3719 break;
3720 }
3721 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003722 }
3723 }
3724 }
3725
Chris Lattner6fc205f2006-05-05 06:39:07 +00003726 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003727 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3728 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3729 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3730 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003731 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003732 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003733 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3734 I.getType(), TD) &&
3735 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3736 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003737 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3738 Op1C->getOperand(0),
3739 I.getName());
3740 InsertNewInstBefore(NewOp, I);
3741 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3742 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003743 }
Chris Lattnere511b742006-11-14 07:46:50 +00003744
3745 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003746 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3747 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3748 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003749 SI0->getOperand(1) == SI1->getOperand(1) &&
3750 (SI0->hasOneUse() || SI1->hasOneUse())) {
3751 Instruction *NewOp =
3752 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3753 SI1->getOperand(0),
3754 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003755 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3756 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003757 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003758 }
3759
Chris Lattner99c65742007-10-24 05:38:08 +00003760 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3761 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3762 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3763 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3764 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3765 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3766 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3767 // If either of the constants are nans, then the whole thing returns
3768 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003769 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003770 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3771 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3772 RHS->getOperand(0));
3773 }
3774 }
3775 }
3776
Chris Lattner7e708292002-06-25 16:13:24 +00003777 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003778}
3779
Chris Lattnerafe91a52006-06-15 19:07:26 +00003780/// CollectBSwapParts - Look to see if the specified value defines a single byte
3781/// in the result. If it does, and if the specified byte hasn't been filled in
3782/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003783static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003784 Instruction *I = dyn_cast<Instruction>(V);
3785 if (I == 0) return true;
3786
3787 // If this is an or instruction, it is an inner node of the bswap.
3788 if (I->getOpcode() == Instruction::Or)
3789 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3790 CollectBSwapParts(I->getOperand(1), ByteValues);
3791
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003792 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003793 // If this is a shift by a constant int, and it is "24", then its operand
3794 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003795 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003796 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003797 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003798 8*(ByteValues.size()-1))
3799 return true;
3800
3801 unsigned DestNo;
3802 if (I->getOpcode() == Instruction::Shl) {
3803 // X << 24 defines the top byte with the lowest of the input bytes.
3804 DestNo = ByteValues.size()-1;
3805 } else {
3806 // X >>u 24 defines the low byte with the highest of the input bytes.
3807 DestNo = 0;
3808 }
3809
3810 // If the destination byte value is already defined, the values are or'd
3811 // together, which isn't a bswap (unless it's an or of the same bits).
3812 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3813 return true;
3814 ByteValues[DestNo] = I->getOperand(0);
3815 return false;
3816 }
3817
3818 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3819 // don't have this.
3820 Value *Shift = 0, *ShiftLHS = 0;
3821 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3822 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3823 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3824 return true;
3825 Instruction *SI = cast<Instruction>(Shift);
3826
3827 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003828 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3829 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003830 return true;
3831
3832 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3833 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003834 if (AndAmt->getValue().getActiveBits() > 64)
3835 return true;
3836 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003837 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003838 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003839 break;
3840 // Unknown mask for bswap.
3841 if (DestByte == ByteValues.size()) return true;
3842
Reid Spencerb83eb642006-10-20 07:07:24 +00003843 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003844 unsigned SrcByte;
3845 if (SI->getOpcode() == Instruction::Shl)
3846 SrcByte = DestByte - ShiftBytes;
3847 else
3848 SrcByte = DestByte + ShiftBytes;
3849
3850 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3851 if (SrcByte != ByteValues.size()-DestByte-1)
3852 return true;
3853
3854 // If the destination byte value is already defined, the values are or'd
3855 // together, which isn't a bswap (unless it's an or of the same bits).
3856 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3857 return true;
3858 ByteValues[DestByte] = SI->getOperand(0);
3859 return false;
3860}
3861
3862/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3863/// If so, insert the new bswap intrinsic and return it.
3864Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003865 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3866 if (!ITy || ITy->getBitWidth() % 16)
3867 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003868
3869 /// ByteValues - For each byte of the result, we keep track of which value
3870 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003871 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003872 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003873
3874 // Try to find all the pieces corresponding to the bswap.
3875 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3876 CollectBSwapParts(I.getOperand(1), ByteValues))
3877 return 0;
3878
3879 // Check to see if all of the bytes come from the same value.
3880 Value *V = ByteValues[0];
3881 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3882
3883 // Check to make sure that all of the bytes come from the same value.
3884 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3885 if (ByteValues[i] != V)
3886 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003887 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003888 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003889 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003890 return new CallInst(F, V);
3891}
3892
3893
Chris Lattner7e708292002-06-25 16:13:24 +00003894Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003895 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003896 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003897
Chris Lattner42593e62007-03-24 23:56:43 +00003898 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003899 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003900
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003901 // or X, X = X
3902 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003903 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003904
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003905 // See if we can simplify any instructions used by the instruction whose sole
3906 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003907 if (!isa<VectorType>(I.getType())) {
3908 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3909 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3910 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3911 KnownZero, KnownOne))
3912 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003913 } else if (isa<ConstantAggregateZero>(Op1)) {
3914 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3915 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3916 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3917 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00003918 }
Chris Lattner041a6c92007-06-15 05:26:55 +00003919
3920
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003921
Chris Lattner3f5b8772002-05-06 16:14:14 +00003922 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003923 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003924 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003925 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3926 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003927 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003928 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003929 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003930 return BinaryOperator::createAnd(Or,
3931 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003932 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003933
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003934 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3935 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003936 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003937 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003938 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003939 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003940 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003941 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003942
3943 // Try to fold constant and into select arguments.
3944 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003945 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003946 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003947 if (isa<PHINode>(Op0))
3948 if (Instruction *NV = FoldOpIntoPhi(I))
3949 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003950 }
3951
Chris Lattner4f637d42006-01-06 17:59:59 +00003952 Value *A = 0, *B = 0;
3953 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003954
3955 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3956 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3957 return ReplaceInstUsesWith(I, Op1);
3958 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3959 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3960 return ReplaceInstUsesWith(I, Op0);
3961
Chris Lattner6423d4c2006-07-10 20:25:24 +00003962 // (A | B) | C and A | (B | C) -> bswap if possible.
3963 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003964 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003965 match(Op1, m_Or(m_Value(), m_Value())) ||
3966 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3967 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003968 if (Instruction *BSwap = MatchBSwap(I))
3969 return BSwap;
3970 }
3971
Chris Lattner6e4c6492005-05-09 04:58:36 +00003972 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3973 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003974 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003975 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3976 InsertNewInstBefore(NOr, I);
3977 NOr->takeName(Op0);
3978 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003979 }
3980
3981 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3982 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00003983 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00003984 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3985 InsertNewInstBefore(NOr, I);
3986 NOr->takeName(Op0);
3987 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00003988 }
3989
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003990 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00003991 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00003992 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3993 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00003994 Value *V1 = 0, *V2 = 0, *V3 = 0;
3995 C1 = dyn_cast<ConstantInt>(C);
3996 C2 = dyn_cast<ConstantInt>(D);
3997 if (C1 && C2) { // (A & C1)|(B & C2)
3998 // If we have: ((V + N) & C1) | (V & C2)
3999 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4000 // replace with V+N.
4001 if (C1->getValue() == ~C2->getValue()) {
4002 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4003 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4004 // Add commutes, try both ways.
4005 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4006 return ReplaceInstUsesWith(I, A);
4007 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4008 return ReplaceInstUsesWith(I, A);
4009 }
4010 // Or commutes, try both ways.
4011 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4012 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4013 // Add commutes, try both ways.
4014 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4015 return ReplaceInstUsesWith(I, B);
4016 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4017 return ReplaceInstUsesWith(I, B);
4018 }
4019 }
Chris Lattner044e5332007-04-08 08:01:49 +00004020 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004021 }
4022
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004023 // Check to see if we have any common things being and'ed. If so, find the
4024 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004025 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4026 if (A == B) // (A & C)|(A & D) == A & (C|D)
4027 V1 = A, V2 = C, V3 = D;
4028 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4029 V1 = A, V2 = B, V3 = C;
4030 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4031 V1 = C, V2 = A, V3 = D;
4032 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4033 V1 = C, V2 = A, V3 = B;
4034
4035 if (V1) {
4036 Value *Or =
4037 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4038 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004039 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004040 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004041 }
Chris Lattnere511b742006-11-14 07:46:50 +00004042
4043 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004044 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4045 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4046 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004047 SI0->getOperand(1) == SI1->getOperand(1) &&
4048 (SI0->hasOneUse() || SI1->hasOneUse())) {
4049 Instruction *NewOp =
4050 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4051 SI1->getOperand(0),
4052 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004053 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4054 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004055 }
4056 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004057
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004058 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4059 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004060 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004061 } else {
4062 A = 0;
4063 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004064 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004065 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4066 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004067 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004068
Misha Brukmancb6267b2004-07-30 12:50:08 +00004069 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004070 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4071 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4072 I.getName()+".demorgan"), I);
4073 return BinaryOperator::createNot(And);
4074 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004075 }
Chris Lattnera2881962003-02-18 19:28:33 +00004076
Reid Spencere4d87aa2006-12-23 06:05:41 +00004077 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4078 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4079 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004080 return R;
4081
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004082 Value *LHSVal, *RHSVal;
4083 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004084 ICmpInst::Predicate LHSCC, RHSCC;
4085 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4086 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4087 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4088 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4089 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4090 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4091 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004092 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4093 // We can't fold (ugt x, C) | (sgt x, C2).
4094 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004095 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004096 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004097 bool NeedsSwap;
4098 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004099 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004100 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004101 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004102
4103 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004104 std::swap(LHS, RHS);
4105 std::swap(LHSCst, RHSCst);
4106 std::swap(LHSCC, RHSCC);
4107 }
4108
Reid Spencere4d87aa2006-12-23 06:05:41 +00004109 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004110 // comparing a value against two constants and or'ing the result
4111 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004112 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4113 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004114 // equal.
4115 assert(LHSCst != RHSCst && "Compares not folded above?");
4116
4117 switch (LHSCC) {
4118 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004119 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004120 switch (RHSCC) {
4121 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004122 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004123 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4124 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4125 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4126 LHSVal->getName()+".off");
4127 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004128 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004129 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004130 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004131 break; // (X == 13 | X == 15) -> no change
4132 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4133 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004134 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004135 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4136 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4137 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004138 return ReplaceInstUsesWith(I, RHS);
4139 }
4140 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004141 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004142 switch (RHSCC) {
4143 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004144 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4145 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4146 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004147 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004148 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4149 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4150 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004151 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004152 }
4153 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004154 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004155 switch (RHSCC) {
4156 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004157 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004158 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004159 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004160 // If RHSCst is [us]MAXINT, it is always false. Not handling
4161 // this can cause overflow.
4162 if (RHSCst->isMaxValue(false))
4163 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004164 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4165 false, I);
4166 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4167 break;
4168 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4169 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004170 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004171 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4172 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004173 }
4174 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004175 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004176 switch (RHSCC) {
4177 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004178 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4179 break;
4180 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004181 // If RHSCst is [us]MAXINT, it is always false. Not handling
4182 // this can cause overflow.
4183 if (RHSCst->isMaxValue(true))
4184 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004185 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4186 false, I);
4187 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4188 break;
4189 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4190 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4191 return ReplaceInstUsesWith(I, RHS);
4192 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4193 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004194 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004195 break;
4196 case ICmpInst::ICMP_UGT:
4197 switch (RHSCC) {
4198 default: assert(0 && "Unknown integer condition code!");
4199 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4200 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4201 return ReplaceInstUsesWith(I, LHS);
4202 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4203 break;
4204 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4205 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004206 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004207 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4208 break;
4209 }
4210 break;
4211 case ICmpInst::ICMP_SGT:
4212 switch (RHSCC) {
4213 default: assert(0 && "Unknown integer condition code!");
4214 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4215 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4216 return ReplaceInstUsesWith(I, LHS);
4217 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4218 break;
4219 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4220 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004221 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004222 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4223 break;
4224 }
4225 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004226 }
4227 }
4228 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004229
4230 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004231 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004232 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004233 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4234 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004235 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004236 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004237 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4238 I.getType(), TD) &&
4239 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4240 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004241 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4242 Op1C->getOperand(0),
4243 I.getName());
4244 InsertNewInstBefore(NewOp, I);
4245 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4246 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004247 }
Chris Lattner99c65742007-10-24 05:38:08 +00004248 }
4249
4250
4251 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4252 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4253 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4254 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4255 RHS->getPredicate() == FCmpInst::FCMP_UNO)
4256 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4257 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4258 // If either of the constants are nans, then the whole thing returns
4259 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004260 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004261 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4262
4263 // Otherwise, no need to compare the two constants, compare the
4264 // rest.
4265 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4266 RHS->getOperand(0));
4267 }
4268 }
4269 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004270
Chris Lattner7e708292002-06-25 16:13:24 +00004271 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004272}
4273
Chris Lattnerc317d392004-02-16 01:20:27 +00004274// XorSelf - Implements: X ^ X --> 0
4275struct XorSelf {
4276 Value *RHS;
4277 XorSelf(Value *rhs) : RHS(rhs) {}
4278 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4279 Instruction *apply(BinaryOperator &Xor) const {
4280 return &Xor;
4281 }
4282};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004283
4284
Chris Lattner7e708292002-06-25 16:13:24 +00004285Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004286 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004287 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004288
Chris Lattnere87597f2004-10-16 18:11:37 +00004289 if (isa<UndefValue>(Op1))
4290 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4291
Chris Lattnerc317d392004-02-16 01:20:27 +00004292 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4293 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004294 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004295 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004296 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004297
4298 // See if we can simplify any instructions used by the instruction whose sole
4299 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004300 if (!isa<VectorType>(I.getType())) {
4301 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4302 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4303 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4304 KnownZero, KnownOne))
4305 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004306 } else if (isa<ConstantAggregateZero>(Op1)) {
4307 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004308 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004309
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004310 // Is this a ~ operation?
4311 if (Value *NotOp = dyn_castNotVal(&I)) {
4312 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4313 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4314 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4315 if (Op0I->getOpcode() == Instruction::And ||
4316 Op0I->getOpcode() == Instruction::Or) {
4317 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4318 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4319 Instruction *NotY =
4320 BinaryOperator::createNot(Op0I->getOperand(1),
4321 Op0I->getOperand(1)->getName()+".not");
4322 InsertNewInstBefore(NotY, I);
4323 if (Op0I->getOpcode() == Instruction::And)
4324 return BinaryOperator::createOr(Op0NotVal, NotY);
4325 else
4326 return BinaryOperator::createAnd(Op0NotVal, NotY);
4327 }
4328 }
4329 }
4330 }
4331
4332
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004333 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004334 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4335 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4336 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004337 return new ICmpInst(ICI->getInversePredicate(),
4338 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004339
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004340 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4341 return new FCmpInst(FCI->getInversePredicate(),
4342 FCI->getOperand(0), FCI->getOperand(1));
4343 }
4344
Reid Spencere4d87aa2006-12-23 06:05:41 +00004345 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004346 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004347 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4348 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004349 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4350 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004351 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004352 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004353 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004354
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004355 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004356 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004357 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004358 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004359 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4360 return BinaryOperator::createSub(
4361 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004362 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004363 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004364 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004365 // (X + C) ^ signbit -> (X + C + signbit)
4366 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4367 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004368
Chris Lattner7c4049c2004-01-12 19:35:11 +00004369 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004370 } else if (Op0I->getOpcode() == Instruction::Or) {
4371 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004372 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004373 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4374 // Anything in both C1 and C2 is known to be zero, remove it from
4375 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004376 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004377 NewRHS = ConstantExpr::getAnd(NewRHS,
4378 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004379 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004380 I.setOperand(0, Op0I->getOperand(0));
4381 I.setOperand(1, NewRHS);
4382 return &I;
4383 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004384 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004385 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004386
4387 // Try to fold constant and into select arguments.
4388 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004389 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004390 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004391 if (isa<PHINode>(Op0))
4392 if (Instruction *NV = FoldOpIntoPhi(I))
4393 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004394 }
4395
Chris Lattner8d969642003-03-10 23:06:50 +00004396 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004397 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004398 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004399
Chris Lattner8d969642003-03-10 23:06:50 +00004400 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004401 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004402 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004403
Chris Lattner318bf792007-03-18 22:51:34 +00004404
4405 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4406 if (Op1I) {
4407 Value *A, *B;
4408 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4409 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004410 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004411 I.swapOperands();
4412 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004413 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004414 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004415 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004416 }
Chris Lattner318bf792007-03-18 22:51:34 +00004417 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4418 if (Op0 == A) // A^(A^B) == B
4419 return ReplaceInstUsesWith(I, B);
4420 else if (Op0 == B) // A^(B^A) == B
4421 return ReplaceInstUsesWith(I, A);
4422 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004423 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004424 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004425 std::swap(A, B);
4426 }
Chris Lattner318bf792007-03-18 22:51:34 +00004427 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004428 I.swapOperands(); // Simplified below.
4429 std::swap(Op0, Op1);
4430 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004431 }
Chris Lattner318bf792007-03-18 22:51:34 +00004432 }
4433
4434 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4435 if (Op0I) {
4436 Value *A, *B;
4437 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4438 if (A == Op1) // (B|A)^B == (A|B)^B
4439 std::swap(A, B);
4440 if (B == Op1) { // (A|B)^B == A & ~B
4441 Instruction *NotB =
4442 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4443 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004444 }
Chris Lattner318bf792007-03-18 22:51:34 +00004445 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4446 if (Op1 == A) // (A^B)^A == B
4447 return ReplaceInstUsesWith(I, B);
4448 else if (Op1 == B) // (B^A)^A == B
4449 return ReplaceInstUsesWith(I, A);
4450 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4451 if (A == Op1) // (A&B)^A -> (B&A)^A
4452 std::swap(A, B);
4453 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004454 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004455 Instruction *N =
4456 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004457 return BinaryOperator::createAnd(N, Op1);
4458 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004459 }
Chris Lattner318bf792007-03-18 22:51:34 +00004460 }
4461
4462 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4463 if (Op0I && Op1I && Op0I->isShift() &&
4464 Op0I->getOpcode() == Op1I->getOpcode() &&
4465 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4466 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4467 Instruction *NewOp =
4468 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4469 Op1I->getOperand(0),
4470 Op0I->getName()), I);
4471 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4472 Op1I->getOperand(1));
4473 }
4474
4475 if (Op0I && Op1I) {
4476 Value *A, *B, *C, *D;
4477 // (A & B)^(A | B) -> A ^ B
4478 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4479 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4480 if ((A == C && B == D) || (A == D && B == C))
4481 return BinaryOperator::createXor(A, B);
4482 }
4483 // (A | B)^(A & B) -> A ^ B
4484 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4485 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4486 if ((A == C && B == D) || (A == D && B == C))
4487 return BinaryOperator::createXor(A, B);
4488 }
4489
4490 // (A & B)^(C & D)
4491 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4492 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4493 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4494 // (X & Y)^(X & Y) -> (Y^Z) & X
4495 Value *X = 0, *Y = 0, *Z = 0;
4496 if (A == C)
4497 X = A, Y = B, Z = D;
4498 else if (A == D)
4499 X = A, Y = B, Z = C;
4500 else if (B == C)
4501 X = B, Y = A, Z = D;
4502 else if (B == D)
4503 X = B, Y = A, Z = C;
4504
4505 if (X) {
4506 Instruction *NewOp =
4507 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4508 return BinaryOperator::createAnd(NewOp, X);
4509 }
4510 }
4511 }
4512
Reid Spencere4d87aa2006-12-23 06:05:41 +00004513 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4514 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4515 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004516 return R;
4517
Chris Lattner6fc205f2006-05-05 06:39:07 +00004518 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004519 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004520 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004521 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4522 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004523 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004524 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004525 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4526 I.getType(), TD) &&
4527 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4528 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004529 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4530 Op1C->getOperand(0),
4531 I.getName());
4532 InsertNewInstBefore(NewOp, I);
4533 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4534 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004535 }
Chris Lattner99c65742007-10-24 05:38:08 +00004536 }
Chris Lattner7e708292002-06-25 16:13:24 +00004537 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004538}
4539
Chris Lattnera96879a2004-09-29 17:40:11 +00004540/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4541/// overflowed for this type.
4542static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004543 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004544 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004545
Reid Spencere4e40032007-03-21 23:19:50 +00004546 if (IsSigned)
4547 if (In2->getValue().isNegative())
4548 return Result->getValue().sgt(In1->getValue());
4549 else
4550 return Result->getValue().slt(In1->getValue());
4551 else
4552 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004553}
4554
Chris Lattner574da9b2005-01-13 20:14:25 +00004555/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4556/// code necessary to compute the offset from the base pointer (without adding
4557/// in the base pointer). Return the result as a signed integer of intptr size.
4558static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4559 TargetData &TD = IC.getTargetData();
4560 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004561 const Type *IntPtrTy = TD.getIntPtrType();
4562 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004563
4564 // Build a mask for high order bits.
Chris Lattnere62f0212007-04-28 04:52:43 +00004565 unsigned IntPtrWidth = TD.getPointerSize()*8;
4566 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004567
Chris Lattner574da9b2005-01-13 20:14:25 +00004568 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4569 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004570 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004571 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4572 if (OpC->isZero()) continue;
4573
4574 // Handle a struct index, which adds its field offset to the pointer.
4575 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4576 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4577
4578 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4579 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004580 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004581 Result = IC.InsertNewInstBefore(
4582 BinaryOperator::createAdd(Result,
4583 ConstantInt::get(IntPtrTy, Size),
4584 GEP->getName()+".offs"), I);
4585 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004586 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004587
4588 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4589 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4590 Scale = ConstantExpr::getMul(OC, Scale);
4591 if (Constant *RC = dyn_cast<Constant>(Result))
4592 Result = ConstantExpr::getAdd(RC, Scale);
4593 else {
4594 // Emit an add instruction.
4595 Result = IC.InsertNewInstBefore(
4596 BinaryOperator::createAdd(Result, Scale,
4597 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004598 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004599 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004600 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004601 // Convert to correct type.
4602 if (Op->getType() != IntPtrTy) {
4603 if (Constant *OpC = dyn_cast<Constant>(Op))
4604 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4605 else
4606 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4607 Op->getName()+".c"), I);
4608 }
4609 if (Size != 1) {
4610 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4611 if (Constant *OpC = dyn_cast<Constant>(Op))
4612 Op = ConstantExpr::getMul(OpC, Scale);
4613 else // We'll let instcombine(mul) convert this to a shl if possible.
4614 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4615 GEP->getName()+".idx"), I);
4616 }
4617
4618 // Emit an add instruction.
4619 if (isa<Constant>(Op) && isa<Constant>(Result))
4620 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4621 cast<Constant>(Result));
4622 else
4623 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4624 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004625 }
4626 return Result;
4627}
4628
Reid Spencere4d87aa2006-12-23 06:05:41 +00004629/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004630/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004631Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4632 ICmpInst::Predicate Cond,
4633 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004634 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004635
4636 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4637 if (isa<PointerType>(CI->getOperand(0)->getType()))
4638 RHS = CI->getOperand(0);
4639
Chris Lattner574da9b2005-01-13 20:14:25 +00004640 Value *PtrBase = GEPLHS->getOperand(0);
4641 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004642 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4643 // This transformation is valid because we know pointers can't overflow.
4644 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4645 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4646 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004647 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004648 // If the base pointers are different, but the indices are the same, just
4649 // compare the base pointer.
4650 if (PtrBase != GEPRHS->getOperand(0)) {
4651 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004652 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004653 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004654 if (IndicesTheSame)
4655 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4656 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4657 IndicesTheSame = false;
4658 break;
4659 }
4660
4661 // If all indices are the same, just compare the base pointers.
4662 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004663 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4664 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004665
4666 // Otherwise, the base pointers are different and the indices are
4667 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004668 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004669 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004670
Chris Lattnere9d782b2005-01-13 22:25:21 +00004671 // If one of the GEPs has all zero indices, recurse.
4672 bool AllZeros = true;
4673 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4674 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4675 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4676 AllZeros = false;
4677 break;
4678 }
4679 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004680 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4681 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004682
4683 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004684 AllZeros = true;
4685 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4686 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4687 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4688 AllZeros = false;
4689 break;
4690 }
4691 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004692 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004693
Chris Lattner4401c9c2005-01-14 00:20:05 +00004694 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4695 // If the GEPs only differ by one index, compare it.
4696 unsigned NumDifferences = 0; // Keep track of # differences.
4697 unsigned DiffOperand = 0; // The operand that differs.
4698 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4699 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004700 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4701 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004702 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004703 NumDifferences = 2;
4704 break;
4705 } else {
4706 if (NumDifferences++) break;
4707 DiffOperand = i;
4708 }
4709 }
4710
4711 if (NumDifferences == 0) // SAME GEP?
4712 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004713 ConstantInt::get(Type::Int1Ty,
4714 isTrueWhenEqual(Cond)));
4715
Chris Lattner4401c9c2005-01-14 00:20:05 +00004716 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004717 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4718 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004719 // Make sure we do a signed comparison here.
4720 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004721 }
4722 }
4723
Reid Spencere4d87aa2006-12-23 06:05:41 +00004724 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004725 // the result to fold to a constant!
4726 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4727 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4728 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4729 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4730 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004731 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004732 }
4733 }
4734 return 0;
4735}
4736
Reid Spencere4d87aa2006-12-23 06:05:41 +00004737Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4738 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004739 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004740
Chris Lattner58e97462007-01-14 19:42:17 +00004741 // Fold trivial predicates.
4742 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4743 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4744 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4745 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4746
4747 // Simplify 'fcmp pred X, X'
4748 if (Op0 == Op1) {
4749 switch (I.getPredicate()) {
4750 default: assert(0 && "Unknown predicate!");
4751 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4752 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4753 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4754 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4755 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4756 case FCmpInst::FCMP_OLT: // True if ordered and less than
4757 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4758 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4759
4760 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4761 case FCmpInst::FCMP_ULT: // True if unordered or less than
4762 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4763 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4764 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4765 I.setPredicate(FCmpInst::FCMP_UNO);
4766 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4767 return &I;
4768
4769 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4770 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4771 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4772 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4773 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4774 I.setPredicate(FCmpInst::FCMP_ORD);
4775 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4776 return &I;
4777 }
4778 }
4779
Reid Spencere4d87aa2006-12-23 06:05:41 +00004780 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004781 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00004782
Reid Spencere4d87aa2006-12-23 06:05:41 +00004783 // Handle fcmp with constant RHS
4784 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4785 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4786 switch (LHSI->getOpcode()) {
4787 case Instruction::PHI:
4788 if (Instruction *NV = FoldOpIntoPhi(I))
4789 return NV;
4790 break;
4791 case Instruction::Select:
4792 // If either operand of the select is a constant, we can fold the
4793 // comparison into the select arms, which will cause one to be
4794 // constant folded and the select turned into a bitwise or.
4795 Value *Op1 = 0, *Op2 = 0;
4796 if (LHSI->hasOneUse()) {
4797 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4798 // Fold the known value into the constant operand.
4799 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4800 // Insert a new FCmp of the other select operand.
4801 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4802 LHSI->getOperand(2), RHSC,
4803 I.getName()), I);
4804 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4805 // Fold the known value into the constant operand.
4806 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4807 // Insert a new FCmp of the other select operand.
4808 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4809 LHSI->getOperand(1), RHSC,
4810 I.getName()), I);
4811 }
4812 }
4813
4814 if (Op1)
4815 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4816 break;
4817 }
4818 }
4819
4820 return Changed ? &I : 0;
4821}
4822
4823Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4824 bool Changed = SimplifyCompare(I);
4825 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4826 const Type *Ty = Op0->getType();
4827
4828 // icmp X, X
4829 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00004830 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4831 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004832
4833 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004834 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00004835
Reid Spencere4d87aa2006-12-23 06:05:41 +00004836 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004837 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004838 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4839 isa<ConstantPointerNull>(Op0)) &&
4840 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004841 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00004842 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4843 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00004844
Reid Spencere4d87aa2006-12-23 06:05:41 +00004845 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00004846 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004847 switch (I.getPredicate()) {
4848 default: assert(0 && "Invalid icmp instruction!");
4849 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004850 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004851 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004852 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004853 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004854 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00004855 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004856
Reid Spencere4d87aa2006-12-23 06:05:41 +00004857 case ICmpInst::ICMP_UGT:
4858 case ICmpInst::ICMP_SGT:
4859 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00004860 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004861 case ICmpInst::ICMP_ULT:
4862 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00004863 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4864 InsertNewInstBefore(Not, I);
4865 return BinaryOperator::createAnd(Not, Op1);
4866 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004867 case ICmpInst::ICMP_UGE:
4868 case ICmpInst::ICMP_SGE:
4869 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00004870 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004871 case ICmpInst::ICMP_ULE:
4872 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00004873 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4874 InsertNewInstBefore(Not, I);
4875 return BinaryOperator::createOr(Not, Op1);
4876 }
4877 }
Chris Lattner8b170942002-08-09 23:47:40 +00004878 }
4879
Chris Lattner2be51ae2004-06-09 04:24:29 +00004880 // See if we are doing a comparison between a constant and an instruction that
4881 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00004882 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00004883 Value *A, *B;
4884
Chris Lattnerb6566012008-01-05 01:18:20 +00004885 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4886 if (I.isEquality() && CI->isNullValue() &&
4887 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4888 // (icmp cond A B) if cond is equality
4889 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00004890 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00004891
Reid Spencere4d87aa2006-12-23 06:05:41 +00004892 switch (I.getPredicate()) {
4893 default: break;
4894 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4895 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004896 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004897 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4898 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4899 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4900 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004901 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4902 if (CI->isMinValue(true))
4903 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4904 ConstantInt::getAllOnesValue(Op0->getType()));
4905
Reid Spencere4d87aa2006-12-23 06:05:41 +00004906 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004907
Reid Spencere4d87aa2006-12-23 06:05:41 +00004908 case ICmpInst::ICMP_SLT:
4909 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004910 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004911 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4912 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4913 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4914 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4915 break;
4916
4917 case ICmpInst::ICMP_UGT:
4918 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004919 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004920 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4921 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4922 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4923 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004924
4925 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4926 if (CI->isMaxValue(true))
4927 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4928 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004929 break;
4930
4931 case ICmpInst::ICMP_SGT:
4932 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004933 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004934 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4935 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4936 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4937 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4938 break;
4939
4940 case ICmpInst::ICMP_ULE:
4941 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004942 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004943 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4944 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4945 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4946 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4947 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004948
Reid Spencere4d87aa2006-12-23 06:05:41 +00004949 case ICmpInst::ICMP_SLE:
4950 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004951 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004952 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4953 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4954 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4955 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4956 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004957
Reid Spencere4d87aa2006-12-23 06:05:41 +00004958 case ICmpInst::ICMP_UGE:
4959 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004960 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004961 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4962 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4963 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4964 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4965 break;
4966
4967 case ICmpInst::ICMP_SGE:
4968 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004969 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004970 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4971 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4972 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4973 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4974 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004975 }
4976
Reid Spencere4d87aa2006-12-23 06:05:41 +00004977 // If we still have a icmp le or icmp ge instruction, turn it into the
4978 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00004979 // already been handled above, this requires little checking.
4980 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00004981 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00004982 default: break;
4983 case ICmpInst::ICMP_ULE:
4984 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4985 case ICmpInst::ICMP_SLE:
4986 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4987 case ICmpInst::ICMP_UGE:
4988 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4989 case ICmpInst::ICMP_SGE:
4990 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00004991 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004992
4993 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00004994 // in the input. If this comparison is a normal comparison, it demands all
4995 // bits, if it is a sign bit comparison, it only demands the sign bit.
4996
4997 bool UnusedBit;
4998 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
4999
Reid Spencer0460fb32007-03-22 20:36:03 +00005000 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5001 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005002 if (SimplifyDemandedBits(Op0,
5003 isSignBit ? APInt::getSignBit(BitWidth)
5004 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005005 KnownZero, KnownOne, 0))
5006 return &I;
5007
5008 // Given the known and unknown bits, compute a range that the LHS could be
5009 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005010 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005011 // Compute the Min, Max and RHS values based on the known bits. For the
5012 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005013 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5014 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005015 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005016 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5017 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005018 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005019 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5020 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005021 }
5022 switch (I.getPredicate()) { // LE/GE have been folded already.
5023 default: assert(0 && "Unknown icmp opcode!");
5024 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005025 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005026 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005027 break;
5028 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005029 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005030 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005031 break;
5032 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005033 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005034 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005035 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005036 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005037 break;
5038 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005039 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005040 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005041 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005042 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005043 break;
5044 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005045 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005046 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005047 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005048 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005049 break;
5050 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005051 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005052 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005053 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005054 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005055 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005056 }
5057 }
5058
Reid Spencere4d87aa2006-12-23 06:05:41 +00005059 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005060 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005061 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005062 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005063 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5064 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005065 }
5066
Chris Lattner01deb9d2007-04-03 17:43:25 +00005067 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005068 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5069 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5070 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005071 case Instruction::GetElementPtr:
5072 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005073 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005074 bool isAllZeros = true;
5075 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5076 if (!isa<Constant>(LHSI->getOperand(i)) ||
5077 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5078 isAllZeros = false;
5079 break;
5080 }
5081 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005082 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005083 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5084 }
5085 break;
5086
Chris Lattner6970b662005-04-23 15:31:55 +00005087 case Instruction::PHI:
5088 if (Instruction *NV = FoldOpIntoPhi(I))
5089 return NV;
5090 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005091 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005092 // If either operand of the select is a constant, we can fold the
5093 // comparison into the select arms, which will cause one to be
5094 // constant folded and the select turned into a bitwise or.
5095 Value *Op1 = 0, *Op2 = 0;
5096 if (LHSI->hasOneUse()) {
5097 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5098 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005099 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5100 // Insert a new ICmp of the other select operand.
5101 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5102 LHSI->getOperand(2), RHSC,
5103 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005104 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5105 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005106 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5107 // Insert a new ICmp of the other select operand.
5108 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5109 LHSI->getOperand(1), RHSC,
5110 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005111 }
5112 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005113
Chris Lattner6970b662005-04-23 15:31:55 +00005114 if (Op1)
5115 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5116 break;
5117 }
Chris Lattner4802d902007-04-06 18:57:34 +00005118 case Instruction::Malloc:
5119 // If we have (malloc != null), and if the malloc has a single use, we
5120 // can assume it is successful and remove the malloc.
5121 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5122 AddToWorkList(LHSI);
5123 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5124 !isTrueWhenEqual(I)));
5125 }
5126 break;
5127 }
Chris Lattner6970b662005-04-23 15:31:55 +00005128 }
5129
Reid Spencere4d87aa2006-12-23 06:05:41 +00005130 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005131 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005132 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005133 return NI;
5134 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005135 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5136 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005137 return NI;
5138
Reid Spencere4d87aa2006-12-23 06:05:41 +00005139 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005140 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5141 // now.
5142 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5143 if (isa<PointerType>(Op0->getType()) &&
5144 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005145 // We keep moving the cast from the left operand over to the right
5146 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005147 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005148
Chris Lattner57d86372007-01-06 01:45:59 +00005149 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5150 // so eliminate it as well.
5151 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5152 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005153
Chris Lattnerde90b762003-11-03 04:25:02 +00005154 // If Op1 is a constant, we can fold the cast into the constant.
Chris Lattner57d86372007-01-06 01:45:59 +00005155 if (Op0->getType() != Op1->getType())
Chris Lattnerde90b762003-11-03 04:25:02 +00005156 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005157 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005158 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005159 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005160 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005161 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005162 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005163 }
Chris Lattner57d86372007-01-06 01:45:59 +00005164 }
5165
5166 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005167 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005168 // This comes up when you have code like
5169 // int X = A < B;
5170 // if (X) ...
5171 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005172 // with a constant or another cast from the same type.
5173 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005174 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005175 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005176 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005177
Chris Lattner65b72ba2006-09-18 04:22:48 +00005178 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005179 Value *A, *B, *C, *D;
5180 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5181 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5182 Value *OtherVal = A == Op1 ? B : A;
5183 return new ICmpInst(I.getPredicate(), OtherVal,
5184 Constant::getNullValue(A->getType()));
5185 }
5186
5187 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5188 // A^c1 == C^c2 --> A == C^(c1^c2)
5189 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5190 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5191 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005192 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005193 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5194 return new ICmpInst(I.getPredicate(), A,
5195 InsertNewInstBefore(Xor, I));
5196 }
5197
5198 // A^B == A^D -> B == D
5199 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5200 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5201 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5202 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5203 }
5204 }
5205
5206 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5207 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005208 // A == (A^B) -> B == 0
5209 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005210 return new ICmpInst(I.getPredicate(), OtherVal,
5211 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005212 }
5213 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005214 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005215 return new ICmpInst(I.getPredicate(), B,
5216 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005217 }
5218 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005219 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005220 return new ICmpInst(I.getPredicate(), B,
5221 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005222 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005223
Chris Lattner9c2328e2006-11-14 06:06:06 +00005224 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5225 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5226 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5227 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5228 Value *X = 0, *Y = 0, *Z = 0;
5229
5230 if (A == C) {
5231 X = B; Y = D; Z = A;
5232 } else if (A == D) {
5233 X = B; Y = C; Z = A;
5234 } else if (B == C) {
5235 X = A; Y = D; Z = B;
5236 } else if (B == D) {
5237 X = A; Y = C; Z = B;
5238 }
5239
5240 if (X) { // Build (X^Y) & Z
5241 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5242 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5243 I.setOperand(0, Op1);
5244 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5245 return &I;
5246 }
5247 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005248 }
Chris Lattner7e708292002-06-25 16:13:24 +00005249 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005250}
5251
Chris Lattner562ef782007-06-20 23:46:26 +00005252
5253/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5254/// and CmpRHS are both known to be integer constants.
5255Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5256 ConstantInt *DivRHS) {
5257 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5258 const APInt &CmpRHSV = CmpRHS->getValue();
5259
5260 // FIXME: If the operand types don't match the type of the divide
5261 // then don't attempt this transform. The code below doesn't have the
5262 // logic to deal with a signed divide and an unsigned compare (and
5263 // vice versa). This is because (x /s C1) <s C2 produces different
5264 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5265 // (x /u C1) <u C2. Simply casting the operands and result won't
5266 // work. :( The if statement below tests that condition and bails
5267 // if it finds it.
5268 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5269 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5270 return 0;
5271 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005272 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005273
5274 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5275 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5276 // C2 (CI). By solving for X we can turn this into a range check
5277 // instead of computing a divide.
5278 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5279
5280 // Determine if the product overflows by seeing if the product is
5281 // not equal to the divide. Make sure we do the same kind of divide
5282 // as in the LHS instruction that we're folding.
5283 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5284 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5285
5286 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005287 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005288
Chris Lattner1dbfd482007-06-21 18:11:19 +00005289 // Figure out the interval that is being checked. For example, a comparison
5290 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5291 // Compute this interval based on the constants involved and the signedness of
5292 // the compare/divide. This computes a half-open interval, keeping track of
5293 // whether either value in the interval overflows. After analysis each
5294 // overflow variable is set to 0 if it's corresponding bound variable is valid
5295 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5296 int LoOverflow = 0, HiOverflow = 0;
5297 ConstantInt *LoBound = 0, *HiBound = 0;
5298
5299
Chris Lattner562ef782007-06-20 23:46:26 +00005300 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005301 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005302 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005303 HiOverflow = LoOverflow = ProdOV;
5304 if (!HiOverflow)
5305 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005306 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005307 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005308 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005309 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5310 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005311 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005312 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5313 HiOverflow = LoOverflow = ProdOV;
5314 if (!HiOverflow)
5315 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005316 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005317 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005318 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5319 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005320 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005321 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005322 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005323 }
Dan Gohman76491272008-02-13 22:09:18 +00005324 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005325 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005326 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005327 LoBound = AddOne(DivRHS);
5328 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005329 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5330 HiOverflow = 1; // [INTMIN+1, overflow)
5331 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5332 }
Dan Gohman76491272008-02-13 22:09:18 +00005333 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005334 // e.g. X/-5 op 3 --> [-19, -14)
5335 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005336 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005337 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005338 HiBound = AddOne(Prod);
5339 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005340 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005341 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005342 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005343 HiBound = Subtract(Prod, DivRHS);
5344 }
5345
Chris Lattner1dbfd482007-06-21 18:11:19 +00005346 // Dividing by a negative swaps the condition. LT <-> GT
5347 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005348 }
5349
5350 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005351 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005352 default: assert(0 && "Unhandled icmp opcode!");
5353 case ICmpInst::ICMP_EQ:
5354 if (LoOverflow && HiOverflow)
5355 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5356 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005357 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005358 ICmpInst::ICMP_UGE, X, LoBound);
5359 else if (LoOverflow)
5360 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5361 ICmpInst::ICMP_ULT, X, HiBound);
5362 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005363 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005364 case ICmpInst::ICMP_NE:
5365 if (LoOverflow && HiOverflow)
5366 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5367 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005368 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005369 ICmpInst::ICMP_ULT, X, LoBound);
5370 else if (LoOverflow)
5371 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5372 ICmpInst::ICMP_UGE, X, HiBound);
5373 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005374 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005375 case ICmpInst::ICMP_ULT:
5376 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005377 if (LoOverflow == +1) // Low bound is greater than input range.
5378 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5379 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005380 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005381 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005382 case ICmpInst::ICMP_UGT:
5383 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005384 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005385 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005386 else if (HiOverflow == -1) // High bound less than input range.
5387 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5388 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005389 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5390 else
5391 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5392 }
5393}
5394
5395
Chris Lattner01deb9d2007-04-03 17:43:25 +00005396/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5397///
5398Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5399 Instruction *LHSI,
5400 ConstantInt *RHS) {
5401 const APInt &RHSV = RHS->getValue();
5402
5403 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005404 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005405 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5406 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5407 // fold the xor.
5408 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5409 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5410 Value *CompareVal = LHSI->getOperand(0);
5411
5412 // If the sign bit of the XorCST is not set, there is no change to
5413 // the operation, just stop using the Xor.
5414 if (!XorCST->getValue().isNegative()) {
5415 ICI.setOperand(0, CompareVal);
5416 AddToWorkList(LHSI);
5417 return &ICI;
5418 }
5419
5420 // Was the old condition true if the operand is positive?
5421 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5422
5423 // If so, the new one isn't.
5424 isTrueIfPositive ^= true;
5425
5426 if (isTrueIfPositive)
5427 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5428 else
5429 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5430 }
5431 }
5432 break;
5433 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5434 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5435 LHSI->getOperand(0)->hasOneUse()) {
5436 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5437
5438 // If the LHS is an AND of a truncating cast, we can widen the
5439 // and/compare to be the input width without changing the value
5440 // produced, eliminating a cast.
5441 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5442 // We can do this transformation if either the AND constant does not
5443 // have its sign bit set or if it is an equality comparison.
5444 // Extending a relational comparison when we're checking the sign
5445 // bit would not work.
5446 if (Cast->hasOneUse() &&
Dan Gohman76491272008-02-13 22:09:18 +00005447 (ICI.isEquality() || AndCST->getValue().isNonNegative() &&
5448 RHSV.isNonNegative())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005449 uint32_t BitWidth =
5450 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5451 APInt NewCST = AndCST->getValue();
5452 NewCST.zext(BitWidth);
5453 APInt NewCI = RHSV;
5454 NewCI.zext(BitWidth);
5455 Instruction *NewAnd =
5456 BinaryOperator::createAnd(Cast->getOperand(0),
5457 ConstantInt::get(NewCST),LHSI->getName());
5458 InsertNewInstBefore(NewAnd, ICI);
5459 return new ICmpInst(ICI.getPredicate(), NewAnd,
5460 ConstantInt::get(NewCI));
5461 }
5462 }
5463
5464 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5465 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5466 // happens a LOT in code produced by the C front-end, for bitfield
5467 // access.
5468 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5469 if (Shift && !Shift->isShift())
5470 Shift = 0;
5471
5472 ConstantInt *ShAmt;
5473 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5474 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5475 const Type *AndTy = AndCST->getType(); // Type of the and.
5476
5477 // We can fold this as long as we can't shift unknown bits
5478 // into the mask. This can only happen with signed shift
5479 // rights, as they sign-extend.
5480 if (ShAmt) {
5481 bool CanFold = Shift->isLogicalShift();
5482 if (!CanFold) {
5483 // To test for the bad case of the signed shr, see if any
5484 // of the bits shifted in could be tested after the mask.
5485 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5486 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5487
5488 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5489 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5490 AndCST->getValue()) == 0)
5491 CanFold = true;
5492 }
5493
5494 if (CanFold) {
5495 Constant *NewCst;
5496 if (Shift->getOpcode() == Instruction::Shl)
5497 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5498 else
5499 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5500
5501 // Check to see if we are shifting out any of the bits being
5502 // compared.
5503 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5504 // If we shifted bits out, the fold is not going to work out.
5505 // As a special case, check to see if this means that the
5506 // result is always true or false now.
5507 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5508 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5509 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5510 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5511 } else {
5512 ICI.setOperand(1, NewCst);
5513 Constant *NewAndCST;
5514 if (Shift->getOpcode() == Instruction::Shl)
5515 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5516 else
5517 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5518 LHSI->setOperand(1, NewAndCST);
5519 LHSI->setOperand(0, Shift->getOperand(0));
5520 AddToWorkList(Shift); // Shift is dead.
5521 AddUsesToWorkList(ICI);
5522 return &ICI;
5523 }
5524 }
5525 }
5526
5527 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5528 // preferable because it allows the C<<Y expression to be hoisted out
5529 // of a loop if Y is invariant and X is not.
5530 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5531 ICI.isEquality() && !Shift->isArithmeticShift() &&
5532 isa<Instruction>(Shift->getOperand(0))) {
5533 // Compute C << Y.
5534 Value *NS;
5535 if (Shift->getOpcode() == Instruction::LShr) {
5536 NS = BinaryOperator::createShl(AndCST,
5537 Shift->getOperand(1), "tmp");
5538 } else {
5539 // Insert a logical shift.
5540 NS = BinaryOperator::createLShr(AndCST,
5541 Shift->getOperand(1), "tmp");
5542 }
5543 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5544
5545 // Compute X & (C << Y).
5546 Instruction *NewAnd =
5547 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5548 InsertNewInstBefore(NewAnd, ICI);
5549
5550 ICI.setOperand(0, NewAnd);
5551 return &ICI;
5552 }
5553 }
5554 break;
5555
Chris Lattnera0141b92007-07-15 20:42:37 +00005556 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5557 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5558 if (!ShAmt) break;
5559
5560 uint32_t TypeBits = RHSV.getBitWidth();
5561
5562 // Check that the shift amount is in range. If not, don't perform
5563 // undefined shifts. When the shift is visited it will be
5564 // simplified.
5565 if (ShAmt->uge(TypeBits))
5566 break;
5567
5568 if (ICI.isEquality()) {
5569 // If we are comparing against bits always shifted out, the
5570 // comparison cannot succeed.
5571 Constant *Comp =
5572 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5573 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5574 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5575 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5576 return ReplaceInstUsesWith(ICI, Cst);
5577 }
5578
5579 if (LHSI->hasOneUse()) {
5580 // Otherwise strength reduce the shift into an and.
5581 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5582 Constant *Mask =
5583 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005584
Chris Lattnera0141b92007-07-15 20:42:37 +00005585 Instruction *AndI =
5586 BinaryOperator::createAnd(LHSI->getOperand(0),
5587 Mask, LHSI->getName()+".mask");
5588 Value *And = InsertNewInstBefore(AndI, ICI);
5589 return new ICmpInst(ICI.getPredicate(), And,
5590 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005591 }
5592 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005593
5594 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5595 bool TrueIfSigned = false;
5596 if (LHSI->hasOneUse() &&
5597 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5598 // (X << 31) <s 0 --> (X&1) != 0
5599 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5600 (TypeBits-ShAmt->getZExtValue()-1));
5601 Instruction *AndI =
5602 BinaryOperator::createAnd(LHSI->getOperand(0),
5603 Mask, LHSI->getName()+".mask");
5604 Value *And = InsertNewInstBefore(AndI, ICI);
5605
5606 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5607 And, Constant::getNullValue(And->getType()));
5608 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005609 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005610 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005611
5612 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005613 case Instruction::AShr: {
5614 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5615 if (!ShAmt) break;
5616
5617 if (ICI.isEquality()) {
5618 // Check that the shift amount is in range. If not, don't perform
5619 // undefined shifts. When the shift is visited it will be
5620 // simplified.
5621 uint32_t TypeBits = RHSV.getBitWidth();
5622 if (ShAmt->uge(TypeBits))
5623 break;
5624 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5625
5626 // If we are comparing against bits always shifted out, the
5627 // comparison cannot succeed.
5628 APInt Comp = RHSV << ShAmtVal;
5629 if (LHSI->getOpcode() == Instruction::LShr)
5630 Comp = Comp.lshr(ShAmtVal);
5631 else
5632 Comp = Comp.ashr(ShAmtVal);
5633
5634 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5635 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5636 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5637 return ReplaceInstUsesWith(ICI, Cst);
5638 }
5639
5640 if (LHSI->hasOneUse() || RHSV == 0) {
5641 // Otherwise strength reduce the shift into an and.
5642 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5643 Constant *Mask = ConstantInt::get(Val);
Chris Lattner01deb9d2007-04-03 17:43:25 +00005644
Chris Lattnera0141b92007-07-15 20:42:37 +00005645 Instruction *AndI =
5646 BinaryOperator::createAnd(LHSI->getOperand(0),
5647 Mask, LHSI->getName()+".mask");
5648 Value *And = InsertNewInstBefore(AndI, ICI);
5649 return new ICmpInst(ICI.getPredicate(), And,
5650 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005651 }
5652 }
5653 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005654 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005655
5656 case Instruction::SDiv:
5657 case Instruction::UDiv:
5658 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5659 // Fold this div into the comparison, producing a range check.
5660 // Determine, based on the divide type, what the range is being
5661 // checked. If there is an overflow on the low or high side, remember
5662 // it, otherwise compute the range [low, hi) bounding the new value.
5663 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005664 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5665 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5666 DivRHS))
5667 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005668 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00005669
5670 case Instruction::Add:
5671 // Fold: icmp pred (add, X, C1), C2
5672
5673 if (!ICI.isEquality()) {
5674 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5675 if (!LHSC) break;
5676 const APInt &LHSV = LHSC->getValue();
5677
5678 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5679 .subtract(LHSV);
5680
5681 if (ICI.isSignedPredicate()) {
5682 if (CR.getLower().isSignBit()) {
5683 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5684 ConstantInt::get(CR.getUpper()));
5685 } else if (CR.getUpper().isSignBit()) {
5686 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5687 ConstantInt::get(CR.getLower()));
5688 }
5689 } else {
5690 if (CR.getLower().isMinValue()) {
5691 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5692 ConstantInt::get(CR.getUpper()));
5693 } else if (CR.getUpper().isMinValue()) {
5694 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5695 ConstantInt::get(CR.getLower()));
5696 }
5697 }
5698 }
5699 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005700 }
5701
5702 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5703 if (ICI.isEquality()) {
5704 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5705
5706 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5707 // the second operand is a constant, simplify a bit.
5708 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5709 switch (BO->getOpcode()) {
5710 case Instruction::SRem:
5711 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5712 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5713 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5714 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5715 Instruction *NewRem =
5716 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5717 BO->getName());
5718 InsertNewInstBefore(NewRem, ICI);
5719 return new ICmpInst(ICI.getPredicate(), NewRem,
5720 Constant::getNullValue(BO->getType()));
5721 }
5722 }
5723 break;
5724 case Instruction::Add:
5725 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5726 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5727 if (BO->hasOneUse())
5728 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5729 Subtract(RHS, BOp1C));
5730 } else if (RHSV == 0) {
5731 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5732 // efficiently invertible, or if the add has just this one use.
5733 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5734
5735 if (Value *NegVal = dyn_castNegVal(BOp1))
5736 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5737 else if (Value *NegVal = dyn_castNegVal(BOp0))
5738 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5739 else if (BO->hasOneUse()) {
5740 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5741 InsertNewInstBefore(Neg, ICI);
5742 Neg->takeName(BO);
5743 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5744 }
5745 }
5746 break;
5747 case Instruction::Xor:
5748 // For the xor case, we can xor two constants together, eliminating
5749 // the explicit xor.
5750 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5751 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5752 ConstantExpr::getXor(RHS, BOC));
5753
5754 // FALLTHROUGH
5755 case Instruction::Sub:
5756 // Replace (([sub|xor] A, B) != 0) with (A != B)
5757 if (RHSV == 0)
5758 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5759 BO->getOperand(1));
5760 break;
5761
5762 case Instruction::Or:
5763 // If bits are being or'd in that are not present in the constant we
5764 // are comparing against, then the comparison could never succeed!
5765 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5766 Constant *NotCI = ConstantExpr::getNot(RHS);
5767 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5768 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5769 isICMP_NE));
5770 }
5771 break;
5772
5773 case Instruction::And:
5774 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5775 // If bits are being compared against that are and'd out, then the
5776 // comparison can never succeed!
5777 if ((RHSV & ~BOC->getValue()) != 0)
5778 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5779 isICMP_NE));
5780
5781 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5782 if (RHS == BOC && RHSV.isPowerOf2())
5783 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5784 ICmpInst::ICMP_NE, LHSI,
5785 Constant::getNullValue(RHS->getType()));
5786
5787 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5788 if (isSignBit(BOC)) {
5789 Value *X = BO->getOperand(0);
5790 Constant *Zero = Constant::getNullValue(X->getType());
5791 ICmpInst::Predicate pred = isICMP_NE ?
5792 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5793 return new ICmpInst(pred, X, Zero);
5794 }
5795
5796 // ((X & ~7) == 0) --> X < 8
5797 if (RHSV == 0 && isHighOnes(BOC)) {
5798 Value *X = BO->getOperand(0);
5799 Constant *NegX = ConstantExpr::getNeg(BOC);
5800 ICmpInst::Predicate pred = isICMP_NE ?
5801 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5802 return new ICmpInst(pred, X, NegX);
5803 }
5804 }
5805 default: break;
5806 }
5807 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5808 // Handle icmp {eq|ne} <intrinsic>, intcst.
5809 if (II->getIntrinsicID() == Intrinsic::bswap) {
5810 AddToWorkList(II);
5811 ICI.setOperand(0, II->getOperand(1));
5812 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5813 return &ICI;
5814 }
5815 }
5816 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00005817 // If the LHS is a cast from an integral value of the same size,
5818 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00005819 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5820 Value *CastOp = Cast->getOperand(0);
5821 const Type *SrcTy = CastOp->getType();
5822 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5823 if (SrcTy->isInteger() &&
5824 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5825 // If this is an unsigned comparison, try to make the comparison use
5826 // smaller constant values.
5827 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5828 // X u< 128 => X s> -1
5829 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5830 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5831 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5832 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5833 // X u> 127 => X s< 0
5834 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5835 Constant::getNullValue(SrcTy));
5836 }
5837 }
5838 }
5839 }
5840 return 0;
5841}
5842
5843/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5844/// We only handle extending casts so far.
5845///
Reid Spencere4d87aa2006-12-23 06:05:41 +00005846Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5847 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00005848 Value *LHSCIOp = LHSCI->getOperand(0);
5849 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005850 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005851 Value *RHSCIOp;
5852
Chris Lattner8c756c12007-05-05 22:41:33 +00005853 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5854 // integer type is the same size as the pointer type.
5855 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5856 getTargetData().getPointerSizeInBits() ==
5857 cast<IntegerType>(DestTy)->getBitWidth()) {
5858 Value *RHSOp = 0;
5859 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00005860 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00005861 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5862 RHSOp = RHSC->getOperand(0);
5863 // If the pointer types don't match, insert a bitcast.
5864 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00005865 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00005866 }
5867
5868 if (RHSOp)
5869 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5870 }
5871
5872 // The code below only handles extension cast instructions, so far.
5873 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005874 if (LHSCI->getOpcode() != Instruction::ZExt &&
5875 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00005876 return 0;
5877
Reid Spencere4d87aa2006-12-23 06:05:41 +00005878 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5879 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005880
Reid Spencere4d87aa2006-12-23 06:05:41 +00005881 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005882 // Not an extension from the same type?
5883 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005884 if (RHSCIOp->getType() != LHSCIOp->getType())
5885 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00005886
Nick Lewycky4189a532008-01-28 03:48:02 +00005887 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00005888 // and the other is a zext), then we can't handle this.
5889 if (CI->getOpcode() != LHSCI->getOpcode())
5890 return 0;
5891
Nick Lewycky4189a532008-01-28 03:48:02 +00005892 // Deal with equality cases early.
5893 if (ICI.isEquality())
5894 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5895
5896 // A signed comparison of sign extended values simplifies into a
5897 // signed comparison.
5898 if (isSignedCmp && isSignedExt)
5899 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5900
5901 // The other three cases all fold into an unsigned comparison.
5902 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00005903 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005904
Reid Spencere4d87aa2006-12-23 06:05:41 +00005905 // If we aren't dealing with a constant on the RHS, exit early
5906 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5907 if (!CI)
5908 return 0;
5909
5910 // Compute the constant that would happen if we truncated to SrcTy then
5911 // reextended to DestTy.
5912 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5913 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5914
5915 // If the re-extended constant didn't change...
5916 if (Res2 == CI) {
5917 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5918 // For example, we might have:
5919 // %A = sext short %X to uint
5920 // %B = icmp ugt uint %A, 1330
5921 // It is incorrect to transform this into
5922 // %B = icmp ugt short %X, 1330
5923 // because %A may have negative value.
5924 //
5925 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5926 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00005927 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00005928 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5929 else
5930 return 0;
5931 }
5932
5933 // The re-extended constant changed so the constant cannot be represented
5934 // in the shorter type. Consequently, we cannot emit a simple comparison.
5935
5936 // First, handle some easy cases. We know the result cannot be equal at this
5937 // point so handle the ICI.isEquality() cases
5938 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005939 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005940 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005941 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005942
5943 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5944 // should have been folded away previously and not enter in here.
5945 Value *Result;
5946 if (isSignedCmp) {
5947 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00005948 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005949 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00005950 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005951 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00005952 } else {
5953 // We're performing an unsigned comparison.
5954 if (isSignedExt) {
5955 // We're performing an unsigned comp with a sign extended value.
5956 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005957 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005958 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5959 NegOne, ICI.getName()), ICI);
5960 } else {
5961 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005962 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005963 }
5964 }
5965
5966 // Finally, return the value computed.
5967 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5968 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5969 return ReplaceInstUsesWith(ICI, Result);
5970 } else {
5971 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5972 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5973 "ICmp should be folded!");
5974 if (Constant *CI = dyn_cast<Constant>(Result))
5975 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5976 else
5977 return BinaryOperator::createNot(Result);
5978 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00005979}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005980
Reid Spencer832254e2007-02-02 02:16:23 +00005981Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5982 return commonShiftTransforms(I);
5983}
5984
5985Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5986 return commonShiftTransforms(I);
5987}
5988
5989Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00005990 if (Instruction *R = commonShiftTransforms(I))
5991 return R;
5992
5993 Value *Op0 = I.getOperand(0);
5994
5995 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5996 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5997 if (CSI->isAllOnesValue())
5998 return ReplaceInstUsesWith(I, CSI);
5999
6000 // See if we can turn a signed shr into an unsigned shr.
6001 if (MaskedValueIsZero(Op0,
6002 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6003 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6004
6005 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006006}
6007
6008Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6009 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006010 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006011
6012 // shl X, 0 == X and shr X, 0 == X
6013 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006014 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006015 Op0 == Constant::getNullValue(Op0->getType()))
6016 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006017
Reid Spencere4d87aa2006-12-23 06:05:41 +00006018 if (isa<UndefValue>(Op0)) {
6019 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006020 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006021 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006022 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6023 }
6024 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006025 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6026 return ReplaceInstUsesWith(I, Op0);
6027 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006028 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006029 }
6030
Chris Lattner2eefe512004-04-09 19:05:30 +00006031 // Try to fold constant and into select arguments.
6032 if (isa<Constant>(Op0))
6033 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006034 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006035 return R;
6036
Reid Spencerb83eb642006-10-20 07:07:24 +00006037 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006038 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6039 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006040 return 0;
6041}
6042
Reid Spencerb83eb642006-10-20 07:07:24 +00006043Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006044 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006045 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006046
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006047 // See if we can simplify any instructions used by the instruction whose sole
6048 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006049 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6050 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6051 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006052 KnownZero, KnownOne))
6053 return &I;
6054
Chris Lattner4d5542c2006-01-06 07:12:35 +00006055 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6056 // of a signed value.
6057 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006058 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006059 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006060 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6061 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006062 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006063 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006064 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006065 }
6066
6067 // ((X*C1) << C2) == (X * (C1 << C2))
6068 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6069 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6070 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6071 return BinaryOperator::createMul(BO->getOperand(0),
6072 ConstantExpr::getShl(BOOp, Op1));
6073
6074 // Try to fold constant and into select arguments.
6075 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6076 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6077 return R;
6078 if (isa<PHINode>(Op0))
6079 if (Instruction *NV = FoldOpIntoPhi(I))
6080 return NV;
6081
Chris Lattner8999dd32007-12-22 09:07:47 +00006082 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6083 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6084 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6085 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6086 // place. Don't try to do this transformation in this case. Also, we
6087 // require that the input operand is a shift-by-constant so that we have
6088 // confidence that the shifts will get folded together. We could do this
6089 // xform in more cases, but it is unlikely to be profitable.
6090 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6091 isa<ConstantInt>(TrOp->getOperand(1))) {
6092 // Okay, we'll do this xform. Make the shift of shift.
6093 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6094 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6095 I.getName());
6096 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6097
6098 // For logical shifts, the truncation has the effect of making the high
6099 // part of the register be zeros. Emulate this by inserting an AND to
6100 // clear the top bits as needed. This 'and' will usually be zapped by
6101 // other xforms later if dead.
6102 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6103 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6104 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6105
6106 // The mask we constructed says what the trunc would do if occurring
6107 // between the shifts. We want to know the effect *after* the second
6108 // shift. We know that it is a logical shift by a constant, so adjust the
6109 // mask as appropriate.
6110 if (I.getOpcode() == Instruction::Shl)
6111 MaskV <<= Op1->getZExtValue();
6112 else {
6113 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6114 MaskV = MaskV.lshr(Op1->getZExtValue());
6115 }
6116
6117 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6118 TI->getName());
6119 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6120
6121 // Return the value truncated to the interesting size.
6122 return new TruncInst(And, I.getType());
6123 }
6124 }
6125
Chris Lattner4d5542c2006-01-06 07:12:35 +00006126 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006127 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6128 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6129 Value *V1, *V2;
6130 ConstantInt *CC;
6131 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006132 default: break;
6133 case Instruction::Add:
6134 case Instruction::And:
6135 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006136 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006137 // These operators commute.
6138 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006139 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6140 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006141 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006142 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006143 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006144 Op0BO->getName());
6145 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006146 Instruction *X =
6147 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6148 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006149 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006150 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006151 return BinaryOperator::createAnd(X, ConstantInt::get(
6152 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006153 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006154
Chris Lattner150f12a2005-09-18 06:30:59 +00006155 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006156 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006157 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006158 match(Op0BOOp1,
6159 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006160 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6161 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006162 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006163 Op0BO->getOperand(0), Op1,
6164 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006165 InsertNewInstBefore(YS, I); // (Y << C)
6166 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006167 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006168 V1->getName()+".mask");
6169 InsertNewInstBefore(XM, I); // X & (CC << C)
6170
6171 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6172 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006173 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006174
Reid Spencera07cb7d2007-02-02 14:41:37 +00006175 // FALL THROUGH.
6176 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006177 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006178 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6179 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006180 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006181 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006182 Op0BO->getOperand(1), Op1,
6183 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006184 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006185 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00006186 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006187 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006188 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006189 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006190 return BinaryOperator::createAnd(X, ConstantInt::get(
6191 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006192 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006193
Chris Lattner13d4ab42006-05-31 21:14:00 +00006194 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006195 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6196 match(Op0BO->getOperand(0),
6197 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006198 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006199 cast<BinaryOperator>(Op0BO->getOperand(0))
6200 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006201 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006202 Op0BO->getOperand(1), Op1,
6203 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006204 InsertNewInstBefore(YS, I); // (Y << C)
6205 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006206 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006207 V1->getName()+".mask");
6208 InsertNewInstBefore(XM, I); // X & (CC << C)
6209
Chris Lattner13d4ab42006-05-31 21:14:00 +00006210 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006211 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006212
Chris Lattner11021cb2005-09-18 05:12:10 +00006213 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006214 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006215 }
6216
6217
6218 // If the operand is an bitwise operator with a constant RHS, and the
6219 // shift is the only use, we can pull it out of the shift.
6220 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6221 bool isValid = true; // Valid only for And, Or, Xor
6222 bool highBitSet = false; // Transform if high bit of constant set?
6223
6224 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006225 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006226 case Instruction::Add:
6227 isValid = isLeftShift;
6228 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006229 case Instruction::Or:
6230 case Instruction::Xor:
6231 highBitSet = false;
6232 break;
6233 case Instruction::And:
6234 highBitSet = true;
6235 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006236 }
6237
6238 // If this is a signed shift right, and the high bit is modified
6239 // by the logical operation, do not perform the transformation.
6240 // The highBitSet boolean indicates the value of the high bit of
6241 // the constant which would cause it to be modified for this
6242 // operation.
6243 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006244 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006245 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006246
6247 if (isValid) {
6248 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6249
6250 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00006251 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006252 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006253 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006254
6255 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6256 NewRHS);
6257 }
6258 }
6259 }
6260 }
6261
Chris Lattnerad0124c2006-01-06 07:52:12 +00006262 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006263 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6264 if (ShiftOp && !ShiftOp->isShift())
6265 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006266
Reid Spencerb83eb642006-10-20 07:07:24 +00006267 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006268 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006269 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6270 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006271 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6272 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6273 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006274
Zhou Sheng4351c642007-04-02 08:20:41 +00006275 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006276 if (AmtSum > TypeBits)
6277 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006278
6279 const IntegerType *Ty = cast<IntegerType>(I.getType());
6280
6281 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006282 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006283 return BinaryOperator::create(I.getOpcode(), X,
6284 ConstantInt::get(Ty, AmtSum));
6285 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6286 I.getOpcode() == Instruction::AShr) {
6287 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6288 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6289 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6290 I.getOpcode() == Instruction::LShr) {
6291 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6292 Instruction *Shift =
6293 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6294 InsertNewInstBefore(Shift, I);
6295
Zhou Shenge9e03f62007-03-28 15:02:20 +00006296 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006297 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006298 }
6299
Chris Lattnerb87056f2007-02-05 00:57:54 +00006300 // Okay, if we get here, one shift must be left, and the other shift must be
6301 // right. See if the amounts are equal.
6302 if (ShiftAmt1 == ShiftAmt2) {
6303 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6304 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006305 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006306 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006307 }
6308 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6309 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006310 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006311 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006312 }
6313 // We can simplify ((X << C) >>s C) into a trunc + sext.
6314 // NOTE: we could do this for any C, but that would make 'unusual' integer
6315 // types. For now, just stick to ones well-supported by the code
6316 // generators.
6317 const Type *SExtType = 0;
6318 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006319 case 1 :
6320 case 8 :
6321 case 16 :
6322 case 32 :
6323 case 64 :
6324 case 128:
6325 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6326 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006327 default: break;
6328 }
6329 if (SExtType) {
6330 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6331 InsertNewInstBefore(NewTrunc, I);
6332 return new SExtInst(NewTrunc, Ty);
6333 }
6334 // Otherwise, we can't handle it yet.
6335 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006336 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006337
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006338 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006339 if (I.getOpcode() == Instruction::Shl) {
6340 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6341 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006342 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006343 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006344 InsertNewInstBefore(Shift, I);
6345
Reid Spencer55702aa2007-03-25 21:11:44 +00006346 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6347 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006348 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006349
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006350 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006351 if (I.getOpcode() == Instruction::LShr) {
6352 assert(ShiftOp->getOpcode() == Instruction::Shl);
6353 Instruction *Shift =
6354 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6355 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006356
Reid Spencerd5e30f02007-03-26 17:18:58 +00006357 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006358 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006359 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006360
6361 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6362 } else {
6363 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006364 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006365
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006366 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006367 if (I.getOpcode() == Instruction::Shl) {
6368 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6369 ShiftOp->getOpcode() == Instruction::AShr);
6370 Instruction *Shift =
6371 BinaryOperator::create(ShiftOp->getOpcode(), X,
6372 ConstantInt::get(Ty, ShiftDiff));
6373 InsertNewInstBefore(Shift, I);
6374
Reid Spencer55702aa2007-03-25 21:11:44 +00006375 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006376 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006377 }
6378
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006379 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006380 if (I.getOpcode() == Instruction::LShr) {
6381 assert(ShiftOp->getOpcode() == Instruction::Shl);
6382 Instruction *Shift =
6383 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6384 InsertNewInstBefore(Shift, I);
6385
Reid Spencer68d27cf2007-03-26 23:45:51 +00006386 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006387 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006388 }
6389
6390 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006391 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006392 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006393 return 0;
6394}
6395
Chris Lattnera1be5662002-05-02 17:06:02 +00006396
Chris Lattnercfd65102005-10-29 04:36:15 +00006397/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6398/// expression. If so, decompose it, returning some value X, such that Val is
6399/// X*Scale+Offset.
6400///
6401static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006402 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006403 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006404 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006405 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006406 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006407 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006408 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6409 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6410 if (I->getOpcode() == Instruction::Shl) {
6411 // This is a value scaled by '1 << the shift amt'.
6412 Scale = 1U << RHS->getZExtValue();
6413 Offset = 0;
6414 return I->getOperand(0);
6415 } else if (I->getOpcode() == Instruction::Mul) {
6416 // This value is scaled by 'RHS'.
6417 Scale = RHS->getZExtValue();
6418 Offset = 0;
6419 return I->getOperand(0);
6420 } else if (I->getOpcode() == Instruction::Add) {
6421 // We have X+C. Check to see if we really have (X*C2)+C1,
6422 // where C1 is divisible by C2.
6423 unsigned SubScale;
6424 Value *SubVal =
6425 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6426 Offset += RHS->getZExtValue();
6427 Scale = SubScale;
6428 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006429 }
6430 }
6431 }
6432
6433 // Otherwise, we can't look past this.
6434 Scale = 1;
6435 Offset = 0;
6436 return Val;
6437}
6438
6439
Chris Lattnerb3f83972005-10-24 06:03:58 +00006440/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6441/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006442Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006443 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006444 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006445
Chris Lattnerb53c2382005-10-24 06:22:12 +00006446 // Remove any uses of AI that are dead.
6447 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006448
Chris Lattnerb53c2382005-10-24 06:22:12 +00006449 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6450 Instruction *User = cast<Instruction>(*UI++);
6451 if (isInstructionTriviallyDead(User)) {
6452 while (UI != E && *UI == User)
6453 ++UI; // If this instruction uses AI more than once, don't break UI.
6454
Chris Lattnerb53c2382005-10-24 06:22:12 +00006455 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006456 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006457 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006458 }
6459 }
6460
Chris Lattnerb3f83972005-10-24 06:03:58 +00006461 // Get the type really allocated and the type casted to.
6462 const Type *AllocElTy = AI.getAllocatedType();
6463 const Type *CastElTy = PTy->getElementType();
6464 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006465
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006466 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6467 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006468 if (CastElTyAlign < AllocElTyAlign) return 0;
6469
Chris Lattner39387a52005-10-24 06:35:18 +00006470 // If the allocation has multiple uses, only promote it if we are strictly
6471 // increasing the alignment of the resultant allocation. If we keep it the
6472 // same, we open the door to infinite loops of various kinds.
6473 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6474
Duncan Sands514ab342007-11-01 20:53:16 +00006475 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6476 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006477 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006478
Chris Lattner455fcc82005-10-29 03:19:53 +00006479 // See if we can satisfy the modulus by pulling a scale out of the array
6480 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006481 unsigned ArraySizeScale;
6482 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006483 Value *NumElements = // See if the array size is a decomposable linear expr.
6484 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6485
Chris Lattner455fcc82005-10-29 03:19:53 +00006486 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6487 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006488 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6489 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006490
Chris Lattner455fcc82005-10-29 03:19:53 +00006491 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6492 Value *Amt = 0;
6493 if (Scale == 1) {
6494 Amt = NumElements;
6495 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006496 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006497 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6498 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006499 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006500 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006501 else if (Scale != 1) {
6502 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6503 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006504 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006505 }
6506
Jeff Cohen86796be2007-04-04 16:58:57 +00006507 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6508 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00006509 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6510 Amt = InsertNewInstBefore(Tmp, AI);
6511 }
6512
Chris Lattnerb3f83972005-10-24 06:03:58 +00006513 AllocationInst *New;
6514 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006515 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006516 else
Chris Lattner6934a042007-02-11 01:23:03 +00006517 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006518 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006519 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006520
6521 // If the allocation has multiple uses, insert a cast and change all things
6522 // that used it to use the new cast. This will also hack on CI, but it will
6523 // die soon.
6524 if (!AI.hasOneUse()) {
6525 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006526 // New is the allocation instruction, pointer typed. AI is the original
6527 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6528 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006529 InsertNewInstBefore(NewCast, AI);
6530 AI.replaceAllUsesWith(NewCast);
6531 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006532 return ReplaceInstUsesWith(CI, New);
6533}
6534
Chris Lattner70074e02006-05-13 02:06:03 +00006535/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006536/// and return it as type Ty without inserting any new casts and without
6537/// changing the computed value. This is used by code that tries to decide
6538/// whether promoting or shrinking integer operations to wider or smaller types
6539/// will allow us to eliminate a truncate or extend.
6540///
6541/// This is a truncation operation if Ty is smaller than V->getType(), or an
6542/// extension operation if Ty is larger.
6543static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner951626b2007-08-02 06:11:14 +00006544 unsigned CastOpc, int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006545 // We can always evaluate constants in another type.
6546 if (isa<ConstantInt>(V))
6547 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006548
6549 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006550 if (!I) return false;
6551
6552 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006553
Chris Lattner951626b2007-08-02 06:11:14 +00006554 // If this is an extension or truncate, we can often eliminate it.
6555 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6556 // If this is a cast from the destination type, we can trivially eliminate
6557 // it, and this will remove a cast overall.
6558 if (I->getOperand(0)->getType() == Ty) {
6559 // If the first operand is itself a cast, and is eliminable, do not count
6560 // this as an eliminable cast. We would prefer to eliminate those two
6561 // casts first.
6562 if (!isa<CastInst>(I->getOperand(0)))
6563 ++NumCastsRemoved;
6564 return true;
6565 }
6566 }
6567
6568 // We can't extend or shrink something that has multiple uses: doing so would
6569 // require duplicating the instruction in general, which isn't profitable.
6570 if (!I->hasOneUse()) return false;
6571
Chris Lattner70074e02006-05-13 02:06:03 +00006572 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006573 case Instruction::Add:
6574 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006575 case Instruction::And:
6576 case Instruction::Or:
6577 case Instruction::Xor:
6578 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006579 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6580 NumCastsRemoved) &&
6581 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6582 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006583
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006584 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006585 // A multiply can be truncated by truncating its operands.
6586 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6587 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6588 NumCastsRemoved) &&
6589 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6590 NumCastsRemoved);
6591
Chris Lattner46b96052006-11-29 07:18:39 +00006592 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006593 // If we are truncating the result of this SHL, and if it's a shift of a
6594 // constant amount, we can always perform a SHL in a smaller type.
6595 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006596 uint32_t BitWidth = Ty->getBitWidth();
6597 if (BitWidth < OrigTy->getBitWidth() &&
6598 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006599 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6600 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006601 }
6602 break;
6603 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006604 // If this is a truncate of a logical shr, we can truncate it to a smaller
6605 // lshr iff we know that the bits we would otherwise be shifting in are
6606 // already zeros.
6607 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006608 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6609 uint32_t BitWidth = Ty->getBitWidth();
6610 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006611 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006612 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6613 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006614 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6615 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006616 }
6617 }
Chris Lattner46b96052006-11-29 07:18:39 +00006618 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006619 case Instruction::ZExt:
6620 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006621 case Instruction::Trunc:
6622 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006623 // can safely replace it. Note that replacing it does not reduce the number
6624 // of casts in the input.
6625 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006626 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006627
Reid Spencer3da59db2006-11-27 01:05:10 +00006628 break;
6629 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006630 // TODO: Can handle more cases here.
6631 break;
6632 }
6633
6634 return false;
6635}
6636
6637/// EvaluateInDifferentType - Given an expression that
6638/// CanEvaluateInDifferentType returns true for, actually insert the code to
6639/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006640Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006641 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006642 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006643 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006644
6645 // Otherwise, it must be an instruction.
6646 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006647 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006648 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006649 case Instruction::Add:
6650 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006651 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006652 case Instruction::And:
6653 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006654 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006655 case Instruction::AShr:
6656 case Instruction::LShr:
6657 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006658 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006659 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6660 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6661 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006662 break;
6663 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006664 case Instruction::Trunc:
6665 case Instruction::ZExt:
6666 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006667 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006668 // just return the source. There's no need to insert it because it is not
6669 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006670 if (I->getOperand(0)->getType() == Ty)
6671 return I->getOperand(0);
6672
Chris Lattner951626b2007-08-02 06:11:14 +00006673 // Otherwise, must be the same type of case, so just reinsert a new one.
6674 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6675 Ty, I->getName());
6676 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006677 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006678 // TODO: Can handle more cases here.
6679 assert(0 && "Unreachable!");
6680 break;
6681 }
6682
6683 return InsertNewInstBefore(Res, *I);
6684}
6685
Reid Spencer3da59db2006-11-27 01:05:10 +00006686/// @brief Implement the transforms common to all CastInst visitors.
6687Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006688 Value *Src = CI.getOperand(0);
6689
Dan Gohman23d9d272007-05-11 21:10:54 +00006690 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00006691 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006692 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006693 if (Instruction::CastOps opc =
6694 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6695 // The first cast (CSrc) is eliminable so we need to fix up or replace
6696 // the second cast (CI). CSrc will then have a good chance of being dead.
6697 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006698 }
6699 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006700
Reid Spencer3da59db2006-11-27 01:05:10 +00006701 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006702 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6703 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6704 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006705
6706 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006707 if (isa<PHINode>(Src))
6708 if (Instruction *NV = FoldOpIntoPhi(CI))
6709 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006710
Reid Spencer3da59db2006-11-27 01:05:10 +00006711 return 0;
6712}
6713
Chris Lattnerd3e28342007-04-27 17:44:50 +00006714/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6715Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6716 Value *Src = CI.getOperand(0);
6717
Chris Lattnerd3e28342007-04-27 17:44:50 +00006718 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00006719 // If casting the result of a getelementptr instruction with no offset, turn
6720 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00006721 if (GEP->hasAllZeroIndices()) {
6722 // Changing the cast operand is usually not a good idea but it is safe
6723 // here because the pointer operand is being replaced with another
6724 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00006725 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00006726 CI.setOperand(0, GEP->getOperand(0));
6727 return &CI;
6728 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006729
6730 // If the GEP has a single use, and the base pointer is a bitcast, and the
6731 // GEP computes a constant offset, see if we can convert these three
6732 // instructions into fewer. This typically happens with unions and other
6733 // non-type-safe code.
6734 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6735 if (GEP->hasAllConstantIndices()) {
6736 // We are guaranteed to get a constant from EmitGEPOffset.
6737 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6738 int64_t Offset = OffsetV->getSExtValue();
6739
6740 // Get the base pointer input of the bitcast, and the type it points to.
6741 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6742 const Type *GEPIdxTy =
6743 cast<PointerType>(OrigBase->getType())->getElementType();
6744 if (GEPIdxTy->isSized()) {
6745 SmallVector<Value*, 8> NewIndices;
6746
Chris Lattnerc42e2262007-05-05 01:59:31 +00006747 // Start with the index over the outer type. Note that the type size
6748 // might be zero (even if the offset isn't zero) if the indexed type
6749 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00006750 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00006751 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00006752 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00006753 FirstIdx = Offset/TySize;
6754 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00006755
Chris Lattnerc42e2262007-05-05 01:59:31 +00006756 // Handle silly modulus not returning values values [0..TySize).
6757 if (Offset < 0) {
6758 --FirstIdx;
6759 Offset += TySize;
6760 assert(Offset >= 0);
6761 }
Chris Lattnerd717c182007-05-05 22:32:24 +00006762 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00006763 }
6764
6765 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00006766
6767 // Index into the types. If we fail, set OrigBase to null.
6768 while (Offset) {
6769 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6770 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006771 if (Offset < (int64_t)SL->getSizeInBytes()) {
6772 unsigned Elt = SL->getElementContainingOffset(Offset);
6773 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00006774
Chris Lattner6b6aef82007-05-15 00:16:00 +00006775 Offset -= SL->getElementOffset(Elt);
6776 GEPIdxTy = STy->getElementType(Elt);
6777 } else {
6778 // Otherwise, we can't index into this, bail out.
6779 Offset = 0;
6780 OrigBase = 0;
6781 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006782 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6783 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00006784 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00006785 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6786 Offset %= EltSize;
6787 } else {
6788 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6789 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006790 GEPIdxTy = STy->getElementType();
6791 } else {
6792 // Otherwise, we can't index into this, bail out.
6793 Offset = 0;
6794 OrigBase = 0;
6795 }
6796 }
6797 if (OrigBase) {
6798 // If we were able to index down into an element, create the GEP
6799 // and bitcast the result. This eliminates one bitcast, potentially
6800 // two.
David Greeneb8f74792007-09-04 15:46:09 +00006801 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6802 NewIndices.begin(),
6803 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00006804 InsertNewInstBefore(NGEP, CI);
6805 NGEP->takeName(GEP);
6806
Chris Lattner9bc14642007-04-28 00:57:34 +00006807 if (isa<BitCastInst>(CI))
6808 return new BitCastInst(NGEP, CI.getType());
6809 assert(isa<PtrToIntInst>(CI));
6810 return new PtrToIntInst(NGEP, CI.getType());
6811 }
6812 }
6813 }
6814 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00006815 }
6816
6817 return commonCastTransforms(CI);
6818}
6819
6820
6821
Chris Lattnerc739cd62007-03-03 05:27:34 +00006822/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6823/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006824/// cases.
6825/// @brief Implement the transforms common to CastInst with integer operands
6826Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6827 if (Instruction *Result = commonCastTransforms(CI))
6828 return Result;
6829
6830 Value *Src = CI.getOperand(0);
6831 const Type *SrcTy = Src->getType();
6832 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006833 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6834 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006835
Reid Spencer3da59db2006-11-27 01:05:10 +00006836 // See if we can simplify any instructions used by the LHS whose sole
6837 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00006838 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6839 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00006840 KnownZero, KnownOne))
6841 return &CI;
6842
6843 // If the source isn't an instruction or has more than one use then we
6844 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006845 Instruction *SrcI = dyn_cast<Instruction>(Src);
6846 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006847 return 0;
6848
Chris Lattnerc739cd62007-03-03 05:27:34 +00006849 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00006850 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00006851 if (!isa<BitCastInst>(CI) &&
6852 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00006853 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006854 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00006855 // eliminates the cast, so it is always a win. If this is a zero-extension,
6856 // we need to do an AND to maintain the clear top-part of the computation,
6857 // so we require that the input have eliminated at least one cast. If this
6858 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00006859 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00006860 bool DoXForm;
6861 switch (CI.getOpcode()) {
6862 default:
6863 // All the others use floating point so we shouldn't actually
6864 // get here because of the check above.
6865 assert(0 && "Unknown cast type");
6866 case Instruction::Trunc:
6867 DoXForm = true;
6868 break;
6869 case Instruction::ZExt:
6870 DoXForm = NumCastsRemoved >= 1;
6871 break;
6872 case Instruction::SExt:
6873 DoXForm = NumCastsRemoved >= 2;
6874 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006875 }
6876
6877 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00006878 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6879 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00006880 assert(Res->getType() == DestTy);
6881 switch (CI.getOpcode()) {
6882 default: assert(0 && "Unknown cast type!");
6883 case Instruction::Trunc:
6884 case Instruction::BitCast:
6885 // Just replace this cast with the result.
6886 return ReplaceInstUsesWith(CI, Res);
6887 case Instruction::ZExt: {
6888 // We need to emit an AND to clear the high bits.
6889 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00006890 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6891 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00006892 return BinaryOperator::createAnd(Res, C);
6893 }
6894 case Instruction::SExt:
6895 // We need to emit a cast to truncate, then a cast to sext.
6896 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00006897 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6898 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00006899 }
6900 }
6901 }
6902
6903 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6904 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6905
6906 switch (SrcI->getOpcode()) {
6907 case Instruction::Add:
6908 case Instruction::Mul:
6909 case Instruction::And:
6910 case Instruction::Or:
6911 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00006912 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00006913 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6914 // Don't insert two casts if they cannot be eliminated. We allow
6915 // two casts to be inserted if the sizes are the same. This could
6916 // only be converting signedness, which is a noop.
6917 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00006918 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6919 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00006920 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00006921 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6922 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6923 return BinaryOperator::create(
6924 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006925 }
6926 }
6927
6928 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6929 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6930 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006931 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006932 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006933 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006934 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6935 }
6936 break;
6937 case Instruction::SDiv:
6938 case Instruction::UDiv:
6939 case Instruction::SRem:
6940 case Instruction::URem:
6941 // If we are just changing the sign, rewrite.
6942 if (DestBitSize == SrcBitSize) {
6943 // Don't insert two casts if they cannot be eliminated. We allow
6944 // two casts to be inserted if the sizes are the same. This could
6945 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006946 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6947 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00006948 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6949 Op0, DestTy, SrcI);
6950 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6951 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006952 return BinaryOperator::create(
6953 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6954 }
6955 }
6956 break;
6957
6958 case Instruction::Shl:
6959 // Allow changing the sign of the source operand. Do not allow
6960 // changing the size of the shift, UNLESS the shift amount is a
6961 // constant. We must not change variable sized shifts to a smaller
6962 // size, because it is undefined to shift more bits out than exist
6963 // in the value.
6964 if (DestBitSize == SrcBitSize ||
6965 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006966 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6967 Instruction::BitCast : Instruction::Trunc);
6968 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00006969 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00006970 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006971 }
6972 break;
6973 case Instruction::AShr:
6974 // If this is a signed shr, and if all bits shifted in are about to be
6975 // truncated off, turn it into an unsigned shr to allow greater
6976 // simplifications.
6977 if (DestBitSize < SrcBitSize &&
6978 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006979 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00006980 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6981 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00006982 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00006983 }
6984 }
6985 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006986 }
6987 return 0;
6988}
6989
Chris Lattner8a9f5712007-04-11 06:57:46 +00006990Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006991 if (Instruction *Result = commonIntCastTransforms(CI))
6992 return Result;
6993
6994 Value *Src = CI.getOperand(0);
6995 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006996 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6997 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00006998
6999 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7000 switch (SrcI->getOpcode()) {
7001 default: break;
7002 case Instruction::LShr:
7003 // We can shrink lshr to something smaller if we know the bits shifted in
7004 // are already zeros.
7005 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007006 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007007
7008 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007009 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007010 Value* SrcIOp0 = SrcI->getOperand(0);
7011 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007012 if (ShAmt >= DestBitWidth) // All zeros.
7013 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7014
7015 // Okay, we can shrink this. Truncate the input, then return a new
7016 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007017 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7018 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7019 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007020 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007021 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007022 } else { // This is a variable shr.
7023
7024 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7025 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7026 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007027 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007028 Value *One = ConstantInt::get(SrcI->getType(), 1);
7029
Reid Spencer832254e2007-02-02 02:16:23 +00007030 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00007031 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007032 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007033 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7034 SrcI->getOperand(0),
7035 "tmp"), CI);
7036 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007037 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007038 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007039 }
7040 break;
7041 }
7042 }
7043
7044 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007045}
7046
Chris Lattner8a9f5712007-04-11 06:57:46 +00007047Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007048 // If one of the common conversion will work ..
7049 if (Instruction *Result = commonIntCastTransforms(CI))
7050 return Result;
7051
7052 Value *Src = CI.getOperand(0);
7053
7054 // If this is a cast of a cast
7055 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007056 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7057 // types and if the sizes are just right we can convert this into a logical
7058 // 'and' which will be much cheaper than the pair of casts.
7059 if (isa<TruncInst>(CSrc)) {
7060 // Get the sizes of the types involved
7061 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007062 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7063 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7064 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007065 // If we're actually extending zero bits and the trunc is a no-op
7066 if (MidSize < DstSize && SrcSize == DstSize) {
7067 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007068 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007069 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007070 Instruction *And =
7071 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7072 // Unfortunately, if the type changed, we need to cast it back.
7073 if (And->getType() != CI.getType()) {
7074 And->setName(CSrc->getName()+".mask");
7075 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00007076 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007077 }
7078 return And;
7079 }
7080 }
7081 }
7082
Chris Lattner66bc3252007-04-11 05:45:39 +00007083 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7084 // If we are just checking for a icmp eq of a single bit and zext'ing it
7085 // to an integer, then shift the bit to the appropriate place and then
7086 // cast to integer to avoid the comparison.
7087 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007088 const APInt &Op1CV = Op1C->getValue();
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007089
7090 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7091 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7092 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7093 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7094 Value *In = ICI->getOperand(0);
7095 Value *Sh = ConstantInt::get(In->getType(),
7096 In->getType()->getPrimitiveSizeInBits()-1);
7097 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007098 In->getName()+".lobit"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007099 CI);
7100 if (In->getType() != CI.getType())
7101 In = CastInst::createIntegerCast(In, CI.getType(),
7102 false/*ZExt*/, "tmp", &CI);
7103
7104 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7105 Constant *One = ConstantInt::get(In->getType(), 1);
7106 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007107 In->getName()+".not"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007108 CI);
7109 }
7110
7111 return ReplaceInstUsesWith(CI, In);
7112 }
7113
7114
7115
Chris Lattnerba417832007-04-11 06:12:58 +00007116 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7117 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7118 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7119 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7120 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7121 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7122 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7123 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Chris Lattner66bc3252007-04-11 05:45:39 +00007124 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7125 // This only works for EQ and NE
7126 ICI->isEquality()) {
7127 // If Op1C some other power of two, convert:
7128 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7129 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7130 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7131 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7132
7133 APInt KnownZeroMask(~KnownZero);
7134 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7135 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7136 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7137 // (X&4) == 2 --> false
7138 // (X&4) != 2 --> true
7139 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7140 Res = ConstantExpr::getZExt(Res, CI.getType());
7141 return ReplaceInstUsesWith(CI, Res);
7142 }
7143
7144 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7145 Value *In = ICI->getOperand(0);
7146 if (ShiftAmt) {
7147 // Perform a logical shr by shiftamt.
7148 // Insert the shift to put the result in the low bit.
7149 In = InsertNewInstBefore(
7150 BinaryOperator::createLShr(In,
7151 ConstantInt::get(In->getType(), ShiftAmt),
7152 In->getName()+".lobit"), CI);
7153 }
7154
7155 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7156 Constant *One = ConstantInt::get(In->getType(), 1);
7157 In = BinaryOperator::createXor(In, One, "tmp");
7158 InsertNewInstBefore(cast<Instruction>(In), CI);
7159 }
7160
7161 if (CI.getType() == In->getType())
7162 return ReplaceInstUsesWith(CI, In);
7163 else
7164 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7165 }
7166 }
7167 }
7168 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007169 return 0;
7170}
7171
Chris Lattner8a9f5712007-04-11 06:57:46 +00007172Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007173 if (Instruction *I = commonIntCastTransforms(CI))
7174 return I;
7175
Chris Lattner8a9f5712007-04-11 06:57:46 +00007176 Value *Src = CI.getOperand(0);
7177
7178 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7179 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7180 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7181 // If we are just checking for a icmp eq of a single bit and zext'ing it
7182 // to an integer, then shift the bit to the appropriate place and then
7183 // cast to integer to avoid the comparison.
7184 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7185 const APInt &Op1CV = Op1C->getValue();
7186
7187 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7188 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7189 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7190 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7191 Value *In = ICI->getOperand(0);
7192 Value *Sh = ConstantInt::get(In->getType(),
7193 In->getType()->getPrimitiveSizeInBits()-1);
7194 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007195 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007196 CI);
7197 if (In->getType() != CI.getType())
7198 In = CastInst::createIntegerCast(In, CI.getType(),
7199 true/*SExt*/, "tmp", &CI);
7200
7201 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7202 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7203 In->getName()+".not"), CI);
7204
7205 return ReplaceInstUsesWith(CI, In);
7206 }
7207 }
7208 }
7209
Chris Lattnerba417832007-04-11 06:12:58 +00007210 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007211}
7212
Chris Lattnerb7530652008-01-27 05:29:54 +00007213/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7214/// in the specified FP type without changing its value.
7215static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy,
7216 const fltSemantics &Sem) {
7217 APFloat F = CFP->getValueAPF();
7218 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7219 return ConstantFP::get(FPTy, F);
7220 return 0;
7221}
7222
7223/// LookThroughFPExtensions - If this is an fp extension instruction, look
7224/// through it until we get the source value.
7225static Value *LookThroughFPExtensions(Value *V) {
7226 if (Instruction *I = dyn_cast<Instruction>(V))
7227 if (I->getOpcode() == Instruction::FPExt)
7228 return LookThroughFPExtensions(I->getOperand(0));
7229
7230 // If this value is a constant, return the constant in the smallest FP type
7231 // that can accurately represent it. This allows us to turn
7232 // (float)((double)X+2.0) into x+2.0f.
7233 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7234 if (CFP->getType() == Type::PPC_FP128Ty)
7235 return V; // No constant folding of this.
7236 // See if the value can be truncated to float and then reextended.
7237 if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7238 return V;
7239 if (CFP->getType() == Type::DoubleTy)
7240 return V; // Won't shrink.
7241 if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7242 return V;
7243 // Don't try to shrink to various long double types.
7244 }
7245
7246 return V;
7247}
7248
7249Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7250 if (Instruction *I = commonCastTransforms(CI))
7251 return I;
7252
7253 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7254 // smaller than the destination type, we can eliminate the truncate by doing
7255 // the add as the smaller type. This applies to add/sub/mul/div as well as
7256 // many builtins (sqrt, etc).
7257 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7258 if (OpI && OpI->hasOneUse()) {
7259 switch (OpI->getOpcode()) {
7260 default: break;
7261 case Instruction::Add:
7262 case Instruction::Sub:
7263 case Instruction::Mul:
7264 case Instruction::FDiv:
7265 case Instruction::FRem:
7266 const Type *SrcTy = OpI->getType();
7267 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7268 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7269 if (LHSTrunc->getType() != SrcTy &&
7270 RHSTrunc->getType() != SrcTy) {
7271 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7272 // If the source types were both smaller than the destination type of
7273 // the cast, do this xform.
7274 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7275 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7276 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7277 CI.getType(), CI);
7278 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7279 CI.getType(), CI);
7280 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7281 }
7282 }
7283 break;
7284 }
7285 }
7286 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007287}
7288
7289Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7290 return commonCastTransforms(CI);
7291}
7292
7293Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007294 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007295}
7296
7297Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007298 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007299}
7300
7301Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7302 return commonCastTransforms(CI);
7303}
7304
7305Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7306 return commonCastTransforms(CI);
7307}
7308
7309Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007310 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007311}
7312
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007313Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7314 if (Instruction *I = commonCastTransforms(CI))
7315 return I;
7316
7317 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7318 if (!DestPointee->isSized()) return 0;
7319
7320 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7321 ConstantInt *Cst;
7322 Value *X;
7323 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7324 m_ConstantInt(Cst)))) {
7325 // If the source and destination operands have the same type, see if this
7326 // is a single-index GEP.
7327 if (X->getType() == CI.getType()) {
7328 // Get the size of the pointee type.
7329 uint64_t Size = TD->getABITypeSizeInBits(DestPointee);
7330
7331 // Convert the constant to intptr type.
7332 APInt Offset = Cst->getValue();
7333 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7334
7335 // If Offset is evenly divisible by Size, we can do this xform.
7336 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7337 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7338 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7339 }
7340 }
7341 // TODO: Could handle other cases, e.g. where add is indexing into field of
7342 // struct etc.
7343 } else if (CI.getOperand(0)->hasOneUse() &&
7344 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7345 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7346 // "inttoptr+GEP" instead of "add+intptr".
7347
7348 // Get the size of the pointee type.
7349 uint64_t Size = TD->getABITypeSize(DestPointee);
7350
7351 // Convert the constant to intptr type.
7352 APInt Offset = Cst->getValue();
7353 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7354
7355 // If Offset is evenly divisible by Size, we can do this xform.
7356 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7357 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7358
7359 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7360 "tmp"), CI);
7361 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7362 }
7363 }
7364 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007365}
7366
Chris Lattnerd3e28342007-04-27 17:44:50 +00007367Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007368 // If the operands are integer typed then apply the integer transforms,
7369 // otherwise just apply the common ones.
7370 Value *Src = CI.getOperand(0);
7371 const Type *SrcTy = Src->getType();
7372 const Type *DestTy = CI.getType();
7373
Chris Lattner42a75512007-01-15 02:27:26 +00007374 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007375 if (Instruction *Result = commonIntCastTransforms(CI))
7376 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007377 } else if (isa<PointerType>(SrcTy)) {
7378 if (Instruction *I = commonPointerCastTransforms(CI))
7379 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007380 } else {
7381 if (Instruction *Result = commonCastTransforms(CI))
7382 return Result;
7383 }
7384
7385
7386 // Get rid of casts from one type to the same type. These are useless and can
7387 // be replaced by the operand.
7388 if (DestTy == Src->getType())
7389 return ReplaceInstUsesWith(CI, Src);
7390
Reid Spencer3da59db2006-11-27 01:05:10 +00007391 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007392 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7393 const Type *DstElTy = DstPTy->getElementType();
7394 const Type *SrcElTy = SrcPTy->getElementType();
7395
7396 // If we are casting a malloc or alloca to a pointer to a type of the same
7397 // size, rewrite the allocation instruction to allocate the "right" type.
7398 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7399 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7400 return V;
7401
Chris Lattnerd717c182007-05-05 22:32:24 +00007402 // If the source and destination are pointers, and this cast is equivalent
7403 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007404 // This can enhance SROA and other transforms that want type-safe pointers.
7405 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7406 unsigned NumZeros = 0;
7407 while (SrcElTy != DstElTy &&
7408 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7409 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7410 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7411 ++NumZeros;
7412 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007413
Chris Lattnerd3e28342007-04-27 17:44:50 +00007414 // If we found a path from the src to dest, create the getelementptr now.
7415 if (SrcElTy == DstElTy) {
7416 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose IIIc331d302007-09-05 20:36:41 +00007417 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7418 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007419 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007420 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007421
Reid Spencer3da59db2006-11-27 01:05:10 +00007422 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7423 if (SVI->hasOneUse()) {
7424 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7425 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007426 if (isa<VectorType>(DestTy) &&
7427 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007428 SVI->getType()->getNumElements()) {
7429 CastInst *Tmp;
7430 // If either of the operands is a cast from CI.getType(), then
7431 // evaluating the shuffle in the casted destination's type will allow
7432 // us to eliminate at least one cast.
7433 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7434 Tmp->getOperand(0)->getType() == DestTy) ||
7435 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7436 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007437 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7438 SVI->getOperand(0), DestTy, &CI);
7439 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7440 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007441 // Return a new shuffle vector. Use the same element ID's, as we
7442 // know the vector types match #elts.
7443 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007444 }
7445 }
7446 }
7447 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007448 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007449}
7450
Chris Lattnere576b912004-04-09 23:46:01 +00007451/// GetSelectFoldableOperands - We want to turn code that looks like this:
7452/// %C = or %A, %B
7453/// %D = select %cond, %C, %A
7454/// into:
7455/// %C = select %cond, %B, 0
7456/// %D = or %A, %C
7457///
7458/// Assuming that the specified instruction is an operand to the select, return
7459/// a bitmask indicating which operands of this instruction are foldable if they
7460/// equal the other incoming value of the select.
7461///
7462static unsigned GetSelectFoldableOperands(Instruction *I) {
7463 switch (I->getOpcode()) {
7464 case Instruction::Add:
7465 case Instruction::Mul:
7466 case Instruction::And:
7467 case Instruction::Or:
7468 case Instruction::Xor:
7469 return 3; // Can fold through either operand.
7470 case Instruction::Sub: // Can only fold on the amount subtracted.
7471 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007472 case Instruction::LShr:
7473 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007474 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007475 default:
7476 return 0; // Cannot fold
7477 }
7478}
7479
7480/// GetSelectFoldableConstant - For the same transformation as the previous
7481/// function, return the identity constant that goes into the select.
7482static Constant *GetSelectFoldableConstant(Instruction *I) {
7483 switch (I->getOpcode()) {
7484 default: assert(0 && "This cannot happen!"); abort();
7485 case Instruction::Add:
7486 case Instruction::Sub:
7487 case Instruction::Or:
7488 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007489 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007490 case Instruction::LShr:
7491 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007492 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007493 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007494 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007495 case Instruction::Mul:
7496 return ConstantInt::get(I->getType(), 1);
7497 }
7498}
7499
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007500/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7501/// have the same opcode and only one use each. Try to simplify this.
7502Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7503 Instruction *FI) {
7504 if (TI->getNumOperands() == 1) {
7505 // If this is a non-volatile load or a cast from the same type,
7506 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007507 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007508 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7509 return 0;
7510 } else {
7511 return 0; // unknown unary op.
7512 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007513
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007514 // Fold this by inserting a select from the input values.
7515 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7516 FI->getOperand(0), SI.getName()+".v");
7517 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007518 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7519 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007520 }
7521
Reid Spencer832254e2007-02-02 02:16:23 +00007522 // Only handle binary operators here.
7523 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007524 return 0;
7525
7526 // Figure out if the operations have any operands in common.
7527 Value *MatchOp, *OtherOpT, *OtherOpF;
7528 bool MatchIsOpZero;
7529 if (TI->getOperand(0) == FI->getOperand(0)) {
7530 MatchOp = TI->getOperand(0);
7531 OtherOpT = TI->getOperand(1);
7532 OtherOpF = FI->getOperand(1);
7533 MatchIsOpZero = true;
7534 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7535 MatchOp = TI->getOperand(1);
7536 OtherOpT = TI->getOperand(0);
7537 OtherOpF = FI->getOperand(0);
7538 MatchIsOpZero = false;
7539 } else if (!TI->isCommutative()) {
7540 return 0;
7541 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7542 MatchOp = TI->getOperand(0);
7543 OtherOpT = TI->getOperand(1);
7544 OtherOpF = FI->getOperand(0);
7545 MatchIsOpZero = true;
7546 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7547 MatchOp = TI->getOperand(1);
7548 OtherOpT = TI->getOperand(0);
7549 OtherOpF = FI->getOperand(1);
7550 MatchIsOpZero = true;
7551 } else {
7552 return 0;
7553 }
7554
7555 // If we reach here, they do have operations in common.
7556 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7557 OtherOpF, SI.getName()+".v");
7558 InsertNewInstBefore(NewSI, SI);
7559
7560 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7561 if (MatchIsOpZero)
7562 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7563 else
7564 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007565 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007566 assert(0 && "Shouldn't get here");
7567 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007568}
7569
Chris Lattner3d69f462004-03-12 05:52:32 +00007570Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007571 Value *CondVal = SI.getCondition();
7572 Value *TrueVal = SI.getTrueValue();
7573 Value *FalseVal = SI.getFalseValue();
7574
7575 // select true, X, Y -> X
7576 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007577 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007578 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007579
7580 // select C, X, X -> X
7581 if (TrueVal == FalseVal)
7582 return ReplaceInstUsesWith(SI, TrueVal);
7583
Chris Lattnere87597f2004-10-16 18:11:37 +00007584 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7585 return ReplaceInstUsesWith(SI, FalseVal);
7586 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7587 return ReplaceInstUsesWith(SI, TrueVal);
7588 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7589 if (isa<Constant>(TrueVal))
7590 return ReplaceInstUsesWith(SI, TrueVal);
7591 else
7592 return ReplaceInstUsesWith(SI, FalseVal);
7593 }
7594
Reid Spencer4fe16d62007-01-11 18:21:29 +00007595 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007596 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007597 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007598 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007599 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007600 } else {
7601 // Change: A = select B, false, C --> A = and !B, C
7602 Value *NotCond =
7603 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7604 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007605 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007606 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007607 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007608 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007609 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007610 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007611 } else {
7612 // Change: A = select B, C, true --> A = or !B, C
7613 Value *NotCond =
7614 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7615 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007616 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007617 }
7618 }
Chris Lattnercfa59752007-11-25 21:27:53 +00007619
7620 // select a, b, a -> a&b
7621 // select a, a, b -> a|b
7622 if (CondVal == TrueVal)
7623 return BinaryOperator::createOr(CondVal, FalseVal);
7624 else if (CondVal == FalseVal)
7625 return BinaryOperator::createAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007626 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007627
Chris Lattner2eefe512004-04-09 19:05:30 +00007628 // Selecting between two integer constants?
7629 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7630 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00007631 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00007632 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007633 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00007634 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00007635 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00007636 Value *NotCond =
7637 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007638 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007639 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007640 }
Chris Lattnerba417832007-04-11 06:12:58 +00007641
7642 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00007643
Reid Spencere4d87aa2006-12-23 06:05:41 +00007644 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007645
Reid Spencere4d87aa2006-12-23 06:05:41 +00007646 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00007647 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00007648 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007649 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007650 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00007651 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00007652 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007653 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00007654 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7655 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7656 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00007657 InsertNewInstBefore(SRA, SI);
7658
Reid Spencer3da59db2006-11-27 01:05:10 +00007659 // Finally, convert to the type of the select RHS. We figure out
7660 // if this requires a SExt, Trunc or BitCast based on the sizes.
7661 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00007662 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7663 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007664 if (SRASize < SISize)
7665 opc = Instruction::SExt;
7666 else if (SRASize > SISize)
7667 opc = Instruction::Trunc;
7668 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00007669 }
7670 }
7671
7672
7673 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00007674 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00007675 // non-constant value, eliminate this whole mess. This corresponds to
7676 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00007677 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00007678 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007679 cast<Constant>(IC->getOperand(1))->isNullValue())
7680 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7681 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007682 isa<ConstantInt>(ICA->getOperand(1)) &&
7683 (ICA->getOperand(1) == TrueValC ||
7684 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007685 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7686 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00007687 // know whether we have a icmp_ne or icmp_eq and whether the
7688 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00007689 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007690 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00007691 Value *V = ICA;
7692 if (ShouldNotVal)
7693 V = InsertNewInstBefore(BinaryOperator::create(
7694 Instruction::Xor, V, ICA->getOperand(1)), SI);
7695 return ReplaceInstUsesWith(SI, V);
7696 }
Chris Lattnerb8456462006-09-20 04:44:59 +00007697 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007698 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007699
7700 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007701 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7702 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00007703 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007704 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7705 // This is not safe in general for floating point:
7706 // consider X== -0, Y== +0.
7707 // It becomes safe if either operand is a nonzero constant.
7708 ConstantFP *CFPt, *CFPf;
7709 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7710 !CFPt->getValueAPF().isZero()) ||
7711 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7712 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00007713 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007714 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007715 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007716 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007717 return ReplaceInstUsesWith(SI, TrueVal);
7718 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7719
Reid Spencere4d87aa2006-12-23 06:05:41 +00007720 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00007721 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007722 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7723 // This is not safe in general for floating point:
7724 // consider X== -0, Y== +0.
7725 // It becomes safe if either operand is a nonzero constant.
7726 ConstantFP *CFPt, *CFPf;
7727 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7728 !CFPt->getValueAPF().isZero()) ||
7729 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7730 !CFPf->getValueAPF().isZero()))
7731 return ReplaceInstUsesWith(SI, FalseVal);
7732 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007733 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007734 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7735 return ReplaceInstUsesWith(SI, TrueVal);
7736 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7737 }
7738 }
7739
7740 // See if we are selecting two values based on a comparison of the two values.
7741 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7742 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7743 // Transform (X == Y) ? X : Y -> Y
7744 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7745 return ReplaceInstUsesWith(SI, FalseVal);
7746 // Transform (X != Y) ? X : Y -> X
7747 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7748 return ReplaceInstUsesWith(SI, TrueVal);
7749 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7750
7751 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7752 // Transform (X == Y) ? Y : X -> X
7753 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7754 return ReplaceInstUsesWith(SI, FalseVal);
7755 // Transform (X != Y) ? Y : X -> Y
7756 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00007757 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007758 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7759 }
7760 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007761
Chris Lattner87875da2005-01-13 22:52:24 +00007762 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7763 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7764 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00007765 Instruction *AddOp = 0, *SubOp = 0;
7766
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007767 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7768 if (TI->getOpcode() == FI->getOpcode())
7769 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7770 return IV;
7771
7772 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7773 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00007774 if (TI->getOpcode() == Instruction::Sub &&
7775 FI->getOpcode() == Instruction::Add) {
7776 AddOp = FI; SubOp = TI;
7777 } else if (FI->getOpcode() == Instruction::Sub &&
7778 TI->getOpcode() == Instruction::Add) {
7779 AddOp = TI; SubOp = FI;
7780 }
7781
7782 if (AddOp) {
7783 Value *OtherAddOp = 0;
7784 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7785 OtherAddOp = AddOp->getOperand(1);
7786 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7787 OtherAddOp = AddOp->getOperand(0);
7788 }
7789
7790 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00007791 // So at this point we know we have (Y -> OtherAddOp):
7792 // select C, (add X, Y), (sub X, Z)
7793 Value *NegVal; // Compute -Z
7794 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7795 NegVal = ConstantExpr::getNeg(C);
7796 } else {
7797 NegVal = InsertNewInstBefore(
7798 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00007799 }
Chris Lattner97f37a42006-02-24 18:05:58 +00007800
7801 Value *NewTrueOp = OtherAddOp;
7802 Value *NewFalseOp = NegVal;
7803 if (AddOp != TI)
7804 std::swap(NewTrueOp, NewFalseOp);
7805 Instruction *NewSel =
7806 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7807
7808 NewSel = InsertNewInstBefore(NewSel, SI);
7809 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00007810 }
7811 }
7812 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007813
Chris Lattnere576b912004-04-09 23:46:01 +00007814 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00007815 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00007816 // See the comment above GetSelectFoldableOperands for a description of the
7817 // transformation we are doing here.
7818 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7819 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7820 !isa<Constant>(FalseVal))
7821 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7822 unsigned OpToFold = 0;
7823 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7824 OpToFold = 1;
7825 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7826 OpToFold = 2;
7827 }
7828
7829 if (OpToFold) {
7830 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007831 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007832 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00007833 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007834 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007835 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7836 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00007837 else {
7838 assert(0 && "Unknown instruction!!");
7839 }
7840 }
7841 }
Chris Lattnera96879a2004-09-29 17:40:11 +00007842
Chris Lattnere576b912004-04-09 23:46:01 +00007843 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7844 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7845 !isa<Constant>(TrueVal))
7846 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7847 unsigned OpToFold = 0;
7848 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7849 OpToFold = 1;
7850 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7851 OpToFold = 2;
7852 }
7853
7854 if (OpToFold) {
7855 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007856 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007857 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00007858 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007859 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007860 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7861 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00007862 else
Chris Lattnere576b912004-04-09 23:46:01 +00007863 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00007864 }
7865 }
7866 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00007867
7868 if (BinaryOperator::isNot(CondVal)) {
7869 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7870 SI.setOperand(1, FalseVal);
7871 SI.setOperand(2, TrueVal);
7872 return &SI;
7873 }
7874
Chris Lattner3d69f462004-03-12 05:52:32 +00007875 return 0;
7876}
7877
Chris Lattnerf2369f22007-08-09 19:05:49 +00007878/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7879/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
7880/// and it is more than the alignment of the ultimate object, see if we can
7881/// increase the alignment of the ultimate object, making this check succeed.
7882static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7883 unsigned PrefAlign = 0) {
Chris Lattner95a959d2006-03-06 20:18:44 +00007884 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7885 unsigned Align = GV->getAlignment();
Andrew Lenharthb410df92007-11-08 18:45:15 +00007886 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007887 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattnerf2369f22007-08-09 19:05:49 +00007888
7889 // If there is a large requested alignment and we can, bump up the alignment
7890 // of the global.
7891 if (PrefAlign > Align && GV->hasInitializer()) {
7892 GV->setAlignment(PrefAlign);
7893 Align = PrefAlign;
7894 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007895 return Align;
7896 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7897 unsigned Align = AI->getAlignment();
7898 if (Align == 0 && TD) {
7899 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007900 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007901 else if (isa<MallocInst>(AI)) {
7902 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007903 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00007904 Align =
7905 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007906 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00007907 Align =
7908 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007909 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00007910 }
7911 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00007912
7913 // If there is a requested alignment and if this is an alloca, round up. We
7914 // don't do this for malloc, because some systems can't respect the request.
7915 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7916 AI->setAlignment(PrefAlign);
7917 Align = PrefAlign;
7918 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007919 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00007920 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00007921 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00007922 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00007923 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7924 TD, PrefAlign);
Chris Lattner9bc14642007-04-28 00:57:34 +00007925 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Chris Lattner95a959d2006-03-06 20:18:44 +00007926 // If all indexes are zero, it is just the alignment of the base pointer.
7927 bool AllZeroOperands = true;
7928 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7929 if (!isa<Constant>(GEPI->getOperand(i)) ||
7930 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7931 AllZeroOperands = false;
7932 break;
7933 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00007934
7935 if (AllZeroOperands) {
7936 // Treat this like a bitcast.
7937 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7938 }
7939
7940 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7941 if (BaseAlignment == 0) return 0;
7942
Chris Lattner95a959d2006-03-06 20:18:44 +00007943 // Otherwise, if the base alignment is >= the alignment we expect for the
7944 // base pointer type, then we know that the resultant pointer is aligned at
7945 // least as much as its type requires.
7946 if (!TD) return 0;
7947
7948 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007949 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00007950 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7951 if (Align <= BaseAlignment) {
Chris Lattner51c26e92006-03-07 01:28:57 +00007952 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007953 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00007954 Align = std::min(Align, (unsigned)
7955 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7956 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00007957 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007958 return 0;
7959 }
7960 return 0;
7961}
7962
Chris Lattnerf497b022008-01-13 23:50:23 +00007963Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
7964 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
7965 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
7966 unsigned MinAlign = std::min(DstAlign, SrcAlign);
7967 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
7968
7969 if (CopyAlign < MinAlign) {
7970 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
7971 return MI;
7972 }
7973
7974 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
7975 // load/store.
7976 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
7977 if (MemOpLength == 0) return 0;
7978
Chris Lattner37ac6082008-01-14 00:28:35 +00007979 // Source and destination pointer types are always "i8*" for intrinsic. See
7980 // if the size is something we can handle with a single primitive load/store.
7981 // A single load+store correctly handles overlapping memory in the memmove
7982 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00007983 unsigned Size = MemOpLength->getZExtValue();
7984 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00007985 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00007986
Chris Lattner37ac6082008-01-14 00:28:35 +00007987 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00007988 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00007989
7990 // Memcpy forces the use of i8* for the source and destination. That means
7991 // that if you're using memcpy to move one double around, you'll get a cast
7992 // from double* to i8*. We'd much rather use a double load+store rather than
7993 // an i64 load+store, here because this improves the odds that the source or
7994 // dest address will be promotable. See if we can find a better type than the
7995 // integer datatype.
7996 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
7997 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
7998 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
7999 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8000 // down through these levels if so.
8001 while (!SrcETy->isFirstClassType()) {
8002 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8003 if (STy->getNumElements() == 1)
8004 SrcETy = STy->getElementType(0);
8005 else
8006 break;
8007 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8008 if (ATy->getNumElements() == 1)
8009 SrcETy = ATy->getElementType();
8010 else
8011 break;
8012 } else
8013 break;
8014 }
8015
8016 if (SrcETy->isFirstClassType())
8017 NewPtrTy = PointerType::getUnqual(SrcETy);
8018 }
8019 }
8020
8021
Chris Lattnerf497b022008-01-13 23:50:23 +00008022 // If the memcpy/memmove provides better alignment info than we can
8023 // infer, use it.
8024 SrcAlign = std::max(SrcAlign, CopyAlign);
8025 DstAlign = std::max(DstAlign, CopyAlign);
8026
8027 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8028 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008029 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8030 InsertNewInstBefore(L, *MI);
8031 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8032
8033 // Set the size of the copy to 0, it will be deleted on the next iteration.
8034 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8035 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008036}
Chris Lattner3d69f462004-03-12 05:52:32 +00008037
Chris Lattner8b0ea312006-01-13 20:11:04 +00008038/// visitCallInst - CallInst simplification. This mostly only handles folding
8039/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8040/// the heavy lifting.
8041///
Chris Lattner9fe38862003-06-19 17:00:31 +00008042Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008043 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8044 if (!II) return visitCallSite(&CI);
8045
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008046 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8047 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008048 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008049 bool Changed = false;
8050
8051 // memmove/cpy/set of zero bytes is a noop.
8052 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8053 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8054
Chris Lattner35b9e482004-10-12 04:52:52 +00008055 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008056 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008057 // Replace the instruction with just byte operations. We would
8058 // transform other cases to loads/stores, but we don't know if
8059 // alignment is sufficient.
8060 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008061 }
8062
Chris Lattner35b9e482004-10-12 04:52:52 +00008063 // If we have a memmove and the source operation is a constant global,
8064 // then the source and dest pointers can't alias, so we can change this
8065 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008066 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008067 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8068 if (GVSrc->isConstant()) {
8069 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008070 Intrinsic::ID MemCpyID;
8071 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8072 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008073 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008074 MemCpyID = Intrinsic::memcpy_i64;
8075 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008076 Changed = true;
8077 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008078 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008079
Chris Lattner95a959d2006-03-06 20:18:44 +00008080 // If we can determine a pointer alignment that is bigger than currently
8081 // set, update the alignment.
8082 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008083 if (Instruction *I = SimplifyMemTransfer(MI))
8084 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008085 } else if (isa<MemSetInst>(MI)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008086 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00008087 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008088 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00008089 Changed = true;
8090 }
8091 }
8092
Chris Lattner8b0ea312006-01-13 20:11:04 +00008093 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008094 } else {
8095 switch (II->getIntrinsicID()) {
8096 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008097 case Intrinsic::ppc_altivec_lvx:
8098 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008099 case Intrinsic::x86_sse_loadu_ps:
8100 case Intrinsic::x86_sse2_loadu_pd:
8101 case Intrinsic::x86_sse2_loadu_dq:
8102 // Turn PPC lvx -> load if the pointer is known aligned.
8103 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008104 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008105 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8106 PointerType::getUnqual(II->getType()),
8107 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008108 return new LoadInst(Ptr);
8109 }
8110 break;
8111 case Intrinsic::ppc_altivec_stvx:
8112 case Intrinsic::ppc_altivec_stvxl:
8113 // Turn stvx -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008114 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008115 const Type *OpPtrTy =
8116 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008117 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008118 return new StoreInst(II->getOperand(1), Ptr);
8119 }
8120 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008121 case Intrinsic::x86_sse_storeu_ps:
8122 case Intrinsic::x86_sse2_storeu_pd:
8123 case Intrinsic::x86_sse2_storeu_dq:
8124 case Intrinsic::x86_sse2_storel_dq:
8125 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008126 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008127 const Type *OpPtrTy =
8128 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008129 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008130 return new StoreInst(II->getOperand(2), Ptr);
8131 }
8132 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008133
8134 case Intrinsic::x86_sse_cvttss2si: {
8135 // These intrinsics only demands the 0th element of its input vector. If
8136 // we can simplify the input based on that, do so now.
8137 uint64_t UndefElts;
8138 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8139 UndefElts)) {
8140 II->setOperand(1, V);
8141 return II;
8142 }
8143 break;
8144 }
8145
Chris Lattnere2ed0572006-04-06 19:19:17 +00008146 case Intrinsic::ppc_altivec_vperm:
8147 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008148 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008149 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8150
8151 // Check that all of the elements are integer constants or undefs.
8152 bool AllEltsOk = true;
8153 for (unsigned i = 0; i != 16; ++i) {
8154 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8155 !isa<UndefValue>(Mask->getOperand(i))) {
8156 AllEltsOk = false;
8157 break;
8158 }
8159 }
8160
8161 if (AllEltsOk) {
8162 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008163 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8164 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008165 Value *Result = UndefValue::get(Op0->getType());
8166
8167 // Only extract each element once.
8168 Value *ExtractedElts[32];
8169 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8170
8171 for (unsigned i = 0; i != 16; ++i) {
8172 if (isa<UndefValue>(Mask->getOperand(i)))
8173 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008174 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008175 Idx &= 31; // Match the hardware behavior.
8176
8177 if (ExtractedElts[Idx] == 0) {
8178 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008179 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008180 InsertNewInstBefore(Elt, CI);
8181 ExtractedElts[Idx] = Elt;
8182 }
8183
8184 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00008185 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008186 InsertNewInstBefore(cast<Instruction>(Result), CI);
8187 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008188 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008189 }
8190 }
8191 break;
8192
Chris Lattnera728ddc2006-01-13 21:28:09 +00008193 case Intrinsic::stackrestore: {
8194 // If the save is right next to the restore, remove the restore. This can
8195 // happen when variable allocas are DCE'd.
8196 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8197 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8198 BasicBlock::iterator BI = SS;
8199 if (&*++BI == II)
8200 return EraseInstFromFunction(CI);
8201 }
8202 }
8203
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008204 // Scan down this block to see if there is another stack restore in the
8205 // same block without an intervening call/alloca.
8206 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008207 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008208 bool CannotRemove = false;
8209 for (++BI; &*BI != TI; ++BI) {
8210 if (isa<AllocaInst>(BI)) {
8211 CannotRemove = true;
8212 break;
8213 }
8214 if (isa<CallInst>(BI)) {
8215 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008216 CannotRemove = true;
8217 break;
8218 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008219 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008220 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008221 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008222 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008223
8224 // If the stack restore is in a return/unwind block and if there are no
8225 // allocas or calls between the restore and the return, nuke the restore.
8226 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8227 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008228 break;
8229 }
8230 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008231 }
8232
Chris Lattner8b0ea312006-01-13 20:11:04 +00008233 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008234}
8235
8236// InvokeInst simplification
8237//
8238Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008239 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008240}
8241
Chris Lattnera44d8a22003-10-07 22:32:43 +00008242// visitCallSite - Improvements for call and invoke instructions.
8243//
8244Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008245 bool Changed = false;
8246
8247 // If the callee is a constexpr cast of a function, attempt to move the cast
8248 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008249 if (transformConstExprCastCall(CS)) return 0;
8250
Chris Lattner6c266db2003-10-07 22:54:13 +00008251 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008252
Chris Lattner08b22ec2005-05-13 07:09:09 +00008253 if (Function *CalleeF = dyn_cast<Function>(Callee))
8254 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8255 Instruction *OldCall = CS.getInstruction();
8256 // If the call and callee calling conventions don't match, this call must
8257 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008258 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008259 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8260 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008261 if (!OldCall->use_empty())
8262 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8263 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8264 return EraseInstFromFunction(*OldCall);
8265 return 0;
8266 }
8267
Chris Lattner17be6352004-10-18 02:59:09 +00008268 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8269 // This instruction is not reachable, just remove it. We insert a store to
8270 // undef so that we know that this code is not reachable, despite the fact
8271 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008272 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008273 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008274 CS.getInstruction());
8275
8276 if (!CS.getInstruction()->use_empty())
8277 CS.getInstruction()->
8278 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8279
8280 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8281 // Don't break the CFG, insert a dummy cond branch.
8282 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008283 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008284 }
Chris Lattner17be6352004-10-18 02:59:09 +00008285 return EraseInstFromFunction(*CS.getInstruction());
8286 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008287
Duncan Sandscdb6d922007-09-17 10:26:40 +00008288 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8289 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8290 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8291 return transformCallThroughTrampoline(CS);
8292
Chris Lattner6c266db2003-10-07 22:54:13 +00008293 const PointerType *PTy = cast<PointerType>(Callee->getType());
8294 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8295 if (FTy->isVarArg()) {
8296 // See if we can optimize any arguments passed through the varargs area of
8297 // the call.
8298 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8299 E = CS.arg_end(); I != E; ++I)
8300 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8301 // If this cast does not effect the value passed through the varargs
8302 // area, we can eliminate the use of the cast.
8303 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00008304 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008305 *I = Op;
8306 Changed = true;
8307 }
8308 }
8309 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008310
Duncan Sandsf0c33542007-12-19 21:13:37 +00008311 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008312 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008313 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008314 Changed = true;
8315 }
8316
Chris Lattner6c266db2003-10-07 22:54:13 +00008317 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008318}
8319
Chris Lattner9fe38862003-06-19 17:00:31 +00008320// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8321// attempt to move the cast to the arguments of the call/invoke.
8322//
8323bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8324 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8325 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008326 if (CE->getOpcode() != Instruction::BitCast ||
8327 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008328 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008329 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008330 Instruction *Caller = CS.getInstruction();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008331 const ParamAttrsList* CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008332
8333 // Okay, this is a cast from a function to a different type. Unless doing so
8334 // would cause a type conversion of one of our arguments, change this call to
8335 // be a direct call with arguments casted to the appropriate types.
8336 //
8337 const FunctionType *FT = Callee->getFunctionType();
8338 const Type *OldRetTy = Caller->getType();
8339
Chris Lattnerf78616b2004-01-14 06:06:08 +00008340 // Check to see if we are changing the return type...
8341 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00008342 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008343 // Conversion is ok if changing from pointer to int of same size.
8344 !(isa<PointerType>(FT->getReturnType()) &&
8345 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008346 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008347
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008348 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008349 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008350 FT->getReturnType() != Type::VoidTy &&
8351 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008352 return false; // Cannot transform this return value.
8353
Duncan Sands6c3470e2008-01-07 17:16:06 +00008354 if (CallerPAL && !Caller->use_empty()) {
8355 uint16_t RAttrs = CallerPAL->getParamAttrs(0);
8356 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8357 return false; // Attribute not compatible with transformed value.
8358 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008359
Chris Lattnerf78616b2004-01-14 06:06:08 +00008360 // If the callsite is an invoke instruction, and the return value is used by
8361 // a PHI node in a successor, we cannot change the return type of the call
8362 // because there is no place to put the cast instruction (without breaking
8363 // the critical edge). Bail out in this case.
8364 if (!Caller->use_empty())
8365 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8366 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8367 UI != E; ++UI)
8368 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8369 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008370 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008371 return false;
8372 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008373
8374 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8375 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008376
Chris Lattner9fe38862003-06-19 17:00:31 +00008377 CallSite::arg_iterator AI = CS.arg_begin();
8378 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8379 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008380 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008381
8382 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008383 return false; // Cannot transform this parameter value.
8384
Duncan Sands6c3470e2008-01-07 17:16:06 +00008385 if (CallerPAL) {
8386 uint16_t PAttrs = CallerPAL->getParamAttrs(i + 1);
8387 if (PAttrs & ParamAttr::typeIncompatible(ParamTy))
8388 return false; // Attribute not compatible with transformed value.
8389 }
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008390
Reid Spencer3da59db2006-11-27 01:05:10 +00008391 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008392 // Some conversions are safe even if we do not have a body.
8393 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00008394 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00008395 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00008396 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008397 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8398 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00008399 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00008400 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008401 }
8402
8403 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008404 Callee->isDeclaration())
Chris Lattner9fe38862003-06-19 17:00:31 +00008405 return false; // Do not delete arguments unless we have a function body...
8406
Duncan Sandse1e520f2008-01-13 08:02:44 +00008407 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && CallerPAL)
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008408 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008409 // won't be dropping them. Check that these extra arguments have attributes
8410 // that are compatible with being a vararg call argument.
8411 for (unsigned i = CallerPAL->size(); i; --i) {
8412 if (CallerPAL->getParamIndex(i - 1) <= FT->getNumParams())
8413 break;
8414 uint16_t PAttrs = CallerPAL->getParamAttrsAtIndex(i - 1);
8415 if (PAttrs & ParamAttr::VarArgsIncompatible)
8416 return false;
8417 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008418
Chris Lattner9fe38862003-06-19 17:00:31 +00008419 // Okay, we decided that this is a safe thing to do: go ahead and start
8420 // inserting cast instructions as necessary...
8421 std::vector<Value*> Args;
8422 Args.reserve(NumActualArgs);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008423 ParamAttrsVector attrVec;
8424 attrVec.reserve(NumCommonArgs);
8425
8426 // Get any return attributes.
8427 uint16_t RAttrs = CallerPAL ? CallerPAL->getParamAttrs(0) : 0;
8428
8429 // If the return value is not being used, the type may not be compatible
8430 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00008431 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008432
8433 // Add the new return attributes.
8434 if (RAttrs)
8435 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008436
8437 AI = CS.arg_begin();
8438 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8439 const Type *ParamTy = FT->getParamType(i);
8440 if ((*AI)->getType() == ParamTy) {
8441 Args.push_back(*AI);
8442 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008443 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008444 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008445 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008446 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008447 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008448
8449 // Add any parameter attributes.
8450 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8451 if (PAttrs)
8452 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008453 }
8454
8455 // If the function takes more arguments than the call was taking, add them
8456 // now...
8457 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8458 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8459
8460 // If we are removing arguments to the function, emit an obnoxious warning...
8461 if (FT->getNumParams() < NumActualArgs)
8462 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008463 cerr << "WARNING: While resolving call to function '"
8464 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008465 } else {
8466 // Add all of the arguments in their promoted form to the arg list...
8467 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8468 const Type *PTy = getPromotedType((*AI)->getType());
8469 if (PTy != (*AI)->getType()) {
8470 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008471 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8472 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008473 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008474 InsertNewInstBefore(Cast, *Caller);
8475 Args.push_back(Cast);
8476 } else {
8477 Args.push_back(*AI);
8478 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008479
Duncan Sandse1e520f2008-01-13 08:02:44 +00008480 // Add any parameter attributes.
8481 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8482 if (PAttrs)
8483 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8484 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008485 }
8486
8487 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008488 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008489
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008490 const ParamAttrsList* NewCallerPAL = ParamAttrsList::get(attrVec);
8491
Chris Lattner9fe38862003-06-19 17:00:31 +00008492 Instruction *NC;
8493 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008494 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greenef1355a52007-08-27 19:04:21 +00008495 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008496 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008497 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008498 } else {
Chris Lattner684b22d2007-08-02 16:53:43 +00008499 NC = new CallInst(Callee, Args.begin(), Args.end(),
8500 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008501 CallInst *CI = cast<CallInst>(Caller);
8502 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008503 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008504 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008505 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008506 }
8507
Chris Lattner6934a042007-02-11 01:23:03 +00008508 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008509 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008510 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008511 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008512 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008513 OldRetTy, false);
8514 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008515
8516 // If this is an invoke instruction, we should insert it after the first
8517 // non-phi, instruction in the normal successor block.
8518 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8519 BasicBlock::iterator I = II->getNormalDest()->begin();
8520 while (isa<PHINode>(I)) ++I;
8521 InsertNewInstBefore(NC, *I);
8522 } else {
8523 // Otherwise, it's a call, just insert cast right after the call instr
8524 InsertNewInstBefore(NC, *Caller);
8525 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008526 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008527 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008528 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008529 }
8530 }
8531
8532 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8533 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008534 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008535 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008536 return true;
8537}
8538
Duncan Sandscdb6d922007-09-17 10:26:40 +00008539// transformCallThroughTrampoline - Turn a call to a function created by the
8540// init_trampoline intrinsic into a direct call to the underlying function.
8541//
8542Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8543 Value *Callee = CS.getCalledValue();
8544 const PointerType *PTy = cast<PointerType>(Callee->getType());
8545 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008546 const ParamAttrsList *Attrs = CS.getParamAttrs();
8547
8548 // If the call already has the 'nest' attribute somewhere then give up -
8549 // otherwise 'nest' would occur twice after splicing in the chain.
8550 if (Attrs && Attrs->hasAttrSomewhere(ParamAttr::Nest))
8551 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008552
8553 IntrinsicInst *Tramp =
8554 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8555
8556 Function *NestF =
8557 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8558 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8559 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8560
Duncan Sandsdc024672007-11-27 13:23:08 +00008561 if (const ParamAttrsList *NestAttrs = NestF->getParamAttrs()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008562 unsigned NestIdx = 1;
8563 const Type *NestTy = 0;
8564 uint16_t NestAttr = 0;
8565
8566 // Look for a parameter marked with the 'nest' attribute.
8567 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8568 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8569 if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8570 // Record the parameter type and any other attributes.
8571 NestTy = *I;
8572 NestAttr = NestAttrs->getParamAttrs(NestIdx);
8573 break;
8574 }
8575
8576 if (NestTy) {
8577 Instruction *Caller = CS.getInstruction();
8578 std::vector<Value*> NewArgs;
8579 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8580
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008581 ParamAttrsVector NewAttrs;
8582 NewAttrs.reserve(Attrs ? Attrs->size() + 1 : 1);
8583
Duncan Sandscdb6d922007-09-17 10:26:40 +00008584 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008585 // mean appending it. Likewise for attributes.
8586
8587 // Add any function result attributes.
8588 uint16_t Attr = Attrs ? Attrs->getParamAttrs(0) : 0;
8589 if (Attr)
8590 NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8591
Duncan Sandscdb6d922007-09-17 10:26:40 +00008592 {
8593 unsigned Idx = 1;
8594 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8595 do {
8596 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008597 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008598 Value *NestVal = Tramp->getOperand(3);
8599 if (NestVal->getType() != NestTy)
8600 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8601 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008602 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008603 }
8604
8605 if (I == E)
8606 break;
8607
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008608 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008609 NewArgs.push_back(*I);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008610 Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8611 if (Attr)
8612 NewAttrs.push_back
8613 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008614
8615 ++Idx, ++I;
8616 } while (1);
8617 }
8618
8619 // The trampoline may have been bitcast to a bogus type (FTy).
8620 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008621 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008622
Duncan Sandscdb6d922007-09-17 10:26:40 +00008623 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008624 NewTypes.reserve(FTy->getNumParams()+1);
8625
Duncan Sandscdb6d922007-09-17 10:26:40 +00008626 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008627 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008628 {
8629 unsigned Idx = 1;
8630 FunctionType::param_iterator I = FTy->param_begin(),
8631 E = FTy->param_end();
8632
8633 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008634 if (Idx == NestIdx)
8635 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008636 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008637
8638 if (I == E)
8639 break;
8640
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008641 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008642 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008643
8644 ++Idx, ++I;
8645 } while (1);
8646 }
8647
8648 // Replace the trampoline call with a direct call. Let the generic
8649 // code sort out any function type mismatches.
8650 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00008651 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008652 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8653 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Duncan Sandsdc024672007-11-27 13:23:08 +00008654 const ParamAttrsList *NewPAL = ParamAttrsList::get(NewAttrs);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008655
8656 Instruction *NewCaller;
8657 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8658 NewCaller = new InvokeInst(NewCallee,
8659 II->getNormalDest(), II->getUnwindDest(),
8660 NewArgs.begin(), NewArgs.end(),
8661 Caller->getName(), Caller);
8662 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008663 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008664 } else {
8665 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8666 Caller->getName(), Caller);
8667 if (cast<CallInst>(Caller)->isTailCall())
8668 cast<CallInst>(NewCaller)->setTailCall();
8669 cast<CallInst>(NewCaller)->
8670 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008671 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008672 }
8673 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8674 Caller->replaceAllUsesWith(NewCaller);
8675 Caller->eraseFromParent();
8676 RemoveFromWorkList(Caller);
8677 return 0;
8678 }
8679 }
8680
8681 // Replace the trampoline call with a direct call. Since there is no 'nest'
8682 // parameter, there is no need to adjust the argument list. Let the generic
8683 // code sort out any function type mismatches.
8684 Constant *NewCallee =
8685 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8686 CS.setCalledFunction(NewCallee);
8687 return CS.getInstruction();
8688}
8689
Chris Lattner7da52b22006-11-01 04:51:18 +00008690/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8691/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8692/// and a single binop.
8693Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8694 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00008695 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8696 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00008697 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008698 Value *LHSVal = FirstInst->getOperand(0);
8699 Value *RHSVal = FirstInst->getOperand(1);
8700
8701 const Type *LHSType = LHSVal->getType();
8702 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00008703
8704 // Scan to see if all operands are the same opcode, all have one use, and all
8705 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00008706 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00008707 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00008708 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008709 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00008710 // types or GEP's with different index types.
8711 I->getOperand(0)->getType() != LHSType ||
8712 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00008713 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008714
8715 // If they are CmpInst instructions, check their predicates
8716 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8717 if (cast<CmpInst>(I)->getPredicate() !=
8718 cast<CmpInst>(FirstInst)->getPredicate())
8719 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008720
8721 // Keep track of which operand needs a phi node.
8722 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8723 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00008724 }
8725
Chris Lattner53738a42006-11-08 19:42:28 +00008726 // Otherwise, this is safe to transform, determine if it is profitable.
8727
8728 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8729 // Indexes are often folded into load/store instructions, so we don't want to
8730 // hide them behind a phi.
8731 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8732 return 0;
8733
Chris Lattner7da52b22006-11-01 04:51:18 +00008734 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00008735 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00008736 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008737 if (LHSVal == 0) {
8738 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8739 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8740 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008741 InsertNewInstBefore(NewLHS, PN);
8742 LHSVal = NewLHS;
8743 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008744
8745 if (RHSVal == 0) {
8746 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8747 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8748 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008749 InsertNewInstBefore(NewRHS, PN);
8750 RHSVal = NewRHS;
8751 }
8752
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008753 // Add all operands to the new PHIs.
8754 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8755 if (NewLHS) {
8756 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8757 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8758 }
8759 if (NewRHS) {
8760 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8761 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8762 }
8763 }
8764
Chris Lattner7da52b22006-11-01 04:51:18 +00008765 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00008766 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008767 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8768 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8769 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00008770 else {
8771 assert(isa<GetElementPtrInst>(FirstInst));
8772 return new GetElementPtrInst(LHSVal, RHSVal);
8773 }
Chris Lattner7da52b22006-11-01 04:51:18 +00008774}
8775
Chris Lattner76c73142006-11-01 07:13:54 +00008776/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8777/// of the block that defines it. This means that it must be obvious the value
8778/// of the load is not changed from the point of the load to the end of the
8779/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008780///
8781/// Finally, it is safe, but not profitable, to sink a load targetting a
8782/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8783/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00008784static bool isSafeToSinkLoad(LoadInst *L) {
8785 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8786
8787 for (++BBI; BBI != E; ++BBI)
8788 if (BBI->mayWriteToMemory())
8789 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008790
8791 // Check for non-address taken alloca. If not address-taken already, it isn't
8792 // profitable to do this xform.
8793 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8794 bool isAddressTaken = false;
8795 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8796 UI != E; ++UI) {
8797 if (isa<LoadInst>(UI)) continue;
8798 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8799 // If storing TO the alloca, then the address isn't taken.
8800 if (SI->getOperand(1) == AI) continue;
8801 }
8802 isAddressTaken = true;
8803 break;
8804 }
8805
8806 if (!isAddressTaken)
8807 return false;
8808 }
8809
Chris Lattner76c73142006-11-01 07:13:54 +00008810 return true;
8811}
8812
Chris Lattner9fe38862003-06-19 17:00:31 +00008813
Chris Lattnerbac32862004-11-14 19:13:23 +00008814// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8815// operator and they all are only used by the PHI, PHI together their
8816// inputs, and do the operation once, to the result of the PHI.
8817Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8818 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8819
8820 // Scan the instruction, looking for input operations that can be folded away.
8821 // If all input operands to the phi are the same instruction (e.g. a cast from
8822 // the same type or "+42") we can pull the operation through the PHI, reducing
8823 // code size and simplifying code.
8824 Constant *ConstantOp = 0;
8825 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00008826 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00008827 if (isa<CastInst>(FirstInst)) {
8828 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00008829 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008830 // Can fold binop, compare or shift here if the RHS is a constant,
8831 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00008832 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00008833 if (ConstantOp == 0)
8834 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00008835 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8836 isVolatile = LI->isVolatile();
8837 // We can't sink the load if the loaded value could be modified between the
8838 // load and the PHI.
8839 if (LI->getParent() != PN.getIncomingBlock(0) ||
8840 !isSafeToSinkLoad(LI))
8841 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00008842 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00008843 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00008844 return FoldPHIArgBinOpIntoPHI(PN);
8845 // Can't handle general GEPs yet.
8846 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008847 } else {
8848 return 0; // Cannot fold this operation.
8849 }
8850
8851 // Check to see if all arguments are the same operation.
8852 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8853 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8854 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00008855 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00008856 return 0;
8857 if (CastSrcTy) {
8858 if (I->getOperand(0)->getType() != CastSrcTy)
8859 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00008860 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008861 // We can't sink the load if the loaded value could be modified between
8862 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00008863 if (LI->isVolatile() != isVolatile ||
8864 LI->getParent() != PN.getIncomingBlock(i) ||
8865 !isSafeToSinkLoad(LI))
8866 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008867 } else if (I->getOperand(1) != ConstantOp) {
8868 return 0;
8869 }
8870 }
8871
8872 // Okay, they are all the same operation. Create a new PHI node of the
8873 // correct type, and PHI together all of the LHS's of the instructions.
8874 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8875 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00008876 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00008877
8878 Value *InVal = FirstInst->getOperand(0);
8879 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00008880
8881 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00008882 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8883 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8884 if (NewInVal != InVal)
8885 InVal = 0;
8886 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8887 }
8888
8889 Value *PhiVal;
8890 if (InVal) {
8891 // The new PHI unions all of the same values together. This is really
8892 // common, so we handle it intelligently here for compile-time speed.
8893 PhiVal = InVal;
8894 delete NewPN;
8895 } else {
8896 InsertNewInstBefore(NewPN, PN);
8897 PhiVal = NewPN;
8898 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008899
Chris Lattnerbac32862004-11-14 19:13:23 +00008900 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00008901 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8902 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00008903 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00008904 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00008905 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00008906 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008907 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8908 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8909 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00008910 else
Reid Spencer832254e2007-02-02 02:16:23 +00008911 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00008912 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008913}
Chris Lattnera1be5662002-05-02 17:06:02 +00008914
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008915/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8916/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008917static bool DeadPHICycle(PHINode *PN,
8918 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008919 if (PN->use_empty()) return true;
8920 if (!PN->hasOneUse()) return false;
8921
8922 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008923 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008924 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00008925
8926 // Don't scan crazily complex things.
8927 if (PotentiallyDeadPHIs.size() == 16)
8928 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008929
8930 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8931 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008932
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008933 return false;
8934}
8935
Chris Lattnercf5008a2007-11-06 21:52:06 +00008936/// PHIsEqualValue - Return true if this phi node is always equal to
8937/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
8938/// z = some value; x = phi (y, z); y = phi (x, z)
8939static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
8940 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
8941 // See if we already saw this PHI node.
8942 if (!ValueEqualPHIs.insert(PN))
8943 return true;
8944
8945 // Don't scan crazily complex things.
8946 if (ValueEqualPHIs.size() == 16)
8947 return false;
8948
8949 // Scan the operands to see if they are either phi nodes or are equal to
8950 // the value.
8951 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8952 Value *Op = PN->getIncomingValue(i);
8953 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
8954 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
8955 return false;
8956 } else if (Op != NonPhiInVal)
8957 return false;
8958 }
8959
8960 return true;
8961}
8962
8963
Chris Lattner473945d2002-05-06 18:06:38 +00008964// PHINode simplification
8965//
Chris Lattner7e708292002-06-25 16:13:24 +00008966Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00008967 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00008968 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00008969
Owen Anderson7e057142006-07-10 22:03:18 +00008970 if (Value *V = PN.hasConstantValue())
8971 return ReplaceInstUsesWith(PN, V);
8972
Owen Anderson7e057142006-07-10 22:03:18 +00008973 // If all PHI operands are the same operation, pull them through the PHI,
8974 // reducing code size.
8975 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8976 PN.getIncomingValue(0)->hasOneUse())
8977 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8978 return Result;
8979
8980 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8981 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8982 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008983 if (PN.hasOneUse()) {
8984 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8985 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00008986 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00008987 PotentiallyDeadPHIs.insert(&PN);
8988 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8989 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8990 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00008991
8992 // If this phi has a single use, and if that use just computes a value for
8993 // the next iteration of a loop, delete the phi. This occurs with unused
8994 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8995 // common case here is good because the only other things that catch this
8996 // are induction variable analysis (sometimes) and ADCE, which is only run
8997 // late.
8998 if (PHIUser->hasOneUse() &&
8999 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9000 PHIUser->use_back() == &PN) {
9001 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9002 }
9003 }
Owen Anderson7e057142006-07-10 22:03:18 +00009004
Chris Lattnercf5008a2007-11-06 21:52:06 +00009005 // We sometimes end up with phi cycles that non-obviously end up being the
9006 // same value, for example:
9007 // z = some value; x = phi (y, z); y = phi (x, z)
9008 // where the phi nodes don't necessarily need to be in the same block. Do a
9009 // quick check to see if the PHI node only contains a single non-phi value, if
9010 // so, scan to see if the phi cycle is actually equal to that value.
9011 {
9012 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9013 // Scan for the first non-phi operand.
9014 while (InValNo != NumOperandVals &&
9015 isa<PHINode>(PN.getIncomingValue(InValNo)))
9016 ++InValNo;
9017
9018 if (InValNo != NumOperandVals) {
9019 Value *NonPhiInVal = PN.getOperand(InValNo);
9020
9021 // Scan the rest of the operands to see if there are any conflicts, if so
9022 // there is no need to recursively scan other phis.
9023 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9024 Value *OpVal = PN.getIncomingValue(InValNo);
9025 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9026 break;
9027 }
9028
9029 // If we scanned over all operands, then we have one unique value plus
9030 // phi values. Scan PHI nodes to see if they all merge in each other or
9031 // the value.
9032 if (InValNo == NumOperandVals) {
9033 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9034 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9035 return ReplaceInstUsesWith(PN, NonPhiInVal);
9036 }
9037 }
9038 }
Chris Lattner60921c92003-12-19 05:58:40 +00009039 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009040}
9041
Reid Spencer17212df2006-12-12 09:18:51 +00009042static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9043 Instruction *InsertPoint,
9044 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009045 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9046 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009047 // We must cast correctly to the pointer type. Ensure that we
9048 // sign extend the integer value if it is smaller as this is
9049 // used for address computation.
9050 Instruction::CastOps opcode =
9051 (VTySize < PtrSize ? Instruction::SExt :
9052 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9053 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009054}
9055
Chris Lattnera1be5662002-05-02 17:06:02 +00009056
Chris Lattner7e708292002-06-25 16:13:24 +00009057Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009058 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009059 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009060 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009061 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009062 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009063
Chris Lattnere87597f2004-10-16 18:11:37 +00009064 if (isa<UndefValue>(GEP.getOperand(0)))
9065 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9066
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009067 bool HasZeroPointerIndex = false;
9068 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9069 HasZeroPointerIndex = C->isNullValue();
9070
9071 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009072 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009073
Chris Lattner28977af2004-04-05 01:30:19 +00009074 // Eliminate unneeded casts for indices.
9075 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009076
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009077 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009078 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009079 if (isa<SequentialType>(*GTI)) {
9080 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009081 if (CI->getOpcode() == Instruction::ZExt ||
9082 CI->getOpcode() == Instruction::SExt) {
9083 const Type *SrcTy = CI->getOperand(0)->getType();
9084 // We can eliminate a cast from i32 to i64 iff the target
9085 // is a 32-bit pointer target.
9086 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9087 MadeChange = true;
9088 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009089 }
9090 }
9091 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009092 // If we are using a wider index than needed for this platform, shrink it
9093 // to what we need. If the incoming value needs a cast instruction,
9094 // insert it. This explicit cast can make subsequent optimizations more
9095 // obvious.
9096 Value *Op = GEP.getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00009097 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits())
Chris Lattner4f1134e2004-04-17 18:16:10 +00009098 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009099 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009100 MadeChange = true;
9101 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009102 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9103 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009104 GEP.setOperand(i, Op);
9105 MadeChange = true;
9106 }
Chris Lattner28977af2004-04-05 01:30:19 +00009107 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009108 }
Chris Lattner28977af2004-04-05 01:30:19 +00009109 if (MadeChange) return &GEP;
9110
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009111 // If this GEP instruction doesn't move the pointer, and if the input operand
9112 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9113 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009114 if (GEP.hasAllZeroIndices()) {
9115 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9116 // If the bitcast is of an allocation, and the allocation will be
9117 // converted to match the type of the cast, don't touch this.
9118 if (isa<AllocationInst>(BCI->getOperand(0))) {
9119 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009120 if (Instruction *I = visitBitCast(*BCI)) {
9121 if (I != BCI) {
9122 I->takeName(BCI);
9123 BCI->getParent()->getInstList().insert(BCI, I);
9124 ReplaceInstUsesWith(*BCI, I);
9125 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009126 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009127 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009128 }
9129 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9130 }
9131 }
9132
Chris Lattner90ac28c2002-08-02 19:29:35 +00009133 // Combine Indices - If the source pointer to this getelementptr instruction
9134 // is a getelementptr instruction, combine the indices of the two
9135 // getelementptr instructions into a single instruction.
9136 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009137 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009138 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009139 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009140
9141 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009142 // Note that if our source is a gep chain itself that we wait for that
9143 // chain to be resolved before we perform this transformation. This
9144 // avoids us creating a TON of code in some cases.
9145 //
9146 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9147 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9148 return 0; // Wait until our source is folded to completion.
9149
Chris Lattner72588fc2007-02-15 22:48:32 +00009150 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009151
9152 // Find out whether the last index in the source GEP is a sequential idx.
9153 bool EndsWithSequential = false;
9154 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9155 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009156 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009157
Chris Lattner90ac28c2002-08-02 19:29:35 +00009158 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009159 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009160 // Replace: gep (gep %P, long B), long A, ...
9161 // With: T = long A+B; gep %P, T, ...
9162 //
Chris Lattner620ce142004-05-07 22:09:22 +00009163 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009164 if (SO1 == Constant::getNullValue(SO1->getType())) {
9165 Sum = GO1;
9166 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9167 Sum = SO1;
9168 } else {
9169 // If they aren't the same type, convert both to an integer of the
9170 // target's pointer size.
9171 if (SO1->getType() != GO1->getType()) {
9172 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009173 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009174 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009175 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009176 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009177 unsigned PS = TD->getPointerSizeInBits();
9178 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009179 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009180 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009181
Duncan Sands514ab342007-11-01 20:53:16 +00009182 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009183 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009184 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009185 } else {
9186 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009187 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9188 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009189 }
9190 }
9191 }
Chris Lattner620ce142004-05-07 22:09:22 +00009192 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9193 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9194 else {
Chris Lattner48595f12004-06-10 02:07:29 +00009195 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9196 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009197 }
Chris Lattner28977af2004-04-05 01:30:19 +00009198 }
Chris Lattner620ce142004-05-07 22:09:22 +00009199
9200 // Recycle the GEP we already have if possible.
9201 if (SrcGEPOperands.size() == 2) {
9202 GEP.setOperand(0, SrcGEPOperands[0]);
9203 GEP.setOperand(1, Sum);
9204 return &GEP;
9205 } else {
9206 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9207 SrcGEPOperands.end()-1);
9208 Indices.push_back(Sum);
9209 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9210 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009211 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009212 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009213 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009214 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009215 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9216 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009217 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9218 }
9219
9220 if (!Indices.empty())
David Greeneb8f74792007-09-04 15:46:09 +00009221 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9222 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009223
Chris Lattner620ce142004-05-07 22:09:22 +00009224 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009225 // GEP of global variable. If all of the indices for this GEP are
9226 // constants, we can promote this to a constexpr instead of an instruction.
9227
9228 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009229 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009230 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9231 for (; I != E && isa<Constant>(*I); ++I)
9232 Indices.push_back(cast<Constant>(*I));
9233
9234 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009235 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9236 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009237
9238 // Replace all uses of the GEP with the new constexpr...
9239 return ReplaceInstUsesWith(GEP, CE);
9240 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009241 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009242 if (!isa<PointerType>(X->getType())) {
9243 // Not interesting. Source pointer must be a cast from pointer.
9244 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009245 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9246 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009247 //
9248 // This occurs when the program declares an array extern like "int X[];"
9249 //
9250 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9251 const PointerType *XTy = cast<PointerType>(X->getType());
9252 if (const ArrayType *XATy =
9253 dyn_cast<ArrayType>(XTy->getElementType()))
9254 if (const ArrayType *CATy =
9255 dyn_cast<ArrayType>(CPTy->getElementType()))
9256 if (CATy->getElementType() == XATy->getElementType()) {
9257 // At this point, we know that the cast source type is a pointer
9258 // to an array of the same type as the destination pointer
9259 // array. Because the array type is never stepped over (there
9260 // is a leading zero) we can fold the cast into this GEP.
9261 GEP.setOperand(0, X);
9262 return &GEP;
9263 }
9264 } else if (GEP.getNumOperands() == 2) {
9265 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009266 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9267 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009268 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9269 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9270 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009271 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9272 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009273 Value *Idx[2];
9274 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9275 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009276 Value *V = InsertNewInstBefore(
David Greeneb8f74792007-09-04 15:46:09 +00009277 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009278 // V and GEP are both pointer types --> BitCast
9279 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009280 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009281
9282 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009283 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009284 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009285 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009286
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009287 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009288 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009289 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009290
9291 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9292 // allow either a mul, shift, or constant here.
9293 Value *NewIdx = 0;
9294 ConstantInt *Scale = 0;
9295 if (ArrayEltSize == 1) {
9296 NewIdx = GEP.getOperand(1);
9297 Scale = ConstantInt::get(NewIdx->getType(), 1);
9298 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009299 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009300 Scale = CI;
9301 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9302 if (Inst->getOpcode() == Instruction::Shl &&
9303 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009304 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9305 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9306 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009307 NewIdx = Inst->getOperand(0);
9308 } else if (Inst->getOpcode() == Instruction::Mul &&
9309 isa<ConstantInt>(Inst->getOperand(1))) {
9310 Scale = cast<ConstantInt>(Inst->getOperand(1));
9311 NewIdx = Inst->getOperand(0);
9312 }
9313 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009314
Chris Lattner7835cdd2005-09-13 18:36:04 +00009315 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009316 // out, perform the transformation. Note, we don't know whether Scale is
9317 // signed or not. We'll use unsigned version of division/modulo
9318 // operation after making sure Scale doesn't have the sign bit set.
9319 if (Scale && Scale->getSExtValue() >= 0LL &&
9320 Scale->getZExtValue() % ArrayEltSize == 0) {
9321 Scale = ConstantInt::get(Scale->getType(),
9322 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009323 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009324 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009325 false /*ZExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009326 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9327 NewIdx = InsertNewInstBefore(Sc, GEP);
9328 }
9329
9330 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009331 Value *Idx[2];
9332 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9333 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009334 Instruction *NewGEP =
David Greeneb8f74792007-09-04 15:46:09 +00009335 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009336 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9337 // The NewGEP must be pointer typed, so must the old one -> BitCast
9338 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009339 }
9340 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009341 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009342 }
9343
Chris Lattner8a2a3112001-12-14 16:52:21 +00009344 return 0;
9345}
9346
Chris Lattner0864acf2002-11-04 16:18:53 +00009347Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9348 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9349 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009350 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9351 const Type *NewTy =
9352 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009353 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009354
9355 // Create and insert the replacement instruction...
9356 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009357 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009358 else {
9359 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009360 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009361 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009362
9363 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009364
Chris Lattner0864acf2002-11-04 16:18:53 +00009365 // Scan to the end of the allocation instructions, to skip over a block of
9366 // allocas if possible...
9367 //
9368 BasicBlock::iterator It = New;
9369 while (isa<AllocationInst>(*It)) ++It;
9370
9371 // Now that I is pointing to the first non-allocation-inst in the block,
9372 // insert our getelementptr instruction...
9373 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009374 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009375 Value *Idx[2];
9376 Idx[0] = NullIdx;
9377 Idx[1] = NullIdx;
9378 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Chris Lattner693787a2005-05-04 19:10:26 +00009379 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009380
9381 // Now make everything use the getelementptr instead of the original
9382 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009383 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009384 } else if (isa<UndefValue>(AI.getArraySize())) {
9385 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009386 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009387
9388 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9389 // Note that we only do this for alloca's, because malloc should allocate and
9390 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009391 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009392 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009393 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9394
Chris Lattner0864acf2002-11-04 16:18:53 +00009395 return 0;
9396}
9397
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009398Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9399 Value *Op = FI.getOperand(0);
9400
Chris Lattner17be6352004-10-18 02:59:09 +00009401 // free undef -> unreachable.
9402 if (isa<UndefValue>(Op)) {
9403 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009404 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009405 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009406 return EraseInstFromFunction(FI);
9407 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009408
Chris Lattner6160e852004-02-28 04:57:37 +00009409 // If we have 'free null' delete the instruction. This can happen in stl code
9410 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009411 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009412 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009413
9414 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9415 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9416 FI.setOperand(0, CI->getOperand(0));
9417 return &FI;
9418 }
9419
9420 // Change free (gep X, 0,0,0,0) into free(X)
9421 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9422 if (GEPI->hasAllZeroIndices()) {
9423 AddToWorkList(GEPI);
9424 FI.setOperand(0, GEPI->getOperand(0));
9425 return &FI;
9426 }
9427 }
9428
9429 // Change free(malloc) into nothing, if the malloc has a single use.
9430 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9431 if (MI->hasOneUse()) {
9432 EraseInstFromFunction(FI);
9433 return EraseInstFromFunction(*MI);
9434 }
Chris Lattner6160e852004-02-28 04:57:37 +00009435
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009436 return 0;
9437}
9438
9439
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009440/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009441static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9442 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009443 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009444 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009445
Devang Patel99db6ad2007-10-18 19:52:32 +00009446 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9447 // Instead of loading constant c string, use corresponding integer value
9448 // directly if string length is small enough.
9449 const std::string &Str = CE->getOperand(0)->getStringValue();
9450 if (!Str.empty()) {
9451 unsigned len = Str.length();
9452 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9453 unsigned numBits = Ty->getPrimitiveSizeInBits();
9454 // Replace LI with immediate integer store.
9455 if ((numBits >> 3) == len + 1) {
9456 APInt StrVal(numBits, 0);
9457 APInt SingleChar(numBits, 0);
9458 if (TD->isLittleEndian()) {
9459 for (signed i = len-1; i >= 0; i--) {
9460 SingleChar = (uint64_t) Str[i];
9461 StrVal = (StrVal << 8) | SingleChar;
9462 }
9463 } else {
9464 for (unsigned i = 0; i < len; i++) {
9465 SingleChar = (uint64_t) Str[i];
9466 StrVal = (StrVal << 8) | SingleChar;
9467 }
9468 // Append NULL at the end.
9469 SingleChar = 0;
9470 StrVal = (StrVal << 8) | SingleChar;
9471 }
9472 Value *NL = ConstantInt::get(StrVal);
9473 return IC.ReplaceInstUsesWith(LI, NL);
9474 }
9475 }
9476 }
9477
Chris Lattnerb89e0712004-07-13 01:49:43 +00009478 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009479 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009480 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009481
Reid Spencer42230162007-01-22 05:51:25 +00009482 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009483 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009484 // If the source is an array, the code below will not succeed. Check to
9485 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9486 // constants.
9487 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9488 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9489 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009490 Value *Idxs[2];
9491 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9492 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009493 SrcTy = cast<PointerType>(CastOp->getType());
9494 SrcPTy = SrcTy->getElementType();
9495 }
9496
Reid Spencer42230162007-01-22 05:51:25 +00009497 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009498 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009499 // Do not allow turning this into a load of an integer, which is then
9500 // casted to a pointer, this pessimizes pointer analysis a lot.
9501 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009502 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9503 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009504
Chris Lattnerf9527852005-01-31 04:50:46 +00009505 // Okay, we are casting from one integer or pointer type to another of
9506 // the same size. Instead of casting the pointer before the load, cast
9507 // the result of the loaded value.
9508 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9509 CI->getName(),
9510 LI.isVolatile()),LI);
9511 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009512 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009513 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009514 }
9515 }
9516 return 0;
9517}
9518
Chris Lattnerc10aced2004-09-19 18:43:46 +00009519/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009520/// from this value cannot trap. If it is not obviously safe to load from the
9521/// specified pointer, we do a quick local scan of the basic block containing
9522/// ScanFrom, to determine if the address is already accessed.
9523static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009524 // If it is an alloca it is always safe to load from.
9525 if (isa<AllocaInst>(V)) return true;
9526
Duncan Sands46318cd2007-09-19 10:25:38 +00009527 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009528 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009529 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009530 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009531
9532 // Otherwise, be a little bit agressive by scanning the local block where we
9533 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009534 // from/to. If so, the previous load or store would have already trapped,
9535 // so there is no harm doing an extra load (also, CSE will later eliminate
9536 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00009537 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9538
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009539 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00009540 --BBI;
9541
9542 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9543 if (LI->getOperand(0) == V) return true;
9544 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9545 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00009546
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009547 }
Chris Lattner8a375202004-09-19 19:18:10 +00009548 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00009549}
9550
Chris Lattner8d2e8882007-08-11 18:48:48 +00009551/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9552/// until we find the underlying object a pointer is referring to or something
9553/// we don't understand. Note that the returned pointer may be offset from the
9554/// input, because we ignore GEP indices.
9555static Value *GetUnderlyingObject(Value *Ptr) {
9556 while (1) {
9557 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9558 if (CE->getOpcode() == Instruction::BitCast ||
9559 CE->getOpcode() == Instruction::GetElementPtr)
9560 Ptr = CE->getOperand(0);
9561 else
9562 return Ptr;
9563 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9564 Ptr = BCI->getOperand(0);
9565 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9566 Ptr = GEP->getOperand(0);
9567 } else {
9568 return Ptr;
9569 }
9570 }
9571}
9572
Chris Lattner833b8a42003-06-26 05:06:25 +00009573Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9574 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00009575
Dan Gohman9941f742007-07-20 16:34:21 +00009576 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009577 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009578 if (KnownAlign > LI.getAlignment())
9579 LI.setAlignment(KnownAlign);
9580
Chris Lattner37366c12005-05-01 04:24:53 +00009581 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00009582 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +00009583 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +00009584 return Res;
9585
9586 // None of the following transforms are legal for volatile loads.
9587 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00009588
Chris Lattner62f254d2005-09-12 22:00:15 +00009589 if (&LI.getParent()->front() != &LI) {
9590 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009591 // If the instruction immediately before this is a store to the same
9592 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00009593 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9594 if (SI->getOperand(1) == LI.getOperand(0))
9595 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009596 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9597 if (LIB->getOperand(0) == LI.getOperand(0))
9598 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00009599 }
Chris Lattner37366c12005-05-01 04:24:53 +00009600
Christopher Lambb15147e2007-12-29 07:56:53 +00009601 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9602 const Value *GEPI0 = GEPI->getOperand(0);
9603 // TODO: Consider a target hook for valid address spaces for this xform.
9604 if (isa<ConstantPointerNull>(GEPI0) &&
9605 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +00009606 // Insert a new store to null instruction before the load to indicate
9607 // that this code is not reachable. We do this instead of inserting
9608 // an unreachable instruction directly because we cannot modify the
9609 // CFG.
9610 new StoreInst(UndefValue::get(LI.getType()),
9611 Constant::getNullValue(Op->getType()), &LI);
9612 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9613 }
Christopher Lambb15147e2007-12-29 07:56:53 +00009614 }
Chris Lattner37366c12005-05-01 04:24:53 +00009615
Chris Lattnere87597f2004-10-16 18:11:37 +00009616 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00009617 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +00009618 // TODO: Consider a target hook for valid address spaces for this xform.
9619 if (isa<UndefValue>(C) || (C->isNullValue() &&
9620 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +00009621 // Insert a new store to null instruction before the load to indicate that
9622 // this code is not reachable. We do this instead of inserting an
9623 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00009624 new StoreInst(UndefValue::get(LI.getType()),
9625 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00009626 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009627 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009628
Chris Lattnere87597f2004-10-16 18:11:37 +00009629 // Instcombine load (constant global) into the value loaded.
9630 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009631 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00009632 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00009633
Chris Lattnere87597f2004-10-16 18:11:37 +00009634 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9635 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9636 if (CE->getOpcode() == Instruction::GetElementPtr) {
9637 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009638 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00009639 if (Constant *V =
9640 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00009641 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00009642 if (CE->getOperand(0)->isNullValue()) {
9643 // Insert a new store to null instruction before the load to indicate
9644 // that this code is not reachable. We do this instead of inserting
9645 // an unreachable instruction directly because we cannot modify the
9646 // CFG.
9647 new StoreInst(UndefValue::get(LI.getType()),
9648 Constant::getNullValue(Op->getType()), &LI);
9649 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9650 }
9651
Reid Spencer3da59db2006-11-27 01:05:10 +00009652 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +00009653 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +00009654 return Res;
9655 }
9656 }
Chris Lattner8d2e8882007-08-11 18:48:48 +00009657
9658 // If this load comes from anywhere in a constant global, and if the global
9659 // is all undef or zero, we know what it loads.
9660 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9661 if (GV->isConstant() && GV->hasInitializer()) {
9662 if (GV->getInitializer()->isNullValue())
9663 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9664 else if (isa<UndefValue>(GV->getInitializer()))
9665 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9666 }
9667 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00009668
Chris Lattner37366c12005-05-01 04:24:53 +00009669 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009670 // Change select and PHI nodes to select values instead of addresses: this
9671 // helps alias analysis out a lot, allows many others simplifications, and
9672 // exposes redundancy in the code.
9673 //
9674 // Note that we cannot do the transformation unless we know that the
9675 // introduced loads cannot trap! Something like this is valid as long as
9676 // the condition is always false: load (select bool %C, int* null, int* %G),
9677 // but it would not be valid if we transformed it to load from null
9678 // unconditionally.
9679 //
9680 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9681 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00009682 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9683 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009684 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009685 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009686 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009687 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009688 return new SelectInst(SI->getCondition(), V1, V2);
9689 }
9690
Chris Lattner684fe212004-09-23 15:46:00 +00009691 // load (select (cond, null, P)) -> load P
9692 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9693 if (C->isNullValue()) {
9694 LI.setOperand(0, SI->getOperand(2));
9695 return &LI;
9696 }
9697
9698 // load (select (cond, P, null)) -> load P
9699 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9700 if (C->isNullValue()) {
9701 LI.setOperand(0, SI->getOperand(1));
9702 return &LI;
9703 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00009704 }
9705 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009706 return 0;
9707}
9708
Reid Spencer55af2b52007-01-19 21:20:31 +00009709/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009710/// when possible.
9711static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9712 User *CI = cast<User>(SI.getOperand(1));
9713 Value *CastOp = CI->getOperand(0);
9714
9715 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9716 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9717 const Type *SrcPTy = SrcTy->getElementType();
9718
Reid Spencer42230162007-01-22 05:51:25 +00009719 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009720 // If the source is an array, the code below will not succeed. Check to
9721 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9722 // constants.
9723 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9724 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9725 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009726 Value* Idxs[2];
9727 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9728 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009729 SrcTy = cast<PointerType>(CastOp->getType());
9730 SrcPTy = SrcTy->getElementType();
9731 }
9732
Reid Spencer67f827c2007-01-20 23:35:48 +00009733 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9734 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9735 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009736
9737 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00009738 // the same size. Instead of casting the pointer before
9739 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009740 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00009741 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00009742 Instruction::CastOps opcode = Instruction::BitCast;
9743 const Type* CastSrcTy = SIOp0->getType();
9744 const Type* CastDstTy = SrcPTy;
9745 if (isa<PointerType>(CastDstTy)) {
9746 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00009747 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00009748 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00009749 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00009750 opcode = Instruction::PtrToInt;
9751 }
9752 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00009753 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009754 else
Reid Spencer3da59db2006-11-27 01:05:10 +00009755 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00009756 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9757 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009758 return new StoreInst(NewCast, CastOp);
9759 }
9760 }
9761 }
9762 return 0;
9763}
9764
Chris Lattner2f503e62005-01-31 05:36:43 +00009765Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9766 Value *Val = SI.getOperand(0);
9767 Value *Ptr = SI.getOperand(1);
9768
9769 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00009770 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009771 ++NumCombined;
9772 return 0;
9773 }
Chris Lattner836692d2007-01-15 06:51:56 +00009774
9775 // If the RHS is an alloca with a single use, zapify the store, making the
9776 // alloca dead.
9777 if (Ptr->hasOneUse()) {
9778 if (isa<AllocaInst>(Ptr)) {
9779 EraseInstFromFunction(SI);
9780 ++NumCombined;
9781 return 0;
9782 }
9783
9784 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9785 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9786 GEP->getOperand(0)->hasOneUse()) {
9787 EraseInstFromFunction(SI);
9788 ++NumCombined;
9789 return 0;
9790 }
9791 }
Chris Lattner2f503e62005-01-31 05:36:43 +00009792
Dan Gohman9941f742007-07-20 16:34:21 +00009793 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009794 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009795 if (KnownAlign > SI.getAlignment())
9796 SI.setAlignment(KnownAlign);
9797
Chris Lattner9ca96412006-02-08 03:25:32 +00009798 // Do really simple DSE, to catch cases where there are several consequtive
9799 // stores to the same location, separated by a few arithmetic operations. This
9800 // situation often occurs with bitfield accesses.
9801 BasicBlock::iterator BBI = &SI;
9802 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9803 --ScanInsts) {
9804 --BBI;
9805
9806 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9807 // Prev store isn't volatile, and stores to the same location?
9808 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9809 ++NumDeadStore;
9810 ++BBI;
9811 EraseInstFromFunction(*PrevSI);
9812 continue;
9813 }
9814 break;
9815 }
9816
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009817 // If this is a load, we have to stop. However, if the loaded value is from
9818 // the pointer we're loading and is producing the pointer we're storing,
9819 // then *this* store is dead (X = load P; store X -> P).
9820 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +00009821 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009822 EraseInstFromFunction(SI);
9823 ++NumCombined;
9824 return 0;
9825 }
9826 // Otherwise, this is a load from some other location. Stores before it
9827 // may not be dead.
9828 break;
9829 }
9830
Chris Lattner9ca96412006-02-08 03:25:32 +00009831 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009832 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00009833 break;
9834 }
9835
9836
9837 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00009838
9839 // store X, null -> turns into 'unreachable' in SimplifyCFG
9840 if (isa<ConstantPointerNull>(Ptr)) {
9841 if (!isa<UndefValue>(Val)) {
9842 SI.setOperand(0, UndefValue::get(Val->getType()));
9843 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +00009844 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00009845 ++NumCombined;
9846 }
9847 return 0; // Do not modify these!
9848 }
9849
9850 // store undef, Ptr -> noop
9851 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00009852 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009853 ++NumCombined;
9854 return 0;
9855 }
9856
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009857 // If the pointer destination is a cast, see if we can fold the cast into the
9858 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00009859 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009860 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9861 return Res;
9862 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00009863 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009864 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9865 return Res;
9866
Chris Lattner408902b2005-09-12 23:23:25 +00009867
9868 // If this store is the last instruction in the basic block, and if the block
9869 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00009870 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00009871 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009872 if (BI->isUnconditional())
9873 if (SimplifyStoreAtEndOfBlock(SI))
9874 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +00009875
Chris Lattner2f503e62005-01-31 05:36:43 +00009876 return 0;
9877}
9878
Chris Lattner3284d1f2007-04-15 00:07:55 +00009879/// SimplifyStoreAtEndOfBlock - Turn things like:
9880/// if () { *P = v1; } else { *P = v2 }
9881/// into a phi node with a store in the successor.
9882///
Chris Lattner31755a02007-04-15 01:02:18 +00009883/// Simplify things like:
9884/// *P = v1; if () { *P = v2; }
9885/// into a phi node with a store in the successor.
9886///
Chris Lattner3284d1f2007-04-15 00:07:55 +00009887bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9888 BasicBlock *StoreBB = SI.getParent();
9889
9890 // Check to see if the successor block has exactly two incoming edges. If
9891 // so, see if the other predecessor contains a store to the same location.
9892 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +00009893 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +00009894
9895 // Determine whether Dest has exactly two predecessors and, if so, compute
9896 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +00009897 pred_iterator PI = pred_begin(DestBB);
9898 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009899 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +00009900 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009901 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +00009902 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009903 return false;
9904
9905 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +00009906 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +00009907 return false;
Chris Lattner31755a02007-04-15 01:02:18 +00009908 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009909 }
Chris Lattner31755a02007-04-15 01:02:18 +00009910 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009911 return false;
9912
9913
Chris Lattner31755a02007-04-15 01:02:18 +00009914 // Verify that the other block ends in a branch and is not otherwise empty.
9915 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009916 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +00009917 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +00009918 return false;
9919
Chris Lattner31755a02007-04-15 01:02:18 +00009920 // If the other block ends in an unconditional branch, check for the 'if then
9921 // else' case. there is an instruction before the branch.
9922 StoreInst *OtherStore = 0;
9923 if (OtherBr->isUnconditional()) {
9924 // If this isn't a store, or isn't a store to the same location, bail out.
9925 --BBI;
9926 OtherStore = dyn_cast<StoreInst>(BBI);
9927 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9928 return false;
9929 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +00009930 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +00009931 // destinations is StoreBB, then we have the if/then case.
9932 if (OtherBr->getSuccessor(0) != StoreBB &&
9933 OtherBr->getSuccessor(1) != StoreBB)
9934 return false;
9935
9936 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +00009937 // if/then triangle. See if there is a store to the same ptr as SI that
9938 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +00009939 for (;; --BBI) {
9940 // Check to see if we find the matching store.
9941 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9942 if (OtherStore->getOperand(1) != SI.getOperand(1))
9943 return false;
9944 break;
9945 }
Chris Lattnerd717c182007-05-05 22:32:24 +00009946 // If we find something that may be using the stored value, or if we run
9947 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +00009948 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9949 BBI == OtherBB->begin())
9950 return false;
9951 }
9952
9953 // In order to eliminate the store in OtherBr, we have to
9954 // make sure nothing reads the stored value in StoreBB.
9955 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9956 // FIXME: This should really be AA driven.
9957 if (isa<LoadInst>(I) || I->mayWriteToMemory())
9958 return false;
9959 }
9960 }
Chris Lattner3284d1f2007-04-15 00:07:55 +00009961
Chris Lattner31755a02007-04-15 01:02:18 +00009962 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +00009963 Value *MergedVal = OtherStore->getOperand(0);
9964 if (MergedVal != SI.getOperand(0)) {
9965 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9966 PN->reserveOperandSpace(2);
9967 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +00009968 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9969 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +00009970 }
9971
9972 // Advance to a place where it is safe to insert the new store and
9973 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +00009974 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009975 while (isa<PHINode>(BBI)) ++BBI;
9976 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9977 OtherStore->isVolatile()), *BBI);
9978
9979 // Nuke the old stores.
9980 EraseInstFromFunction(SI);
9981 EraseInstFromFunction(*OtherStore);
9982 ++NumCombined;
9983 return true;
9984}
9985
Chris Lattner2f503e62005-01-31 05:36:43 +00009986
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00009987Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9988 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00009989 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00009990 BasicBlock *TrueDest;
9991 BasicBlock *FalseDest;
9992 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9993 !isa<Constant>(X)) {
9994 // Swap Destinations and condition...
9995 BI.setCondition(X);
9996 BI.setSuccessor(0, FalseDest);
9997 BI.setSuccessor(1, TrueDest);
9998 return &BI;
9999 }
10000
Reid Spencere4d87aa2006-12-23 06:05:41 +000010001 // Cannonicalize fcmp_one -> fcmp_oeq
10002 FCmpInst::Predicate FPred; Value *Y;
10003 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10004 TrueDest, FalseDest)))
10005 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10006 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10007 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010008 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010009 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10010 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010011 // Swap Destinations and condition...
10012 BI.setCondition(NewSCC);
10013 BI.setSuccessor(0, FalseDest);
10014 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010015 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010016 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010017 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010018 return &BI;
10019 }
10020
10021 // Cannonicalize icmp_ne -> icmp_eq
10022 ICmpInst::Predicate IPred;
10023 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10024 TrueDest, FalseDest)))
10025 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10026 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10027 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10028 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010029 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010030 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10031 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010032 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010033 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010034 BI.setSuccessor(0, FalseDest);
10035 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010036 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010037 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010038 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010039 return &BI;
10040 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010041
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010042 return 0;
10043}
Chris Lattner0864acf2002-11-04 16:18:53 +000010044
Chris Lattner46238a62004-07-03 00:26:11 +000010045Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10046 Value *Cond = SI.getCondition();
10047 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10048 if (I->getOpcode() == Instruction::Add)
10049 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10050 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10051 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010052 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010053 AddRHS));
10054 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010055 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010056 return &SI;
10057 }
10058 }
10059 return 0;
10060}
10061
Chris Lattner220b0cf2006-03-05 00:22:33 +000010062/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10063/// is to leave as a vector operation.
10064static bool CheapToScalarize(Value *V, bool isConstant) {
10065 if (isa<ConstantAggregateZero>(V))
10066 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010067 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010068 if (isConstant) return true;
10069 // If all elts are the same, we can extract.
10070 Constant *Op0 = C->getOperand(0);
10071 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10072 if (C->getOperand(i) != Op0)
10073 return false;
10074 return true;
10075 }
10076 Instruction *I = dyn_cast<Instruction>(V);
10077 if (!I) return false;
10078
10079 // Insert element gets simplified to the inserted element or is deleted if
10080 // this is constant idx extract element and its a constant idx insertelt.
10081 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10082 isa<ConstantInt>(I->getOperand(2)))
10083 return true;
10084 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10085 return true;
10086 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10087 if (BO->hasOneUse() &&
10088 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10089 CheapToScalarize(BO->getOperand(1), isConstant)))
10090 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010091 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10092 if (CI->hasOneUse() &&
10093 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10094 CheapToScalarize(CI->getOperand(1), isConstant)))
10095 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010096
10097 return false;
10098}
10099
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010100/// Read and decode a shufflevector mask.
10101///
10102/// It turns undef elements into values that are larger than the number of
10103/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010104static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10105 unsigned NElts = SVI->getType()->getNumElements();
10106 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10107 return std::vector<unsigned>(NElts, 0);
10108 if (isa<UndefValue>(SVI->getOperand(2)))
10109 return std::vector<unsigned>(NElts, 2*NElts);
10110
10111 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010112 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010113 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10114 if (isa<UndefValue>(CP->getOperand(i)))
10115 Result.push_back(NElts*2); // undef -> 8
10116 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010117 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010118 return Result;
10119}
10120
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010121/// FindScalarElement - Given a vector and an element number, see if the scalar
10122/// value is already around as a register, for example if it were inserted then
10123/// extracted from the vector.
10124static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010125 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10126 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010127 unsigned Width = PTy->getNumElements();
10128 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010129 return UndefValue::get(PTy->getElementType());
10130
10131 if (isa<UndefValue>(V))
10132 return UndefValue::get(PTy->getElementType());
10133 else if (isa<ConstantAggregateZero>(V))
10134 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010135 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010136 return CP->getOperand(EltNo);
10137 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10138 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010139 if (!isa<ConstantInt>(III->getOperand(2)))
10140 return 0;
10141 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010142
10143 // If this is an insert to the element we are looking for, return the
10144 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010145 if (EltNo == IIElt)
10146 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010147
10148 // Otherwise, the insertelement doesn't modify the value, recurse on its
10149 // vector input.
10150 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010151 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010152 unsigned InEl = getShuffleMask(SVI)[EltNo];
10153 if (InEl < Width)
10154 return FindScalarElement(SVI->getOperand(0), InEl);
10155 else if (InEl < Width*2)
10156 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10157 else
10158 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010159 }
10160
10161 // Otherwise, we don't know.
10162 return 0;
10163}
10164
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010165Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010166
Dan Gohman07a96762007-07-16 14:29:03 +000010167 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010168 if (isa<UndefValue>(EI.getOperand(0)))
10169 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10170
Dan Gohman07a96762007-07-16 14:29:03 +000010171 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010172 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10173 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10174
Reid Spencer9d6565a2007-02-15 02:26:10 +000010175 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010176 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010177 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010178 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010179 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010180 if (C->getOperand(i) != op0) {
10181 op0 = 0;
10182 break;
10183 }
10184 if (op0)
10185 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010186 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010187
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010188 // If extracting a specified index from the vector, see if we can recursively
10189 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010190 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010191 unsigned IndexVal = IdxC->getZExtValue();
10192 unsigned VectorWidth =
10193 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10194
10195 // If this is extracting an invalid index, turn this into undef, to avoid
10196 // crashing the code below.
10197 if (IndexVal >= VectorWidth)
10198 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10199
Chris Lattner867b99f2006-10-05 06:55:50 +000010200 // This instruction only demands the single element from the input vector.
10201 // If the input vector has a single use, simplify it based on this use
10202 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010203 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010204 uint64_t UndefElts;
10205 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010206 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010207 UndefElts)) {
10208 EI.setOperand(0, V);
10209 return &EI;
10210 }
10211 }
10212
Reid Spencerb83eb642006-10-20 07:07:24 +000010213 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010214 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010215
10216 // If the this extractelement is directly using a bitcast from a vector of
10217 // the same number of elements, see if we can find the source element from
10218 // it. In this case, we will end up needing to bitcast the scalars.
10219 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10220 if (const VectorType *VT =
10221 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10222 if (VT->getNumElements() == VectorWidth)
10223 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10224 return new BitCastInst(Elt, EI.getType());
10225 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010226 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010227
Chris Lattner73fa49d2006-05-25 22:53:38 +000010228 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010229 if (I->hasOneUse()) {
10230 // Push extractelement into predecessor operation if legal and
10231 // profitable to do so
10232 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010233 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10234 if (CheapToScalarize(BO, isConstantElt)) {
10235 ExtractElementInst *newEI0 =
10236 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10237 EI.getName()+".lhs");
10238 ExtractElementInst *newEI1 =
10239 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10240 EI.getName()+".rhs");
10241 InsertNewInstBefore(newEI0, EI);
10242 InsertNewInstBefore(newEI1, EI);
10243 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10244 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010245 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010246 unsigned AS =
10247 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010248 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10249 PointerType::get(EI.getType(), AS),EI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010250 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +000010251 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010252 InsertNewInstBefore(GEP, EI);
10253 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010254 }
10255 }
10256 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10257 // Extracting the inserted element?
10258 if (IE->getOperand(2) == EI.getOperand(1))
10259 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10260 // If the inserted and extracted elements are constants, they must not
10261 // be the same value, extract from the pre-inserted value instead.
10262 if (isa<Constant>(IE->getOperand(2)) &&
10263 isa<Constant>(EI.getOperand(1))) {
10264 AddUsesToWorkList(EI);
10265 EI.setOperand(0, IE->getOperand(0));
10266 return &EI;
10267 }
10268 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10269 // If this is extracting an element from a shufflevector, figure out where
10270 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010271 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10272 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010273 Value *Src;
10274 if (SrcIdx < SVI->getType()->getNumElements())
10275 Src = SVI->getOperand(0);
10276 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10277 SrcIdx -= SVI->getType()->getNumElements();
10278 Src = SVI->getOperand(1);
10279 } else {
10280 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010281 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010282 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010283 }
10284 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010285 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010286 return 0;
10287}
10288
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010289/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10290/// elements from either LHS or RHS, return the shuffle mask and true.
10291/// Otherwise, return false.
10292static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10293 std::vector<Constant*> &Mask) {
10294 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10295 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010296 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010297
10298 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010299 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010300 return true;
10301 } else if (V == LHS) {
10302 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010303 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010304 return true;
10305 } else if (V == RHS) {
10306 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010307 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010308 return true;
10309 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10310 // If this is an insert of an extract from some other vector, include it.
10311 Value *VecOp = IEI->getOperand(0);
10312 Value *ScalarOp = IEI->getOperand(1);
10313 Value *IdxOp = IEI->getOperand(2);
10314
Chris Lattnerd929f062006-04-27 21:14:21 +000010315 if (!isa<ConstantInt>(IdxOp))
10316 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010317 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010318
10319 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10320 // Okay, we can handle this if the vector we are insertinting into is
10321 // transitively ok.
10322 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10323 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010324 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010325 return true;
10326 }
10327 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10328 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010329 EI->getOperand(0)->getType() == V->getType()) {
10330 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010331 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010332
10333 // This must be extracting from either LHS or RHS.
10334 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10335 // Okay, we can handle this if the vector we are insertinting into is
10336 // transitively ok.
10337 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10338 // If so, update the mask to reflect the inserted value.
10339 if (EI->getOperand(0) == LHS) {
10340 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010341 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010342 } else {
10343 assert(EI->getOperand(0) == RHS);
10344 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010345 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010346
10347 }
10348 return true;
10349 }
10350 }
10351 }
10352 }
10353 }
10354 // TODO: Handle shufflevector here!
10355
10356 return false;
10357}
10358
10359/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10360/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10361/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010362static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010363 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010364 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010365 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010366 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010367 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010368
10369 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010370 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010371 return V;
10372 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010373 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010374 return V;
10375 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10376 // If this is an insert of an extract from some other vector, include it.
10377 Value *VecOp = IEI->getOperand(0);
10378 Value *ScalarOp = IEI->getOperand(1);
10379 Value *IdxOp = IEI->getOperand(2);
10380
10381 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10382 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10383 EI->getOperand(0)->getType() == V->getType()) {
10384 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010385 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10386 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010387
10388 // Either the extracted from or inserted into vector must be RHSVec,
10389 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010390 if (EI->getOperand(0) == RHS || RHS == 0) {
10391 RHS = EI->getOperand(0);
10392 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010393 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010394 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010395 return V;
10396 }
10397
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010398 if (VecOp == RHS) {
10399 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010400 // Everything but the extracted element is replaced with the RHS.
10401 for (unsigned i = 0; i != NumElts; ++i) {
10402 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010403 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010404 }
10405 return V;
10406 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010407
10408 // If this insertelement is a chain that comes from exactly these two
10409 // vectors, return the vector and the effective shuffle.
10410 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10411 return EI->getOperand(0);
10412
Chris Lattnerefb47352006-04-15 01:39:45 +000010413 }
10414 }
10415 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010416 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010417
10418 // Otherwise, can't do anything fancy. Return an identity vector.
10419 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010420 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010421 return V;
10422}
10423
10424Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10425 Value *VecOp = IE.getOperand(0);
10426 Value *ScalarOp = IE.getOperand(1);
10427 Value *IdxOp = IE.getOperand(2);
10428
Chris Lattner599ded12007-04-09 01:11:16 +000010429 // Inserting an undef or into an undefined place, remove this.
10430 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10431 ReplaceInstUsesWith(IE, VecOp);
10432
Chris Lattnerefb47352006-04-15 01:39:45 +000010433 // If the inserted element was extracted from some other vector, and if the
10434 // indexes are constant, try to turn this into a shufflevector operation.
10435 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10436 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10437 EI->getOperand(0)->getType() == IE.getType()) {
10438 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010439 unsigned ExtractedIdx =
10440 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010441 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010442
10443 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10444 return ReplaceInstUsesWith(IE, VecOp);
10445
10446 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10447 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10448
10449 // If we are extracting a value from a vector, then inserting it right
10450 // back into the same place, just use the input vector.
10451 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10452 return ReplaceInstUsesWith(IE, VecOp);
10453
10454 // We could theoretically do this for ANY input. However, doing so could
10455 // turn chains of insertelement instructions into a chain of shufflevector
10456 // instructions, and right now we do not merge shufflevectors. As such,
10457 // only do this in a situation where it is clear that there is benefit.
10458 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10459 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10460 // the values of VecOp, except then one read from EIOp0.
10461 // Build a new shuffle mask.
10462 std::vector<Constant*> Mask;
10463 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000010464 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010465 else {
10466 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000010467 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000010468 NumVectorElts));
10469 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000010470 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010471 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000010472 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010473 }
10474
10475 // If this insertelement isn't used by some other insertelement, turn it
10476 // (and any insertelements it points to), into one big shuffle.
10477 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10478 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010479 Value *RHS = 0;
10480 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10481 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10482 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000010483 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010484 }
10485 }
10486 }
10487
10488 return 0;
10489}
10490
10491
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010492Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10493 Value *LHS = SVI.getOperand(0);
10494 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000010495 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010496
10497 bool MadeChange = false;
10498
Chris Lattner867b99f2006-10-05 06:55:50 +000010499 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000010500 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010501 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10502
Chris Lattnere4929dd2007-01-05 07:36:08 +000010503 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000010504 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000010505 if (isa<UndefValue>(SVI.getOperand(1))) {
10506 // Scan to see if there are any references to the RHS. If so, replace them
10507 // with undef element refs and set MadeChange to true.
10508 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10509 if (Mask[i] >= e && Mask[i] != 2*e) {
10510 Mask[i] = 2*e;
10511 MadeChange = true;
10512 }
10513 }
10514
10515 if (MadeChange) {
10516 // Remap any references to RHS to use LHS.
10517 std::vector<Constant*> Elts;
10518 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10519 if (Mask[i] == 2*e)
10520 Elts.push_back(UndefValue::get(Type::Int32Ty));
10521 else
10522 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10523 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000010524 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000010525 }
10526 }
Chris Lattnerefb47352006-04-15 01:39:45 +000010527
Chris Lattner863bcff2006-05-25 23:48:38 +000010528 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10529 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10530 if (LHS == RHS || isa<UndefValue>(LHS)) {
10531 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010532 // shuffle(undef,undef,mask) -> undef.
10533 return ReplaceInstUsesWith(SVI, LHS);
10534 }
10535
Chris Lattner863bcff2006-05-25 23:48:38 +000010536 // Remap any references to RHS to use LHS.
10537 std::vector<Constant*> Elts;
10538 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000010539 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010540 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010541 else {
10542 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10543 (Mask[i] < e && isa<UndefValue>(LHS)))
10544 Mask[i] = 2*e; // Turn into undef.
10545 else
10546 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010547 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010548 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010549 }
Chris Lattner863bcff2006-05-25 23:48:38 +000010550 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010551 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000010552 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010553 LHS = SVI.getOperand(0);
10554 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010555 MadeChange = true;
10556 }
10557
Chris Lattner7b2e27922006-05-26 00:29:06 +000010558 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000010559 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000010560
Chris Lattner863bcff2006-05-25 23:48:38 +000010561 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10562 if (Mask[i] >= e*2) continue; // Ignore undef values.
10563 // Is this an identity shuffle of the LHS value?
10564 isLHSID &= (Mask[i] == i);
10565
10566 // Is this an identity shuffle of the RHS value?
10567 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000010568 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010569
Chris Lattner863bcff2006-05-25 23:48:38 +000010570 // Eliminate identity shuffles.
10571 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10572 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010573
Chris Lattner7b2e27922006-05-26 00:29:06 +000010574 // If the LHS is a shufflevector itself, see if we can combine it with this
10575 // one without producing an unusual shuffle. Here we are really conservative:
10576 // we are absolutely afraid of producing a shuffle mask not in the input
10577 // program, because the code gen may not be smart enough to turn a merged
10578 // shuffle into two specific shuffles: it may produce worse code. As such,
10579 // we only merge two shuffles if the result is one of the two input shuffle
10580 // masks. In this case, merging the shuffles just removes one instruction,
10581 // which we know is safe. This is good for things like turning:
10582 // (splat(splat)) -> splat.
10583 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10584 if (isa<UndefValue>(RHS)) {
10585 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10586
10587 std::vector<unsigned> NewMask;
10588 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10589 if (Mask[i] >= 2*e)
10590 NewMask.push_back(2*e);
10591 else
10592 NewMask.push_back(LHSMask[Mask[i]]);
10593
10594 // If the result mask is equal to the src shuffle or this shuffle mask, do
10595 // the replacement.
10596 if (NewMask == LHSMask || NewMask == Mask) {
10597 std::vector<Constant*> Elts;
10598 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10599 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010600 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010601 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010602 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010603 }
10604 }
10605 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10606 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000010607 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010608 }
10609 }
10610 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000010611
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010612 return MadeChange ? &SVI : 0;
10613}
10614
10615
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010616
Chris Lattnerea1c4542004-12-08 23:43:58 +000010617
10618/// TryToSinkInstruction - Try to move the specified instruction from its
10619/// current block into the beginning of DestBlock, which can only happen if it's
10620/// safe to move the instruction past all of the instructions between it and the
10621/// end of its block.
10622static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10623 assert(I->hasOneUse() && "Invariants didn't hold!");
10624
Chris Lattner108e9022005-10-27 17:13:11 +000010625 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10626 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000010627
Chris Lattnerea1c4542004-12-08 23:43:58 +000010628 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000010629 if (isa<AllocaInst>(I) && I->getParent() ==
10630 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000010631 return false;
10632
Chris Lattner96a52a62004-12-09 07:14:34 +000010633 // We can only sink load instructions if there is nothing between the load and
10634 // the end of block that could change the value.
10635 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +000010636 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10637 Scan != E; ++Scan)
10638 if (Scan->mayWriteToMemory())
10639 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000010640 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000010641
10642 BasicBlock::iterator InsertPos = DestBlock->begin();
10643 while (isa<PHINode>(InsertPos)) ++InsertPos;
10644
Chris Lattner4bc5f802005-08-08 19:11:57 +000010645 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000010646 ++NumSunkInst;
10647 return true;
10648}
10649
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010650
10651/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10652/// all reachable code to the worklist.
10653///
10654/// This has a couple of tricks to make the code faster and more powerful. In
10655/// particular, we constant fold and DCE instructions as we go, to avoid adding
10656/// them to the worklist (this significantly speeds up instcombine on code where
10657/// many instructions are dead or constant). Additionally, if we find a branch
10658/// whose condition is a known constant, we only visit the reachable successors.
10659///
10660static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000010661 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000010662 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010663 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000010664 std::vector<BasicBlock*> Worklist;
10665 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010666
Chris Lattner2c7718a2007-03-23 19:17:18 +000010667 while (!Worklist.empty()) {
10668 BB = Worklist.back();
10669 Worklist.pop_back();
10670
10671 // We have now visited this block! If we've already been here, ignore it.
10672 if (!Visited.insert(BB)) continue;
10673
10674 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10675 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010676
Chris Lattner2c7718a2007-03-23 19:17:18 +000010677 // DCE instruction if trivially dead.
10678 if (isInstructionTriviallyDead(Inst)) {
10679 ++NumDeadInst;
10680 DOUT << "IC: DCE: " << *Inst;
10681 Inst->eraseFromParent();
10682 continue;
10683 }
10684
10685 // ConstantProp instruction if trivially constant.
10686 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10687 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10688 Inst->replaceAllUsesWith(C);
10689 ++NumConstProp;
10690 Inst->eraseFromParent();
10691 continue;
10692 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000010693
Chris Lattner2c7718a2007-03-23 19:17:18 +000010694 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010695 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000010696
10697 // Recursively visit successors. If this is a branch or switch on a
10698 // constant, only visit the reachable successor.
10699 TerminatorInst *TI = BB->getTerminator();
10700 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10701 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10702 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10703 Worklist.push_back(BI->getSuccessor(!CondVal));
10704 continue;
10705 }
10706 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10707 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10708 // See if this is an explicit destination.
10709 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10710 if (SI->getCaseValue(i) == Cond) {
10711 Worklist.push_back(SI->getSuccessor(i));
10712 continue;
10713 }
10714
10715 // Otherwise it is the default destination.
10716 Worklist.push_back(SI->getSuccessor(0));
10717 continue;
10718 }
10719 }
10720
10721 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10722 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010723 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010724}
10725
Chris Lattnerec9c3582007-03-03 02:04:50 +000010726bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010727 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000010728 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000010729
10730 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10731 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000010732
Chris Lattnerb3d59702005-07-07 20:40:38 +000010733 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010734 // Do a depth-first traversal of the function, populate the worklist with
10735 // the reachable instructions. Ignore blocks that are not reachable. Keep
10736 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000010737 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010738 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000010739
Chris Lattnerb3d59702005-07-07 20:40:38 +000010740 // Do a quick scan over the function. If we find any blocks that are
10741 // unreachable, remove any instructions inside of them. This prevents
10742 // the instcombine code from having to deal with some bad special cases.
10743 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10744 if (!Visited.count(BB)) {
10745 Instruction *Term = BB->getTerminator();
10746 while (Term != BB->begin()) { // Remove instrs bottom-up
10747 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000010748
Bill Wendlingb7427032006-11-26 09:46:52 +000010749 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000010750 ++NumDeadInst;
10751
10752 if (!I->use_empty())
10753 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10754 I->eraseFromParent();
10755 }
10756 }
10757 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010758
Chris Lattnerdbab3862007-03-02 21:28:56 +000010759 while (!Worklist.empty()) {
10760 Instruction *I = RemoveOneFromWorkList();
10761 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000010762
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010763 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000010764 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010765 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000010766 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010767 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000010768 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000010769
Bill Wendlingb7427032006-11-26 09:46:52 +000010770 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010771
10772 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010773 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010774 continue;
10775 }
Chris Lattner62b14df2002-09-02 04:59:56 +000010776
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010777 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000010778 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010779 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010780
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010781 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010782 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000010783 ReplaceInstUsesWith(*I, C);
10784
Chris Lattner62b14df2002-09-02 04:59:56 +000010785 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010786 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010787 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010788 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000010789 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000010790
Chris Lattnerea1c4542004-12-08 23:43:58 +000010791 // See if we can trivially sink this instruction to a successor basic block.
10792 if (I->hasOneUse()) {
10793 BasicBlock *BB = I->getParent();
10794 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10795 if (UserParent != BB) {
10796 bool UserIsSuccessor = false;
10797 // See if the user is one of our successors.
10798 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10799 if (*SI == UserParent) {
10800 UserIsSuccessor = true;
10801 break;
10802 }
10803
10804 // If the user is one of our immediate successors, and if that successor
10805 // only has us as a predecessors (we'd have to split the critical edge
10806 // otherwise), we can keep going.
10807 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10808 next(pred_begin(UserParent)) == pred_end(UserParent))
10809 // Okay, the CFG is simple enough, try to sink this instruction.
10810 Changed |= TryToSinkInstruction(I, UserParent);
10811 }
10812 }
10813
Chris Lattner8a2a3112001-12-14 16:52:21 +000010814 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000010815#ifndef NDEBUG
10816 std::string OrigI;
10817#endif
10818 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000010819 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000010820 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010821 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010822 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010823 DOUT << "IC: Old = " << *I
10824 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000010825
Chris Lattnerf523d062004-06-09 05:08:07 +000010826 // Everything uses the new instruction now.
10827 I->replaceAllUsesWith(Result);
10828
10829 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010830 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000010831 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010832
Chris Lattner6934a042007-02-11 01:23:03 +000010833 // Move the name to the new instruction first.
10834 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010835
10836 // Insert the new instruction into the basic block...
10837 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000010838 BasicBlock::iterator InsertPos = I;
10839
10840 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10841 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10842 ++InsertPos;
10843
10844 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010845
Chris Lattner00d51312004-05-01 23:27:23 +000010846 // Make sure that we reprocess all operands now that we reduced their
10847 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010848 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000010849
Chris Lattnerf523d062004-06-09 05:08:07 +000010850 // Instructions can end up on the worklist more than once. Make sure
10851 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010852 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010853
10854 // Erase the old instruction.
10855 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000010856 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000010857#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000010858 DOUT << "IC: Mod = " << OrigI
10859 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000010860#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000010861
Chris Lattner90ac28c2002-08-02 19:29:35 +000010862 // If the instruction was modified, it's possible that it is now dead.
10863 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000010864 if (isInstructionTriviallyDead(I)) {
10865 // Make sure we process all operands now that we are reducing their
10866 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000010867 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010868
Chris Lattner00d51312004-05-01 23:27:23 +000010869 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010870 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010871 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000010872 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000010873 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000010874 AddToWorkList(I);
10875 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000010876 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010877 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010878 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000010879 }
10880 }
10881
Chris Lattnerec9c3582007-03-03 02:04:50 +000010882 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000010883
10884 // Do an explicit clear, this shrinks the map if needed.
10885 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010886 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010887}
10888
Chris Lattnerec9c3582007-03-03 02:04:50 +000010889
10890bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000010891 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10892
Chris Lattnerec9c3582007-03-03 02:04:50 +000010893 bool EverMadeChange = false;
10894
10895 // Iterate while there is work to do.
10896 unsigned Iteration = 0;
10897 while (DoOneIteration(F, Iteration++))
10898 EverMadeChange = true;
10899 return EverMadeChange;
10900}
10901
Brian Gaeke96d4bf72004-07-27 17:43:21 +000010902FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010903 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010904}
Brian Gaeked0fde302003-11-11 22:41:34 +000010905