blob: cd452b5cd7e213dddaed6414bc1b3b03c7985a26 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9dbb4292009-11-09 23:28:39 +000045#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000046#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner173234a2008-06-02 01:18:21 +000047#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000048#include "llvm/Target/TargetData.h"
49#include "llvm/Transforms/Utils/BasicBlockUtils.h"
50#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000051#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000052#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000053#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000054#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000055#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000056#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000057#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000058#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000059#include "llvm/Support/PatternMatch.h"
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000060#include "llvm/Support/TargetFolder.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000061#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000062#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000063#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000064#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000065#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000066#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000067#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000068#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000069using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000070using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072STATISTIC(NumCombined , "Number of insts combined");
73STATISTIC(NumConstProp, "Number of constant folds");
74STATISTIC(NumDeadInst , "Number of dead inst eliminated");
75STATISTIC(NumDeadStore, "Number of dead stores eliminated");
76STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000077
Chris Lattner0e5f4992006-12-19 21:40:18 +000078namespace {
Chris Lattner873ff012009-08-30 05:55:36 +000079 /// InstCombineWorklist - This is the worklist management logic for
80 /// InstCombine.
81 class InstCombineWorklist {
82 SmallVector<Instruction*, 256> Worklist;
83 DenseMap<Instruction*, unsigned> WorklistMap;
84
85 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
86 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
87 public:
88 InstCombineWorklist() {}
89
90 bool isEmpty() const { return Worklist.empty(); }
91
92 /// Add - Add the specified instruction to the worklist if it isn't already
93 /// in it.
94 void Add(Instruction *I) {
Jeffrey Yasskin43069632009-10-08 00:12:24 +000095 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
96 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner873ff012009-08-30 05:55:36 +000097 Worklist.push_back(I);
Jeffrey Yasskin43069632009-10-08 00:12:24 +000098 }
Chris Lattner873ff012009-08-30 05:55:36 +000099 }
100
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000101 void AddValue(Value *V) {
102 if (Instruction *I = dyn_cast<Instruction>(V))
103 Add(I);
104 }
105
Chris Lattner67f7d542009-10-12 03:58:40 +0000106 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
107 /// which should only be done when the worklist is empty and when the group
108 /// has no duplicates.
109 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
110 assert(Worklist.empty() && "Worklist must be empty to add initial group");
111 Worklist.reserve(NumEntries+16);
112 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
113 for (; NumEntries; --NumEntries) {
114 Instruction *I = List[NumEntries-1];
115 WorklistMap.insert(std::make_pair(I, Worklist.size()));
116 Worklist.push_back(I);
117 }
118 }
119
Chris Lattner7a1e9242009-08-30 06:13:40 +0000120 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +0000121 void Remove(Instruction *I) {
122 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
123 if (It == WorklistMap.end()) return; // Not in worklist.
124
125 // Don't bother moving everything down, just null out the slot.
126 Worklist[It->second] = 0;
127
128 WorklistMap.erase(It);
129 }
130
131 Instruction *RemoveOne() {
132 Instruction *I = Worklist.back();
133 Worklist.pop_back();
134 WorklistMap.erase(I);
135 return I;
136 }
137
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000138 /// AddUsersToWorkList - When an instruction is simplified, add all users of
139 /// the instruction to the work lists because they might get more simplified
140 /// now.
141 ///
142 void AddUsersToWorkList(Instruction &I) {
143 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
144 UI != UE; ++UI)
145 Add(cast<Instruction>(*UI));
146 }
147
Chris Lattner873ff012009-08-30 05:55:36 +0000148
149 /// Zap - check that the worklist is empty and nuke the backing store for
150 /// the map if it is large.
151 void Zap() {
152 assert(WorklistMap.empty() && "Worklist empty, but map not?");
153
154 // Do an explicit clear, this shrinks the map if needed.
155 WorklistMap.clear();
156 }
157 };
158} // end anonymous namespace.
159
160
161namespace {
Chris Lattner74381062009-08-30 07:44:24 +0000162 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
163 /// just like the normal insertion helper, but also adds any new instructions
164 /// to the instcombine worklist.
165 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
166 InstCombineWorklist &Worklist;
167 public:
168 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
169
170 void InsertHelper(Instruction *I, const Twine &Name,
171 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
172 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
173 Worklist.Add(I);
174 }
175 };
176} // end anonymous namespace
177
178
179namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000180 class InstCombiner : public FunctionPass,
181 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000182 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000183 bool MustPreserveLCSSA;
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000184 bool MadeIRChange;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000185 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000186 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000187 InstCombineWorklist Worklist;
188
Chris Lattner74381062009-08-30 07:44:24 +0000189 /// Builder - This is an IRBuilder that automatically inserts new
190 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +0000191 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000192 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000193
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000194 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000195 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000196
Owen Andersone922c022009-07-22 00:24:57 +0000197 LLVMContext *Context;
198 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000199
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000200 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000201 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000202
203 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000204
Chris Lattner97e52e42002-04-28 21:27:06 +0000205 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000206 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000207 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000208 }
209
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000210 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000211
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000212 // Visitation implementation - Implement instruction combining for different
213 // instruction types. The semantics are as follows:
214 // Return Value:
215 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000216 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000217 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000218 //
Chris Lattner7e708292002-06-25 16:13:24 +0000219 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000220 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner092543c2009-11-04 08:05:20 +0000221 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
Chris Lattner7e708292002-06-25 16:13:24 +0000222 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000223 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000224 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000225 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000226 Instruction *visitURem(BinaryOperator &I);
227 Instruction *visitSRem(BinaryOperator &I);
228 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000229 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000230 Instruction *commonRemTransforms(BinaryOperator &I);
231 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000232 Instruction *commonDivTransforms(BinaryOperator &I);
233 Instruction *commonIDivTransforms(BinaryOperator &I);
234 Instruction *visitUDiv(BinaryOperator &I);
235 Instruction *visitSDiv(BinaryOperator &I);
236 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000237 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000238 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000239 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000240 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000241 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000242 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000243 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000244 Instruction *visitOr (BinaryOperator &I);
245 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000246 Instruction *visitShl(BinaryOperator &I);
247 Instruction *visitAShr(BinaryOperator &I);
248 Instruction *visitLShr(BinaryOperator &I);
249 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000250 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
251 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000252 Instruction *visitFCmpInst(FCmpInst &I);
253 Instruction *visitICmpInst(ICmpInst &I);
254 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000255 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
256 Instruction *LHS,
257 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000258 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
259 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000260
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000261 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000262 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000263 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000264 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000265 Instruction *commonCastTransforms(CastInst &CI);
266 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000267 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000268 Instruction *visitTrunc(TruncInst &CI);
269 Instruction *visitZExt(ZExtInst &CI);
270 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000271 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000272 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000273 Instruction *visitFPToUI(FPToUIInst &FI);
274 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000275 Instruction *visitUIToFP(CastInst &CI);
276 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000277 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000278 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000279 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000280 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
281 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000282 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000283 Instruction *visitSelectInst(SelectInst &SI);
284 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000285 Instruction *visitCallInst(CallInst &CI);
286 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner9956c052009-11-08 19:23:30 +0000287
288 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
Chris Lattner7e708292002-06-25 16:13:24 +0000289 Instruction *visitPHINode(PHINode &PN);
290 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000291 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000292 Instruction *visitFree(Instruction &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000293 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000294 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000295 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000296 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000297 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000298 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000299 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000300 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000301
302 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000303 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000304
Chris Lattner9fe38862003-06-19 17:00:31 +0000305 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000306 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000307 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000308 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000309 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
310 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000311 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000312 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
313
Chris Lattner9fe38862003-06-19 17:00:31 +0000314
Chris Lattner28977af2004-04-05 01:30:19 +0000315 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000316 // InsertNewInstBefore - insert an instruction New before instruction Old
317 // in the program. Add the new instruction to the worklist.
318 //
Chris Lattner955f3312004-09-28 21:48:02 +0000319 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000320 assert(New && New->getParent() == 0 &&
321 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000322 BasicBlock *BB = Old.getParent();
323 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000324 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000325 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000326 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000327
Chris Lattner8b170942002-08-09 23:47:40 +0000328 // ReplaceInstUsesWith - This method is to be used when an instruction is
329 // found to be dead, replacable with another preexisting expression. Here
330 // we add all uses of I to the worklist, replace all uses of I with the new
331 // value, then return I, so that the inst combiner will know that I was
332 // modified.
333 //
334 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000335 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000336
337 // If we are replacing the instruction with itself, this must be in a
338 // segment of unreachable code, so just clobber the instruction.
339 if (&I == V)
340 V = UndefValue::get(I.getType());
341
342 I.replaceAllUsesWith(V);
343 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000344 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000345
346 // EraseInstFromFunction - When dealing with an instruction that has side
347 // effects or produces a void value, we can't rely on DCE to delete the
348 // instruction. Instead, visit methods should return the value returned by
349 // this function.
350 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000351 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000352
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000353 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000354 // Make sure that we reprocess all operands now that we reduced their
355 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000356 if (I.getNumOperands() < 8) {
357 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
358 if (Instruction *Op = dyn_cast<Instruction>(*i))
359 Worklist.Add(Op);
360 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000361 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000362 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000363 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000364 return 0; // Don't do anything with FI
365 }
Chris Lattner173234a2008-06-02 01:18:21 +0000366
367 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
368 APInt &KnownOne, unsigned Depth = 0) const {
369 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
370 }
371
372 bool MaskedValueIsZero(Value *V, const APInt &Mask,
373 unsigned Depth = 0) const {
374 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
375 }
376 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
377 return llvm::ComputeNumSignBits(Op, TD, Depth);
378 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000379
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000380 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000381
Reid Spencere4d87aa2006-12-23 06:05:41 +0000382 /// SimplifyCommutative - This performs a few simplifications for
383 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000384 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000385
Chris Lattner886ab6c2009-01-31 08:15:18 +0000386 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
387 /// based on the demanded bits.
388 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
389 APInt& KnownZero, APInt& KnownOne,
390 unsigned Depth);
391 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000392 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000393 unsigned Depth=0);
394
395 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
396 /// SimplifyDemandedBits knows about. See if the instruction has any
397 /// properties that allow us to simplify its operands.
398 bool SimplifyDemandedInstructionBits(Instruction &Inst);
399
Evan Cheng388df622009-02-03 10:05:09 +0000400 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
401 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000402
Chris Lattner5d1704d2009-09-27 19:57:57 +0000403 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
404 // which has a PHI node as operand #0, see if we can fold the instruction
405 // into the PHI (which is only possible if all operands to the PHI are
406 // constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000407 //
408 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
409 // that would normally be unprofitable because they strongly encourage jump
410 // threading.
411 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000412
Chris Lattnerbac32862004-11-14 19:13:23 +0000413 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
414 // operator and they all are only used by the PHI, PHI together their
415 // inputs, and do the operation once, to the result of the PHI.
416 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000417 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000418 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner751a3622009-11-01 20:04:24 +0000419 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000420
Chris Lattner7da52b22006-11-01 04:51:18 +0000421
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000422 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
423 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000424
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000425 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000426 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000427 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000428 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000429 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000430 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000431 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000432 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000433 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000434
Chris Lattnerafe91a52006-06-15 19:07:26 +0000435
Reid Spencerc55b2432006-12-13 18:21:21 +0000436 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000437
Dan Gohman6de29f82009-06-15 22:12:54 +0000438 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000439 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000440 unsigned GetOrEnforceKnownAlignment(Value *V,
441 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000442
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000443 };
Chris Lattner873ff012009-08-30 05:55:36 +0000444} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000445
Dan Gohman844731a2008-05-13 00:00:25 +0000446char InstCombiner::ID = 0;
447static RegisterPass<InstCombiner>
448X("instcombine", "Combine redundant instructions");
449
Chris Lattner4f98c562003-03-10 21:43:22 +0000450// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000451// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000452static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000453 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000454 if (BinaryOperator::isNeg(V) ||
455 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000456 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000457 return 3;
458 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000459 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000460 if (isa<Argument>(V)) return 3;
461 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000462}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000463
Chris Lattnerc8802d22003-03-11 00:12:48 +0000464// isOnlyUse - Return true if this instruction will be deleted if we stop using
465// it.
466static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000467 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000468}
469
Chris Lattner4cb170c2004-02-23 06:38:22 +0000470// getPromotedType - Return the specified type promoted as it would be to pass
471// though a va_arg area...
472static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000473 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
474 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000475 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000476 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000477 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000478}
479
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000480/// getBitCastOperand - If the specified operand is a CastInst, a constant
481/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
482/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000483static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000484 if (Operator *O = dyn_cast<Operator>(V)) {
485 if (O->getOpcode() == Instruction::BitCast)
486 return O->getOperand(0);
487 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
488 if (GEP->hasAllZeroIndices())
489 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000490 }
Chris Lattnereed48272005-09-13 00:40:14 +0000491 return 0;
492}
493
Reid Spencer3da59db2006-11-27 01:05:10 +0000494/// This function is a wrapper around CastInst::isEliminableCastPair. It
495/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000496static Instruction::CastOps
497isEliminableCastPair(
498 const CastInst *CI, ///< The first cast instruction
499 unsigned opcode, ///< The opcode of the second cast instruction
500 const Type *DstTy, ///< The target type for the second cast instruction
501 TargetData *TD ///< The target data for pointer size
502) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000503
Reid Spencer3da59db2006-11-27 01:05:10 +0000504 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
505 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000506
Reid Spencer3da59db2006-11-27 01:05:10 +0000507 // Get the opcodes of the two Cast instructions
508 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
509 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000510
Chris Lattnera0e69692009-03-24 18:35:40 +0000511 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000512 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000513 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000514
515 // We don't want to form an inttoptr or ptrtoint that converts to an integer
516 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000517 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000518 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000519 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000520 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000521 Res = 0;
522
523 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000524}
525
526/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
527/// in any code being generated. It does not require codegen if V is simple
528/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000529static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
530 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000531 if (V->getType() == Ty || isa<Constant>(V)) return false;
532
Chris Lattner01575b72006-05-25 23:24:33 +0000533 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000534 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000535 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000536 return false;
537 return true;
538}
539
Chris Lattner4f98c562003-03-10 21:43:22 +0000540// SimplifyCommutative - This performs a few simplifications for commutative
541// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000542//
Chris Lattner4f98c562003-03-10 21:43:22 +0000543// 1. Order operands such that they are listed from right (least complex) to
544// left (most complex). This puts constants before unary operators before
545// binary operators.
546//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000547// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
548// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000549//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000550bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000551 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000552 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000553 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000554
Chris Lattner4f98c562003-03-10 21:43:22 +0000555 if (!I.isAssociative()) return Changed;
556 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000557 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
558 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
559 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000560 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000561 cast<Constant>(I.getOperand(1)),
562 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000563 I.setOperand(0, Op->getOperand(0));
564 I.setOperand(1, Folded);
565 return true;
566 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
567 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
568 isOnlyUse(Op) && isOnlyUse(Op1)) {
569 Constant *C1 = cast<Constant>(Op->getOperand(1));
570 Constant *C2 = cast<Constant>(Op1->getOperand(1));
571
572 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000573 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000574 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000575 Op1->getOperand(0),
576 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000577 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000578 I.setOperand(0, New);
579 I.setOperand(1, Folded);
580 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000581 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000582 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000583 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000584}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000585
Chris Lattner8d969642003-03-10 23:06:50 +0000586// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
587// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000588//
Dan Gohman186a6362009-08-12 16:04:34 +0000589static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000590 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000591 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000592
Chris Lattner0ce85802004-12-14 20:08:06 +0000593 // Constants can be considered to be negated values if they can be folded.
594 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000595 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000596
597 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
598 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000599 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000600
Chris Lattner8d969642003-03-10 23:06:50 +0000601 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000602}
603
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000604// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
605// instruction if the LHS is a constant negative zero (which is the 'negate'
606// form).
607//
Dan Gohman186a6362009-08-12 16:04:34 +0000608static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000609 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000610 return BinaryOperator::getFNegArgument(V);
611
612 // Constants can be considered to be negated values if they can be folded.
613 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000614 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000615
616 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
617 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000618 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000619
620 return 0;
621}
622
Chris Lattner48b59ec2009-10-26 15:40:07 +0000623/// isFreeToInvert - Return true if the specified value is free to invert (apply
624/// ~ to). This happens in cases where the ~ can be eliminated.
625static inline bool isFreeToInvert(Value *V) {
626 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000627 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000628 return true;
629
630 // Constants can be considered to be not'ed values.
631 if (isa<ConstantInt>(V))
632 return true;
633
634 // Compares can be inverted if they have a single use.
635 if (CmpInst *CI = dyn_cast<CmpInst>(V))
636 return CI->hasOneUse();
637
638 return false;
639}
640
641static inline Value *dyn_castNotVal(Value *V) {
642 // If this is not(not(x)) don't return that this is a not: we want the two
643 // not's to be folded first.
644 if (BinaryOperator::isNot(V)) {
645 Value *Operand = BinaryOperator::getNotArgument(V);
646 if (!isFreeToInvert(Operand))
647 return Operand;
648 }
Chris Lattner8d969642003-03-10 23:06:50 +0000649
650 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000651 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000652 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000653 return 0;
654}
655
Chris Lattner48b59ec2009-10-26 15:40:07 +0000656
657
Chris Lattnerc8802d22003-03-11 00:12:48 +0000658// dyn_castFoldableMul - If this value is a multiply that can be folded into
659// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000660// non-constant operand of the multiply, and set CST to point to the multiplier.
661// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000662//
Dan Gohman186a6362009-08-12 16:04:34 +0000663static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000664 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000665 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000666 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000667 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000668 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000669 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000670 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000671 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000672 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000673 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000674 CST = ConstantInt::get(V->getType()->getContext(),
675 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000676 return I->getOperand(0);
677 }
678 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000679 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000680}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000681
Reid Spencer7177c3a2007-03-25 05:33:51 +0000682/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000683static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000684 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000685 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000686}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000687/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000688static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000689 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000690 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000691}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000692/// MultiplyOverflows - True if the multiply can not be expressed in an int
693/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000694static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000695 uint32_t W = C1->getBitWidth();
696 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
697 if (sign) {
698 LHSExt.sext(W * 2);
699 RHSExt.sext(W * 2);
700 } else {
701 LHSExt.zext(W * 2);
702 RHSExt.zext(W * 2);
703 }
704
705 APInt MulExt = LHSExt * RHSExt;
706
707 if (sign) {
708 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
709 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
710 return MulExt.slt(Min) || MulExt.sgt(Max);
711 } else
712 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
713}
Chris Lattner955f3312004-09-28 21:48:02 +0000714
Reid Spencere7816b52007-03-08 01:52:58 +0000715
Chris Lattner255d8912006-02-11 09:31:47 +0000716/// ShrinkDemandedConstant - Check to see if the specified operand of the
717/// specified instruction is a constant integer. If so, check to see if there
718/// are any bits set in the constant that are not demanded. If so, shrink the
719/// constant and return true.
720static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000721 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000722 assert(I && "No instruction?");
723 assert(OpNo < I->getNumOperands() && "Operand index too large");
724
725 // If the operand is not a constant integer, nothing to do.
726 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
727 if (!OpC) return false;
728
729 // If there are no bits set that aren't demanded, nothing to do.
730 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
731 if ((~Demanded & OpC->getValue()) == 0)
732 return false;
733
734 // This instruction is producing bits that are not demanded. Shrink the RHS.
735 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000736 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000737 return true;
738}
739
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000740// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
741// set of known zero and one bits, compute the maximum and minimum values that
742// could have the specified known zero and known one bits, returning them in
743// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000744static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000745 const APInt& KnownOne,
746 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000747 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
748 KnownZero.getBitWidth() == Min.getBitWidth() &&
749 KnownZero.getBitWidth() == Max.getBitWidth() &&
750 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000751 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000752
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000753 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
754 // bit if it is unknown.
755 Min = KnownOne;
756 Max = KnownOne|UnknownBits;
757
Dan Gohman1c8491e2009-04-25 17:12:48 +0000758 if (UnknownBits.isNegative()) { // Sign bit is unknown
759 Min.set(Min.getBitWidth()-1);
760 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000761 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000762}
763
764// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
765// a set of known zero and one bits, compute the maximum and minimum values that
766// could have the specified known zero and known one bits, returning them in
767// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000768static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000769 const APInt &KnownOne,
770 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000771 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
772 KnownZero.getBitWidth() == Min.getBitWidth() &&
773 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000774 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000775 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000776
777 // The minimum value is when the unknown bits are all zeros.
778 Min = KnownOne;
779 // The maximum value is when the unknown bits are all ones.
780 Max = KnownOne|UnknownBits;
781}
Chris Lattner255d8912006-02-11 09:31:47 +0000782
Chris Lattner886ab6c2009-01-31 08:15:18 +0000783/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
784/// SimplifyDemandedBits knows about. See if the instruction has any
785/// properties that allow us to simplify its operands.
786bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000787 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000788 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
789 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
790
791 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
792 KnownZero, KnownOne, 0);
793 if (V == 0) return false;
794 if (V == &Inst) return true;
795 ReplaceInstUsesWith(Inst, V);
796 return true;
797}
798
799/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
800/// specified instruction operand if possible, updating it in place. It returns
801/// true if it made any change and false otherwise.
802bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
803 APInt &KnownZero, APInt &KnownOne,
804 unsigned Depth) {
805 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
806 KnownZero, KnownOne, Depth);
807 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000808 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000809 return true;
810}
811
812
813/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
814/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000815/// that only the bits set in DemandedMask of the result of V are ever used
816/// downstream. Consequently, depending on the mask and V, it may be possible
817/// to replace V with a constant or one of its operands. In such cases, this
818/// function does the replacement and returns true. In all other cases, it
819/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000820/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000821/// to be zero in the expression. These are provided to potentially allow the
822/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
823/// the expression. KnownOne and KnownZero always follow the invariant that
824/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
825/// the bits in KnownOne and KnownZero may only be accurate for those bits set
826/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
827/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000828///
829/// This returns null if it did not change anything and it permits no
830/// simplification. This returns V itself if it did some simplification of V's
831/// operands based on the information about what bits are demanded. This returns
832/// some other non-null value if it found out that V is equal to another value
833/// in the context where the specified bits are demanded, but not for all users.
834Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
835 APInt &KnownZero, APInt &KnownOne,
836 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000837 assert(V != 0 && "Null pointer of Value???");
838 assert(Depth <= 6 && "Limit Search Depth");
839 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000840 const Type *VTy = V->getType();
841 assert((TD || !isa<PointerType>(VTy)) &&
842 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000843 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
844 (!VTy->isIntOrIntVector() ||
845 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000846 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000847 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000848 "Value *V, DemandedMask, KnownZero and KnownOne "
849 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000850 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
851 // We know all of the bits for a constant!
852 KnownOne = CI->getValue() & DemandedMask;
853 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000854 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000855 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000856 if (isa<ConstantPointerNull>(V)) {
857 // We know all of the bits for a constant!
858 KnownOne.clear();
859 KnownZero = DemandedMask;
860 return 0;
861 }
862
Chris Lattner08d2cc72009-01-31 07:26:06 +0000863 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000864 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000865 if (DemandedMask == 0) { // Not demanding any bits from V.
866 if (isa<UndefValue>(V))
867 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000868 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000869 }
870
Chris Lattner4598c942009-01-31 08:24:16 +0000871 if (Depth == 6) // Limit search depth.
872 return 0;
873
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000874 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
875 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
876
Dan Gohman1c8491e2009-04-25 17:12:48 +0000877 Instruction *I = dyn_cast<Instruction>(V);
878 if (!I) {
879 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
880 return 0; // Only analyze instructions.
881 }
882
Chris Lattner4598c942009-01-31 08:24:16 +0000883 // If there are multiple uses of this value and we aren't at the root, then
884 // we can't do any simplifications of the operands, because DemandedMask
885 // only reflects the bits demanded by *one* of the users.
886 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000887 // Despite the fact that we can't simplify this instruction in all User's
888 // context, we can at least compute the knownzero/knownone bits, and we can
889 // do simplifications that apply to *just* the one user if we know that
890 // this instruction has a simpler value in that context.
891 if (I->getOpcode() == Instruction::And) {
892 // If either the LHS or the RHS are Zero, the result is zero.
893 ComputeMaskedBits(I->getOperand(1), DemandedMask,
894 RHSKnownZero, RHSKnownOne, Depth+1);
895 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
896 LHSKnownZero, LHSKnownOne, Depth+1);
897
898 // If all of the demanded bits are known 1 on one side, return the other.
899 // These bits cannot contribute to the result of the 'and' in this
900 // context.
901 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
902 (DemandedMask & ~LHSKnownZero))
903 return I->getOperand(0);
904 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
905 (DemandedMask & ~RHSKnownZero))
906 return I->getOperand(1);
907
908 // If all of the demanded bits in the inputs are known zeros, return zero.
909 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000910 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000911
912 } else if (I->getOpcode() == Instruction::Or) {
913 // We can simplify (X|Y) -> X or Y in the user's context if we know that
914 // only bits from X or Y are demanded.
915
916 // If either the LHS or the RHS are One, the result is One.
917 ComputeMaskedBits(I->getOperand(1), DemandedMask,
918 RHSKnownZero, RHSKnownOne, Depth+1);
919 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
920 LHSKnownZero, LHSKnownOne, Depth+1);
921
922 // If all of the demanded bits are known zero on one side, return the
923 // other. These bits cannot contribute to the result of the 'or' in this
924 // context.
925 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
926 (DemandedMask & ~LHSKnownOne))
927 return I->getOperand(0);
928 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
929 (DemandedMask & ~RHSKnownOne))
930 return I->getOperand(1);
931
932 // If all of the potentially set bits on one side are known to be set on
933 // the other side, just use the 'other' side.
934 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
935 (DemandedMask & (~RHSKnownZero)))
936 return I->getOperand(0);
937 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
938 (DemandedMask & (~LHSKnownZero)))
939 return I->getOperand(1);
940 }
941
Chris Lattner4598c942009-01-31 08:24:16 +0000942 // Compute the KnownZero/KnownOne bits to simplify things downstream.
943 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
944 return 0;
945 }
946
947 // If this is the root being simplified, allow it to have multiple uses,
948 // just set the DemandedMask to all bits so that we can try to simplify the
949 // operands. This allows visitTruncInst (for example) to simplify the
950 // operand of a trunc without duplicating all the logic below.
951 if (Depth == 0 && !V->hasOneUse())
952 DemandedMask = APInt::getAllOnesValue(BitWidth);
953
Reid Spencer8cb68342007-03-12 17:25:59 +0000954 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000955 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000956 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000957 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000958 case Instruction::And:
959 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000960 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
961 RHSKnownZero, RHSKnownOne, Depth+1) ||
962 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000963 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000964 return I;
965 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
966 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000967
968 // If all of the demanded bits are known 1 on one side, return the other.
969 // These bits cannot contribute to the result of the 'and'.
970 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
971 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000972 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000973 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
974 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000975 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000976
977 // If all of the demanded bits in the inputs are known zeros, return zero.
978 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000979 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000980
981 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000982 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000983 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000984
985 // Output known-1 bits are only known if set in both the LHS & RHS.
986 RHSKnownOne &= LHSKnownOne;
987 // Output known-0 are known to be clear if zero in either the LHS | RHS.
988 RHSKnownZero |= LHSKnownZero;
989 break;
990 case Instruction::Or:
991 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000992 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
993 RHSKnownZero, RHSKnownOne, Depth+1) ||
994 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000995 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000996 return I;
997 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
998 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000999
1000 // If all of the demanded bits are known zero on one side, return the other.
1001 // These bits cannot contribute to the result of the 'or'.
1002 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1003 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001004 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001005 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1006 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001007 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001008
1009 // If all of the potentially set bits on one side are known to be set on
1010 // the other side, just use the 'other' side.
1011 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1012 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001013 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001014 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1015 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001016 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001017
1018 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001019 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001020 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001021
1022 // Output known-0 bits are only known if clear in both the LHS & RHS.
1023 RHSKnownZero &= LHSKnownZero;
1024 // Output known-1 are known to be set if set in either the LHS | RHS.
1025 RHSKnownOne |= LHSKnownOne;
1026 break;
1027 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001028 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1029 RHSKnownZero, RHSKnownOne, Depth+1) ||
1030 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001031 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001032 return I;
1033 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1034 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001035
1036 // If all of the demanded bits are known zero on one side, return the other.
1037 // These bits cannot contribute to the result of the 'xor'.
1038 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001039 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001040 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001041 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001042
1043 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1044 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1045 (RHSKnownOne & LHSKnownOne);
1046 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1047 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1048 (RHSKnownOne & LHSKnownZero);
1049
1050 // If all of the demanded bits are known to be zero on one side or the
1051 // other, turn this into an *inclusive* or.
1052 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001053 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1054 Instruction *Or =
1055 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1056 I->getName());
1057 return InsertNewInstBefore(Or, *I);
1058 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001059
1060 // If all of the demanded bits on one side are known, and all of the set
1061 // bits on that side are also known to be set on the other side, turn this
1062 // into an AND, as we know the bits will be cleared.
1063 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1064 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1065 // all known
1066 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001067 Constant *AndC = Constant::getIntegerValue(VTy,
1068 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001069 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001070 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001071 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001072 }
1073 }
1074
1075 // If the RHS is a constant, see if we can simplify it.
1076 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001077 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001079
Chris Lattnerd0883142009-10-11 22:22:13 +00001080 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1081 // are flipping are known to be set, then the xor is just resetting those
1082 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1083 // simplifying both of them.
1084 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1085 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1086 isa<ConstantInt>(I->getOperand(1)) &&
1087 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1088 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1089 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1090 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1091 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1092
1093 Constant *AndC =
1094 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1095 Instruction *NewAnd =
1096 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1097 InsertNewInstBefore(NewAnd, *I);
1098
1099 Constant *XorC =
1100 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1101 Instruction *NewXor =
1102 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1103 return InsertNewInstBefore(NewXor, *I);
1104 }
1105
1106
Reid Spencer8cb68342007-03-12 17:25:59 +00001107 RHSKnownZero = KnownZeroOut;
1108 RHSKnownOne = KnownOneOut;
1109 break;
1110 }
1111 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001112 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1113 RHSKnownZero, RHSKnownOne, Depth+1) ||
1114 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001115 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001116 return I;
1117 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1118 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001119
1120 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001121 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1122 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001123 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001124
1125 // Only known if known in both the LHS and RHS.
1126 RHSKnownOne &= LHSKnownOne;
1127 RHSKnownZero &= LHSKnownZero;
1128 break;
1129 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001130 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001131 DemandedMask.zext(truncBf);
1132 RHSKnownZero.zext(truncBf);
1133 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001134 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001135 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001136 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001137 DemandedMask.trunc(BitWidth);
1138 RHSKnownZero.trunc(BitWidth);
1139 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001140 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001141 break;
1142 }
1143 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001144 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001145 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001146
1147 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1148 if (const VectorType *SrcVTy =
1149 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1150 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1151 // Don't touch a bitcast between vectors of different element counts.
1152 return false;
1153 } else
1154 // Don't touch a scalar-to-vector bitcast.
1155 return false;
1156 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1157 // Don't touch a vector-to-scalar bitcast.
1158 return false;
1159
Chris Lattner886ab6c2009-01-31 08:15:18 +00001160 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001161 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001162 return I;
1163 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001164 break;
1165 case Instruction::ZExt: {
1166 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001167 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001168
Zhou Shengd48653a2007-03-29 04:45:55 +00001169 DemandedMask.trunc(SrcBitWidth);
1170 RHSKnownZero.trunc(SrcBitWidth);
1171 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001172 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001173 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001174 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001175 DemandedMask.zext(BitWidth);
1176 RHSKnownZero.zext(BitWidth);
1177 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001178 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001179 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001180 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001181 break;
1182 }
1183 case Instruction::SExt: {
1184 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001185 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001186
Reid Spencer8cb68342007-03-12 17:25:59 +00001187 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001188 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001189
Zhou Sheng01542f32007-03-29 02:26:30 +00001190 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001191 // If any of the sign extended bits are demanded, we know that the sign
1192 // bit is demanded.
1193 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001194 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001195
Zhou Shengd48653a2007-03-29 04:45:55 +00001196 InputDemandedBits.trunc(SrcBitWidth);
1197 RHSKnownZero.trunc(SrcBitWidth);
1198 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001199 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001200 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001201 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001202 InputDemandedBits.zext(BitWidth);
1203 RHSKnownZero.zext(BitWidth);
1204 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001205 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001206
1207 // If the sign bit of the input is known set or clear, then we know the
1208 // top bits of the result.
1209
1210 // If the input sign bit is known zero, or if the NewBits are not demanded
1211 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001212 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001213 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001214 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1215 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001216 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001217 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001218 }
1219 break;
1220 }
1221 case Instruction::Add: {
1222 // Figure out what the input bits are. If the top bits of the and result
1223 // are not demanded, then the add doesn't demand them from its input
1224 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001225 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001226
1227 // If there is a constant on the RHS, there are a variety of xformations
1228 // we can do.
1229 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1230 // If null, this should be simplified elsewhere. Some of the xforms here
1231 // won't work if the RHS is zero.
1232 if (RHS->isZero())
1233 break;
1234
1235 // If the top bit of the output is demanded, demand everything from the
1236 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001237 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001238
1239 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001240 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001241 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001242 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001243
1244 // If the RHS of the add has bits set that can't affect the input, reduce
1245 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001246 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001247 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001248
1249 // Avoid excess work.
1250 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1251 break;
1252
1253 // Turn it into OR if input bits are zero.
1254 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1255 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001256 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001257 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001258 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001259 }
1260
1261 // We can say something about the output known-zero and known-one bits,
1262 // depending on potential carries from the input constant and the
1263 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1264 // bits set and the RHS constant is 0x01001, then we know we have a known
1265 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1266
1267 // To compute this, we first compute the potential carry bits. These are
1268 // the bits which may be modified. I'm not aware of a better way to do
1269 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001270 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001271 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001272
1273 // Now that we know which bits have carries, compute the known-1/0 sets.
1274
1275 // Bits are known one if they are known zero in one operand and one in the
1276 // other, and there is no input carry.
1277 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1278 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1279
1280 // Bits are known zero if they are known zero in both operands and there
1281 // is no input carry.
1282 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1283 } else {
1284 // If the high-bits of this ADD are not demanded, then it does not demand
1285 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001286 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001287 // Right fill the mask of bits for this ADD to demand the most
1288 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001289 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001290 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1291 LHSKnownZero, LHSKnownOne, Depth+1) ||
1292 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001293 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001294 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001295 }
1296 }
1297 break;
1298 }
1299 case Instruction::Sub:
1300 // If the high-bits of this SUB are not demanded, then it does not demand
1301 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001302 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001303 // Right fill the mask of bits for this SUB to demand the most
1304 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001305 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001306 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001307 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1308 LHSKnownZero, LHSKnownOne, Depth+1) ||
1309 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001310 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001311 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001312 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001313 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1314 // the known zeros and ones.
1315 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001316 break;
1317 case Instruction::Shl:
1318 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001319 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001320 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001321 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001322 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001323 return I;
1324 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001325 RHSKnownZero <<= ShiftAmt;
1326 RHSKnownOne <<= ShiftAmt;
1327 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001328 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001329 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001330 }
1331 break;
1332 case Instruction::LShr:
1333 // For a logical shift right
1334 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001335 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001336
Reid Spencer8cb68342007-03-12 17:25:59 +00001337 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001338 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001339 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001340 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001341 return I;
1342 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001343 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1344 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001345 if (ShiftAmt) {
1346 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001347 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001348 RHSKnownZero |= HighBits; // high bits known zero.
1349 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001350 }
1351 break;
1352 case Instruction::AShr:
1353 // If this is an arithmetic shift right and only the low-bit is set, we can
1354 // always convert this into a logical shr, even if the shift amount is
1355 // variable. The low bit of the shift cannot be an input sign bit unless
1356 // the shift amount is >= the size of the datatype, which is undefined.
1357 if (DemandedMask == 1) {
1358 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001359 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001360 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001361 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001362 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001363
1364 // If the sign bit is the only bit demanded by this ashr, then there is no
1365 // need to do it, the shift doesn't change the high bit.
1366 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001367 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001368
1369 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001370 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001371
Reid Spencer8cb68342007-03-12 17:25:59 +00001372 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001373 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001374 // If any of the "high bits" are demanded, we should set the sign bit as
1375 // demanded.
1376 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1377 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001378 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001379 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001380 return I;
1381 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001382 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001383 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001384 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1385 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1386
1387 // Handle the sign bits.
1388 APInt SignBit(APInt::getSignBit(BitWidth));
1389 // Adjust to where it is now in the mask.
1390 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1391
1392 // If the input sign bit is known to be zero, or if none of the top bits
1393 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001394 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001395 (HighBits & ~DemandedMask) == HighBits) {
1396 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001397 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001398 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001399 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001400 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1401 RHSKnownOne |= HighBits;
1402 }
1403 }
1404 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001405 case Instruction::SRem:
1406 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001407 APInt RA = Rem->getValue().abs();
1408 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001409 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001410 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001411
Nick Lewycky8e394322008-11-02 02:41:50 +00001412 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001413 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001414 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001415 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001416 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001417
1418 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1419 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001420
1421 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001422
Chris Lattner886ab6c2009-01-31 08:15:18 +00001423 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001424 }
1425 }
1426 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001427 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001428 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1429 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001430 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1431 KnownZero2, KnownOne2, Depth+1) ||
1432 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001433 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001434 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001435
Chris Lattner455e9ab2009-01-21 18:09:24 +00001436 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001437 Leaders = std::max(Leaders,
1438 KnownZero2.countLeadingOnes());
1439 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001440 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001441 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001442 case Instruction::Call:
1443 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1444 switch (II->getIntrinsicID()) {
1445 default: break;
1446 case Intrinsic::bswap: {
1447 // If the only bits demanded come from one byte of the bswap result,
1448 // just shift the input byte into position to eliminate the bswap.
1449 unsigned NLZ = DemandedMask.countLeadingZeros();
1450 unsigned NTZ = DemandedMask.countTrailingZeros();
1451
1452 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1453 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1454 // have 14 leading zeros, round to 8.
1455 NLZ &= ~7;
1456 NTZ &= ~7;
1457 // If we need exactly one byte, we can do this transformation.
1458 if (BitWidth-NLZ-NTZ == 8) {
1459 unsigned ResultBit = NTZ;
1460 unsigned InputBit = BitWidth-NTZ-8;
1461
1462 // Replace this with either a left or right shift to get the byte into
1463 // the right place.
1464 Instruction *NewVal;
1465 if (InputBit > ResultBit)
1466 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001467 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001468 else
1469 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001470 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001471 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001472 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001473 }
1474
1475 // TODO: Could compute known zero/one bits based on the input.
1476 break;
1477 }
1478 }
1479 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001480 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001481 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001482 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001483
1484 // If the client is only demanding bits that we know, return the known
1485 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001486 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1487 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001488 return false;
1489}
1490
Chris Lattner867b99f2006-10-05 06:55:50 +00001491
Mon P Wangaeb06d22008-11-10 04:46:22 +00001492/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001493/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001494/// actually used by the caller. This method analyzes which elements of the
1495/// operand are undef and returns that information in UndefElts.
1496///
1497/// If the information about demanded elements can be used to simplify the
1498/// operation, the operation is simplified, then the resultant value is
1499/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001500Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1501 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001502 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001503 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001504 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001505 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001506
1507 if (isa<UndefValue>(V)) {
1508 // If the entire vector is undefined, just return this info.
1509 UndefElts = EltMask;
1510 return 0;
1511 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1512 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001513 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001514 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001515
Chris Lattner867b99f2006-10-05 06:55:50 +00001516 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001517 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1518 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001519 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001520
1521 std::vector<Constant*> Elts;
1522 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001523 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001524 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001525 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001526 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1527 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001528 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001529 } else { // Otherwise, defined.
1530 Elts.push_back(CP->getOperand(i));
1531 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001532
Chris Lattner867b99f2006-10-05 06:55:50 +00001533 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001534 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001535 return NewCP != CP ? NewCP : 0;
1536 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001537 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001538 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001539
1540 // Check if this is identity. If so, return 0 since we are not simplifying
1541 // anything.
1542 if (DemandedElts == ((1ULL << VWidth) -1))
1543 return 0;
1544
Reid Spencer9d6565a2007-02-15 02:26:10 +00001545 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001546 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001547 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001548 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001549 for (unsigned i = 0; i != VWidth; ++i) {
1550 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1551 Elts.push_back(Elt);
1552 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001553 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001554 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001555 }
1556
Dan Gohman488fbfc2008-09-09 18:11:14 +00001557 // Limit search depth.
1558 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001559 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001560
1561 // If multiple users are using the root value, procede with
1562 // simplification conservatively assuming that all elements
1563 // are needed.
1564 if (!V->hasOneUse()) {
1565 // Quit if we find multiple users of a non-root value though.
1566 // They'll be handled when it's their turn to be visited by
1567 // the main instcombine process.
1568 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001569 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001570 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001571
1572 // Conservatively assume that all elements are needed.
1573 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001574 }
1575
1576 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001577 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001578
1579 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001580 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001581 Value *TmpV;
1582 switch (I->getOpcode()) {
1583 default: break;
1584
1585 case Instruction::InsertElement: {
1586 // If this is a variable index, we don't know which element it overwrites.
1587 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001588 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001589 if (Idx == 0) {
1590 // Note that we can't propagate undef elt info, because we don't know
1591 // which elt is getting updated.
1592 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1593 UndefElts2, Depth+1);
1594 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1595 break;
1596 }
1597
1598 // If this is inserting an element that isn't demanded, remove this
1599 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001600 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001601 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1602 Worklist.Add(I);
1603 return I->getOperand(0);
1604 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001605
1606 // Otherwise, the element inserted overwrites whatever was there, so the
1607 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001608 APInt DemandedElts2 = DemandedElts;
1609 DemandedElts2.clear(IdxNo);
1610 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001611 UndefElts, Depth+1);
1612 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1613
1614 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001615 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001616 break;
1617 }
1618 case Instruction::ShuffleVector: {
1619 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001620 uint64_t LHSVWidth =
1621 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001622 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001623 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001624 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001625 unsigned MaskVal = Shuffle->getMaskValue(i);
1626 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001627 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001628 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001629 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001630 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001631 else
Evan Cheng388df622009-02-03 10:05:09 +00001632 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001633 }
1634 }
1635 }
1636
Nate Begeman7b254672009-02-11 22:36:25 +00001637 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001638 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001639 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001640 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1641
Nate Begeman7b254672009-02-11 22:36:25 +00001642 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001643 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1644 UndefElts3, Depth+1);
1645 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1646
1647 bool NewUndefElts = false;
1648 for (unsigned i = 0; i < VWidth; i++) {
1649 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001650 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001651 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001652 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001653 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001654 NewUndefElts = true;
1655 UndefElts.set(i);
1656 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001657 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001658 if (UndefElts3[MaskVal - LHSVWidth]) {
1659 NewUndefElts = true;
1660 UndefElts.set(i);
1661 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001662 }
1663 }
1664
1665 if (NewUndefElts) {
1666 // Add additional discovered undefs.
1667 std::vector<Constant*> Elts;
1668 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001669 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001670 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001671 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001672 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001673 Shuffle->getMaskValue(i)));
1674 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001675 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001676 MadeChange = true;
1677 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001678 break;
1679 }
Chris Lattner69878332007-04-14 22:29:23 +00001680 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001681 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001682 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1683 if (!VTy) break;
1684 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001685 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001686 unsigned Ratio;
1687
1688 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001689 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001690 // elements as are demanded of us.
1691 Ratio = 1;
1692 InputDemandedElts = DemandedElts;
1693 } else if (VWidth > InVWidth) {
1694 // Untested so far.
1695 break;
1696
1697 // If there are more elements in the result than there are in the source,
1698 // then an input element is live if any of the corresponding output
1699 // elements are live.
1700 Ratio = VWidth/InVWidth;
1701 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001702 if (DemandedElts[OutIdx])
1703 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001704 }
1705 } else {
1706 // Untested so far.
1707 break;
1708
1709 // If there are more elements in the source than there are in the result,
1710 // then an input element is live if the corresponding output element is
1711 // live.
1712 Ratio = InVWidth/VWidth;
1713 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001714 if (DemandedElts[InIdx/Ratio])
1715 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001716 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001717
Chris Lattner69878332007-04-14 22:29:23 +00001718 // div/rem demand all inputs, because they don't want divide by zero.
1719 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1720 UndefElts2, Depth+1);
1721 if (TmpV) {
1722 I->setOperand(0, TmpV);
1723 MadeChange = true;
1724 }
1725
1726 UndefElts = UndefElts2;
1727 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001728 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001729 // If there are more elements in the result than there are in the source,
1730 // then an output element is undef if the corresponding input element is
1731 // undef.
1732 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001733 if (UndefElts2[OutIdx/Ratio])
1734 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001735 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001736 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001737 // If there are more elements in the source than there are in the result,
1738 // then a result element is undef if all of the corresponding input
1739 // elements are undef.
1740 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1741 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001742 if (!UndefElts2[InIdx]) // Not undef?
1743 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001744 }
1745 break;
1746 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001747 case Instruction::And:
1748 case Instruction::Or:
1749 case Instruction::Xor:
1750 case Instruction::Add:
1751 case Instruction::Sub:
1752 case Instruction::Mul:
1753 // div/rem demand all inputs, because they don't want divide by zero.
1754 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1755 UndefElts, Depth+1);
1756 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1757 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1758 UndefElts2, Depth+1);
1759 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1760
1761 // Output elements are undefined if both are undefined. Consider things
1762 // like undef&0. The result is known zero, not undef.
1763 UndefElts &= UndefElts2;
1764 break;
1765
1766 case Instruction::Call: {
1767 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1768 if (!II) break;
1769 switch (II->getIntrinsicID()) {
1770 default: break;
1771
1772 // Binary vector operations that work column-wise. A dest element is a
1773 // function of the corresponding input elements from the two inputs.
1774 case Intrinsic::x86_sse_sub_ss:
1775 case Intrinsic::x86_sse_mul_ss:
1776 case Intrinsic::x86_sse_min_ss:
1777 case Intrinsic::x86_sse_max_ss:
1778 case Intrinsic::x86_sse2_sub_sd:
1779 case Intrinsic::x86_sse2_mul_sd:
1780 case Intrinsic::x86_sse2_min_sd:
1781 case Intrinsic::x86_sse2_max_sd:
1782 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1783 UndefElts, Depth+1);
1784 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1785 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1786 UndefElts2, Depth+1);
1787 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1788
1789 // If only the low elt is demanded and this is a scalarizable intrinsic,
1790 // scalarize it now.
1791 if (DemandedElts == 1) {
1792 switch (II->getIntrinsicID()) {
1793 default: break;
1794 case Intrinsic::x86_sse_sub_ss:
1795 case Intrinsic::x86_sse_mul_ss:
1796 case Intrinsic::x86_sse2_sub_sd:
1797 case Intrinsic::x86_sse2_mul_sd:
1798 // TODO: Lower MIN/MAX/ABS/etc
1799 Value *LHS = II->getOperand(1);
1800 Value *RHS = II->getOperand(2);
1801 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001802 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001803 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001804 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001805 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001806
1807 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001808 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001809 case Intrinsic::x86_sse_sub_ss:
1810 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001811 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001812 II->getName()), *II);
1813 break;
1814 case Intrinsic::x86_sse_mul_ss:
1815 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001816 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001817 II->getName()), *II);
1818 break;
1819 }
1820
1821 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001822 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001823 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001824 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001825 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001826 return New;
1827 }
1828 }
1829
1830 // Output elements are undefined if both are undefined. Consider things
1831 // like undef&0. The result is known zero, not undef.
1832 UndefElts &= UndefElts2;
1833 break;
1834 }
1835 break;
1836 }
1837 }
1838 return MadeChange ? I : 0;
1839}
1840
Dan Gohman45b4e482008-05-19 22:14:15 +00001841
Chris Lattner564a7272003-08-13 19:01:45 +00001842/// AssociativeOpt - Perform an optimization on an associative operator. This
1843/// function is designed to check a chain of associative operators for a
1844/// potential to apply a certain optimization. Since the optimization may be
1845/// applicable if the expression was reassociated, this checks the chain, then
1846/// reassociates the expression as necessary to expose the optimization
1847/// opportunity. This makes use of a special Functor, which must define
1848/// 'shouldApply' and 'apply' methods.
1849///
1850template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001851static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001852 unsigned Opcode = Root.getOpcode();
1853 Value *LHS = Root.getOperand(0);
1854
1855 // Quick check, see if the immediate LHS matches...
1856 if (F.shouldApply(LHS))
1857 return F.apply(Root);
1858
1859 // Otherwise, if the LHS is not of the same opcode as the root, return.
1860 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001861 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001862 // Should we apply this transform to the RHS?
1863 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1864
1865 // If not to the RHS, check to see if we should apply to the LHS...
1866 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1867 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1868 ShouldApply = true;
1869 }
1870
1871 // If the functor wants to apply the optimization to the RHS of LHSI,
1872 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1873 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001874 // Now all of the instructions are in the current basic block, go ahead
1875 // and perform the reassociation.
1876 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1877
1878 // First move the selected RHS to the LHS of the root...
1879 Root.setOperand(0, LHSI->getOperand(1));
1880
1881 // Make what used to be the LHS of the root be the user of the root...
1882 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001883 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001884 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001885 return 0;
1886 }
Chris Lattner65725312004-04-16 18:08:07 +00001887 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001888 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001889 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001890 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001891 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001892
1893 // Now propagate the ExtraOperand down the chain of instructions until we
1894 // get to LHSI.
1895 while (TmpLHSI != LHSI) {
1896 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001897 // Move the instruction to immediately before the chain we are
1898 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001899 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001900 ARI = NextLHSI;
1901
Chris Lattner564a7272003-08-13 19:01:45 +00001902 Value *NextOp = NextLHSI->getOperand(1);
1903 NextLHSI->setOperand(1, ExtraOperand);
1904 TmpLHSI = NextLHSI;
1905 ExtraOperand = NextOp;
1906 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001907
Chris Lattner564a7272003-08-13 19:01:45 +00001908 // Now that the instructions are reassociated, have the functor perform
1909 // the transformation...
1910 return F.apply(Root);
1911 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001912
Chris Lattner564a7272003-08-13 19:01:45 +00001913 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1914 }
1915 return 0;
1916}
1917
Dan Gohman844731a2008-05-13 00:00:25 +00001918namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001919
Nick Lewycky02d639f2008-05-23 04:34:58 +00001920// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001921struct AddRHS {
1922 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001923 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001924 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1925 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001926 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001927 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001928 }
1929};
1930
1931// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1932// iff C1&C2 == 0
1933struct AddMaskingAnd {
1934 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001935 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001936 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001937 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001938 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001939 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001940 }
1941 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001942 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001943 }
1944};
1945
Dan Gohman844731a2008-05-13 00:00:25 +00001946}
1947
Chris Lattner6e7ba452005-01-01 16:22:27 +00001948static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001949 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001950 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001951 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001952
Chris Lattner2eefe512004-04-09 19:05:30 +00001953 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001954 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1955 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001956
Chris Lattner2eefe512004-04-09 19:05:30 +00001957 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1958 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001959 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1960 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001961 }
1962
1963 Value *Op0 = SO, *Op1 = ConstOperand;
1964 if (!ConstIsRHS)
1965 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001966
Chris Lattner6e7ba452005-01-01 16:22:27 +00001967 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001968 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1969 SO->getName()+".op");
1970 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1971 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1972 SO->getName()+".cmp");
1973 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1974 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1975 SO->getName()+".cmp");
1976 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001977}
1978
1979// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1980// constant as the other operand, try to fold the binary operator into the
1981// select arguments. This also works for Cast instructions, which obviously do
1982// not have a second operand.
1983static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1984 InstCombiner *IC) {
1985 // Don't modify shared select instructions
1986 if (!SI->hasOneUse()) return 0;
1987 Value *TV = SI->getOperand(1);
1988 Value *FV = SI->getOperand(2);
1989
1990 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001991 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001992 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001993
Chris Lattner6e7ba452005-01-01 16:22:27 +00001994 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1995 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1996
Gabor Greif051a9502008-04-06 20:25:17 +00001997 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1998 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001999 }
2000 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002001}
2002
Chris Lattner4e998b22004-09-29 05:07:12 +00002003
Chris Lattner5d1704d2009-09-27 19:57:57 +00002004/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2005/// has a PHI node as operand #0, see if we can fold the instruction into the
2006/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00002007///
2008/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2009/// that would normally be unprofitable because they strongly encourage jump
2010/// threading.
2011Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2012 bool AllowAggressive) {
2013 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00002014 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002015 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002016 if (NumPHIValues == 0 ||
2017 // We normally only transform phis with a single use, unless we're trying
2018 // hard to make jump threading happen.
2019 (!PN->hasOneUse() && !AllowAggressive))
2020 return 0;
2021
2022
Chris Lattner5d1704d2009-09-27 19:57:57 +00002023 // Check to see if all of the operands of the PHI are simple constants
2024 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002025 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2026 // bail out. We don't do arbitrary constant expressions here because moving
2027 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002028 BasicBlock *NonConstBB = 0;
2029 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002030 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2031 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002032 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002033 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002034 NonConstBB = PN->getIncomingBlock(i);
2035
2036 // If the incoming non-constant value is in I's block, we have an infinite
2037 // loop.
2038 if (NonConstBB == I.getParent())
2039 return 0;
2040 }
2041
2042 // If there is exactly one non-constant value, we can insert a copy of the
2043 // operation in that block. However, if this is a critical edge, we would be
2044 // inserting the computation one some other paths (e.g. inside a loop). Only
2045 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002046 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002047 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2048 if (!BI || !BI->isUnconditional()) return 0;
2049 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002050
2051 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002052 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002053 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00002054 InsertNewInstBefore(NewPN, *PN);
2055 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002056
2057 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002058 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2059 // We only currently try to fold the condition of a select when it is a phi,
2060 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002061 Value *TrueV = SI->getTrueValue();
2062 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002063 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002064 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002065 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002066 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2067 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002068 Value *InV = 0;
2069 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002070 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002071 } else {
2072 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002073 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2074 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002075 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002076 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002077 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002078 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002079 }
2080 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002081 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002082 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002083 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002084 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002085 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002086 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002087 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002088 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002089 } else {
2090 assert(PN->getIncomingBlock(i) == NonConstBB);
2091 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002092 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002093 PN->getIncomingValue(i), C, "phitmp",
2094 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002095 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002096 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002097 CI->getPredicate(),
2098 PN->getIncomingValue(i), C, "phitmp",
2099 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002100 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002101 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00002102
2103 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002104 }
2105 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002106 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002107 } else {
2108 CastInst *CI = cast<CastInst>(&I);
2109 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002110 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002111 Value *InV;
2112 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002113 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002114 } else {
2115 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002116 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002117 I.getType(), "phitmp",
2118 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002119 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002120 }
2121 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002122 }
2123 }
2124 return ReplaceInstUsesWith(I, NewPN);
2125}
2126
Chris Lattner2454a2e2008-01-29 06:52:45 +00002127
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002128/// WillNotOverflowSignedAdd - Return true if we can prove that:
2129/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2130/// This basically requires proving that the add in the original type would not
2131/// overflow to change the sign bit or have a carry out.
2132bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2133 // There are different heuristics we can use for this. Here are some simple
2134 // ones.
2135
2136 // Add has the property that adding any two 2's complement numbers can only
2137 // have one carry bit which can change a sign. As such, if LHS and RHS each
2138 // have at least two sign bits, we know that the addition of the two values will
2139 // sign extend fine.
2140 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2141 return true;
2142
2143
2144 // If one of the operands only has one non-zero bit, and if the other operand
2145 // has a known-zero bit in a more significant place than it (not including the
2146 // sign bit) the ripple may go up to and fill the zero, but won't change the
2147 // sign. For example, (X & ~4) + 1.
2148
2149 // TODO: Implement.
2150
2151 return false;
2152}
2153
Chris Lattner2454a2e2008-01-29 06:52:45 +00002154
Chris Lattner7e708292002-06-25 16:13:24 +00002155Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002156 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002157 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002158
Chris Lattner66331a42004-04-10 22:01:55 +00002159 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002160 // X + undef -> undef
2161 if (isa<UndefValue>(RHS))
2162 return ReplaceInstUsesWith(I, RHS);
2163
Chris Lattner66331a42004-04-10 22:01:55 +00002164 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002165 if (RHSC->isNullValue())
2166 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002167
Chris Lattner66331a42004-04-10 22:01:55 +00002168 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002169 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002170 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002171 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002172 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002173 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002174
2175 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2176 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002177 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002178 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002179
Eli Friedman709b33d2009-07-13 22:27:52 +00002180 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002181 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002182 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002183 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002184 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002185
2186 if (isa<PHINode>(LHS))
2187 if (Instruction *NV = FoldOpIntoPhi(I))
2188 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002189
Chris Lattner4f637d42006-01-06 17:59:59 +00002190 ConstantInt *XorRHS = 0;
2191 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002192 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002193 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002194 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002195 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002196
Zhou Sheng4351c642007-04-02 08:20:41 +00002197 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002198 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2199 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002200 do {
2201 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002202 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2203 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002204 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2205 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002206 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002207 if (!MaskedValueIsZero(XorLHS,
2208 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002209 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002210 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002211 }
2212 }
2213 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002214 C0080Val = APIntOps::lshr(C0080Val, Size);
2215 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2216 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002217
Reid Spencer35c38852007-03-28 01:36:16 +00002218 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002219 // with funny bit widths then this switch statement should be removed. It
2220 // is just here to get the size of the "middle" type back up to something
2221 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002222 const Type *MiddleType = 0;
2223 switch (Size) {
2224 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002225 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2226 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2227 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002228 }
2229 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002230 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002231 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002232 }
2233 }
Chris Lattner66331a42004-04-10 22:01:55 +00002234 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002235
Owen Anderson1d0be152009-08-13 21:58:54 +00002236 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002237 return BinaryOperator::CreateXor(LHS, RHS);
2238
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002239 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002240 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002241 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002242 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002243
2244 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2245 if (RHSI->getOpcode() == Instruction::Sub)
2246 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2247 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2248 }
2249 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2250 if (LHSI->getOpcode() == Instruction::Sub)
2251 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2252 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2253 }
Robert Bocchino71698282004-07-27 21:02:21 +00002254 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002255
Chris Lattner5c4afb92002-05-08 22:46:53 +00002256 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002257 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002258 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002259 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002260 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002261 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002262 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002263 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002264 }
2265
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002266 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002267 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002268
2269 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002270 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002271 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002272 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002273
Misha Brukmanfd939082005-04-21 23:48:37 +00002274
Chris Lattner50af16a2004-11-13 19:50:12 +00002275 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002276 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002277 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002278 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002279
2280 // X*C1 + X*C2 --> X * (C1+C2)
2281 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002282 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002283 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002284 }
2285
2286 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002287 if (dyn_castFoldableMul(RHS, C2) == LHS)
2288 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002289
Chris Lattnere617c9e2007-01-05 02:17:46 +00002290 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002291 if (dyn_castNotVal(LHS) == RHS ||
2292 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002293 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002294
Chris Lattnerad3448c2003-02-18 19:57:07 +00002295
Chris Lattner564a7272003-08-13 19:01:45 +00002296 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002297 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2298 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002299 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002300
2301 // A+B --> A|B iff A and B have no bits set in common.
2302 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2303 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2304 APInt LHSKnownOne(IT->getBitWidth(), 0);
2305 APInt LHSKnownZero(IT->getBitWidth(), 0);
2306 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2307 if (LHSKnownZero != 0) {
2308 APInt RHSKnownOne(IT->getBitWidth(), 0);
2309 APInt RHSKnownZero(IT->getBitWidth(), 0);
2310 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2311
2312 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002313 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002314 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002315 }
2316 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002317
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002318 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002319 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002320 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002321 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2322 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002323 if (W != Y) {
2324 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002325 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002326 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002327 std::swap(W, X);
2328 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002329 std::swap(Y, Z);
2330 std::swap(W, X);
2331 }
2332 }
2333
2334 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002335 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002336 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002337 }
2338 }
2339 }
2340
Chris Lattner6b032052003-10-02 15:11:26 +00002341 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002342 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002343 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002344 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002345
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002346 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002347 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002348 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002349 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002350 if (Anded == CRHS) {
2351 // See if all bits from the first bit set in the Add RHS up are included
2352 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002353 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002354
2355 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002356 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002357
2358 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002359 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002360
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002361 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2362 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002363 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002364 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002365 }
2366 }
2367 }
2368
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002369 // Try to fold constant add into select arguments.
2370 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002371 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002372 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002373 }
2374
Chris Lattner42790482007-12-20 01:56:58 +00002375 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002376 {
2377 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002378 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002379 if (!SI) {
2380 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002381 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002382 }
Chris Lattner42790482007-12-20 01:56:58 +00002383 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002384 Value *TV = SI->getTrueValue();
2385 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002386 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002387
2388 // Can we fold the add into the argument of the select?
2389 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002390 if (match(FV, m_Zero()) &&
2391 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002392 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002393 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002394 if (match(TV, m_Zero()) &&
2395 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002396 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002397 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002398 }
2399 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002400
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002401 // Check for (add (sext x), y), see if we can merge this into an
2402 // integer add followed by a sext.
2403 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2404 // (add (sext x), cst) --> (sext (add x, cst'))
2405 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2406 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002407 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002408 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002409 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002410 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2411 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002412 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2413 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002414 return new SExtInst(NewAdd, I.getType());
2415 }
2416 }
2417
2418 // (add (sext x), (sext y)) --> (sext (add int x, y))
2419 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2420 // Only do this if x/y have the same type, if at last one of them has a
2421 // single use (so we don't increase the number of sexts), and if the
2422 // integer add will not overflow.
2423 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2424 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2425 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2426 RHSConv->getOperand(0))) {
2427 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002428 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2429 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002430 return new SExtInst(NewAdd, I.getType());
2431 }
2432 }
2433 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002434
2435 return Changed ? &I : 0;
2436}
2437
2438Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2439 bool Changed = SimplifyCommutative(I);
2440 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2441
2442 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2443 // X + 0 --> X
2444 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002445 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002446 (I.getType())->getValueAPF()))
2447 return ReplaceInstUsesWith(I, LHS);
2448 }
2449
2450 if (isa<PHINode>(LHS))
2451 if (Instruction *NV = FoldOpIntoPhi(I))
2452 return NV;
2453 }
2454
2455 // -A + B --> B - A
2456 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002457 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002458 return BinaryOperator::CreateFSub(RHS, LHSV);
2459
2460 // A + -B --> A - B
2461 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002462 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002463 return BinaryOperator::CreateFSub(LHS, V);
2464
2465 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2466 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2467 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2468 return ReplaceInstUsesWith(I, LHS);
2469
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002470 // Check for (add double (sitofp x), y), see if we can merge this into an
2471 // integer add followed by a promotion.
2472 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2473 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2474 // ... if the constant fits in the integer value. This is useful for things
2475 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2476 // requires a constant pool load, and generally allows the add to be better
2477 // instcombined.
2478 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2479 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002480 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002481 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002482 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002483 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2484 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002485 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2486 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002487 return new SIToFPInst(NewAdd, I.getType());
2488 }
2489 }
2490
2491 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2492 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2493 // Only do this if x/y have the same type, if at last one of them has a
2494 // single use (so we don't increase the number of int->fp conversions),
2495 // and if the integer add will not overflow.
2496 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2497 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2498 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2499 RHSConv->getOperand(0))) {
2500 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002501 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00002502 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002503 return new SIToFPInst(NewAdd, I.getType());
2504 }
2505 }
2506 }
2507
Chris Lattner7e708292002-06-25 16:13:24 +00002508 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002509}
2510
Chris Lattner092543c2009-11-04 08:05:20 +00002511
2512/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2513/// code necessary to compute the offset from the base pointer (without adding
2514/// in the base pointer). Return the result as a signed integer of intptr size.
2515static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2516 TargetData &TD = *IC.getTargetData();
2517 gep_type_iterator GTI = gep_type_begin(GEP);
2518 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2519 Value *Result = Constant::getNullValue(IntPtrTy);
2520
2521 // Build a mask for high order bits.
2522 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2523 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2524
2525 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2526 ++i, ++GTI) {
2527 Value *Op = *i;
2528 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2529 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2530 if (OpC->isZero()) continue;
2531
2532 // Handle a struct index, which adds its field offset to the pointer.
2533 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2534 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2535
2536 Result = IC.Builder->CreateAdd(Result,
2537 ConstantInt::get(IntPtrTy, Size),
2538 GEP->getName()+".offs");
2539 continue;
2540 }
2541
2542 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2543 Constant *OC =
2544 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2545 Scale = ConstantExpr::getMul(OC, Scale);
2546 // Emit an add instruction.
2547 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2548 continue;
2549 }
2550 // Convert to correct type.
2551 if (Op->getType() != IntPtrTy)
2552 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2553 if (Size != 1) {
2554 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2555 // We'll let instcombine(mul) convert this to a shl if possible.
2556 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2557 }
2558
2559 // Emit an add instruction.
2560 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2561 }
2562 return Result;
2563}
2564
2565
2566/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2567/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2568/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2569/// be complex, and scales are involved. The above expression would also be
2570/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2571/// This later form is less amenable to optimization though, and we are allowed
2572/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2573///
2574/// If we can't emit an optimized form for this expression, this returns null.
2575///
2576static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2577 InstCombiner &IC) {
2578 TargetData &TD = *IC.getTargetData();
2579 gep_type_iterator GTI = gep_type_begin(GEP);
2580
2581 // Check to see if this gep only has a single variable index. If so, and if
2582 // any constant indices are a multiple of its scale, then we can compute this
2583 // in terms of the scale of the variable index. For example, if the GEP
2584 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2585 // because the expression will cross zero at the same point.
2586 unsigned i, e = GEP->getNumOperands();
2587 int64_t Offset = 0;
2588 for (i = 1; i != e; ++i, ++GTI) {
2589 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2590 // Compute the aggregate offset of constant indices.
2591 if (CI->isZero()) continue;
2592
2593 // Handle a struct index, which adds its field offset to the pointer.
2594 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2595 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2596 } else {
2597 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2598 Offset += Size*CI->getSExtValue();
2599 }
2600 } else {
2601 // Found our variable index.
2602 break;
2603 }
2604 }
2605
2606 // If there are no variable indices, we must have a constant offset, just
2607 // evaluate it the general way.
2608 if (i == e) return 0;
2609
2610 Value *VariableIdx = GEP->getOperand(i);
2611 // Determine the scale factor of the variable element. For example, this is
2612 // 4 if the variable index is into an array of i32.
2613 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2614
2615 // Verify that there are no other variable indices. If so, emit the hard way.
2616 for (++i, ++GTI; i != e; ++i, ++GTI) {
2617 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2618 if (!CI) return 0;
2619
2620 // Compute the aggregate offset of constant indices.
2621 if (CI->isZero()) continue;
2622
2623 // Handle a struct index, which adds its field offset to the pointer.
2624 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2625 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2626 } else {
2627 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2628 Offset += Size*CI->getSExtValue();
2629 }
2630 }
2631
2632 // Okay, we know we have a single variable index, which must be a
2633 // pointer/array/vector index. If there is no offset, life is simple, return
2634 // the index.
2635 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2636 if (Offset == 0) {
2637 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2638 // we don't need to bother extending: the extension won't affect where the
2639 // computation crosses zero.
2640 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2641 VariableIdx = new TruncInst(VariableIdx,
2642 TD.getIntPtrType(VariableIdx->getContext()),
2643 VariableIdx->getName(), &I);
2644 return VariableIdx;
2645 }
2646
2647 // Otherwise, there is an index. The computation we will do will be modulo
2648 // the pointer size, so get it.
2649 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2650
2651 Offset &= PtrSizeMask;
2652 VariableScale &= PtrSizeMask;
2653
2654 // To do this transformation, any constant index must be a multiple of the
2655 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2656 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2657 // multiple of the variable scale.
2658 int64_t NewOffs = Offset / (int64_t)VariableScale;
2659 if (Offset != NewOffs*(int64_t)VariableScale)
2660 return 0;
2661
2662 // Okay, we can do this evaluation. Start by converting the index to intptr.
2663 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2664 if (VariableIdx->getType() != IntPtrTy)
2665 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2666 true /*SExt*/,
2667 VariableIdx->getName(), &I);
2668 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2669 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2670}
2671
2672
2673/// Optimize pointer differences into the same array into a size. Consider:
2674/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2675/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2676///
2677Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2678 const Type *Ty) {
2679 assert(TD && "Must have target data info for this");
2680
2681 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2682 // this.
2683 bool Swapped;
2684 GetElementPtrInst *GEP;
2685
2686 if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2687 GEP->getOperand(0) == RHS)
2688 Swapped = false;
2689 else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2690 GEP->getOperand(0) == LHS)
2691 Swapped = true;
2692 else
2693 return 0;
2694
2695 // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2696
2697 // Emit the offset of the GEP and an intptr_t.
2698 Value *Result = EmitGEPOffset(GEP, *this);
2699
2700 // If we have p - gep(p, ...) then we have to negate the result.
2701 if (Swapped)
2702 Result = Builder->CreateNeg(Result, "diff.neg");
2703
2704 return Builder->CreateIntCast(Result, Ty, true);
2705}
2706
2707
Chris Lattner7e708292002-06-25 16:13:24 +00002708Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002709 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002710
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002711 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002712 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002713
Chris Lattner092543c2009-11-04 08:05:20 +00002714 // If this is a 'B = x-(-A)', change to B = x+A.
Dan Gohman186a6362009-08-12 16:04:34 +00002715 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002716 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002717
Chris Lattnere87597f2004-10-16 18:11:37 +00002718 if (isa<UndefValue>(Op0))
2719 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2720 if (isa<UndefValue>(Op1))
2721 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner092543c2009-11-04 08:05:20 +00002722 if (I.getType() == Type::getInt1Ty(*Context))
2723 return BinaryOperator::CreateXor(Op0, Op1);
2724
Chris Lattnerd65460f2003-11-05 01:06:05 +00002725 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00002726 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00002727 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002728 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002729
Chris Lattnerd65460f2003-11-05 01:06:05 +00002730 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002731 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002732 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002733 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002734
Chris Lattner76b7a062007-01-15 07:02:54 +00002735 // -(X >>u 31) -> (X >>s 31)
2736 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002737 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002738 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002739 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002740 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002741 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002742 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002743 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002744 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002745 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002746 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002747 }
2748 }
Chris Lattner092543c2009-11-04 08:05:20 +00002749 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002750 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2751 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002752 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002753 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002754 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002755 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002756 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002757 }
2758 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002759 }
2760 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002761 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002762
2763 // Try to fold constant sub into select arguments.
2764 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002765 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002766 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002767
2768 // C - zext(bool) -> bool ? C - 1 : C
2769 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002770 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002771 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002772 }
2773
Chris Lattner43d84d62005-04-07 16:15:25 +00002774 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002775 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002776 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002777 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002778 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002779 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002780 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002781 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002782 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2783 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2784 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002785 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002786 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002787 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002788 }
2789
Chris Lattnerfd059242003-10-15 16:48:29 +00002790 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002791 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2792 // is not used by anyone else...
2793 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002794 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002795 // Swap the two operands of the subexpr...
2796 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2797 Op1I->setOperand(0, IIOp1);
2798 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002799
Chris Lattnera2881962003-02-18 19:28:33 +00002800 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002801 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002802 }
2803
2804 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2805 //
2806 if (Op1I->getOpcode() == Instruction::And &&
2807 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2808 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2809
Chris Lattner74381062009-08-30 07:44:24 +00002810 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002811 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002812 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002813
Reid Spencerac5209e2006-10-16 23:08:08 +00002814 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002815 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002816 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002817 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002818 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002819 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002820 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002821
Chris Lattnerad3448c2003-02-18 19:57:07 +00002822 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002823 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002824 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002825 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002826 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002827 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002828 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002829 }
Chris Lattner40371712002-05-09 01:29:19 +00002830 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002831 }
Chris Lattnera2881962003-02-18 19:28:33 +00002832
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002833 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2834 if (Op0I->getOpcode() == Instruction::Add) {
2835 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2836 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2837 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2838 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2839 } else if (Op0I->getOpcode() == Instruction::Sub) {
2840 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002841 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002842 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002843 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002844 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002845
Chris Lattner50af16a2004-11-13 19:50:12 +00002846 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002847 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002848 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002849 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002850
Chris Lattner50af16a2004-11-13 19:50:12 +00002851 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002852 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002853 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002854 }
Chris Lattner092543c2009-11-04 08:05:20 +00002855
2856 // Optimize pointer differences into the same array into a size. Consider:
2857 // &A[10] - &A[0]: we should compile this to "10".
2858 if (TD) {
2859 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(Op0))
2860 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(Op1))
2861 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2862 RHS->getOperand(0),
2863 I.getType()))
2864 return ReplaceInstUsesWith(I, Res);
2865
2866 // trunc(p)-trunc(q) -> trunc(p-q)
2867 if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2868 if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2869 if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2870 if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2871 if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2872 RHS->getOperand(0),
2873 I.getType()))
2874 return ReplaceInstUsesWith(I, Res);
2875 }
2876
Chris Lattner3f5b8772002-05-06 16:14:14 +00002877 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002878}
2879
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002880Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2881 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2882
2883 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002884 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002885 return BinaryOperator::CreateFAdd(Op0, V);
2886
2887 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2888 if (Op1I->getOpcode() == Instruction::FAdd) {
2889 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002890 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002891 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002892 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002893 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002894 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002895 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002896 }
2897
2898 return 0;
2899}
2900
Chris Lattnera0141b92007-07-15 20:42:37 +00002901/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2902/// comparison only checks the sign bit. If it only checks the sign bit, set
2903/// TrueIfSigned if the result of the comparison is true when the input value is
2904/// signed.
2905static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2906 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002907 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002908 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2909 TrueIfSigned = true;
2910 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002911 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2912 TrueIfSigned = true;
2913 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002914 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2915 TrueIfSigned = false;
2916 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002917 case ICmpInst::ICMP_UGT:
2918 // True if LHS u> RHS and RHS == high-bit-mask - 1
2919 TrueIfSigned = true;
2920 return RHS->getValue() ==
2921 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2922 case ICmpInst::ICMP_UGE:
2923 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2924 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002925 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002926 default:
2927 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002928 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002929}
2930
Chris Lattner7e708292002-06-25 16:13:24 +00002931Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002932 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002933 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002934
Chris Lattnera2498472009-10-11 21:36:10 +00002935 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002936 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002937
Chris Lattner8af304a2009-10-11 07:53:15 +00002938 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002939 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2940 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002941
2942 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002943 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002944 if (SI->getOpcode() == Instruction::Shl)
2945 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002946 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002947 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002948
Zhou Sheng843f07672007-04-19 05:39:12 +00002949 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002950 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002951 if (CI->equalsInt(1)) // X * 1 == X
2952 return ReplaceInstUsesWith(I, Op0);
2953 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002954 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002955
Zhou Sheng97b52c22007-03-29 01:57:21 +00002956 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002957 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002958 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002959 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002960 }
Chris Lattnera2498472009-10-11 21:36:10 +00002961 } else if (isa<VectorType>(Op1C->getType())) {
2962 if (Op1C->isNullValue())
2963 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00002964
Chris Lattnera2498472009-10-11 21:36:10 +00002965 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002966 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002967 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002968
2969 // As above, vector X*splat(1.0) -> X in all defined cases.
2970 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002971 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2972 if (CI->equalsInt(1))
2973 return ReplaceInstUsesWith(I, Op0);
2974 }
2975 }
Chris Lattnera2881962003-02-18 19:28:33 +00002976 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002977
2978 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2979 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00002980 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002981 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00002982 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2983 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002984 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002985
2986 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002987
2988 // Try to fold constant mul into select arguments.
2989 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002990 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002991 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002992
2993 if (isa<PHINode>(Op0))
2994 if (Instruction *NV = FoldOpIntoPhi(I))
2995 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002996 }
2997
Dan Gohman186a6362009-08-12 16:04:34 +00002998 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00002999 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003000 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003001
Nick Lewycky0c730792008-11-21 07:33:58 +00003002 // (X / Y) * Y = X - (X % Y)
3003 // (X / Y) * -Y = (X % Y) - X
3004 {
Chris Lattnera2498472009-10-11 21:36:10 +00003005 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00003006 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3007 if (!BO ||
3008 (BO->getOpcode() != Instruction::UDiv &&
3009 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00003010 Op1C = Op0;
3011 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00003012 }
Chris Lattnera2498472009-10-11 21:36:10 +00003013 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00003014 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003015 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00003016 (BO->getOpcode() == Instruction::UDiv ||
3017 BO->getOpcode() == Instruction::SDiv)) {
3018 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3019
Dan Gohmanfa94b942009-08-12 16:33:09 +00003020 // If the division is exact, X % Y is zero.
3021 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3022 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00003023 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00003024 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00003025 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00003026 }
3027
Chris Lattner74381062009-08-30 07:44:24 +00003028 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00003029 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00003030 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003031 else
Chris Lattner74381062009-08-30 07:44:24 +00003032 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003033 Rem->takeName(BO);
3034
Chris Lattnera2498472009-10-11 21:36:10 +00003035 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00003036 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00003037 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003038 }
3039 }
3040
Chris Lattner8af304a2009-10-11 07:53:15 +00003041 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00003042 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00003043 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003044
Chris Lattner8af304a2009-10-11 07:53:15 +00003045 // X*(1 << Y) --> X << Y
3046 // (1 << Y)*X --> X << Y
3047 {
3048 Value *Y;
3049 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00003050 return BinaryOperator::CreateShl(Op1, Y);
3051 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00003052 return BinaryOperator::CreateShl(Op0, Y);
3053 }
3054
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003055 // If one of the operands of the multiply is a cast from a boolean value, then
3056 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00003057 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3058 if (!isa<VectorType>(I.getType())) {
3059 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00003060 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00003061
Chris Lattnerd2c58362009-10-11 21:29:45 +00003062 Value *BoolCast = 0, *OtherOp = 0;
3063 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00003064 BoolCast = Op0, OtherOp = Op1;
3065 else if (MaskedValueIsZero(Op1, Negative2))
3066 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00003067
Chris Lattner0036e3a2009-10-11 21:22:21 +00003068 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00003069 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3070 BoolCast, "tmp");
3071 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003072 }
3073 }
3074
Chris Lattner7e708292002-06-25 16:13:24 +00003075 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003076}
3077
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003078Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3079 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003080 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003081
3082 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00003083 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3084 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003085 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3086 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3087 if (Op1F->isExactlyValue(1.0))
3088 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00003089 } else if (isa<VectorType>(Op1C->getType())) {
3090 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003091 // As above, vector X*splat(1.0) -> X in all defined cases.
3092 if (Constant *Splat = Op1V->getSplatValue()) {
3093 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3094 if (F->isExactlyValue(1.0))
3095 return ReplaceInstUsesWith(I, Op0);
3096 }
3097 }
3098 }
3099
3100 // Try to fold constant mul into select arguments.
3101 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3102 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3103 return R;
3104
3105 if (isa<PHINode>(Op0))
3106 if (Instruction *NV = FoldOpIntoPhi(I))
3107 return NV;
3108 }
3109
Dan Gohman186a6362009-08-12 16:04:34 +00003110 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003111 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003112 return BinaryOperator::CreateFMul(Op0v, Op1v);
3113
3114 return Changed ? &I : 0;
3115}
3116
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003117/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3118/// instruction.
3119bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3120 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3121
3122 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3123 int NonNullOperand = -1;
3124 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3125 if (ST->isNullValue())
3126 NonNullOperand = 2;
3127 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3128 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3129 if (ST->isNullValue())
3130 NonNullOperand = 1;
3131
3132 if (NonNullOperand == -1)
3133 return false;
3134
3135 Value *SelectCond = SI->getOperand(0);
3136
3137 // Change the div/rem to use 'Y' instead of the select.
3138 I.setOperand(1, SI->getOperand(NonNullOperand));
3139
3140 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3141 // problem. However, the select, or the condition of the select may have
3142 // multiple uses. Based on our knowledge that the operand must be non-zero,
3143 // propagate the known value for the select into other uses of it, and
3144 // propagate a known value of the condition into its other users.
3145
3146 // If the select and condition only have a single use, don't bother with this,
3147 // early exit.
3148 if (SI->use_empty() && SelectCond->hasOneUse())
3149 return true;
3150
3151 // Scan the current block backward, looking for other uses of SI.
3152 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3153
3154 while (BBI != BBFront) {
3155 --BBI;
3156 // If we found a call to a function, we can't assume it will return, so
3157 // information from below it cannot be propagated above it.
3158 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3159 break;
3160
3161 // Replace uses of the select or its condition with the known values.
3162 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3163 I != E; ++I) {
3164 if (*I == SI) {
3165 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003166 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003167 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00003168 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3169 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003170 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003171 }
3172 }
3173
3174 // If we past the instruction, quit looking for it.
3175 if (&*BBI == SI)
3176 SI = 0;
3177 if (&*BBI == SelectCond)
3178 SelectCond = 0;
3179
3180 // If we ran out of things to eliminate, break out of the loop.
3181 if (SelectCond == 0 && SI == 0)
3182 break;
3183
3184 }
3185 return true;
3186}
3187
3188
Reid Spencer1628cec2006-10-26 06:15:43 +00003189/// This function implements the transforms on div instructions that work
3190/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3191/// used by the visitors to those instructions.
3192/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003193Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003194 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003195
Chris Lattner50b2ca42008-02-19 06:12:18 +00003196 // undef / X -> 0 for integer.
3197 // undef / X -> undef for FP (the undef could be a snan).
3198 if (isa<UndefValue>(Op0)) {
3199 if (Op0->getType()->isFPOrFPVector())
3200 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00003201 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003202 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003203
3204 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003205 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003206 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003207
Reid Spencer1628cec2006-10-26 06:15:43 +00003208 return 0;
3209}
Misha Brukmanfd939082005-04-21 23:48:37 +00003210
Reid Spencer1628cec2006-10-26 06:15:43 +00003211/// This function implements the transforms common to both integer division
3212/// instructions (udiv and sdiv). It is called by the visitors to those integer
3213/// division instructions.
3214/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003215Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003216 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3217
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003218 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003219 if (Op0 == Op1) {
3220 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003221 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003222 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00003223 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003224 }
3225
Owen Andersoneed707b2009-07-24 23:12:02 +00003226 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003227 return ReplaceInstUsesWith(I, CI);
3228 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003229
Reid Spencer1628cec2006-10-26 06:15:43 +00003230 if (Instruction *Common = commonDivTransforms(I))
3231 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003232
3233 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3234 // This does not apply for fdiv.
3235 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3236 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003237
3238 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3239 // div X, 1 == X
3240 if (RHS->equalsInt(1))
3241 return ReplaceInstUsesWith(I, Op0);
3242
3243 // (X / C1) / C2 -> X / (C1*C2)
3244 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3245 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3246 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003247 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003248 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003249 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003250 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003251 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003252 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003253 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003254
Reid Spencerbca0e382007-03-23 20:05:17 +00003255 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003256 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3257 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3258 return R;
3259 if (isa<PHINode>(Op0))
3260 if (Instruction *NV = FoldOpIntoPhi(I))
3261 return NV;
3262 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003263 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003264
Chris Lattnera2881962003-02-18 19:28:33 +00003265 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003266 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003267 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003268 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003269
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003270 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003271 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003272 return ReplaceInstUsesWith(I, Op0);
3273
Nick Lewycky895f0852008-11-27 20:21:08 +00003274 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3275 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3276 // div X, 1 == X
3277 if (X->isOne())
3278 return ReplaceInstUsesWith(I, Op0);
3279 }
3280
Reid Spencer1628cec2006-10-26 06:15:43 +00003281 return 0;
3282}
3283
3284Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3285 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3286
3287 // Handle the integer div common cases
3288 if (Instruction *Common = commonIDivTransforms(I))
3289 return Common;
3290
Reid Spencer1628cec2006-10-26 06:15:43 +00003291 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003292 // X udiv C^2 -> X >> C
3293 // Check to see if this is an unsigned division with an exact power of 2,
3294 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003295 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003296 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003297 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003298
3299 // X udiv C, where C >= signbit
3300 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003301 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003302 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003303 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003304 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003305 }
3306
3307 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003308 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003309 if (RHSI->getOpcode() == Instruction::Shl &&
3310 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003311 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003312 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003313 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003314 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003315 if (uint32_t C2 = C1.logBase2())
3316 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003317 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003318 }
3319 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003320 }
3321
Reid Spencer1628cec2006-10-26 06:15:43 +00003322 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3323 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003324 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003325 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003326 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003327 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003328 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003329 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003330 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003331 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003332 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003333 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003334
3335 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003336 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003337 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003338
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003339 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003340 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003341 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003342 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003343 return 0;
3344}
3345
Reid Spencer1628cec2006-10-26 06:15:43 +00003346Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3347 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3348
3349 // Handle the integer div common cases
3350 if (Instruction *Common = commonIDivTransforms(I))
3351 return Common;
3352
3353 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3354 // sdiv X, -1 == -X
3355 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003356 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003357
Dan Gohmanfa94b942009-08-12 16:33:09 +00003358 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003359 if (cast<SDivOperator>(&I)->isExact() &&
3360 RHS->getValue().isNonNegative() &&
3361 RHS->getValue().isPowerOf2()) {
3362 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3363 RHS->getValue().exactLogBase2());
3364 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3365 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003366
3367 // -X/C --> X/-C provided the negation doesn't overflow.
3368 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3369 if (isa<Constant>(Sub->getOperand(0)) &&
3370 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003371 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003372 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3373 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003374 }
3375
3376 // If the sign bits of both operands are zero (i.e. we can prove they are
3377 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003378 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003379 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003380 if (MaskedValueIsZero(Op0, Mask)) {
3381 if (MaskedValueIsZero(Op1, Mask)) {
3382 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3383 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3384 }
3385 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003386 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003387 ShiftedInt->getValue().isPowerOf2()) {
3388 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3389 // Safe because the only negative value (1 << Y) can take on is
3390 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3391 // the sign bit set.
3392 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3393 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003394 }
Eli Friedman8be17392009-07-18 09:53:21 +00003395 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003396
3397 return 0;
3398}
3399
3400Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3401 return commonDivTransforms(I);
3402}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003403
Reid Spencer0a783f72006-11-02 01:53:59 +00003404/// This function implements the transforms on rem instructions that work
3405/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3406/// is used by the visitors to those instructions.
3407/// @brief Transforms common to all three rem instructions
3408Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003410
Chris Lattner50b2ca42008-02-19 06:12:18 +00003411 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3412 if (I.getType()->isFPOrFPVector())
3413 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003414 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003415 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003416 if (isa<UndefValue>(Op1))
3417 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003418
3419 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003420 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3421 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003422
Reid Spencer0a783f72006-11-02 01:53:59 +00003423 return 0;
3424}
3425
3426/// This function implements the transforms common to both integer remainder
3427/// instructions (urem and srem). It is called by the visitors to those integer
3428/// remainder instructions.
3429/// @brief Common integer remainder transforms
3430Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3431 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3432
3433 if (Instruction *common = commonRemTransforms(I))
3434 return common;
3435
Dale Johannesened6af242009-01-21 00:35:19 +00003436 // 0 % X == 0 for integer, we don't need to preserve faults!
3437 if (Constant *LHS = dyn_cast<Constant>(Op0))
3438 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003439 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003440
Chris Lattner857e8cd2004-12-12 21:48:58 +00003441 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003442 // X % 0 == undef, we don't need to preserve faults!
3443 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003444 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003445
Chris Lattnera2881962003-02-18 19:28:33 +00003446 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003447 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003448
Chris Lattner97943922006-02-28 05:49:21 +00003449 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3450 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3451 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3452 return R;
3453 } else if (isa<PHINode>(Op0I)) {
3454 if (Instruction *NV = FoldOpIntoPhi(I))
3455 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003456 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003457
3458 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003459 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003460 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003461 }
Chris Lattnera2881962003-02-18 19:28:33 +00003462 }
3463
Reid Spencer0a783f72006-11-02 01:53:59 +00003464 return 0;
3465}
3466
3467Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3468 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3469
3470 if (Instruction *common = commonIRemTransforms(I))
3471 return common;
3472
3473 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3474 // X urem C^2 -> X and C
3475 // Check to see if this is an unsigned remainder with an exact power of 2,
3476 // if so, convert to a bitwise and.
3477 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003478 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003479 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003480 }
3481
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003482 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003483 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3484 if (RHSI->getOpcode() == Instruction::Shl &&
3485 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003486 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003487 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003488 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003489 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003490 }
3491 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003492 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003493
Reid Spencer0a783f72006-11-02 01:53:59 +00003494 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3495 // where C1&C2 are powers of two.
3496 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3497 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3498 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3499 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003500 if ((STO->getValue().isPowerOf2()) &&
3501 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003502 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3503 SI->getName()+".t");
3504 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3505 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003506 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003507 }
3508 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003509 }
3510
Chris Lattner3f5b8772002-05-06 16:14:14 +00003511 return 0;
3512}
3513
Reid Spencer0a783f72006-11-02 01:53:59 +00003514Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3515 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3516
Dan Gohmancff55092007-11-05 23:16:33 +00003517 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003518 if (Instruction *Common = commonIRemTransforms(I))
3519 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003520
Dan Gohman186a6362009-08-12 16:04:34 +00003521 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003522 if (!isa<Constant>(RHSNeg) ||
3523 (isa<ConstantInt>(RHSNeg) &&
3524 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003525 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003526 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003527 I.setOperand(1, RHSNeg);
3528 return &I;
3529 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003530
Dan Gohmancff55092007-11-05 23:16:33 +00003531 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003532 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003533 if (I.getType()->isInteger()) {
3534 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3535 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3536 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003537 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003538 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003539 }
3540
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003541 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003542 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3543 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003544
Nick Lewycky9dce8732008-12-20 16:48:00 +00003545 bool hasNegative = false;
3546 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3547 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3548 if (RHS->getValue().isNegative())
3549 hasNegative = true;
3550
3551 if (hasNegative) {
3552 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003553 for (unsigned i = 0; i != VWidth; ++i) {
3554 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3555 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003556 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003557 else
3558 Elts[i] = RHS;
3559 }
3560 }
3561
Owen Andersonaf7ec972009-07-28 21:19:26 +00003562 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003563 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003564 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003565 I.setOperand(1, NewRHSV);
3566 return &I;
3567 }
3568 }
3569 }
3570
Reid Spencer0a783f72006-11-02 01:53:59 +00003571 return 0;
3572}
3573
3574Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003575 return commonRemTransforms(I);
3576}
3577
Chris Lattner457dd822004-06-09 07:59:58 +00003578// isOneBitSet - Return true if there is exactly one bit set in the specified
3579// constant.
3580static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003581 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003582}
3583
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003584// isHighOnes - Return true if the constant is of the form 1+0+.
3585// This is the same as lowones(~X).
3586static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003587 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003588}
3589
Reid Spencere4d87aa2006-12-23 06:05:41 +00003590/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003591/// are carefully arranged to allow folding of expressions such as:
3592///
3593/// (A < B) | (A > B) --> (A != B)
3594///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003595/// Note that this is only valid if the first and second predicates have the
3596/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003597///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003598/// Three bits are used to represent the condition, as follows:
3599/// 0 A > B
3600/// 1 A == B
3601/// 2 A < B
3602///
3603/// <=> Value Definition
3604/// 000 0 Always false
3605/// 001 1 A > B
3606/// 010 2 A == B
3607/// 011 3 A >= B
3608/// 100 4 A < B
3609/// 101 5 A != B
3610/// 110 6 A <= B
3611/// 111 7 Always true
3612///
3613static unsigned getICmpCode(const ICmpInst *ICI) {
3614 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003615 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003616 case ICmpInst::ICMP_UGT: return 1; // 001
3617 case ICmpInst::ICMP_SGT: return 1; // 001
3618 case ICmpInst::ICMP_EQ: return 2; // 010
3619 case ICmpInst::ICMP_UGE: return 3; // 011
3620 case ICmpInst::ICMP_SGE: return 3; // 011
3621 case ICmpInst::ICMP_ULT: return 4; // 100
3622 case ICmpInst::ICMP_SLT: return 4; // 100
3623 case ICmpInst::ICMP_NE: return 5; // 101
3624 case ICmpInst::ICMP_ULE: return 6; // 110
3625 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003626 // True -> 7
3627 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003628 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003629 return 0;
3630 }
3631}
3632
Evan Cheng8db90722008-10-14 17:15:11 +00003633/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3634/// predicate into a three bit mask. It also returns whether it is an ordered
3635/// predicate by reference.
3636static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3637 isOrdered = false;
3638 switch (CC) {
3639 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3640 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003641 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3642 case FCmpInst::FCMP_UGT: return 1; // 001
3643 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3644 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003645 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3646 case FCmpInst::FCMP_UGE: return 3; // 011
3647 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3648 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003649 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3650 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003651 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3652 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003653 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003654 default:
3655 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003656 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003657 return 0;
3658 }
3659}
3660
Reid Spencere4d87aa2006-12-23 06:05:41 +00003661/// getICmpValue - This is the complement of getICmpCode, which turns an
3662/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003663/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003664/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003665static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003666 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003667 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003668 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003669 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003670 case 1:
3671 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003672 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003673 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003674 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3675 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003676 case 3:
3677 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003678 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003679 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003680 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003681 case 4:
3682 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003683 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003684 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003685 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3686 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003687 case 6:
3688 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003689 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003690 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003691 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003692 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003693 }
3694}
3695
Evan Cheng8db90722008-10-14 17:15:11 +00003696/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3697/// opcode and two operands into either a FCmp instruction. isordered is passed
3698/// in to determine which kind of predicate to use in the new fcmp instruction.
3699static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003700 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003701 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003702 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003703 case 0:
3704 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003705 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003706 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003707 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003708 case 1:
3709 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003710 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003711 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003712 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003713 case 2:
3714 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003715 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003716 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003717 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003718 case 3:
3719 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003720 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003721 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003722 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003723 case 4:
3724 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003725 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003726 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003727 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003728 case 5:
3729 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003730 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003731 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003732 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003733 case 6:
3734 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003735 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003736 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003737 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003738 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003739 }
3740}
3741
Chris Lattnerb9553d62008-11-16 04:55:20 +00003742/// PredicatesFoldable - Return true if both predicates match sign or if at
3743/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003744static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003745 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3746 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3747 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003748}
3749
3750namespace {
3751// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3752struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003753 InstCombiner &IC;
3754 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003755 ICmpInst::Predicate pred;
3756 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3757 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3758 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003759 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003760 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3761 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003762 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3763 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003764 return false;
3765 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003766 Instruction *apply(Instruction &Log) const {
3767 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3768 if (ICI->getOperand(0) != LHS) {
3769 assert(ICI->getOperand(1) == LHS);
3770 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003771 }
3772
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003773 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003774 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003775 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003776 unsigned Code;
3777 switch (Log.getOpcode()) {
3778 case Instruction::And: Code = LHSCode & RHSCode; break;
3779 case Instruction::Or: Code = LHSCode | RHSCode; break;
3780 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003781 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003782 }
3783
Nick Lewycky4a134af2009-10-25 05:20:17 +00003784 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Andersond672ecb2009-07-03 00:17:18 +00003785 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003786 if (Instruction *I = dyn_cast<Instruction>(RV))
3787 return I;
3788 // Otherwise, it's a constant boolean value...
3789 return IC.ReplaceInstUsesWith(Log, RV);
3790 }
3791};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003792} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003793
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003794// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3795// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003796// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003797Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003798 ConstantInt *OpRHS,
3799 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003800 BinaryOperator &TheAnd) {
3801 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003802 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003803 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003804 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003805
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003806 switch (Op->getOpcode()) {
3807 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003808 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003809 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003810 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003811 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003812 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003813 }
3814 break;
3815 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003816 if (Together == AndRHS) // (X | C) & C --> C
3817 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003818
Chris Lattner6e7ba452005-01-01 16:22:27 +00003819 if (Op->hasOneUse() && Together != OpRHS) {
3820 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003821 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003822 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003823 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003824 }
3825 break;
3826 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003827 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003828 // Adding a one to a single bit bit-field should be turned into an XOR
3829 // of the bit. First thing to check is to see if this AND is with a
3830 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003831 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003832
3833 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003834 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003835 // Ok, at this point, we know that we are masking the result of the
3836 // ADD down to exactly one bit. If the constant we are adding has
3837 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003838 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003839
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003840 // Check to see if any bits below the one bit set in AndRHSV are set.
3841 if ((AddRHS & (AndRHSV-1)) == 0) {
3842 // If not, the only thing that can effect the output of the AND is
3843 // the bit specified by AndRHSV. If that bit is set, the effect of
3844 // the XOR is to toggle the bit. If it is clear, then the ADD has
3845 // no effect.
3846 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3847 TheAnd.setOperand(0, X);
3848 return &TheAnd;
3849 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003850 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003851 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003852 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003853 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003854 }
3855 }
3856 }
3857 }
3858 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003859
3860 case Instruction::Shl: {
3861 // We know that the AND will not produce any of the bits shifted in, so if
3862 // the anded constant includes them, clear them now!
3863 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003864 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003865 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003866 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003867 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003868
Zhou Sheng290bec52007-03-29 08:15:12 +00003869 if (CI->getValue() == ShlMask) {
3870 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003871 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3872 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003873 TheAnd.setOperand(1, CI);
3874 return &TheAnd;
3875 }
3876 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003877 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003878 case Instruction::LShr:
3879 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003880 // We know that the AND will not produce any of the bits shifted in, so if
3881 // the anded constant includes them, clear them now! This only applies to
3882 // unsigned shifts, because a signed shr may bring in set bits!
3883 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003884 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003885 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003886 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003887 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003888
Zhou Sheng290bec52007-03-29 08:15:12 +00003889 if (CI->getValue() == ShrMask) {
3890 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003891 return ReplaceInstUsesWith(TheAnd, Op);
3892 } else if (CI != AndRHS) {
3893 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3894 return &TheAnd;
3895 }
3896 break;
3897 }
3898 case Instruction::AShr:
3899 // Signed shr.
3900 // See if this is shifting in some sign extension, then masking it out
3901 // with an and.
3902 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003903 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003904 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003905 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003906 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003907 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003908 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003909 // Make the argument unsigned.
3910 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003911 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003912 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003913 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003914 }
3915 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003916 }
3917 return 0;
3918}
3919
Chris Lattner8b170942002-08-09 23:47:40 +00003920
Chris Lattnera96879a2004-09-29 17:40:11 +00003921/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3922/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003923/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3924/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003925/// insert new instructions.
3926Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003927 bool isSigned, bool Inside,
3928 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003929 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003930 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003931 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003932
Chris Lattnera96879a2004-09-29 17:40:11 +00003933 if (Inside) {
3934 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003935 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003936
Reid Spencere4d87aa2006-12-23 06:05:41 +00003937 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003938 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003939 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003940 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003941 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003942 }
3943
3944 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003945 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003946 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003947 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003948 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003949 }
3950
3951 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003952 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003953
Reid Spencere4e40032007-03-21 23:19:50 +00003954 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003955 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003956 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003957 ICmpInst::Predicate pred = (isSigned ?
3958 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003959 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003960 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003961
Reid Spencere4e40032007-03-21 23:19:50 +00003962 // Emit V-Lo >u Hi-1-Lo
3963 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003964 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003965 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003966 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003967 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003968}
3969
Chris Lattner7203e152005-09-18 07:22:02 +00003970// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3971// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3972// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3973// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003974static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003975 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003976 uint32_t BitWidth = Val->getType()->getBitWidth();
3977 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003978
3979 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003980 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003981 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003982 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003983 return true;
3984}
3985
Chris Lattner7203e152005-09-18 07:22:02 +00003986/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3987/// where isSub determines whether the operator is a sub. If we can fold one of
3988/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003989///
3990/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3991/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3992/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3993///
3994/// return (A +/- B).
3995///
3996Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003997 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003998 Instruction &I) {
3999 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4000 if (!LHSI || LHSI->getNumOperands() != 2 ||
4001 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4002
4003 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4004
4005 switch (LHSI->getOpcode()) {
4006 default: return 0;
4007 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00004008 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00004009 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00004010 if ((Mask->getValue().countLeadingZeros() +
4011 Mask->getValue().countPopulation()) ==
4012 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00004013 break;
4014
4015 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4016 // part, we don't need any explicit masks to take them out of A. If that
4017 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00004018 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00004019 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00004020 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004021 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004022 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004023 break;
4024 }
4025 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004026 return 0;
4027 case Instruction::Or:
4028 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004029 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004030 if ((Mask->getValue().countLeadingZeros() +
4031 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00004032 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004033 break;
4034 return 0;
4035 }
4036
Chris Lattnerc8e77562005-09-18 04:24:45 +00004037 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00004038 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4039 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004040}
4041
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004042/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4043Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4044 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00004045 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004046 ConstantInt *LHSCst, *RHSCst;
4047 ICmpInst::Predicate LHSCC, RHSCC;
4048
Chris Lattnerea065fb2008-11-16 05:10:52 +00004049 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004050 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004051 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004052 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004053 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004054 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00004055
4056 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4057 // where C is a power of 2
4058 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
4059 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00004060 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004061 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00004062 }
4063
4064 // From here on, we only handle:
4065 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4066 if (Val != Val2) return 0;
4067
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004068 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4069 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4070 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4071 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4072 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4073 return 0;
4074
4075 // We can't fold (ugt x, C) & (sgt x, C2).
4076 if (!PredicatesFoldable(LHSCC, RHSCC))
4077 return 0;
4078
4079 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00004080 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004081 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004082 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004083 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00004084 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004085 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00004086 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4087
4088 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004089 std::swap(LHS, RHS);
4090 std::swap(LHSCst, RHSCst);
4091 std::swap(LHSCC, RHSCC);
4092 }
4093
4094 // At this point, we know we have have two icmp instructions
4095 // comparing a value against two constants and and'ing the result
4096 // together. Because of the above check, we know that we only have
4097 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4098 // (from the FoldICmpLogical check above), that the two constants
4099 // are not equal and that the larger constant is on the RHS
4100 assert(LHSCst != RHSCst && "Compares not folded above?");
4101
4102 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004103 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004104 case ICmpInst::ICMP_EQ:
4105 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004106 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004107 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4108 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4109 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004110 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004111 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4112 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4113 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4114 return ReplaceInstUsesWith(I, LHS);
4115 }
4116 case ICmpInst::ICMP_NE:
4117 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004118 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004119 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00004120 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004121 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004122 break; // (X != 13 & X u< 15) -> no change
4123 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00004124 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004125 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004126 break; // (X != 13 & X s< 15) -> no change
4127 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4128 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4129 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4130 return ReplaceInstUsesWith(I, RHS);
4131 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004132 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00004133 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004134 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004135 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00004136 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004137 }
4138 break; // (X != 13 & X != 15) -> no change
4139 }
4140 break;
4141 case ICmpInst::ICMP_ULT:
4142 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004143 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004144 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4145 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004146 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004147 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4148 break;
4149 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4150 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4151 return ReplaceInstUsesWith(I, LHS);
4152 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4153 break;
4154 }
4155 break;
4156 case ICmpInst::ICMP_SLT:
4157 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004158 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004159 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4160 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004161 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004162 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4163 break;
4164 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4165 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4166 return ReplaceInstUsesWith(I, LHS);
4167 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4168 break;
4169 }
4170 break;
4171 case ICmpInst::ICMP_UGT:
4172 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004173 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004174 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4175 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4176 return ReplaceInstUsesWith(I, RHS);
4177 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4178 break;
4179 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004180 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004181 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004182 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004183 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00004184 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004185 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004186 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4187 break;
4188 }
4189 break;
4190 case ICmpInst::ICMP_SGT:
4191 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004192 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004193 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4194 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4195 return ReplaceInstUsesWith(I, RHS);
4196 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4197 break;
4198 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004199 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004200 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004201 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004202 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00004203 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004204 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004205 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4206 break;
4207 }
4208 break;
4209 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004210
4211 return 0;
4212}
4213
Chris Lattner42d1be02009-07-23 05:14:02 +00004214Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4215 FCmpInst *RHS) {
4216
4217 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4218 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4219 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4220 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4221 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4222 // If either of the constants are nans, then the whole thing returns
4223 // false.
4224 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004225 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004226 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00004227 LHS->getOperand(0), RHS->getOperand(0));
4228 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00004229
4230 // Handle vector zeros. This occurs because the canonical form of
4231 // "fcmp ord x,x" is "fcmp ord x, 0".
4232 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4233 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004234 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004235 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004236 return 0;
4237 }
4238
4239 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4240 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4241 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4242
4243
4244 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4245 // Swap RHS operands to match LHS.
4246 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4247 std::swap(Op1LHS, Op1RHS);
4248 }
4249
4250 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4251 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4252 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004253 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004254
4255 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004256 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004257 if (Op0CC == FCmpInst::FCMP_TRUE)
4258 return ReplaceInstUsesWith(I, RHS);
4259 if (Op1CC == FCmpInst::FCMP_TRUE)
4260 return ReplaceInstUsesWith(I, LHS);
4261
4262 bool Op0Ordered;
4263 bool Op1Ordered;
4264 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4265 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4266 if (Op1Pred == 0) {
4267 std::swap(LHS, RHS);
4268 std::swap(Op0Pred, Op1Pred);
4269 std::swap(Op0Ordered, Op1Ordered);
4270 }
4271 if (Op0Pred == 0) {
4272 // uno && ueq -> uno && (uno || eq) -> ueq
4273 // ord && olt -> ord && (ord && lt) -> olt
4274 if (Op0Ordered == Op1Ordered)
4275 return ReplaceInstUsesWith(I, RHS);
4276
4277 // uno && oeq -> uno && (ord && eq) -> false
4278 // uno && ord -> false
4279 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004280 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004281 // ord && ueq -> ord && (uno || eq) -> oeq
4282 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4283 Op0LHS, Op0RHS, Context));
4284 }
4285 }
4286
4287 return 0;
4288}
4289
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004290
Chris Lattner7e708292002-06-25 16:13:24 +00004291Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004292 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004293 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004294
Chris Lattnerd06094f2009-11-10 00:55:12 +00004295 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4296 return ReplaceInstUsesWith(I, V);
4297
Chris Lattner3f5b8772002-05-06 16:14:14 +00004298
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004299 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004300 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004301 if (SimplifyDemandedInstructionBits(I))
4302 return &I;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004303
Dan Gohman6de29f82009-06-15 22:12:54 +00004304
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004305 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004306 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004307 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004308
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004309 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004310 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004311 Value *Op0LHS = Op0I->getOperand(0);
4312 Value *Op0RHS = Op0I->getOperand(1);
4313 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004314 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004315 case Instruction::Xor:
4316 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004317 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004318 if (!Op0I->hasOneUse()) break;
4319
4320 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4321 // Not masking anything out for the LHS, move to RHS.
4322 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4323 Op0RHS->getName()+".masked");
4324 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4325 }
4326 if (!isa<Constant>(Op0RHS) &&
4327 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4328 // Not masking anything out for the RHS, move to LHS.
4329 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4330 Op0LHS->getName()+".masked");
4331 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004332 }
4333
Chris Lattner6e7ba452005-01-01 16:22:27 +00004334 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004335 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004336 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4337 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4338 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4339 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004340 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004341 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004342 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004343 break;
4344
4345 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004346 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4347 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4348 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4349 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004350 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004351
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004352 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4353 // has 1's for all bits that the subtraction with A might affect.
4354 if (Op0I->hasOneUse()) {
4355 uint32_t BitWidth = AndRHSMask.getBitWidth();
4356 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4357 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4358
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004359 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004360 if (!(A && A->isZero()) && // avoid infinite recursion.
4361 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004362 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004363 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4364 }
4365 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004366 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004367
4368 case Instruction::Shl:
4369 case Instruction::LShr:
4370 // (1 << x) & 1 --> zext(x == 0)
4371 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004372 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004373 Value *NewICmp =
4374 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004375 return new ZExtInst(NewICmp, I.getType());
4376 }
4377 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004378 }
4379
Chris Lattner58403262003-07-23 19:25:52 +00004380 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004381 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004382 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004383 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004384 // If this is an integer truncation or change from signed-to-unsigned, and
4385 // if the source is an and/or with immediate, transform it. This
4386 // frequently occurs for bitfield accesses.
4387 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004388 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004389 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00004390 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00004391 if (CastOp->getOpcode() == Instruction::And) {
4392 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004393 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4394 // This will fold the two constants together, which may allow
4395 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004396 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004397 CastOp->getOperand(0), I.getType(),
4398 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004399 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004400 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004401 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004402 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004403 } else if (CastOp->getOpcode() == Instruction::Or) {
4404 // Change: and (cast (or X, C1) to T), C2
4405 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004406 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004407 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004408 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004409 return ReplaceInstUsesWith(I, AndRHS);
4410 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004411 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004412 }
Chris Lattner06782f82003-07-23 19:36:21 +00004413 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004414
4415 // Try to fold constant and into select arguments.
4416 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004417 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004418 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004419 if (isa<PHINode>(Op0))
4420 if (Instruction *NV = FoldOpIntoPhi(I))
4421 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004422 }
4423
Chris Lattner5b62aa72004-06-18 06:07:51 +00004424
Misha Brukmancb6267b2004-07-30 12:50:08 +00004425 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00004426 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4427 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4428 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4429 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4430 I.getName()+".demorgan");
4431 return BinaryOperator::CreateNot(Or);
4432 }
4433
Chris Lattner2082ad92006-02-13 23:07:23 +00004434 {
Chris Lattner003b6202007-06-15 05:58:24 +00004435 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004436 // (A|B) & ~(A&B) -> A^B
4437 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4438 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4439 ((A == C && B == D) || (A == D && B == C)))
4440 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004441
Chris Lattnerd06094f2009-11-10 00:55:12 +00004442 // ~(A&B) & (A|B) -> A^B
4443 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4444 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4445 ((A == C && B == D) || (A == D && B == C)))
4446 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00004447
4448 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004449 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004450 if (A == Op1) { // (A^B)&A -> A&(A^B)
4451 I.swapOperands(); // Simplify below
4452 std::swap(Op0, Op1);
4453 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4454 cast<BinaryOperator>(Op0)->swapOperands();
4455 I.swapOperands(); // Simplify below
4456 std::swap(Op0, Op1);
4457 }
4458 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004459
Chris Lattner64daab52006-04-01 08:03:55 +00004460 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004461 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004462 if (B == Op0) { // B&(A^B) -> B&(B^A)
4463 cast<BinaryOperator>(Op1)->swapOperands();
4464 std::swap(A, B);
4465 }
Chris Lattner74381062009-08-30 07:44:24 +00004466 if (A == Op0) // A&(A^B) -> A & ~B
4467 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004468 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004469
4470 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004471 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4472 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004473 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004474 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4475 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004476 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004477 }
4478
Reid Spencere4d87aa2006-12-23 06:05:41 +00004479 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4480 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004481 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004482 return R;
4483
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004484 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4485 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4486 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004487 }
4488
Chris Lattner6fc205f2006-05-05 06:39:07 +00004489 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004490 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4491 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4492 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4493 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004494 if (SrcTy == Op1C->getOperand(0)->getType() &&
4495 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004496 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004497 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4498 I.getType(), TD) &&
4499 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4500 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004501 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4502 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004503 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004504 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004505 }
Chris Lattnere511b742006-11-14 07:46:50 +00004506
4507 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004508 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4509 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4510 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004511 SI0->getOperand(1) == SI1->getOperand(1) &&
4512 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004513 Value *NewOp =
4514 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4515 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004516 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004517 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004518 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004519 }
4520
Evan Cheng8db90722008-10-14 17:15:11 +00004521 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004522 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004523 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4524 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4525 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004526 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004527
Chris Lattner7e708292002-06-25 16:13:24 +00004528 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004529}
4530
Chris Lattner8c34cd22008-10-05 02:13:19 +00004531/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4532/// capable of providing pieces of a bswap. The subexpression provides pieces
4533/// of a bswap if it is proven that each of the non-zero bytes in the output of
4534/// the expression came from the corresponding "byte swapped" byte in some other
4535/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4536/// we know that the expression deposits the low byte of %X into the high byte
4537/// of the bswap result and that all other bytes are zero. This expression is
4538/// accepted, the high byte of ByteValues is set to X to indicate a correct
4539/// match.
4540///
4541/// This function returns true if the match was unsuccessful and false if so.
4542/// On entry to the function the "OverallLeftShift" is a signed integer value
4543/// indicating the number of bytes that the subexpression is later shifted. For
4544/// example, if the expression is later right shifted by 16 bits, the
4545/// OverallLeftShift value would be -2 on entry. This is used to specify which
4546/// byte of ByteValues is actually being set.
4547///
4548/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4549/// byte is masked to zero by a user. For example, in (X & 255), X will be
4550/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4551/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4552/// always in the local (OverallLeftShift) coordinate space.
4553///
4554static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4555 SmallVector<Value*, 8> &ByteValues) {
4556 if (Instruction *I = dyn_cast<Instruction>(V)) {
4557 // If this is an or instruction, it may be an inner node of the bswap.
4558 if (I->getOpcode() == Instruction::Or) {
4559 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4560 ByteValues) ||
4561 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4562 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004563 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004564
4565 // If this is a logical shift by a constant multiple of 8, recurse with
4566 // OverallLeftShift and ByteMask adjusted.
4567 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4568 unsigned ShAmt =
4569 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4570 // Ensure the shift amount is defined and of a byte value.
4571 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4572 return true;
4573
4574 unsigned ByteShift = ShAmt >> 3;
4575 if (I->getOpcode() == Instruction::Shl) {
4576 // X << 2 -> collect(X, +2)
4577 OverallLeftShift += ByteShift;
4578 ByteMask >>= ByteShift;
4579 } else {
4580 // X >>u 2 -> collect(X, -2)
4581 OverallLeftShift -= ByteShift;
4582 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004583 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004584 }
4585
4586 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4587 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4588
4589 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4590 ByteValues);
4591 }
4592
4593 // If this is a logical 'and' with a mask that clears bytes, clear the
4594 // corresponding bytes in ByteMask.
4595 if (I->getOpcode() == Instruction::And &&
4596 isa<ConstantInt>(I->getOperand(1))) {
4597 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4598 unsigned NumBytes = ByteValues.size();
4599 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4600 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4601
4602 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4603 // If this byte is masked out by a later operation, we don't care what
4604 // the and mask is.
4605 if ((ByteMask & (1 << i)) == 0)
4606 continue;
4607
4608 // If the AndMask is all zeros for this byte, clear the bit.
4609 APInt MaskB = AndMask & Byte;
4610 if (MaskB == 0) {
4611 ByteMask &= ~(1U << i);
4612 continue;
4613 }
4614
4615 // If the AndMask is not all ones for this byte, it's not a bytezap.
4616 if (MaskB != Byte)
4617 return true;
4618
4619 // Otherwise, this byte is kept.
4620 }
4621
4622 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4623 ByteValues);
4624 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004625 }
4626
Chris Lattner8c34cd22008-10-05 02:13:19 +00004627 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4628 // the input value to the bswap. Some observations: 1) if more than one byte
4629 // is demanded from this input, then it could not be successfully assembled
4630 // into a byteswap. At least one of the two bytes would not be aligned with
4631 // their ultimate destination.
4632 if (!isPowerOf2_32(ByteMask)) return true;
4633 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004634
Chris Lattner8c34cd22008-10-05 02:13:19 +00004635 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4636 // is demanded, it needs to go into byte 0 of the result. This means that the
4637 // byte needs to be shifted until it lands in the right byte bucket. The
4638 // shift amount depends on the position: if the byte is coming from the high
4639 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4640 // low part, it must be shifted left.
4641 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4642 if (InputByteNo < ByteValues.size()/2) {
4643 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4644 return true;
4645 } else {
4646 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4647 return true;
4648 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004649
4650 // If the destination byte value is already defined, the values are or'd
4651 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004652 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004653 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004654 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004655 return false;
4656}
4657
4658/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4659/// If so, insert the new bswap intrinsic and return it.
4660Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004661 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004662 if (!ITy || ITy->getBitWidth() % 16 ||
4663 // ByteMask only allows up to 32-byte values.
4664 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004665 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004666
4667 /// ByteValues - For each byte of the result, we keep track of which value
4668 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004669 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004670 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004671
4672 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004673 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4674 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004675 return 0;
4676
4677 // Check to see if all of the bytes come from the same value.
4678 Value *V = ByteValues[0];
4679 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4680
4681 // Check to make sure that all of the bytes come from the same value.
4682 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4683 if (ByteValues[i] != V)
4684 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004685 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004686 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004687 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004688 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004689}
4690
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004691/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4692/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4693/// we can simplify this expression to "cond ? C : D or B".
4694static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004695 Value *C, Value *D,
4696 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004697 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004698 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004699 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004700 return 0;
4701
Chris Lattnera6a474d2008-11-16 04:26:55 +00004702 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004703 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004704 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004705 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004706 return SelectInst::Create(Cond, C, B);
4707 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004708 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004709 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004710 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004711 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004712 return 0;
4713}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004714
Chris Lattner69d4ced2008-11-16 05:20:07 +00004715/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4716Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4717 ICmpInst *LHS, ICmpInst *RHS) {
4718 Value *Val, *Val2;
4719 ConstantInt *LHSCst, *RHSCst;
4720 ICmpInst::Predicate LHSCC, RHSCC;
4721
4722 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004723 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004724 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004725 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004726 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004727 return 0;
4728
4729 // From here on, we only handle:
4730 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4731 if (Val != Val2) return 0;
4732
4733 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4734 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4735 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4736 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4737 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4738 return 0;
4739
4740 // We can't fold (ugt x, C) | (sgt x, C2).
4741 if (!PredicatesFoldable(LHSCC, RHSCC))
4742 return 0;
4743
4744 // Ensure that the larger constant is on the RHS.
4745 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004746 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004747 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004748 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004749 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4750 else
4751 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4752
4753 if (ShouldSwap) {
4754 std::swap(LHS, RHS);
4755 std::swap(LHSCst, RHSCst);
4756 std::swap(LHSCC, RHSCC);
4757 }
4758
4759 // At this point, we know we have have two icmp instructions
4760 // comparing a value against two constants and or'ing the result
4761 // together. Because of the above check, we know that we only have
4762 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4763 // FoldICmpLogical check above), that the two constants are not
4764 // equal.
4765 assert(LHSCst != RHSCst && "Compares not folded above?");
4766
4767 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004768 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004769 case ICmpInst::ICMP_EQ:
4770 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004771 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004772 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004773 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004774 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004775 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004776 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004777 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004778 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004779 }
4780 break; // (X == 13 | X == 15) -> no change
4781 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4782 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4783 break;
4784 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4785 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4786 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4787 return ReplaceInstUsesWith(I, RHS);
4788 }
4789 break;
4790 case ICmpInst::ICMP_NE:
4791 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004792 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004793 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4794 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4795 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4796 return ReplaceInstUsesWith(I, LHS);
4797 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4798 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4799 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004800 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004801 }
4802 break;
4803 case ICmpInst::ICMP_ULT:
4804 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004805 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004806 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4807 break;
4808 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4809 // If RHSCst is [us]MAXINT, it is always false. Not handling
4810 // this can cause overflow.
4811 if (RHSCst->isMaxValue(false))
4812 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004813 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004814 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004815 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4816 break;
4817 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4818 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4819 return ReplaceInstUsesWith(I, RHS);
4820 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4821 break;
4822 }
4823 break;
4824 case ICmpInst::ICMP_SLT:
4825 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004826 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004827 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4828 break;
4829 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4830 // If RHSCst is [us]MAXINT, it is always false. Not handling
4831 // this can cause overflow.
4832 if (RHSCst->isMaxValue(true))
4833 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004834 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004835 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004836 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4837 break;
4838 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4839 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4840 return ReplaceInstUsesWith(I, RHS);
4841 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4842 break;
4843 }
4844 break;
4845 case ICmpInst::ICMP_UGT:
4846 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004847 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004848 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4849 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4850 return ReplaceInstUsesWith(I, LHS);
4851 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4852 break;
4853 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4854 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004855 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004856 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4857 break;
4858 }
4859 break;
4860 case ICmpInst::ICMP_SGT:
4861 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004862 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004863 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4864 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4865 return ReplaceInstUsesWith(I, LHS);
4866 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4867 break;
4868 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4869 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004870 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004871 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4872 break;
4873 }
4874 break;
4875 }
4876 return 0;
4877}
4878
Chris Lattner5414cc52009-07-23 05:46:22 +00004879Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4880 FCmpInst *RHS) {
4881 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4882 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4883 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4884 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4885 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4886 // If either of the constants are nans, then the whole thing returns
4887 // true.
4888 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004889 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004890
4891 // Otherwise, no need to compare the two constants, compare the
4892 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004893 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004894 LHS->getOperand(0), RHS->getOperand(0));
4895 }
4896
4897 // Handle vector zeros. This occurs because the canonical form of
4898 // "fcmp uno x,x" is "fcmp uno x, 0".
4899 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4900 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004901 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004902 LHS->getOperand(0), RHS->getOperand(0));
4903
4904 return 0;
4905 }
4906
4907 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4908 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4909 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4910
4911 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4912 // Swap RHS operands to match LHS.
4913 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4914 std::swap(Op1LHS, Op1RHS);
4915 }
4916 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4917 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4918 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004919 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004920 Op0LHS, Op0RHS);
4921 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004922 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004923 if (Op0CC == FCmpInst::FCMP_FALSE)
4924 return ReplaceInstUsesWith(I, RHS);
4925 if (Op1CC == FCmpInst::FCMP_FALSE)
4926 return ReplaceInstUsesWith(I, LHS);
4927 bool Op0Ordered;
4928 bool Op1Ordered;
4929 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4930 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4931 if (Op0Ordered == Op1Ordered) {
4932 // If both are ordered or unordered, return a new fcmp with
4933 // or'ed predicates.
4934 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4935 Op0LHS, Op0RHS, Context);
4936 if (Instruction *I = dyn_cast<Instruction>(RV))
4937 return I;
4938 // Otherwise, it's a constant boolean value...
4939 return ReplaceInstUsesWith(I, RV);
4940 }
4941 }
4942 return 0;
4943}
4944
Bill Wendlinga698a472008-12-01 08:23:25 +00004945/// FoldOrWithConstants - This helper function folds:
4946///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004947/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004948///
4949/// into:
4950///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004951/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004952///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004953/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004954Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004955 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004956 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4957 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004958
Bill Wendling286a0542008-12-02 06:24:20 +00004959 Value *V1 = 0;
4960 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004961 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004962
Bill Wendling29976b92008-12-02 06:18:11 +00004963 APInt Xor = CI1->getValue() ^ CI2->getValue();
4964 if (!Xor.isAllOnesValue()) return 0;
4965
Bill Wendling286a0542008-12-02 06:24:20 +00004966 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004967 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004968 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004969 }
4970
4971 return 0;
4972}
4973
Chris Lattner7e708292002-06-25 16:13:24 +00004974Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004975 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004976 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004977
Chris Lattnerd06094f2009-11-10 00:55:12 +00004978 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
4979 return ReplaceInstUsesWith(I, V);
4980
4981
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004982 // See if we can simplify any instructions used by the instruction whose sole
4983 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004984 if (SimplifyDemandedInstructionBits(I))
4985 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004986
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004987 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004988 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004989 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004990 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004991 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004992 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004993 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004994 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004995 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004996 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004997
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004998 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004999 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005000 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005001 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005002 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005003 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005004 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005005 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005006
5007 // Try to fold constant and into select arguments.
5008 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005009 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005010 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005011 if (isa<PHINode>(Op0))
5012 if (Instruction *NV = FoldOpIntoPhi(I))
5013 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005014 }
5015
Chris Lattner4f637d42006-01-06 17:59:59 +00005016 Value *A = 0, *B = 0;
5017 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005018
Chris Lattner6423d4c2006-07-10 20:25:24 +00005019 // (A | B) | C and A | (B | C) -> bswap if possible.
5020 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00005021 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5022 match(Op1, m_Or(m_Value(), m_Value())) ||
5023 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5024 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00005025 if (Instruction *BSwap = MatchBSwap(I))
5026 return BSwap;
5027 }
5028
Chris Lattner6e4c6492005-05-09 04:58:36 +00005029 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005030 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005031 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005032 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005033 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00005034 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005035 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005036 }
5037
5038 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005039 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005040 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005041 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005042 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00005043 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005044 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005045 }
5046
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005047 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00005048 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005049 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5050 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005051 Value *V1 = 0, *V2 = 0, *V3 = 0;
5052 C1 = dyn_cast<ConstantInt>(C);
5053 C2 = dyn_cast<ConstantInt>(D);
5054 if (C1 && C2) { // (A & C1)|(B & C2)
5055 // If we have: ((V + N) & C1) | (V & C2)
5056 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5057 // replace with V+N.
5058 if (C1->getValue() == ~C2->getValue()) {
5059 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00005060 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005061 // Add commutes, try both ways.
5062 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5063 return ReplaceInstUsesWith(I, A);
5064 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5065 return ReplaceInstUsesWith(I, A);
5066 }
5067 // Or commutes, try both ways.
5068 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005069 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005070 // Add commutes, try both ways.
5071 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5072 return ReplaceInstUsesWith(I, B);
5073 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5074 return ReplaceInstUsesWith(I, B);
5075 }
5076 }
Chris Lattner044e5332007-04-08 08:01:49 +00005077 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00005078 }
5079
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005080 // Check to see if we have any common things being and'ed. If so, find the
5081 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005082 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5083 if (A == B) // (A & C)|(A & D) == A & (C|D)
5084 V1 = A, V2 = C, V3 = D;
5085 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5086 V1 = A, V2 = B, V3 = C;
5087 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5088 V1 = C, V2 = A, V3 = D;
5089 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5090 V1 = C, V2 = A, V3 = B;
5091
5092 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00005093 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005094 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00005095 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005096 }
Dan Gohmanb493b272008-10-28 22:38:57 +00005097
Dan Gohman1975d032008-10-30 20:40:10 +00005098 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005099 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005100 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005101 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005102 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005103 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005104 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005105 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005106 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00005107
Bill Wendlingb01865c2008-11-30 13:52:49 +00005108 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005109 if ((match(C, m_Not(m_Specific(D))) &&
5110 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005111 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005112 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005113 if ((match(A, m_Not(m_Specific(D))) &&
5114 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005115 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005116 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005117 if ((match(C, m_Not(m_Specific(B))) &&
5118 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005119 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005120 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005121 if ((match(A, m_Not(m_Specific(B))) &&
5122 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005123 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005124 }
Chris Lattnere511b742006-11-14 07:46:50 +00005125
5126 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00005127 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5128 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5129 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00005130 SI0->getOperand(1) == SI1->getOperand(1) &&
5131 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005132 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5133 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005134 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00005135 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00005136 }
5137 }
Chris Lattner67ca7682003-08-12 19:11:07 +00005138
Bill Wendlingb3833d12008-12-01 01:07:11 +00005139 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005140 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5141 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005142 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005143 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005144 }
5145 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005146 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5147 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005148 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005149 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005150 }
5151
Chris Lattnerd06094f2009-11-10 00:55:12 +00005152 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5153 if (Value *Op0NotVal = dyn_castNotVal(Op0))
5154 if (Value *Op1NotVal = dyn_castNotVal(Op1))
5155 if (Op0->hasOneUse() && Op1->hasOneUse()) {
5156 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5157 I.getName()+".demorgan");
5158 return BinaryOperator::CreateNot(And);
5159 }
Chris Lattnera2881962003-02-18 19:28:33 +00005160
Reid Spencere4d87aa2006-12-23 06:05:41 +00005161 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5162 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005163 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005164 return R;
5165
Chris Lattner69d4ced2008-11-16 05:20:07 +00005166 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5167 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5168 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005169 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005170
5171 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005172 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005173 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005174 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005175 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5176 !isa<ICmpInst>(Op1C->getOperand(0))) {
5177 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005178 if (SrcTy == Op1C->getOperand(0)->getType() &&
5179 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005180 // Only do this if the casts both really cause code to be
5181 // generated.
5182 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5183 I.getType(), TD) &&
5184 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5185 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005186 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5187 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005188 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005189 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005190 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005191 }
Chris Lattner99c65742007-10-24 05:38:08 +00005192 }
5193
5194
5195 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5196 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005197 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5198 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5199 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005200 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005201
Chris Lattner7e708292002-06-25 16:13:24 +00005202 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005203}
5204
Dan Gohman844731a2008-05-13 00:00:25 +00005205namespace {
5206
Chris Lattnerc317d392004-02-16 01:20:27 +00005207// XorSelf - Implements: X ^ X --> 0
5208struct XorSelf {
5209 Value *RHS;
5210 XorSelf(Value *rhs) : RHS(rhs) {}
5211 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5212 Instruction *apply(BinaryOperator &Xor) const {
5213 return &Xor;
5214 }
5215};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005216
Dan Gohman844731a2008-05-13 00:00:25 +00005217}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005218
Chris Lattner7e708292002-06-25 16:13:24 +00005219Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005220 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005221 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005222
Evan Chengd34af782008-03-25 20:07:13 +00005223 if (isa<UndefValue>(Op1)) {
5224 if (isa<UndefValue>(Op0))
5225 // Handle undef ^ undef -> 0 special case. This is a common
5226 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005227 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005228 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005229 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005230
Chris Lattnerc317d392004-02-16 01:20:27 +00005231 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005232 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005233 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005234 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005235 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005236
5237 // See if we can simplify any instructions used by the instruction whose sole
5238 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005239 if (SimplifyDemandedInstructionBits(I))
5240 return &I;
5241 if (isa<VectorType>(I.getType()))
5242 if (isa<ConstantAggregateZero>(Op1))
5243 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005244
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005245 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005246 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005247 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5248 if (Op0I->getOpcode() == Instruction::And ||
5249 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00005250 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5251 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5252 if (dyn_castNotVal(Op0I->getOperand(1)))
5253 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005254 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005255 Value *NotY =
5256 Builder->CreateNot(Op0I->getOperand(1),
5257 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005258 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005259 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005260 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005261 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00005262
5263 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5264 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5265 if (isFreeToInvert(Op0I->getOperand(0)) &&
5266 isFreeToInvert(Op0I->getOperand(1))) {
5267 Value *NotX =
5268 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5269 Value *NotY =
5270 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5271 if (Op0I->getOpcode() == Instruction::And)
5272 return BinaryOperator::CreateOr(NotX, NotY);
5273 return BinaryOperator::CreateAnd(NotX, NotY);
5274 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005275 }
5276 }
5277 }
5278
5279
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005280 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005281 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005282 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005283 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005284 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005285 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005286
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005287 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005288 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005289 FCI->getOperand(0), FCI->getOperand(1));
5290 }
5291
Nick Lewycky517e1f52008-05-31 19:01:33 +00005292 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5293 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5294 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5295 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5296 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005297 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5298 (RHS == ConstantExpr::getCast(Opcode,
5299 ConstantInt::getTrue(*Context),
5300 Op0C->getDestTy()))) {
5301 CI->setPredicate(CI->getInversePredicate());
5302 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005303 }
5304 }
5305 }
5306 }
5307
Reid Spencere4d87aa2006-12-23 06:05:41 +00005308 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005309 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005310 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5311 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005312 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5313 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005314 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005315 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005316 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005317
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005318 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005319 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005320 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005321 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005322 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005323 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005324 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005325 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005326 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005327 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005328 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005329 Constant *C = ConstantInt::get(*Context,
5330 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005331 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005332
Chris Lattner7c4049c2004-01-12 19:35:11 +00005333 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005334 } else if (Op0I->getOpcode() == Instruction::Or) {
5335 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005336 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005337 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005338 // Anything in both C1 and C2 is known to be zero, remove it from
5339 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005340 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5341 NewRHS = ConstantExpr::getAnd(NewRHS,
5342 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005343 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005344 I.setOperand(0, Op0I->getOperand(0));
5345 I.setOperand(1, NewRHS);
5346 return &I;
5347 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005348 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005349 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005350 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005351
5352 // Try to fold constant and into select arguments.
5353 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005354 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005355 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005356 if (isa<PHINode>(Op0))
5357 if (Instruction *NV = FoldOpIntoPhi(I))
5358 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005359 }
5360
Dan Gohman186a6362009-08-12 16:04:34 +00005361 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005362 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005363 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005364
Dan Gohman186a6362009-08-12 16:04:34 +00005365 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005366 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005367 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005368
Chris Lattner318bf792007-03-18 22:51:34 +00005369
5370 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5371 if (Op1I) {
5372 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005373 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005374 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005375 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005376 I.swapOperands();
5377 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005378 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005379 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005380 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005381 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005382 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005383 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005384 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005385 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005386 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005387 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005388 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005389 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005390 std::swap(A, B);
5391 }
Chris Lattner318bf792007-03-18 22:51:34 +00005392 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005393 I.swapOperands(); // Simplified below.
5394 std::swap(Op0, Op1);
5395 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005396 }
Chris Lattner318bf792007-03-18 22:51:34 +00005397 }
5398
5399 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5400 if (Op0I) {
5401 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005402 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005403 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005404 if (A == Op1) // (B|A)^B == (A|B)^B
5405 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005406 if (B == Op1) // (A|B)^B == A & ~B
5407 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005408 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005409 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005410 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005411 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005412 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005413 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005414 if (A == Op1) // (A&B)^A -> (B&A)^A
5415 std::swap(A, B);
5416 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005417 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005418 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005419 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005420 }
Chris Lattner318bf792007-03-18 22:51:34 +00005421 }
5422
5423 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5424 if (Op0I && Op1I && Op0I->isShift() &&
5425 Op0I->getOpcode() == Op1I->getOpcode() &&
5426 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5427 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005428 Value *NewOp =
5429 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5430 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005431 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005432 Op1I->getOperand(1));
5433 }
5434
5435 if (Op0I && Op1I) {
5436 Value *A, *B, *C, *D;
5437 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005438 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5439 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005440 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005441 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005442 }
5443 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005444 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5445 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005446 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005447 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005448 }
5449
5450 // (A & B)^(C & D)
5451 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005452 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5453 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005454 // (X & Y)^(X & Y) -> (Y^Z) & X
5455 Value *X = 0, *Y = 0, *Z = 0;
5456 if (A == C)
5457 X = A, Y = B, Z = D;
5458 else if (A == D)
5459 X = A, Y = B, Z = C;
5460 else if (B == C)
5461 X = B, Y = A, Z = D;
5462 else if (B == D)
5463 X = B, Y = A, Z = C;
5464
5465 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005466 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005467 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005468 }
5469 }
5470 }
5471
Reid Spencere4d87aa2006-12-23 06:05:41 +00005472 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5473 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005474 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005475 return R;
5476
Chris Lattner6fc205f2006-05-05 06:39:07 +00005477 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005478 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005479 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005480 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5481 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005482 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005483 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005484 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5485 I.getType(), TD) &&
5486 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5487 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005488 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5489 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005490 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005491 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005492 }
Chris Lattner99c65742007-10-24 05:38:08 +00005493 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005494
Chris Lattner7e708292002-06-25 16:13:24 +00005495 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005496}
5497
Owen Andersond672ecb2009-07-03 00:17:18 +00005498static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005499 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005500 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005501}
Chris Lattnera96879a2004-09-29 17:40:11 +00005502
Dan Gohman6de29f82009-06-15 22:12:54 +00005503static bool HasAddOverflow(ConstantInt *Result,
5504 ConstantInt *In1, ConstantInt *In2,
5505 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005506 if (IsSigned)
5507 if (In2->getValue().isNegative())
5508 return Result->getValue().sgt(In1->getValue());
5509 else
5510 return Result->getValue().slt(In1->getValue());
5511 else
5512 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005513}
5514
Dan Gohman6de29f82009-06-15 22:12:54 +00005515/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005516/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005517static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005518 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005519 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005520 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005521
Dan Gohman6de29f82009-06-15 22:12:54 +00005522 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5523 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005524 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005525 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5526 ExtractElement(In1, Idx, Context),
5527 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005528 IsSigned))
5529 return true;
5530 }
5531 return false;
5532 }
5533
5534 return HasAddOverflow(cast<ConstantInt>(Result),
5535 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5536 IsSigned);
5537}
5538
5539static bool HasSubOverflow(ConstantInt *Result,
5540 ConstantInt *In1, ConstantInt *In2,
5541 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005542 if (IsSigned)
5543 if (In2->getValue().isNegative())
5544 return Result->getValue().slt(In1->getValue());
5545 else
5546 return Result->getValue().sgt(In1->getValue());
5547 else
5548 return Result->getValue().ugt(In1->getValue());
5549}
5550
Dan Gohman6de29f82009-06-15 22:12:54 +00005551/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5552/// overflowed for this type.
5553static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005554 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005555 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005556 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005557
5558 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5559 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005560 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005561 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5562 ExtractElement(In1, Idx, Context),
5563 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005564 IsSigned))
5565 return true;
5566 }
5567 return false;
5568 }
5569
5570 return HasSubOverflow(cast<ConstantInt>(Result),
5571 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5572 IsSigned);
5573}
5574
Chris Lattner10c0d912008-04-22 02:53:33 +00005575
Reid Spencere4d87aa2006-12-23 06:05:41 +00005576/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005577/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005578Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005579 ICmpInst::Predicate Cond,
5580 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005581 // Look through bitcasts.
5582 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5583 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005584
Chris Lattner574da9b2005-01-13 20:14:25 +00005585 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005586 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005587 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005588 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005589 // know pointers can't overflow since the gep is inbounds. See if we can
5590 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005591 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5592
5593 // If not, synthesize the offset the hard way.
5594 if (Offset == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00005595 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005596 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005597 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005598 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005599 // If the base pointers are different, but the indices are the same, just
5600 // compare the base pointer.
5601 if (PtrBase != GEPRHS->getOperand(0)) {
5602 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005603 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005604 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005605 if (IndicesTheSame)
5606 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5607 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5608 IndicesTheSame = false;
5609 break;
5610 }
5611
5612 // If all indices are the same, just compare the base pointers.
5613 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005614 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005615 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005616
5617 // Otherwise, the base pointers are different and the indices are
5618 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005619 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005620 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005621
Chris Lattnere9d782b2005-01-13 22:25:21 +00005622 // If one of the GEPs has all zero indices, recurse.
5623 bool AllZeros = true;
5624 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5625 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5626 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5627 AllZeros = false;
5628 break;
5629 }
5630 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005631 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5632 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005633
5634 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005635 AllZeros = true;
5636 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5637 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5638 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5639 AllZeros = false;
5640 break;
5641 }
5642 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005643 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005644
Chris Lattner4401c9c2005-01-14 00:20:05 +00005645 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5646 // If the GEPs only differ by one index, compare it.
5647 unsigned NumDifferences = 0; // Keep track of # differences.
5648 unsigned DiffOperand = 0; // The operand that differs.
5649 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5650 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005651 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5652 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005653 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005654 NumDifferences = 2;
5655 break;
5656 } else {
5657 if (NumDifferences++) break;
5658 DiffOperand = i;
5659 }
5660 }
5661
5662 if (NumDifferences == 0) // SAME GEP?
5663 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005664 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005665 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005666
Chris Lattner4401c9c2005-01-14 00:20:05 +00005667 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005668 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5669 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005670 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005671 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005672 }
5673 }
5674
Reid Spencere4d87aa2006-12-23 06:05:41 +00005675 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005676 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005677 if (TD &&
5678 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005679 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5680 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner092543c2009-11-04 08:05:20 +00005681 Value *L = EmitGEPOffset(GEPLHS, *this);
5682 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005683 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005684 }
5685 }
5686 return 0;
5687}
5688
Chris Lattnera5406232008-05-19 20:18:56 +00005689/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5690///
5691Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5692 Instruction *LHSI,
5693 Constant *RHSC) {
5694 if (!isa<ConstantFP>(RHSC)) return 0;
5695 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5696
5697 // Get the width of the mantissa. We don't want to hack on conversions that
5698 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005699 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005700 if (MantissaWidth == -1) return 0; // Unknown.
5701
5702 // Check to see that the input is converted from an integer type that is small
5703 // enough that preserves all bits. TODO: check here for "known" sign bits.
5704 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman6de29f82009-06-15 22:12:54 +00005705 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005706
5707 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005708 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5709 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005710 ++InputSize;
5711
5712 // If the conversion would lose info, don't hack on this.
5713 if ((int)InputSize > MantissaWidth)
5714 return 0;
5715
5716 // Otherwise, we can potentially simplify the comparison. We know that it
5717 // will always come through as an integer value and we know the constant is
5718 // not a NAN (it would have been previously simplified).
5719 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5720
5721 ICmpInst::Predicate Pred;
5722 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005723 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005724 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005725 case FCmpInst::FCMP_OEQ:
5726 Pred = ICmpInst::ICMP_EQ;
5727 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005728 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005729 case FCmpInst::FCMP_OGT:
5730 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5731 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005732 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005733 case FCmpInst::FCMP_OGE:
5734 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5735 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005736 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005737 case FCmpInst::FCMP_OLT:
5738 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5739 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005740 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005741 case FCmpInst::FCMP_OLE:
5742 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5743 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005744 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005745 case FCmpInst::FCMP_ONE:
5746 Pred = ICmpInst::ICMP_NE;
5747 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005748 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005749 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005750 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005751 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005752 }
5753
5754 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5755
5756 // Now we know that the APFloat is a normal number, zero or inf.
5757
Chris Lattner85162782008-05-20 03:50:52 +00005758 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005759 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005760 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005761
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005762 if (!LHSUnsigned) {
5763 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5764 // and large values.
5765 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5766 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5767 APFloat::rmNearestTiesToEven);
5768 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5769 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5770 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005771 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5772 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005773 }
5774 } else {
5775 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5776 // +INF and large values.
5777 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5778 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5779 APFloat::rmNearestTiesToEven);
5780 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5781 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5782 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005783 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5784 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005785 }
Chris Lattnera5406232008-05-19 20:18:56 +00005786 }
5787
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005788 if (!LHSUnsigned) {
5789 // See if the RHS value is < SignedMin.
5790 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5791 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5792 APFloat::rmNearestTiesToEven);
5793 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5794 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5795 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005796 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5797 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005798 }
Chris Lattnera5406232008-05-19 20:18:56 +00005799 }
5800
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005801 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5802 // [0, UMAX], but it may still be fractional. See if it is fractional by
5803 // casting the FP value to the integer value and back, checking for equality.
5804 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005805 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005806 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5807 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005808 if (!RHS.isZero()) {
5809 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005810 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5811 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005812 if (!Equal) {
5813 // If we had a comparison against a fractional value, we have to adjust
5814 // the compare predicate and sometimes the value. RHSC is rounded towards
5815 // zero at this point.
5816 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005817 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005818 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005819 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005820 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005821 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005822 case ICmpInst::ICMP_ULE:
5823 // (float)int <= 4.4 --> int <= 4
5824 // (float)int <= -4.4 --> false
5825 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005826 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005827 break;
5828 case ICmpInst::ICMP_SLE:
5829 // (float)int <= 4.4 --> int <= 4
5830 // (float)int <= -4.4 --> int < -4
5831 if (RHS.isNegative())
5832 Pred = ICmpInst::ICMP_SLT;
5833 break;
5834 case ICmpInst::ICMP_ULT:
5835 // (float)int < -4.4 --> false
5836 // (float)int < 4.4 --> int <= 4
5837 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005838 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005839 Pred = ICmpInst::ICMP_ULE;
5840 break;
5841 case ICmpInst::ICMP_SLT:
5842 // (float)int < -4.4 --> int < -4
5843 // (float)int < 4.4 --> int <= 4
5844 if (!RHS.isNegative())
5845 Pred = ICmpInst::ICMP_SLE;
5846 break;
5847 case ICmpInst::ICMP_UGT:
5848 // (float)int > 4.4 --> int > 4
5849 // (float)int > -4.4 --> true
5850 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005851 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005852 break;
5853 case ICmpInst::ICMP_SGT:
5854 // (float)int > 4.4 --> int > 4
5855 // (float)int > -4.4 --> int >= -4
5856 if (RHS.isNegative())
5857 Pred = ICmpInst::ICMP_SGE;
5858 break;
5859 case ICmpInst::ICMP_UGE:
5860 // (float)int >= -4.4 --> true
5861 // (float)int >= 4.4 --> int > 4
5862 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005863 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005864 Pred = ICmpInst::ICMP_UGT;
5865 break;
5866 case ICmpInst::ICMP_SGE:
5867 // (float)int >= -4.4 --> int >= -4
5868 // (float)int >= 4.4 --> int > 4
5869 if (!RHS.isNegative())
5870 Pred = ICmpInst::ICMP_SGT;
5871 break;
5872 }
Chris Lattnera5406232008-05-19 20:18:56 +00005873 }
5874 }
5875
5876 // Lower this FP comparison into an appropriate integer version of the
5877 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005878 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005879}
5880
Reid Spencere4d87aa2006-12-23 06:05:41 +00005881Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00005882 bool Changed = false;
5883
5884 /// Orders the operands of the compare so that they are listed from most
5885 /// complex to least complex. This puts constants before unary operators,
5886 /// before binary operators.
5887 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
5888 I.swapOperands();
5889 Changed = true;
5890 }
5891
Chris Lattner8b170942002-08-09 23:47:40 +00005892 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner58e97462007-01-14 19:42:17 +00005893
Chris Lattner210c5d42009-11-09 23:55:12 +00005894 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
5895 return ReplaceInstUsesWith(I, V);
5896
Chris Lattner58e97462007-01-14 19:42:17 +00005897 // Simplify 'fcmp pred X, X'
5898 if (Op0 == Op1) {
5899 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005900 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005901 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5902 case FCmpInst::FCMP_ULT: // True if unordered or less than
5903 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5904 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5905 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5906 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005907 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005908 return &I;
5909
5910 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5911 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5912 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5913 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5914 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5915 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005916 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005917 return &I;
5918 }
5919 }
5920
Reid Spencere4d87aa2006-12-23 06:05:41 +00005921 // Handle fcmp with constant RHS
5922 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5923 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5924 switch (LHSI->getOpcode()) {
5925 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005926 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5927 // block. If in the same block, we're encouraging jump threading. If
5928 // not, we are just pessimizing the code by making an i1 phi.
5929 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00005930 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005931 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005932 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005933 case Instruction::SIToFP:
5934 case Instruction::UIToFP:
5935 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5936 return NV;
5937 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005938 case Instruction::Select:
5939 // If either operand of the select is a constant, we can fold the
5940 // comparison into the select arms, which will cause one to be
5941 // constant folded and the select turned into a bitwise or.
5942 Value *Op1 = 0, *Op2 = 0;
5943 if (LHSI->hasOneUse()) {
5944 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5945 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005946 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005947 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005948 Op2 = Builder->CreateFCmp(I.getPredicate(),
5949 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005950 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5951 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005952 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005953 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005954 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5955 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005956 }
5957 }
5958
5959 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005960 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005961 break;
5962 }
5963 }
5964
5965 return Changed ? &I : 0;
5966}
5967
5968Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00005969 bool Changed = false;
5970
5971 /// Orders the operands of the compare so that they are listed from most
5972 /// complex to least complex. This puts constants before unary operators,
5973 /// before binary operators.
5974 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
5975 I.swapOperands();
5976 Changed = true;
5977 }
5978
Reid Spencere4d87aa2006-12-23 06:05:41 +00005979 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005980
Chris Lattner210c5d42009-11-09 23:55:12 +00005981 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
5982 return ReplaceInstUsesWith(I, V);
5983
5984 const Type *Ty = Op0->getType();
Chris Lattner8b170942002-08-09 23:47:40 +00005985
Reid Spencere4d87aa2006-12-23 06:05:41 +00005986 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00005987 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005988 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005989 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005990 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00005991 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00005992 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005993 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005994 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005995 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005996
Reid Spencere4d87aa2006-12-23 06:05:41 +00005997 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005998 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005999 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006000 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006001 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006002 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006003 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006004 case ICmpInst::ICMP_SGT:
6005 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006006 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006007 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006008 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006009 return BinaryOperator::CreateAnd(Not, Op0);
6010 }
6011 case ICmpInst::ICMP_UGE:
6012 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6013 // FALL THROUGH
6014 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006015 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006016 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006017 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006018 case ICmpInst::ICMP_SGE:
6019 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6020 // FALL THROUGH
6021 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006022 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006023 return BinaryOperator::CreateOr(Not, Op0);
6024 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006025 }
Chris Lattner8b170942002-08-09 23:47:40 +00006026 }
6027
Dan Gohman1c8491e2009-04-25 17:12:48 +00006028 unsigned BitWidth = 0;
6029 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006030 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6031 else if (Ty->isIntOrIntVector())
6032 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006033
6034 bool isSignBit = false;
6035
Dan Gohman81b28ce2008-09-16 18:46:06 +00006036 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006037 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006038 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006039
Chris Lattnerb6566012008-01-05 01:18:20 +00006040 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6041 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006042 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006043 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006044 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006045 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006046
Dan Gohman81b28ce2008-09-16 18:46:06 +00006047 // If we have an icmp le or icmp ge instruction, turn it into the
6048 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner210c5d42009-11-09 23:55:12 +00006049 // them being folded in the code below. The SimplifyICmpInst code has
6050 // already handled the edge cases for us, so we just assert on them.
Chris Lattner84dff672008-07-11 05:08:55 +00006051 switch (I.getPredicate()) {
6052 default: break;
6053 case ICmpInst::ICMP_ULE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006054 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006055 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006056 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006057 case ICmpInst::ICMP_SLE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006058 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006059 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006060 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006061 case ICmpInst::ICMP_UGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006062 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006063 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006064 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006065 case ICmpInst::ICMP_SGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006066 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006067 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006068 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006069 }
6070
Chris Lattner183661e2008-07-11 05:40:05 +00006071 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006072 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006073 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006074 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6075 }
6076
6077 // See if we can fold the comparison based on range information we can get
6078 // by checking whether bits are known to be zero or one in the input.
6079 if (BitWidth != 0) {
6080 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6081 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6082
6083 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006084 isSignBit ? APInt::getSignBit(BitWidth)
6085 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006086 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006087 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006088 if (SimplifyDemandedBits(I.getOperandUse(1),
6089 APInt::getAllOnesValue(BitWidth),
6090 Op1KnownZero, Op1KnownOne, 0))
6091 return &I;
6092
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006093 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006094 // in. Compute the Min, Max and RHS values based on the known bits. For the
6095 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006096 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6097 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006098 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006099 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6100 Op0Min, Op0Max);
6101 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6102 Op1Min, Op1Max);
6103 } else {
6104 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6105 Op0Min, Op0Max);
6106 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6107 Op1Min, Op1Max);
6108 }
6109
Chris Lattner183661e2008-07-11 05:40:05 +00006110 // If Min and Max are known to be the same, then SimplifyDemandedBits
6111 // figured out that the LHS is a constant. Just constant fold this now so
6112 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006113 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006114 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006115 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006116 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006117 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006118 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006119
Chris Lattner183661e2008-07-11 05:40:05 +00006120 // Based on the range information we know about the LHS, see if we can
6121 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006122 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006123 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006124 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006125 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006126 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006127 break;
6128 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006129 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006130 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006131 break;
6132 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006133 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006134 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006135 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006136 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006137 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006138 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006139 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6140 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006141 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006142 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006143
6144 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6145 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006146 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006147 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006148 }
Chris Lattner84dff672008-07-11 05:08:55 +00006149 break;
6150 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006151 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006152 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006153 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006154 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006155
6156 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006157 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006158 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6159 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006160 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006161 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006162
6163 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6164 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006165 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006166 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006167 }
Chris Lattner84dff672008-07-11 05:08:55 +00006168 break;
6169 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006170 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006171 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006172 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006173 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006174 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006175 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006176 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6177 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006178 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006179 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006180 }
Chris Lattner84dff672008-07-11 05:08:55 +00006181 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006182 case ICmpInst::ICMP_SGT:
6183 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006184 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006185 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006186 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006187
6188 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006189 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006190 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6191 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006192 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006193 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006194 }
6195 break;
6196 case ICmpInst::ICMP_SGE:
6197 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6198 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006199 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006200 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006201 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006202 break;
6203 case ICmpInst::ICMP_SLE:
6204 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6205 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006206 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006207 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006208 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006209 break;
6210 case ICmpInst::ICMP_UGE:
6211 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6212 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006213 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006214 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006215 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006216 break;
6217 case ICmpInst::ICMP_ULE:
6218 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6219 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006220 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006221 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006222 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006223 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006224 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006225
6226 // Turn a signed comparison into an unsigned one if both operands
6227 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006228 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006229 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6230 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006231 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006232 }
6233
6234 // Test if the ICmpInst instruction is used exclusively by a select as
6235 // part of a minimum or maximum operation. If so, refrain from doing
6236 // any other folding. This helps out other analyses which understand
6237 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6238 // and CodeGen. And in this case, at least one of the comparison
6239 // operands has at least one user besides the compare (the select),
6240 // which would often largely negate the benefit of folding anyway.
6241 if (I.hasOneUse())
6242 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6243 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6244 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6245 return 0;
6246
6247 // See if we are doing a comparison between a constant and an instruction that
6248 // can be folded into the comparison.
6249 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006250 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006251 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006252 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006253 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006254 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6255 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006256 }
6257
Chris Lattner01deb9d2007-04-03 17:43:25 +00006258 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006259 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6260 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6261 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006262 case Instruction::GetElementPtr:
6263 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006264 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006265 bool isAllZeros = true;
6266 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6267 if (!isa<Constant>(LHSI->getOperand(i)) ||
6268 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6269 isAllZeros = false;
6270 break;
6271 }
6272 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006273 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006274 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006275 }
6276 break;
6277
Chris Lattner6970b662005-04-23 15:31:55 +00006278 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006279 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006280 // block. If in the same block, we're encouraging jump threading. If
6281 // not, we are just pessimizing the code by making an i1 phi.
6282 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006283 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006284 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006285 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006286 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006287 // If either operand of the select is a constant, we can fold the
6288 // comparison into the select arms, which will cause one to be
6289 // constant folded and the select turned into a bitwise or.
6290 Value *Op1 = 0, *Op2 = 0;
6291 if (LHSI->hasOneUse()) {
6292 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6293 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006294 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006295 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006296 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6297 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006298 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6299 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006300 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006301 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006302 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6303 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006304 }
6305 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006306
Chris Lattner6970b662005-04-23 15:31:55 +00006307 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006308 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006309 break;
6310 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006311 case Instruction::Call:
6312 // If we have (malloc != null), and if the malloc has a single use, we
6313 // can assume it is successful and remove the malloc.
6314 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6315 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006316 // Need to explicitly erase malloc call here, instead of adding it to
6317 // Worklist, because it won't get DCE'd from the Worklist since
6318 // isInstructionTriviallyDead() returns false for function calls.
6319 // It is OK to replace LHSI/MallocCall with Undef because the
6320 // instruction that uses it will be erased via Worklist.
6321 if (extractMallocCall(LHSI)) {
6322 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6323 EraseInstFromFunction(*LHSI);
6324 return ReplaceInstUsesWith(I,
Victor Hernandez83d63912009-09-18 22:35:49 +00006325 ConstantInt::get(Type::getInt1Ty(*Context),
6326 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006327 }
6328 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6329 if (MallocCall->hasOneUse()) {
6330 MallocCall->replaceAllUsesWith(
6331 UndefValue::get(MallocCall->getType()));
6332 EraseInstFromFunction(*MallocCall);
6333 Worklist.Add(LHSI); // The malloc's bitcast use.
6334 return ReplaceInstUsesWith(I,
6335 ConstantInt::get(Type::getInt1Ty(*Context),
6336 !I.isTrueWhenEqual()));
6337 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006338 }
6339 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006340 }
Chris Lattner6970b662005-04-23 15:31:55 +00006341 }
6342
Reid Spencere4d87aa2006-12-23 06:05:41 +00006343 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006344 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006345 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006346 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006347 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006348 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6349 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006350 return NI;
6351
Reid Spencere4d87aa2006-12-23 06:05:41 +00006352 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006353 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6354 // now.
6355 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6356 if (isa<PointerType>(Op0->getType()) &&
6357 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006358 // We keep moving the cast from the left operand over to the right
6359 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006360 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006361
Chris Lattner57d86372007-01-06 01:45:59 +00006362 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6363 // so eliminate it as well.
6364 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6365 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006366
Chris Lattnerde90b762003-11-03 04:25:02 +00006367 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006368 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006369 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006370 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006371 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006372 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006373 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006374 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006375 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006376 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006377 }
Chris Lattner57d86372007-01-06 01:45:59 +00006378 }
6379
6380 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006381 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006382 // This comes up when you have code like
6383 // int X = A < B;
6384 // if (X) ...
6385 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006386 // with a constant or another cast from the same type.
6387 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006388 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006389 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006390 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006391
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006392 // See if it's the same type of instruction on the left and right.
6393 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6394 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006395 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006396 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006397 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006398 default: break;
6399 case Instruction::Add:
6400 case Instruction::Sub:
6401 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006402 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006403 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006404 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006405 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6406 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6407 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006408 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006409 ? I.getUnsignedPredicate()
6410 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006411 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006412 Op1I->getOperand(0));
6413 }
6414
6415 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006416 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006417 ? I.getUnsignedPredicate()
6418 : I.getSignedPredicate();
6419 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006420 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006421 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006422 }
6423 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006424 break;
6425 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006426 if (!I.isEquality())
6427 break;
6428
Nick Lewycky5d52c452008-08-21 05:56:10 +00006429 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6430 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6431 // Mask = -1 >> count-trailing-zeros(Cst).
6432 if (!CI->isZero() && !CI->isOne()) {
6433 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006434 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006435 APInt::getLowBitsSet(AP.getBitWidth(),
6436 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006437 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006438 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6439 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006440 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006441 }
6442 }
6443 break;
6444 }
6445 }
6446 }
6447 }
6448
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006449 // ~x < ~y --> y < x
6450 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006451 if (match(Op0, m_Not(m_Value(A))) &&
6452 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006453 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006454 }
6455
Chris Lattner65b72ba2006-09-18 04:22:48 +00006456 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006457 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006458
6459 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006460 if (match(Op0, m_Neg(m_Value(A))) &&
6461 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006462 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006463
Dan Gohman4ae51262009-08-12 16:23:25 +00006464 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006465 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6466 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006467 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006468 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006469 }
6470
Dan Gohman4ae51262009-08-12 16:23:25 +00006471 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006472 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006473 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006474 if (match(B, m_ConstantInt(C1)) &&
6475 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006476 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006477 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006478 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6479 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006480 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006481
6482 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006483 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6484 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6485 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6486 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006487 }
6488 }
6489
Dan Gohman4ae51262009-08-12 16:23:25 +00006490 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006491 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006492 // A == (A^B) -> B == 0
6493 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006494 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006495 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006496 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006497
6498 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006499 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006500 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006501 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006502
6503 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006504 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006505 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006506 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006507
Chris Lattner9c2328e2006-11-14 06:06:06 +00006508 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6509 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006510 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6511 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006512 Value *X = 0, *Y = 0, *Z = 0;
6513
6514 if (A == C) {
6515 X = B; Y = D; Z = A;
6516 } else if (A == D) {
6517 X = B; Y = C; Z = A;
6518 } else if (B == C) {
6519 X = A; Y = D; Z = B;
6520 } else if (B == D) {
6521 X = A; Y = C; Z = B;
6522 }
6523
6524 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006525 Op1 = Builder->CreateXor(X, Y, "tmp");
6526 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006527 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006528 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006529 return &I;
6530 }
6531 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006532 }
Chris Lattner7e708292002-06-25 16:13:24 +00006533 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006534}
6535
Chris Lattner562ef782007-06-20 23:46:26 +00006536
6537/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6538/// and CmpRHS are both known to be integer constants.
6539Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6540 ConstantInt *DivRHS) {
6541 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6542 const APInt &CmpRHSV = CmpRHS->getValue();
6543
6544 // FIXME: If the operand types don't match the type of the divide
6545 // then don't attempt this transform. The code below doesn't have the
6546 // logic to deal with a signed divide and an unsigned compare (and
6547 // vice versa). This is because (x /s C1) <s C2 produces different
6548 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6549 // (x /u C1) <u C2. Simply casting the operands and result won't
6550 // work. :( The if statement below tests that condition and bails
6551 // if it finds it.
6552 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00006553 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00006554 return 0;
6555 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006556 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006557 if (DivIsSigned && DivRHS->isAllOnesValue())
6558 return 0; // The overflow computation also screws up here
6559 if (DivRHS->isOne())
6560 return 0; // Not worth bothering, and eliminates some funny cases
6561 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006562
6563 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6564 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6565 // C2 (CI). By solving for X we can turn this into a range check
6566 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006567 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006568
6569 // Determine if the product overflows by seeing if the product is
6570 // not equal to the divide. Make sure we do the same kind of divide
6571 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006572 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6573 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006574
6575 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006576 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006577
Chris Lattner1dbfd482007-06-21 18:11:19 +00006578 // Figure out the interval that is being checked. For example, a comparison
6579 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6580 // Compute this interval based on the constants involved and the signedness of
6581 // the compare/divide. This computes a half-open interval, keeping track of
6582 // whether either value in the interval overflows. After analysis each
6583 // overflow variable is set to 0 if it's corresponding bound variable is valid
6584 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6585 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006586 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006587
Chris Lattner562ef782007-06-20 23:46:26 +00006588 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006589 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006590 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006591 HiOverflow = LoOverflow = ProdOV;
6592 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006593 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006594 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006595 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006596 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006597 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006598 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006599 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006600 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6601 HiOverflow = LoOverflow = ProdOV;
6602 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006603 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006604 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006605 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006606 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006607 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6608 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006609 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006610 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006611 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006612 true) ? -1 : 0;
6613 }
Chris Lattner562ef782007-06-20 23:46:26 +00006614 }
Dan Gohman76491272008-02-13 22:09:18 +00006615 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006616 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006617 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006618 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006619 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006620 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6621 HiOverflow = 1; // [INTMIN+1, overflow)
6622 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6623 }
Dan Gohman76491272008-02-13 22:09:18 +00006624 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006625 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006626 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006627 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006628 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006629 LoOverflow = AddWithOverflow(LoBound, HiBound,
6630 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006631 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006632 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6633 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006634 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006635 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006636 }
6637
Chris Lattner1dbfd482007-06-21 18:11:19 +00006638 // Dividing by a negative swaps the condition. LT <-> GT
6639 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006640 }
6641
6642 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006643 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006644 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006645 case ICmpInst::ICMP_EQ:
6646 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006647 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006648 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006649 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006650 ICmpInst::ICMP_UGE, X, LoBound);
6651 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006652 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006653 ICmpInst::ICMP_ULT, X, HiBound);
6654 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006655 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006656 case ICmpInst::ICMP_NE:
6657 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006658 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006659 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006660 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006661 ICmpInst::ICMP_ULT, X, LoBound);
6662 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006663 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006664 ICmpInst::ICMP_UGE, X, HiBound);
6665 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006666 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006667 case ICmpInst::ICMP_ULT:
6668 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006669 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006670 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006671 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006672 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006673 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006674 case ICmpInst::ICMP_UGT:
6675 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006676 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006677 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006678 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006679 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006680 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006681 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006682 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006683 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006684 }
6685}
6686
6687
Chris Lattner01deb9d2007-04-03 17:43:25 +00006688/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6689///
6690Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6691 Instruction *LHSI,
6692 ConstantInt *RHS) {
6693 const APInt &RHSV = RHS->getValue();
6694
6695 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006696 case Instruction::Trunc:
6697 if (ICI.isEquality() && LHSI->hasOneUse()) {
6698 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6699 // of the high bits truncated out of x are known.
6700 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6701 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6702 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6703 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6704 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6705
6706 // If all the high bits are known, we can do this xform.
6707 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6708 // Pull in the high bits from known-ones set.
6709 APInt NewRHS(RHS->getValue());
6710 NewRHS.zext(SrcBits);
6711 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006712 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006713 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006714 }
6715 }
6716 break;
6717
Duncan Sands0091bf22007-04-04 06:42:45 +00006718 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006719 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6720 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6721 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006722 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6723 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006724 Value *CompareVal = LHSI->getOperand(0);
6725
6726 // If the sign bit of the XorCST is not set, there is no change to
6727 // the operation, just stop using the Xor.
6728 if (!XorCST->getValue().isNegative()) {
6729 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006730 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006731 return &ICI;
6732 }
6733
6734 // Was the old condition true if the operand is positive?
6735 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6736
6737 // If so, the new one isn't.
6738 isTrueIfPositive ^= true;
6739
6740 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006741 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006742 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006743 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006744 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006745 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006746 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006747
6748 if (LHSI->hasOneUse()) {
6749 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6750 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6751 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006752 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006753 ? ICI.getUnsignedPredicate()
6754 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006755 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006756 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006757 }
6758
6759 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006760 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006761 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00006762 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00006763 ? ICI.getUnsignedPredicate()
6764 : ICI.getSignedPredicate();
6765 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006766 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006767 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006768 }
6769 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006770 }
6771 break;
6772 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6773 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6774 LHSI->getOperand(0)->hasOneUse()) {
6775 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6776
6777 // If the LHS is an AND of a truncating cast, we can widen the
6778 // and/compare to be the input width without changing the value
6779 // produced, eliminating a cast.
6780 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6781 // We can do this transformation if either the AND constant does not
6782 // have its sign bit set or if it is an equality comparison.
6783 // Extending a relational comparison when we're checking the sign
6784 // bit would not work.
6785 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006786 (ICI.isEquality() ||
6787 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006788 uint32_t BitWidth =
6789 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6790 APInt NewCST = AndCST->getValue();
6791 NewCST.zext(BitWidth);
6792 APInt NewCI = RHSV;
6793 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006794 Value *NewAnd =
6795 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006796 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006797 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006798 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006799 }
6800 }
6801
6802 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6803 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6804 // happens a LOT in code produced by the C front-end, for bitfield
6805 // access.
6806 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6807 if (Shift && !Shift->isShift())
6808 Shift = 0;
6809
6810 ConstantInt *ShAmt;
6811 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6812 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6813 const Type *AndTy = AndCST->getType(); // Type of the and.
6814
6815 // We can fold this as long as we can't shift unknown bits
6816 // into the mask. This can only happen with signed shift
6817 // rights, as they sign-extend.
6818 if (ShAmt) {
6819 bool CanFold = Shift->isLogicalShift();
6820 if (!CanFold) {
6821 // To test for the bad case of the signed shr, see if any
6822 // of the bits shifted in could be tested after the mask.
6823 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6824 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6825
6826 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6827 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6828 AndCST->getValue()) == 0)
6829 CanFold = true;
6830 }
6831
6832 if (CanFold) {
6833 Constant *NewCst;
6834 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006835 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006836 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006837 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006838
6839 // Check to see if we are shifting out any of the bits being
6840 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006841 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006842 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006843 // If we shifted bits out, the fold is not going to work out.
6844 // As a special case, check to see if this means that the
6845 // result is always true or false now.
6846 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006847 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006848 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006849 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006850 } else {
6851 ICI.setOperand(1, NewCst);
6852 Constant *NewAndCST;
6853 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006854 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006855 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006856 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006857 LHSI->setOperand(1, NewAndCST);
6858 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006859 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006860 return &ICI;
6861 }
6862 }
6863 }
6864
6865 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6866 // preferable because it allows the C<<Y expression to be hoisted out
6867 // of a loop if Y is invariant and X is not.
6868 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006869 ICI.isEquality() && !Shift->isArithmeticShift() &&
6870 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006871 // Compute C << Y.
6872 Value *NS;
6873 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006874 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006875 } else {
6876 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006877 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006878 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006879
6880 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006881 Value *NewAnd =
6882 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006883
6884 ICI.setOperand(0, NewAnd);
6885 return &ICI;
6886 }
6887 }
6888 break;
6889
Chris Lattnera0141b92007-07-15 20:42:37 +00006890 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6891 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6892 if (!ShAmt) break;
6893
6894 uint32_t TypeBits = RHSV.getBitWidth();
6895
6896 // Check that the shift amount is in range. If not, don't perform
6897 // undefined shifts. When the shift is visited it will be
6898 // simplified.
6899 if (ShAmt->uge(TypeBits))
6900 break;
6901
6902 if (ICI.isEquality()) {
6903 // If we are comparing against bits always shifted out, the
6904 // comparison cannot succeed.
6905 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006906 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006907 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006908 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6909 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006910 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006911 return ReplaceInstUsesWith(ICI, Cst);
6912 }
6913
6914 if (LHSI->hasOneUse()) {
6915 // Otherwise strength reduce the shift into an and.
6916 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6917 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006918 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006919 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006920
Chris Lattner74381062009-08-30 07:44:24 +00006921 Value *And =
6922 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006923 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006924 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006925 }
6926 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006927
6928 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6929 bool TrueIfSigned = false;
6930 if (LHSI->hasOneUse() &&
6931 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6932 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006933 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006934 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006935 Value *And =
6936 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006937 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006938 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006939 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006940 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006941 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006942
6943 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006944 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006945 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006946 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006947 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006948
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006949 // Check that the shift amount is in range. If not, don't perform
6950 // undefined shifts. When the shift is visited it will be
6951 // simplified.
6952 uint32_t TypeBits = RHSV.getBitWidth();
6953 if (ShAmt->uge(TypeBits))
6954 break;
6955
6956 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006957
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006958 // If we are comparing against bits always shifted out, the
6959 // comparison cannot succeed.
6960 APInt Comp = RHSV << ShAmtVal;
6961 if (LHSI->getOpcode() == Instruction::LShr)
6962 Comp = Comp.lshr(ShAmtVal);
6963 else
6964 Comp = Comp.ashr(ShAmtVal);
6965
6966 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6967 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006968 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006969 return ReplaceInstUsesWith(ICI, Cst);
6970 }
6971
6972 // Otherwise, check to see if the bits shifted out are known to be zero.
6973 // If so, we can compare against the unshifted value:
6974 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006975 if (LHSI->hasOneUse() &&
6976 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006977 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006978 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006979 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006980 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006981
Evan Chengf30752c2008-04-23 00:38:06 +00006982 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006983 // Otherwise strength reduce the shift into an and.
6984 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00006985 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006986
Chris Lattner74381062009-08-30 07:44:24 +00006987 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6988 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006989 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006990 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006991 }
6992 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006993 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006994
6995 case Instruction::SDiv:
6996 case Instruction::UDiv:
6997 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6998 // Fold this div into the comparison, producing a range check.
6999 // Determine, based on the divide type, what the range is being
7000 // checked. If there is an overflow on the low or high side, remember
7001 // it, otherwise compute the range [low, hi) bounding the new value.
7002 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007003 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7004 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7005 DivRHS))
7006 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007007 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007008
7009 case Instruction::Add:
7010 // Fold: icmp pred (add, X, C1), C2
7011
7012 if (!ICI.isEquality()) {
7013 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7014 if (!LHSC) break;
7015 const APInt &LHSV = LHSC->getValue();
7016
7017 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7018 .subtract(LHSV);
7019
Nick Lewycky4a134af2009-10-25 05:20:17 +00007020 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007021 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007022 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007023 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007024 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007025 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007026 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007027 }
7028 } else {
7029 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007030 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007031 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007032 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007033 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007034 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007035 }
7036 }
7037 }
7038 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007039 }
7040
7041 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7042 if (ICI.isEquality()) {
7043 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7044
7045 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7046 // the second operand is a constant, simplify a bit.
7047 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7048 switch (BO->getOpcode()) {
7049 case Instruction::SRem:
7050 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7051 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7052 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7053 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007054 Value *NewRem =
7055 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7056 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007057 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007058 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007059 }
7060 }
7061 break;
7062 case Instruction::Add:
7063 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7064 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7065 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007066 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007067 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007068 } else if (RHSV == 0) {
7069 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7070 // efficiently invertible, or if the add has just this one use.
7071 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7072
Dan Gohman186a6362009-08-12 16:04:34 +00007073 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007074 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007075 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007076 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007077 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007078 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007079 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007080 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007081 }
7082 }
7083 break;
7084 case Instruction::Xor:
7085 // For the xor case, we can xor two constants together, eliminating
7086 // the explicit xor.
7087 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007088 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007089 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007090
7091 // FALLTHROUGH
7092 case Instruction::Sub:
7093 // Replace (([sub|xor] A, B) != 0) with (A != B)
7094 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007095 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007096 BO->getOperand(1));
7097 break;
7098
7099 case Instruction::Or:
7100 // If bits are being or'd in that are not present in the constant we
7101 // are comparing against, then the comparison could never succeed!
7102 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007103 Constant *NotCI = ConstantExpr::getNot(RHS);
7104 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007105 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007106 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007107 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007108 }
7109 break;
7110
7111 case Instruction::And:
7112 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7113 // If bits are being compared against that are and'd out, then the
7114 // comparison can never succeed!
7115 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007116 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007117 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007118 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007119
7120 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7121 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007122 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007123 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007124 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007125
7126 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007127 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007128 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007129 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007130 ICmpInst::Predicate pred = isICMP_NE ?
7131 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007132 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007133 }
7134
7135 // ((X & ~7) == 0) --> X < 8
7136 if (RHSV == 0 && isHighOnes(BOC)) {
7137 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007138 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007139 ICmpInst::Predicate pred = isICMP_NE ?
7140 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007141 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007142 }
7143 }
7144 default: break;
7145 }
7146 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7147 // Handle icmp {eq|ne} <intrinsic>, intcst.
7148 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007149 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007150 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007151 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007152 return &ICI;
7153 }
7154 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007155 }
7156 return 0;
7157}
7158
7159/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7160/// We only handle extending casts so far.
7161///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007162Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7163 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007164 Value *LHSCIOp = LHSCI->getOperand(0);
7165 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007166 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007167 Value *RHSCIOp;
7168
Chris Lattner8c756c12007-05-05 22:41:33 +00007169 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7170 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007171 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7172 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007173 cast<IntegerType>(DestTy)->getBitWidth()) {
7174 Value *RHSOp = 0;
7175 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007176 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007177 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7178 RHSOp = RHSC->getOperand(0);
7179 // If the pointer types don't match, insert a bitcast.
7180 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007181 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007182 }
7183
7184 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007185 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007186 }
7187
7188 // The code below only handles extension cast instructions, so far.
7189 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007190 if (LHSCI->getOpcode() != Instruction::ZExt &&
7191 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007192 return 0;
7193
Reid Spencere4d87aa2006-12-23 06:05:41 +00007194 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007195 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007196
Reid Spencere4d87aa2006-12-23 06:05:41 +00007197 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007198 // Not an extension from the same type?
7199 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007200 if (RHSCIOp->getType() != LHSCIOp->getType())
7201 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007202
Nick Lewycky4189a532008-01-28 03:48:02 +00007203 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007204 // and the other is a zext), then we can't handle this.
7205 if (CI->getOpcode() != LHSCI->getOpcode())
7206 return 0;
7207
Nick Lewycky4189a532008-01-28 03:48:02 +00007208 // Deal with equality cases early.
7209 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007210 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007211
7212 // A signed comparison of sign extended values simplifies into a
7213 // signed comparison.
7214 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007215 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007216
7217 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007218 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007219 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007220
Reid Spencere4d87aa2006-12-23 06:05:41 +00007221 // If we aren't dealing with a constant on the RHS, exit early
7222 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7223 if (!CI)
7224 return 0;
7225
7226 // Compute the constant that would happen if we truncated to SrcTy then
7227 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007228 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7229 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007230 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007231
7232 // If the re-extended constant didn't change...
7233 if (Res2 == CI) {
7234 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7235 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007236 // %A = sext i16 %X to i32
7237 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007238 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007239 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007240 // because %A may have negative value.
7241 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007242 // However, we allow this when the compare is EQ/NE, because they are
7243 // signless.
7244 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007245 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007246 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007247 }
7248
7249 // The re-extended constant changed so the constant cannot be represented
7250 // in the shorter type. Consequently, we cannot emit a simple comparison.
7251
7252 // First, handle some easy cases. We know the result cannot be equal at this
7253 // point so handle the ICI.isEquality() cases
7254 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007255 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007256 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007257 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007258
7259 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7260 // should have been folded away previously and not enter in here.
7261 Value *Result;
7262 if (isSignedCmp) {
7263 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007264 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007265 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007266 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007267 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007268 } else {
7269 // We're performing an unsigned comparison.
7270 if (isSignedExt) {
7271 // We're performing an unsigned comp with a sign extended value.
7272 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007273 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007274 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007275 } else {
7276 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007277 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007278 }
7279 }
7280
7281 // Finally, return the value computed.
7282 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007283 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007284 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007285
7286 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7287 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7288 "ICmp should be folded!");
7289 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007290 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007291 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007292}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007293
Reid Spencer832254e2007-02-02 02:16:23 +00007294Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7295 return commonShiftTransforms(I);
7296}
7297
7298Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7299 return commonShiftTransforms(I);
7300}
7301
7302Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007303 if (Instruction *R = commonShiftTransforms(I))
7304 return R;
7305
7306 Value *Op0 = I.getOperand(0);
7307
7308 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7309 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7310 if (CSI->isAllOnesValue())
7311 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007312
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007313 // See if we can turn a signed shr into an unsigned shr.
7314 if (MaskedValueIsZero(Op0,
7315 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7316 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7317
7318 // Arithmetic shifting an all-sign-bit value is a no-op.
7319 unsigned NumSignBits = ComputeNumSignBits(Op0);
7320 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7321 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007322
Chris Lattner348f6652007-12-06 01:59:46 +00007323 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007324}
7325
7326Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7327 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007328 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007329
7330 // shl X, 0 == X and shr X, 0 == X
7331 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007332 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7333 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007334 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007335
Reid Spencere4d87aa2006-12-23 06:05:41 +00007336 if (isa<UndefValue>(Op0)) {
7337 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007338 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007339 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007340 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007341 }
7342 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007343 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7344 return ReplaceInstUsesWith(I, Op0);
7345 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007346 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007347 }
7348
Dan Gohman9004c8a2009-05-21 02:28:33 +00007349 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007350 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007351 return &I;
7352
Chris Lattner2eefe512004-04-09 19:05:30 +00007353 // Try to fold constant and into select arguments.
7354 if (isa<Constant>(Op0))
7355 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007356 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007357 return R;
7358
Reid Spencerb83eb642006-10-20 07:07:24 +00007359 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007360 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7361 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007362 return 0;
7363}
7364
Reid Spencerb83eb642006-10-20 07:07:24 +00007365Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007366 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007367 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007368
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007369 // See if we can simplify any instructions used by the instruction whose sole
7370 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007371 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007372
Dan Gohmana119de82009-06-14 23:30:43 +00007373 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7374 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007375 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007376 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007377 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007378 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007379 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007380 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007381 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007382 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007383 }
7384
7385 // ((X*C1) << C2) == (X * (C1 << C2))
7386 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7387 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7388 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007389 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007390 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007391
7392 // Try to fold constant and into select arguments.
7393 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7394 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7395 return R;
7396 if (isa<PHINode>(Op0))
7397 if (Instruction *NV = FoldOpIntoPhi(I))
7398 return NV;
7399
Chris Lattner8999dd32007-12-22 09:07:47 +00007400 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7401 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7402 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7403 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7404 // place. Don't try to do this transformation in this case. Also, we
7405 // require that the input operand is a shift-by-constant so that we have
7406 // confidence that the shifts will get folded together. We could do this
7407 // xform in more cases, but it is unlikely to be profitable.
7408 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7409 isa<ConstantInt>(TrOp->getOperand(1))) {
7410 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007411 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007412 // (shift2 (shift1 & 0x00FF), c2)
7413 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007414
7415 // For logical shifts, the truncation has the effect of making the high
7416 // part of the register be zeros. Emulate this by inserting an AND to
7417 // clear the top bits as needed. This 'and' will usually be zapped by
7418 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007419 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7420 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007421 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7422
7423 // The mask we constructed says what the trunc would do if occurring
7424 // between the shifts. We want to know the effect *after* the second
7425 // shift. We know that it is a logical shift by a constant, so adjust the
7426 // mask as appropriate.
7427 if (I.getOpcode() == Instruction::Shl)
7428 MaskV <<= Op1->getZExtValue();
7429 else {
7430 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7431 MaskV = MaskV.lshr(Op1->getZExtValue());
7432 }
7433
Chris Lattner74381062009-08-30 07:44:24 +00007434 // shift1 & 0x00FF
7435 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7436 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007437
7438 // Return the value truncated to the interesting size.
7439 return new TruncInst(And, I.getType());
7440 }
7441 }
7442
Chris Lattner4d5542c2006-01-06 07:12:35 +00007443 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007444 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7445 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7446 Value *V1, *V2;
7447 ConstantInt *CC;
7448 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007449 default: break;
7450 case Instruction::Add:
7451 case Instruction::And:
7452 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007453 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007454 // These operators commute.
7455 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007456 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007457 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007458 m_Specific(Op1)))) {
7459 Value *YS = // (Y << C)
7460 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7461 // (X + (Y << C))
7462 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7463 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007464 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007465 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007466 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007467 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007468
Chris Lattner150f12a2005-09-18 06:30:59 +00007469 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007470 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007471 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007472 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007473 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007474 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007475 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007476 Value *YS = // (Y << C)
7477 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7478 Op0BO->getName());
7479 // X & (CC << C)
7480 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7481 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007482 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007483 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007484 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007485
Reid Spencera07cb7d2007-02-02 14:41:37 +00007486 // FALL THROUGH.
7487 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007488 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007489 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007490 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007491 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007492 Value *YS = // (Y << C)
7493 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7494 // (X + (Y << C))
7495 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7496 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007497 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007498 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007499 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007500 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007501
Chris Lattner13d4ab42006-05-31 21:14:00 +00007502 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007503 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7504 match(Op0BO->getOperand(0),
7505 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007506 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007507 cast<BinaryOperator>(Op0BO->getOperand(0))
7508 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007509 Value *YS = // (Y << C)
7510 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7511 // X & (CC << C)
7512 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7513 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007514
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007515 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007516 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007517
Chris Lattner11021cb2005-09-18 05:12:10 +00007518 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007519 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007520 }
7521
7522
7523 // If the operand is an bitwise operator with a constant RHS, and the
7524 // shift is the only use, we can pull it out of the shift.
7525 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7526 bool isValid = true; // Valid only for And, Or, Xor
7527 bool highBitSet = false; // Transform if high bit of constant set?
7528
7529 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007530 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007531 case Instruction::Add:
7532 isValid = isLeftShift;
7533 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007534 case Instruction::Or:
7535 case Instruction::Xor:
7536 highBitSet = false;
7537 break;
7538 case Instruction::And:
7539 highBitSet = true;
7540 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007541 }
7542
7543 // If this is a signed shift right, and the high bit is modified
7544 // by the logical operation, do not perform the transformation.
7545 // The highBitSet boolean indicates the value of the high bit of
7546 // the constant which would cause it to be modified for this
7547 // operation.
7548 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007549 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007550 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007551
7552 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007553 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007554
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007555 Value *NewShift =
7556 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007557 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007558
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007559 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007560 NewRHS);
7561 }
7562 }
7563 }
7564 }
7565
Chris Lattnerad0124c2006-01-06 07:52:12 +00007566 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007567 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7568 if (ShiftOp && !ShiftOp->isShift())
7569 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007570
Reid Spencerb83eb642006-10-20 07:07:24 +00007571 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007572 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007573 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7574 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007575 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7576 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7577 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007578
Zhou Sheng4351c642007-04-02 08:20:41 +00007579 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007580
7581 const IntegerType *Ty = cast<IntegerType>(I.getType());
7582
7583 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007584 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007585 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7586 // saturates.
7587 if (AmtSum >= TypeBits) {
7588 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007589 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007590 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7591 }
7592
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007593 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007594 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007595 }
7596
7597 if (ShiftOp->getOpcode() == Instruction::LShr &&
7598 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007599 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007600 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007601
Chris Lattnerb87056f2007-02-05 00:57:54 +00007602 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007603 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007604 }
7605
7606 if (ShiftOp->getOpcode() == Instruction::AShr &&
7607 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007608 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007609 if (AmtSum >= TypeBits)
7610 AmtSum = TypeBits-1;
7611
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007612 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007613
Zhou Shenge9e03f62007-03-28 15:02:20 +00007614 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007615 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007616 }
7617
Chris Lattnerb87056f2007-02-05 00:57:54 +00007618 // Okay, if we get here, one shift must be left, and the other shift must be
7619 // right. See if the amounts are equal.
7620 if (ShiftAmt1 == ShiftAmt2) {
7621 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7622 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007623 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007624 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007625 }
7626 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7627 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007628 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007629 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007630 }
7631 // We can simplify ((X << C) >>s C) into a trunc + sext.
7632 // NOTE: we could do this for any C, but that would make 'unusual' integer
7633 // types. For now, just stick to ones well-supported by the code
7634 // generators.
7635 const Type *SExtType = 0;
7636 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007637 case 1 :
7638 case 8 :
7639 case 16 :
7640 case 32 :
7641 case 64 :
7642 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007643 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007644 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007645 default: break;
7646 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007647 if (SExtType)
7648 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007649 // Otherwise, we can't handle it yet.
7650 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007651 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007652
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007653 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007654 if (I.getOpcode() == Instruction::Shl) {
7655 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7656 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007657 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007658
Reid Spencer55702aa2007-03-25 21:11:44 +00007659 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007660 return BinaryOperator::CreateAnd(Shift,
7661 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007662 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007663
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007664 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007665 if (I.getOpcode() == Instruction::LShr) {
7666 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007667 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007668
Reid Spencerd5e30f02007-03-26 17:18:58 +00007669 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007670 return BinaryOperator::CreateAnd(Shift,
7671 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007672 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007673
7674 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7675 } else {
7676 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007677 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007678
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007679 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007680 if (I.getOpcode() == Instruction::Shl) {
7681 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7682 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007683 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7684 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007685
Reid Spencer55702aa2007-03-25 21:11:44 +00007686 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007687 return BinaryOperator::CreateAnd(Shift,
7688 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007689 }
7690
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007691 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007692 if (I.getOpcode() == Instruction::LShr) {
7693 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007694 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007695
Reid Spencer68d27cf2007-03-26 23:45:51 +00007696 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007697 return BinaryOperator::CreateAnd(Shift,
7698 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007699 }
7700
7701 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007702 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007703 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007704 return 0;
7705}
7706
Chris Lattnera1be5662002-05-02 17:06:02 +00007707
Chris Lattnercfd65102005-10-29 04:36:15 +00007708/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7709/// expression. If so, decompose it, returning some value X, such that Val is
7710/// X*Scale+Offset.
7711///
7712static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007713 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007714 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7715 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007716 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007717 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007718 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007719 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007720 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7721 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7722 if (I->getOpcode() == Instruction::Shl) {
7723 // This is a value scaled by '1 << the shift amt'.
7724 Scale = 1U << RHS->getZExtValue();
7725 Offset = 0;
7726 return I->getOperand(0);
7727 } else if (I->getOpcode() == Instruction::Mul) {
7728 // This value is scaled by 'RHS'.
7729 Scale = RHS->getZExtValue();
7730 Offset = 0;
7731 return I->getOperand(0);
7732 } else if (I->getOpcode() == Instruction::Add) {
7733 // We have X+C. Check to see if we really have (X*C2)+C1,
7734 // where C1 is divisible by C2.
7735 unsigned SubScale;
7736 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007737 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7738 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007739 Offset += RHS->getZExtValue();
7740 Scale = SubScale;
7741 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007742 }
7743 }
7744 }
7745
7746 // Otherwise, we can't look past this.
7747 Scale = 1;
7748 Offset = 0;
7749 return Val;
7750}
7751
7752
Chris Lattnerb3f83972005-10-24 06:03:58 +00007753/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7754/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007755Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00007756 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007757 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007758
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007759 BuilderTy AllocaBuilder(*Builder);
7760 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7761
Chris Lattnerb53c2382005-10-24 06:22:12 +00007762 // Remove any uses of AI that are dead.
7763 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007764
Chris Lattnerb53c2382005-10-24 06:22:12 +00007765 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7766 Instruction *User = cast<Instruction>(*UI++);
7767 if (isInstructionTriviallyDead(User)) {
7768 while (UI != E && *UI == User)
7769 ++UI; // If this instruction uses AI more than once, don't break UI.
7770
Chris Lattnerb53c2382005-10-24 06:22:12 +00007771 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007772 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007773 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007774 }
7775 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007776
7777 // This requires TargetData to get the alloca alignment and size information.
7778 if (!TD) return 0;
7779
Chris Lattnerb3f83972005-10-24 06:03:58 +00007780 // Get the type really allocated and the type casted to.
7781 const Type *AllocElTy = AI.getAllocatedType();
7782 const Type *CastElTy = PTy->getElementType();
7783 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007784
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007785 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7786 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007787 if (CastElTyAlign < AllocElTyAlign) return 0;
7788
Chris Lattner39387a52005-10-24 06:35:18 +00007789 // If the allocation has multiple uses, only promote it if we are strictly
7790 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007791 // same, we open the door to infinite loops of various kinds. (A reference
7792 // from a dbg.declare doesn't count as a use for this purpose.)
7793 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7794 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007795
Duncan Sands777d2302009-05-09 07:06:46 +00007796 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7797 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007798 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007799
Chris Lattner455fcc82005-10-29 03:19:53 +00007800 // See if we can satisfy the modulus by pulling a scale out of the array
7801 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007802 unsigned ArraySizeScale;
7803 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007804 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007805 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7806 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007807
Chris Lattner455fcc82005-10-29 03:19:53 +00007808 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7809 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007810 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7811 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007812
Chris Lattner455fcc82005-10-29 03:19:53 +00007813 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7814 Value *Amt = 0;
7815 if (Scale == 1) {
7816 Amt = NumElements;
7817 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007818 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007819 // Insert before the alloca, not before the cast.
7820 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007821 }
7822
Jeff Cohen86796be2007-04-04 16:58:57 +00007823 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007824 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007825 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007826 }
7827
Victor Hernandez7b929da2009-10-23 21:09:37 +00007828 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007829 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007830 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007831
Dale Johannesena0a66372009-03-05 00:39:02 +00007832 // If the allocation has one real use plus a dbg.declare, just remove the
7833 // declare.
7834 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7835 EraseInstFromFunction(*DI);
7836 }
7837 // If the allocation has multiple real uses, insert a cast and change all
7838 // things that used it to use the new cast. This will also hack on CI, but it
7839 // will die soon.
7840 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007841 // New is the allocation instruction, pointer typed. AI is the original
7842 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007843 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007844 AI.replaceAllUsesWith(NewCast);
7845 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007846 return ReplaceInstUsesWith(CI, New);
7847}
7848
Chris Lattner70074e02006-05-13 02:06:03 +00007849/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007850/// and return it as type Ty without inserting any new casts and without
7851/// changing the computed value. This is used by code that tries to decide
7852/// whether promoting or shrinking integer operations to wider or smaller types
7853/// will allow us to eliminate a truncate or extend.
7854///
7855/// This is a truncation operation if Ty is smaller than V->getType(), or an
7856/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007857///
7858/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7859/// should return true if trunc(V) can be computed by computing V in the smaller
7860/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7861/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7862/// efficiently truncated.
7863///
7864/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7865/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7866/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007867bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007868 unsigned CastOpc,
7869 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007870 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007871 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007872 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007873
7874 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007875 if (!I) return false;
7876
Dan Gohman6de29f82009-06-15 22:12:54 +00007877 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007878
Chris Lattner951626b2007-08-02 06:11:14 +00007879 // If this is an extension or truncate, we can often eliminate it.
7880 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7881 // If this is a cast from the destination type, we can trivially eliminate
7882 // it, and this will remove a cast overall.
7883 if (I->getOperand(0)->getType() == Ty) {
7884 // If the first operand is itself a cast, and is eliminable, do not count
7885 // this as an eliminable cast. We would prefer to eliminate those two
7886 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007887 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007888 ++NumCastsRemoved;
7889 return true;
7890 }
7891 }
7892
7893 // We can't extend or shrink something that has multiple uses: doing so would
7894 // require duplicating the instruction in general, which isn't profitable.
7895 if (!I->hasOneUse()) return false;
7896
Evan Chengf35fd542009-01-15 17:01:23 +00007897 unsigned Opc = I->getOpcode();
7898 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007899 case Instruction::Add:
7900 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007901 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007902 case Instruction::And:
7903 case Instruction::Or:
7904 case Instruction::Xor:
7905 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007906 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007907 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007908 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007909 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007910
Eli Friedman070a9812009-07-13 22:46:01 +00007911 case Instruction::UDiv:
7912 case Instruction::URem: {
7913 // UDiv and URem can be truncated if all the truncated bits are zero.
7914 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7915 uint32_t BitWidth = Ty->getScalarSizeInBits();
7916 if (BitWidth < OrigBitWidth) {
7917 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7918 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7919 MaskedValueIsZero(I->getOperand(1), Mask)) {
7920 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7921 NumCastsRemoved) &&
7922 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7923 NumCastsRemoved);
7924 }
7925 }
7926 break;
7927 }
Chris Lattner46b96052006-11-29 07:18:39 +00007928 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007929 // If we are truncating the result of this SHL, and if it's a shift of a
7930 // constant amount, we can always perform a SHL in a smaller type.
7931 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007932 uint32_t BitWidth = Ty->getScalarSizeInBits();
7933 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007934 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007935 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007936 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007937 }
7938 break;
7939 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007940 // If this is a truncate of a logical shr, we can truncate it to a smaller
7941 // lshr iff we know that the bits we would otherwise be shifting in are
7942 // already zeros.
7943 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007944 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7945 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007946 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007947 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007948 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7949 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007950 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007951 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007952 }
7953 }
Chris Lattner46b96052006-11-29 07:18:39 +00007954 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007955 case Instruction::ZExt:
7956 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007957 case Instruction::Trunc:
7958 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007959 // can safely replace it. Note that replacing it does not reduce the number
7960 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007961 if (Opc == CastOpc)
7962 return true;
7963
7964 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007965 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007966 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007967 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007968 case Instruction::Select: {
7969 SelectInst *SI = cast<SelectInst>(I);
7970 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007971 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007972 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007973 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007974 }
Chris Lattner8114b712008-06-18 04:00:49 +00007975 case Instruction::PHI: {
7976 // We can change a phi if we can change all operands.
7977 PHINode *PN = cast<PHINode>(I);
7978 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7979 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007980 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007981 return false;
7982 return true;
7983 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007984 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007985 // TODO: Can handle more cases here.
7986 break;
7987 }
7988
7989 return false;
7990}
7991
7992/// EvaluateInDifferentType - Given an expression that
7993/// CanEvaluateInDifferentType returns true for, actually insert the code to
7994/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007995Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007996 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007997 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner9956c052009-11-08 19:23:30 +00007998 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007999
8000 // Otherwise, it must be an instruction.
8001 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008002 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008003 unsigned Opc = I->getOpcode();
8004 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008005 case Instruction::Add:
8006 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008007 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008008 case Instruction::And:
8009 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008010 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008011 case Instruction::AShr:
8012 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008013 case Instruction::Shl:
8014 case Instruction::UDiv:
8015 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008016 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008017 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008018 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008019 break;
8020 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008021 case Instruction::Trunc:
8022 case Instruction::ZExt:
8023 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008024 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008025 // just return the source. There's no need to insert it because it is not
8026 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008027 if (I->getOperand(0)->getType() == Ty)
8028 return I->getOperand(0);
8029
Chris Lattner8114b712008-06-18 04:00:49 +00008030 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9956c052009-11-08 19:23:30 +00008031 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008032 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008033 case Instruction::Select: {
8034 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8035 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8036 Res = SelectInst::Create(I->getOperand(0), True, False);
8037 break;
8038 }
Chris Lattner8114b712008-06-18 04:00:49 +00008039 case Instruction::PHI: {
8040 PHINode *OPN = cast<PHINode>(I);
8041 PHINode *NPN = PHINode::Create(Ty);
8042 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8043 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8044 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8045 }
8046 Res = NPN;
8047 break;
8048 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008049 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008050 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008051 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008052 break;
8053 }
8054
Chris Lattner8114b712008-06-18 04:00:49 +00008055 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008056 return InsertNewInstBefore(Res, *I);
8057}
8058
Reid Spencer3da59db2006-11-27 01:05:10 +00008059/// @brief Implement the transforms common to all CastInst visitors.
8060Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008061 Value *Src = CI.getOperand(0);
8062
Dan Gohman23d9d272007-05-11 21:10:54 +00008063 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008064 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008065 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008066 if (Instruction::CastOps opc =
8067 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8068 // The first cast (CSrc) is eliminable so we need to fix up or replace
8069 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008070 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008071 }
8072 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008073
Reid Spencer3da59db2006-11-27 01:05:10 +00008074 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008075 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8076 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8077 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008078
8079 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner9956c052009-11-08 19:23:30 +00008080 if (isa<PHINode>(Src)) {
8081 // We don't do this if this would create a PHI node with an illegal type if
8082 // it is currently legal.
8083 if (!isa<IntegerType>(Src->getType()) ||
8084 !isa<IntegerType>(CI.getType()) ||
8085 (TD && TD->isLegalInteger(CI.getType()->getPrimitiveSizeInBits())) ||
8086 (TD && !TD->isLegalInteger(Src->getType()->getPrimitiveSizeInBits())))
8087 if (Instruction *NV = FoldOpIntoPhi(CI))
8088 return NV;
8089
8090 }
Chris Lattner9fb92132006-04-12 18:09:35 +00008091
Reid Spencer3da59db2006-11-27 01:05:10 +00008092 return 0;
8093}
8094
Chris Lattner46cd5a12009-01-09 05:44:56 +00008095/// FindElementAtOffset - Given a type and a constant offset, determine whether
8096/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008097/// the specified offset. If so, fill them into NewIndices and return the
8098/// resultant element type, otherwise return null.
8099static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8100 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008101 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008102 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008103 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008104 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008105
8106 // Start with the index over the outer type. Note that the type size
8107 // might be zero (even if the offset isn't zero) if the indexed type
8108 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008109 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008110 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008111 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008112 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008113 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008114
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008115 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008116 if (Offset < 0) {
8117 --FirstIdx;
8118 Offset += TySize;
8119 assert(Offset >= 0);
8120 }
8121 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8122 }
8123
Owen Andersoneed707b2009-07-24 23:12:02 +00008124 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008125
8126 // Index into the types. If we fail, set OrigBase to null.
8127 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008128 // Indexing into tail padding between struct/array elements.
8129 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008130 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008131
Chris Lattner46cd5a12009-01-09 05:44:56 +00008132 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8133 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008134 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8135 "Offset must stay within the indexed type");
8136
Chris Lattner46cd5a12009-01-09 05:44:56 +00008137 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008138 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008139
8140 Offset -= SL->getElementOffset(Elt);
8141 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008142 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008143 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008144 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008145 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008146 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008147 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008148 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008149 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008150 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008151 }
8152 }
8153
Chris Lattner3914f722009-01-24 01:00:13 +00008154 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008155}
8156
Chris Lattnerd3e28342007-04-27 17:44:50 +00008157/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8158Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8159 Value *Src = CI.getOperand(0);
8160
Chris Lattnerd3e28342007-04-27 17:44:50 +00008161 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008162 // If casting the result of a getelementptr instruction with no offset, turn
8163 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008164 if (GEP->hasAllZeroIndices()) {
8165 // Changing the cast operand is usually not a good idea but it is safe
8166 // here because the pointer operand is being replaced with another
8167 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008168 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008169 CI.setOperand(0, GEP->getOperand(0));
8170 return &CI;
8171 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008172
8173 // If the GEP has a single use, and the base pointer is a bitcast, and the
8174 // GEP computes a constant offset, see if we can convert these three
8175 // instructions into fewer. This typically happens with unions and other
8176 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008177 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008178 if (GEP->hasAllConstantIndices()) {
8179 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +00008180 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008181 int64_t Offset = OffsetV->getSExtValue();
8182
8183 // Get the base pointer input of the bitcast, and the type it points to.
8184 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8185 const Type *GEPIdxTy =
8186 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008187 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008188 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008189 // If we were able to index down into an element, create the GEP
8190 // and bitcast the result. This eliminates one bitcast, potentially
8191 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008192 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8193 Builder->CreateInBoundsGEP(OrigBase,
8194 NewIndices.begin(), NewIndices.end()) :
8195 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008196 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008197
Chris Lattner46cd5a12009-01-09 05:44:56 +00008198 if (isa<BitCastInst>(CI))
8199 return new BitCastInst(NGEP, CI.getType());
8200 assert(isa<PtrToIntInst>(CI));
8201 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008202 }
8203 }
8204 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008205 }
8206
8207 return commonCastTransforms(CI);
8208}
8209
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008210/// commonIntCastTransforms - This function implements the common transforms
8211/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008212Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8213 if (Instruction *Result = commonCastTransforms(CI))
8214 return Result;
8215
8216 Value *Src = CI.getOperand(0);
8217 const Type *SrcTy = Src->getType();
8218 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008219 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8220 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008221
Reid Spencer3da59db2006-11-27 01:05:10 +00008222 // See if we can simplify any instructions used by the LHS whose sole
8223 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008224 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008225 return &CI;
8226
8227 // If the source isn't an instruction or has more than one use then we
8228 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008229 Instruction *SrcI = dyn_cast<Instruction>(Src);
8230 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008231 return 0;
8232
Chris Lattnerc739cd62007-03-03 05:27:34 +00008233 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008234 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008235 // Only do this if the dest type is a simple type, don't convert the
8236 // expression tree to something weird like i93 unless the source is also
8237 // strange.
Chris Lattner918871e2009-11-07 19:11:46 +00008238 if (TD &&
8239 (TD->isLegalInteger(DestTy->getScalarType()->getPrimitiveSizeInBits()) ||
8240 !TD->isLegalInteger((SrcI->getType()->getScalarType()
8241 ->getPrimitiveSizeInBits()))) &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008242 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008243 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008244 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008245 // eliminates the cast, so it is always a win. If this is a zero-extension,
8246 // we need to do an AND to maintain the clear top-part of the computation,
8247 // so we require that the input have eliminated at least one cast. If this
8248 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008249 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008250 bool DoXForm = false;
8251 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008252 switch (CI.getOpcode()) {
8253 default:
8254 // All the others use floating point so we shouldn't actually
8255 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008256 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008257 case Instruction::Trunc:
8258 DoXForm = true;
8259 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008260 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008261 DoXForm = NumCastsRemoved >= 1;
Chris Lattner918871e2009-11-07 19:11:46 +00008262
Chris Lattner39c27ed2009-01-31 19:05:27 +00008263 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008264 // If it's unnecessary to issue an AND to clear the high bits, it's
8265 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008266 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008267 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8268 if (MaskedValueIsZero(TryRes, Mask))
8269 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008270
8271 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008272 if (TryI->use_empty())
8273 EraseInstFromFunction(*TryI);
8274 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008275 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008276 }
Evan Chengf35fd542009-01-15 17:01:23 +00008277 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008278 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008279 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008280 // If we do not have to emit the truncate + sext pair, then it's always
8281 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008282 //
8283 // It's not safe to eliminate the trunc + sext pair if one of the
8284 // eliminated cast is a truncate. e.g.
8285 // t2 = trunc i32 t1 to i16
8286 // t3 = sext i16 t2 to i32
8287 // !=
8288 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008289 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008290 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8291 if (NumSignBits > (DestBitSize - SrcBitSize))
8292 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008293
8294 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008295 if (TryI->use_empty())
8296 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008297 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008298 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008299 }
Evan Chengf35fd542009-01-15 17:01:23 +00008300 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008301
8302 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008303 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8304 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008305 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8306 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008307 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008308 // Just replace this cast with the result.
8309 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008310
Reid Spencer3da59db2006-11-27 01:05:10 +00008311 assert(Res->getType() == DestTy);
8312 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008313 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008314 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008315 // Just replace this cast with the result.
8316 return ReplaceInstUsesWith(CI, Res);
8317 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008318 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008319
8320 // If the high bits are already zero, just replace this cast with the
8321 // result.
8322 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8323 if (MaskedValueIsZero(Res, Mask))
8324 return ReplaceInstUsesWith(CI, Res);
8325
8326 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008327 Constant *C = ConstantInt::get(*Context,
8328 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008329 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008330 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008331 case Instruction::SExt: {
8332 // If the high bits are already filled with sign bit, just replace this
8333 // cast with the result.
8334 unsigned NumSignBits = ComputeNumSignBits(Res);
8335 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008336 return ReplaceInstUsesWith(CI, Res);
8337
Reid Spencer3da59db2006-11-27 01:05:10 +00008338 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008339 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008340 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008341 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008342 }
8343 }
8344
8345 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8346 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8347
8348 switch (SrcI->getOpcode()) {
8349 case Instruction::Add:
8350 case Instruction::Mul:
8351 case Instruction::And:
8352 case Instruction::Or:
8353 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008354 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008355 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8356 // Don't insert two casts unless at least one can be eliminated.
8357 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008358 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008359 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8360 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008361 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008362 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008363 }
8364 }
8365
8366 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8367 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8368 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008369 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008370 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008371 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008372 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008373 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008374 }
8375 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008376
Eli Friedman65445c52009-07-13 21:45:57 +00008377 case Instruction::Shl: {
8378 // Canonicalize trunc inside shl, if we can.
8379 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8380 if (CI && DestBitSize < SrcBitSize &&
8381 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008382 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8383 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008384 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008385 }
8386 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008387 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008388 }
8389 return 0;
8390}
8391
Chris Lattner8a9f5712007-04-11 06:57:46 +00008392Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008393 if (Instruction *Result = commonIntCastTransforms(CI))
8394 return Result;
8395
8396 Value *Src = CI.getOperand(0);
8397 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008398 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8399 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008400
8401 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008402 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008403 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008404 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008405 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008406 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008407 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008408
Chris Lattner4f9797d2009-03-24 18:15:30 +00008409 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8410 ConstantInt *ShAmtV = 0;
8411 Value *ShiftOp = 0;
8412 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008413 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008414 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8415
8416 // Get a mask for the bits shifting in.
8417 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8418 if (MaskedValueIsZero(ShiftOp, Mask)) {
8419 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008420 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008421
8422 // Okay, we can shrink this. Truncate the input, then return a new
8423 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008424 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008425 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008426 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008427 }
8428 }
Chris Lattner9956c052009-11-08 19:23:30 +00008429
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008430 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008431}
8432
Evan Chengb98a10e2008-03-24 00:21:34 +00008433/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8434/// in order to eliminate the icmp.
8435Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8436 bool DoXform) {
8437 // If we are just checking for a icmp eq of a single bit and zext'ing it
8438 // to an integer, then shift the bit to the appropriate place and then
8439 // cast to integer to avoid the comparison.
8440 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8441 const APInt &Op1CV = Op1C->getValue();
8442
8443 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8444 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8445 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8446 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8447 if (!DoXform) return ICI;
8448
8449 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008450 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008451 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008452 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008453 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008454 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008455
8456 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008457 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008458 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008459 }
8460
8461 return ReplaceInstUsesWith(CI, In);
8462 }
8463
8464
8465
8466 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8467 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8468 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8469 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8470 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8471 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8472 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8473 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8474 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8475 // This only works for EQ and NE
8476 ICI->isEquality()) {
8477 // If Op1C some other power of two, convert:
8478 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8479 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8480 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8481 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8482
8483 APInt KnownZeroMask(~KnownZero);
8484 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8485 if (!DoXform) return ICI;
8486
8487 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8488 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8489 // (X&4) == 2 --> false
8490 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008491 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008492 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008493 return ReplaceInstUsesWith(CI, Res);
8494 }
8495
8496 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8497 Value *In = ICI->getOperand(0);
8498 if (ShiftAmt) {
8499 // Perform a logical shr by shiftamt.
8500 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008501 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8502 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008503 }
8504
8505 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008506 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008507 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008508 }
8509
8510 if (CI.getType() == In->getType())
8511 return ReplaceInstUsesWith(CI, In);
8512 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008513 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008514 }
8515 }
8516 }
8517
8518 return 0;
8519}
8520
Chris Lattner8a9f5712007-04-11 06:57:46 +00008521Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008522 // If one of the common conversion will work ..
8523 if (Instruction *Result = commonIntCastTransforms(CI))
8524 return Result;
8525
8526 Value *Src = CI.getOperand(0);
8527
Chris Lattnera84f47c2009-02-17 20:47:23 +00008528 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8529 // types and if the sizes are just right we can convert this into a logical
8530 // 'and' which will be much cheaper than the pair of casts.
8531 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8532 // Get the sizes of the types involved. We know that the intermediate type
8533 // will be smaller than A or C, but don't know the relation between A and C.
8534 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008535 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8536 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8537 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008538 // If we're actually extending zero bits, then if
8539 // SrcSize < DstSize: zext(a & mask)
8540 // SrcSize == DstSize: a & mask
8541 // SrcSize > DstSize: trunc(a) & mask
8542 if (SrcSize < DstSize) {
8543 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008544 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008545 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008546 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008547 }
8548
8549 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008550 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008551 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008552 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008553 }
8554 if (SrcSize > DstSize) {
8555 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008556 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008557 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008558 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008559 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008560 }
8561 }
8562
Evan Chengb98a10e2008-03-24 00:21:34 +00008563 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8564 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008565
Evan Chengb98a10e2008-03-24 00:21:34 +00008566 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8567 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8568 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8569 // of the (zext icmp) will be transformed.
8570 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8571 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8572 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8573 (transformZExtICmp(LHS, CI, false) ||
8574 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008575 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8576 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008577 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008578 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008579 }
8580
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008581 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008582 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8583 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8584 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8585 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008586 if (TI0->getType() == CI.getType())
8587 return
8588 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008589 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008590 }
8591
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008592 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8593 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8594 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8595 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8596 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8597 And->getOperand(1) == C)
8598 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8599 Value *TI0 = TI->getOperand(0);
8600 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008601 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008602 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008603 return BinaryOperator::CreateXor(NewAnd, ZC);
8604 }
8605 }
8606
Reid Spencer3da59db2006-11-27 01:05:10 +00008607 return 0;
8608}
8609
Chris Lattner8a9f5712007-04-11 06:57:46 +00008610Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008611 if (Instruction *I = commonIntCastTransforms(CI))
8612 return I;
8613
Chris Lattner8a9f5712007-04-11 06:57:46 +00008614 Value *Src = CI.getOperand(0);
8615
Dan Gohman1975d032008-10-30 20:40:10 +00008616 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008617 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008618 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008619 Constant::getAllOnesValue(CI.getType()),
8620 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008621
8622 // See if the value being truncated is already sign extended. If so, just
8623 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008624 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008625 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008626 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8627 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8628 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008629 unsigned NumSignBits = ComputeNumSignBits(Op);
8630
8631 if (OpBits == DestBits) {
8632 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8633 // bits, it is already ready.
8634 if (NumSignBits > DestBits-MidBits)
8635 return ReplaceInstUsesWith(CI, Op);
8636 } else if (OpBits < DestBits) {
8637 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8638 // bits, just sext from i32.
8639 if (NumSignBits > OpBits-MidBits)
8640 return new SExtInst(Op, CI.getType(), "tmp");
8641 } else {
8642 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8643 // bits, just truncate to i32.
8644 if (NumSignBits > OpBits-MidBits)
8645 return new TruncInst(Op, CI.getType(), "tmp");
8646 }
8647 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008648
8649 // If the input is a shl/ashr pair of a same constant, then this is a sign
8650 // extension from a smaller value. If we could trust arbitrary bitwidth
8651 // integers, we could turn this into a truncate to the smaller bit and then
8652 // use a sext for the whole extension. Since we don't, look deeper and check
8653 // for a truncate. If the source and dest are the same type, eliminate the
8654 // trunc and extend and just do shifts. For example, turn:
8655 // %a = trunc i32 %i to i8
8656 // %b = shl i8 %a, 6
8657 // %c = ashr i8 %b, 6
8658 // %d = sext i8 %c to i32
8659 // into:
8660 // %a = shl i32 %i, 30
8661 // %d = ashr i32 %a, 30
8662 Value *A = 0;
8663 ConstantInt *BA = 0, *CA = 0;
8664 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008665 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008666 BA == CA && isa<TruncInst>(A)) {
8667 Value *I = cast<TruncInst>(A)->getOperand(0);
8668 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008669 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8670 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008671 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008672 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008673 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008674 return BinaryOperator::CreateAShr(I, ShAmtV);
8675 }
8676 }
8677
Chris Lattnerba417832007-04-11 06:12:58 +00008678 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008679}
8680
Chris Lattnerb7530652008-01-27 05:29:54 +00008681/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8682/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008683static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008684 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008685 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008686 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008687 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8688 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008689 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008690 return 0;
8691}
8692
8693/// LookThroughFPExtensions - If this is an fp extension instruction, look
8694/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008695static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008696 if (Instruction *I = dyn_cast<Instruction>(V))
8697 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008698 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008699
8700 // If this value is a constant, return the constant in the smallest FP type
8701 // that can accurately represent it. This allows us to turn
8702 // (float)((double)X+2.0) into x+2.0f.
8703 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008704 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008705 return V; // No constant folding of this.
8706 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008707 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008708 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008709 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008710 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008711 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008712 return V;
8713 // Don't try to shrink to various long double types.
8714 }
8715
8716 return V;
8717}
8718
8719Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8720 if (Instruction *I = commonCastTransforms(CI))
8721 return I;
8722
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008723 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008724 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008725 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008726 // many builtins (sqrt, etc).
8727 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8728 if (OpI && OpI->hasOneUse()) {
8729 switch (OpI->getOpcode()) {
8730 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008731 case Instruction::FAdd:
8732 case Instruction::FSub:
8733 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008734 case Instruction::FDiv:
8735 case Instruction::FRem:
8736 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008737 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8738 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008739 if (LHSTrunc->getType() != SrcTy &&
8740 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008741 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008742 // If the source types were both smaller than the destination type of
8743 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008744 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8745 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008746 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8747 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008748 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008749 }
8750 }
8751 break;
8752 }
8753 }
8754 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008755}
8756
8757Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8758 return commonCastTransforms(CI);
8759}
8760
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008761Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008762 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8763 if (OpI == 0)
8764 return commonCastTransforms(FI);
8765
8766 // fptoui(uitofp(X)) --> X
8767 // fptoui(sitofp(X)) --> X
8768 // This is safe if the intermediate type has enough bits in its mantissa to
8769 // accurately represent all values of X. For example, do not do this with
8770 // i64->float->i64. This is also safe for sitofp case, because any negative
8771 // 'X' value would cause an undefined result for the fptoui.
8772 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8773 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008774 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008775 OpI->getType()->getFPMantissaWidth())
8776 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008777
8778 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008779}
8780
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008781Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008782 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8783 if (OpI == 0)
8784 return commonCastTransforms(FI);
8785
8786 // fptosi(sitofp(X)) --> X
8787 // fptosi(uitofp(X)) --> X
8788 // This is safe if the intermediate type has enough bits in its mantissa to
8789 // accurately represent all values of X. For example, do not do this with
8790 // i64->float->i64. This is also safe for sitofp case, because any negative
8791 // 'X' value would cause an undefined result for the fptoui.
8792 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8793 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008794 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008795 OpI->getType()->getFPMantissaWidth())
8796 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008797
8798 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008799}
8800
8801Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8802 return commonCastTransforms(CI);
8803}
8804
8805Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8806 return commonCastTransforms(CI);
8807}
8808
Chris Lattnera0e69692009-03-24 18:35:40 +00008809Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8810 // If the destination integer type is smaller than the intptr_t type for
8811 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8812 // trunc to be exposed to other transforms. Don't do this for extending
8813 // ptrtoint's, because we don't know if the target sign or zero extends its
8814 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008815 if (TD &&
8816 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008817 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8818 TD->getIntPtrType(CI.getContext()),
8819 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008820 return new TruncInst(P, CI.getType());
8821 }
8822
Chris Lattnerd3e28342007-04-27 17:44:50 +00008823 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008824}
8825
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008826Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008827 // If the source integer type is larger than the intptr_t type for
8828 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8829 // allows the trunc to be exposed to other transforms. Don't do this for
8830 // extending inttoptr's, because we don't know if the target sign or zero
8831 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008832 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008833 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008834 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8835 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008836 return new IntToPtrInst(P, CI.getType());
8837 }
8838
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008839 if (Instruction *I = commonCastTransforms(CI))
8840 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008841
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008842 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008843}
8844
Chris Lattnerd3e28342007-04-27 17:44:50 +00008845Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008846 // If the operands are integer typed then apply the integer transforms,
8847 // otherwise just apply the common ones.
8848 Value *Src = CI.getOperand(0);
8849 const Type *SrcTy = Src->getType();
8850 const Type *DestTy = CI.getType();
8851
Eli Friedman7e25d452009-07-13 20:53:00 +00008852 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008853 if (Instruction *I = commonPointerCastTransforms(CI))
8854 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008855 } else {
8856 if (Instruction *Result = commonCastTransforms(CI))
8857 return Result;
8858 }
8859
8860
8861 // Get rid of casts from one type to the same type. These are useless and can
8862 // be replaced by the operand.
8863 if (DestTy == Src->getType())
8864 return ReplaceInstUsesWith(CI, Src);
8865
Reid Spencer3da59db2006-11-27 01:05:10 +00008866 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008867 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8868 const Type *DstElTy = DstPTy->getElementType();
8869 const Type *SrcElTy = SrcPTy->getElementType();
8870
Nate Begeman83ad90a2008-03-31 00:22:16 +00008871 // If the address spaces don't match, don't eliminate the bitcast, which is
8872 // required for changing types.
8873 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8874 return 0;
8875
Victor Hernandez83d63912009-09-18 22:35:49 +00008876 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008877 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008878 // There is no need to modify malloc calls because it is their bitcast that
8879 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00008880 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00008881 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8882 return V;
8883
Chris Lattnerd717c182007-05-05 22:32:24 +00008884 // If the source and destination are pointers, and this cast is equivalent
8885 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008886 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008887 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008888 unsigned NumZeros = 0;
8889 while (SrcElTy != DstElTy &&
8890 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8891 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8892 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8893 ++NumZeros;
8894 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008895
Chris Lattnerd3e28342007-04-27 17:44:50 +00008896 // If we found a path from the src to dest, create the getelementptr now.
8897 if (SrcElTy == DstElTy) {
8898 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008899 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8900 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008901 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008902 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008903
Eli Friedman2451a642009-07-18 23:06:53 +00008904 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8905 if (DestVTy->getNumElements() == 1) {
8906 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008907 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008908 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008909 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008910 }
8911 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8912 }
8913 }
8914
8915 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8916 if (SrcVTy->getNumElements() == 1) {
8917 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008918 Value *Elem =
8919 Builder->CreateExtractElement(Src,
8920 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008921 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8922 }
8923 }
8924 }
8925
Reid Spencer3da59db2006-11-27 01:05:10 +00008926 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8927 if (SVI->hasOneUse()) {
8928 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8929 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008930 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008931 cast<VectorType>(DestTy)->getNumElements() ==
8932 SVI->getType()->getNumElements() &&
8933 SVI->getType()->getNumElements() ==
8934 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008935 CastInst *Tmp;
8936 // If either of the operands is a cast from CI.getType(), then
8937 // evaluating the shuffle in the casted destination's type will allow
8938 // us to eliminate at least one cast.
8939 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8940 Tmp->getOperand(0)->getType() == DestTy) ||
8941 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8942 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008943 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8944 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008945 // Return a new shuffle vector. Use the same element ID's, as we
8946 // know the vector types match #elts.
8947 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008948 }
8949 }
8950 }
8951 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008952 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008953}
8954
Chris Lattnere576b912004-04-09 23:46:01 +00008955/// GetSelectFoldableOperands - We want to turn code that looks like this:
8956/// %C = or %A, %B
8957/// %D = select %cond, %C, %A
8958/// into:
8959/// %C = select %cond, %B, 0
8960/// %D = or %A, %C
8961///
8962/// Assuming that the specified instruction is an operand to the select, return
8963/// a bitmask indicating which operands of this instruction are foldable if they
8964/// equal the other incoming value of the select.
8965///
8966static unsigned GetSelectFoldableOperands(Instruction *I) {
8967 switch (I->getOpcode()) {
8968 case Instruction::Add:
8969 case Instruction::Mul:
8970 case Instruction::And:
8971 case Instruction::Or:
8972 case Instruction::Xor:
8973 return 3; // Can fold through either operand.
8974 case Instruction::Sub: // Can only fold on the amount subtracted.
8975 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008976 case Instruction::LShr:
8977 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008978 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008979 default:
8980 return 0; // Cannot fold
8981 }
8982}
8983
8984/// GetSelectFoldableConstant - For the same transformation as the previous
8985/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00008986static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008987 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00008988 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008989 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00008990 case Instruction::Add:
8991 case Instruction::Sub:
8992 case Instruction::Or:
8993 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008994 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008995 case Instruction::LShr:
8996 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00008997 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008998 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00008999 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009000 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009001 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009002 }
9003}
9004
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009005/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9006/// have the same opcode and only one use each. Try to simplify this.
9007Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9008 Instruction *FI) {
9009 if (TI->getNumOperands() == 1) {
9010 // If this is a non-volatile load or a cast from the same type,
9011 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009012 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009013 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9014 return 0;
9015 } else {
9016 return 0; // unknown unary op.
9017 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009018
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009019 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009020 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009021 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009022 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009023 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009024 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009025 }
9026
Reid Spencer832254e2007-02-02 02:16:23 +00009027 // Only handle binary operators here.
9028 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009029 return 0;
9030
9031 // Figure out if the operations have any operands in common.
9032 Value *MatchOp, *OtherOpT, *OtherOpF;
9033 bool MatchIsOpZero;
9034 if (TI->getOperand(0) == FI->getOperand(0)) {
9035 MatchOp = TI->getOperand(0);
9036 OtherOpT = TI->getOperand(1);
9037 OtherOpF = FI->getOperand(1);
9038 MatchIsOpZero = true;
9039 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9040 MatchOp = TI->getOperand(1);
9041 OtherOpT = TI->getOperand(0);
9042 OtherOpF = FI->getOperand(0);
9043 MatchIsOpZero = false;
9044 } else if (!TI->isCommutative()) {
9045 return 0;
9046 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9047 MatchOp = TI->getOperand(0);
9048 OtherOpT = TI->getOperand(1);
9049 OtherOpF = FI->getOperand(0);
9050 MatchIsOpZero = true;
9051 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9052 MatchOp = TI->getOperand(1);
9053 OtherOpT = TI->getOperand(0);
9054 OtherOpF = FI->getOperand(1);
9055 MatchIsOpZero = true;
9056 } else {
9057 return 0;
9058 }
9059
9060 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009061 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9062 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009063 InsertNewInstBefore(NewSI, SI);
9064
9065 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9066 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009067 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009068 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009069 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009070 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009071 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009072 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009073}
9074
Evan Chengde621922009-03-31 20:42:45 +00009075static bool isSelect01(Constant *C1, Constant *C2) {
9076 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9077 if (!C1I)
9078 return false;
9079 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9080 if (!C2I)
9081 return false;
9082 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9083}
9084
9085/// FoldSelectIntoOp - Try fold the select into one of the operands to
9086/// facilitate further optimization.
9087Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9088 Value *FalseVal) {
9089 // See the comment above GetSelectFoldableOperands for a description of the
9090 // transformation we are doing here.
9091 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9092 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9093 !isa<Constant>(FalseVal)) {
9094 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9095 unsigned OpToFold = 0;
9096 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9097 OpToFold = 1;
9098 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9099 OpToFold = 2;
9100 }
9101
9102 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009103 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009104 Value *OOp = TVI->getOperand(2-OpToFold);
9105 // Avoid creating select between 2 constants unless it's selecting
9106 // between 0 and 1.
9107 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9108 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9109 InsertNewInstBefore(NewSel, SI);
9110 NewSel->takeName(TVI);
9111 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9112 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009113 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009114 }
9115 }
9116 }
9117 }
9118 }
9119
9120 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9121 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9122 !isa<Constant>(TrueVal)) {
9123 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9124 unsigned OpToFold = 0;
9125 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9126 OpToFold = 1;
9127 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9128 OpToFold = 2;
9129 }
9130
9131 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009132 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009133 Value *OOp = FVI->getOperand(2-OpToFold);
9134 // Avoid creating select between 2 constants unless it's selecting
9135 // between 0 and 1.
9136 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9137 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9138 InsertNewInstBefore(NewSel, SI);
9139 NewSel->takeName(FVI);
9140 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9141 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009142 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009143 }
9144 }
9145 }
9146 }
9147 }
9148
9149 return 0;
9150}
9151
Dan Gohman81b28ce2008-09-16 18:46:06 +00009152/// visitSelectInstWithICmp - Visit a SelectInst that has an
9153/// ICmpInst as its first operand.
9154///
9155Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9156 ICmpInst *ICI) {
9157 bool Changed = false;
9158 ICmpInst::Predicate Pred = ICI->getPredicate();
9159 Value *CmpLHS = ICI->getOperand(0);
9160 Value *CmpRHS = ICI->getOperand(1);
9161 Value *TrueVal = SI.getTrueValue();
9162 Value *FalseVal = SI.getFalseValue();
9163
9164 // Check cases where the comparison is with a constant that
9165 // can be adjusted to fit the min/max idiom. We may edit ICI in
9166 // place here, so make sure the select is the only user.
9167 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009168 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009169 switch (Pred) {
9170 default: break;
9171 case ICmpInst::ICMP_ULT:
9172 case ICmpInst::ICMP_SLT: {
9173 // X < MIN ? T : F --> F
9174 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9175 return ReplaceInstUsesWith(SI, FalseVal);
9176 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009177 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009178 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9179 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9180 Pred = ICmpInst::getSwappedPredicate(Pred);
9181 CmpRHS = AdjustedRHS;
9182 std::swap(FalseVal, TrueVal);
9183 ICI->setPredicate(Pred);
9184 ICI->setOperand(1, CmpRHS);
9185 SI.setOperand(1, TrueVal);
9186 SI.setOperand(2, FalseVal);
9187 Changed = true;
9188 }
9189 break;
9190 }
9191 case ICmpInst::ICMP_UGT:
9192 case ICmpInst::ICMP_SGT: {
9193 // X > MAX ? T : F --> F
9194 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9195 return ReplaceInstUsesWith(SI, FalseVal);
9196 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009197 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009198 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9199 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9200 Pred = ICmpInst::getSwappedPredicate(Pred);
9201 CmpRHS = AdjustedRHS;
9202 std::swap(FalseVal, TrueVal);
9203 ICI->setPredicate(Pred);
9204 ICI->setOperand(1, CmpRHS);
9205 SI.setOperand(1, TrueVal);
9206 SI.setOperand(2, FalseVal);
9207 Changed = true;
9208 }
9209 break;
9210 }
9211 }
9212
Dan Gohman1975d032008-10-30 20:40:10 +00009213 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9214 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009215 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009216 if (match(TrueVal, m_ConstantInt<-1>()) &&
9217 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009218 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009219 else if (match(TrueVal, m_ConstantInt<0>()) &&
9220 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009221 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9222
Dan Gohman1975d032008-10-30 20:40:10 +00009223 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9224 // If we are just checking for a icmp eq of a single bit and zext'ing it
9225 // to an integer, then shift the bit to the appropriate place and then
9226 // cast to integer to avoid the comparison.
9227 const APInt &Op1CV = CI->getValue();
9228
9229 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9230 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9231 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009232 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009233 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009234 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009235 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009236 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009237 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009238 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009239 if (In->getType() != SI.getType())
9240 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009241 true/*SExt*/, "tmp", ICI);
9242
9243 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009244 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009245 In->getName()+".not"), *ICI);
9246
9247 return ReplaceInstUsesWith(SI, In);
9248 }
9249 }
9250 }
9251
Dan Gohman81b28ce2008-09-16 18:46:06 +00009252 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9253 // Transform (X == Y) ? X : Y -> Y
9254 if (Pred == ICmpInst::ICMP_EQ)
9255 return ReplaceInstUsesWith(SI, FalseVal);
9256 // Transform (X != Y) ? X : Y -> X
9257 if (Pred == ICmpInst::ICMP_NE)
9258 return ReplaceInstUsesWith(SI, TrueVal);
9259 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9260
9261 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9262 // Transform (X == Y) ? Y : X -> X
9263 if (Pred == ICmpInst::ICMP_EQ)
9264 return ReplaceInstUsesWith(SI, FalseVal);
9265 // Transform (X != Y) ? Y : X -> Y
9266 if (Pred == ICmpInst::ICMP_NE)
9267 return ReplaceInstUsesWith(SI, TrueVal);
9268 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9269 }
9270
9271 /// NOTE: if we wanted to, this is where to detect integer ABS
9272
9273 return Changed ? &SI : 0;
9274}
9275
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009276
Chris Lattner7f239582009-10-22 00:17:26 +00009277/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9278/// PHI node (but the two may be in different blocks). See if the true/false
9279/// values (V) are live in all of the predecessor blocks of the PHI. For
9280/// example, cases like this cannot be mapped:
9281///
9282/// X = phi [ C1, BB1], [C2, BB2]
9283/// Y = add
9284/// Z = select X, Y, 0
9285///
9286/// because Y is not live in BB1/BB2.
9287///
9288static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9289 const SelectInst &SI) {
9290 // If the value is a non-instruction value like a constant or argument, it
9291 // can always be mapped.
9292 const Instruction *I = dyn_cast<Instruction>(V);
9293 if (I == 0) return true;
9294
9295 // If V is a PHI node defined in the same block as the condition PHI, we can
9296 // map the arguments.
9297 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9298
9299 if (const PHINode *VP = dyn_cast<PHINode>(I))
9300 if (VP->getParent() == CondPHI->getParent())
9301 return true;
9302
9303 // Otherwise, if the PHI and select are defined in the same block and if V is
9304 // defined in a different block, then we can transform it.
9305 if (SI.getParent() == CondPHI->getParent() &&
9306 I->getParent() != CondPHI->getParent())
9307 return true;
9308
9309 // Otherwise we have a 'hard' case and we can't tell without doing more
9310 // detailed dominator based analysis, punt.
9311 return false;
9312}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009313
Chris Lattner3d69f462004-03-12 05:52:32 +00009314Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009315 Value *CondVal = SI.getCondition();
9316 Value *TrueVal = SI.getTrueValue();
9317 Value *FalseVal = SI.getFalseValue();
9318
9319 // select true, X, Y -> X
9320 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009321 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009322 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009323
9324 // select C, X, X -> X
9325 if (TrueVal == FalseVal)
9326 return ReplaceInstUsesWith(SI, TrueVal);
9327
Chris Lattnere87597f2004-10-16 18:11:37 +00009328 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9329 return ReplaceInstUsesWith(SI, FalseVal);
9330 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9331 return ReplaceInstUsesWith(SI, TrueVal);
9332 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9333 if (isa<Constant>(TrueVal))
9334 return ReplaceInstUsesWith(SI, TrueVal);
9335 else
9336 return ReplaceInstUsesWith(SI, FalseVal);
9337 }
9338
Owen Anderson1d0be152009-08-13 21:58:54 +00009339 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009340 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009341 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009342 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009343 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009344 } else {
9345 // Change: A = select B, false, C --> A = and !B, C
9346 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009347 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009348 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009349 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009350 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009351 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009352 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009353 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009354 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009355 } else {
9356 // Change: A = select B, C, true --> A = or !B, C
9357 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009358 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009359 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009360 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009361 }
9362 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009363
9364 // select a, b, a -> a&b
9365 // select a, a, b -> a|b
9366 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009367 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009368 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009369 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009370 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009371
Chris Lattner2eefe512004-04-09 19:05:30 +00009372 // Selecting between two integer constants?
9373 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9374 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009375 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009376 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009377 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009378 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009379 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009380 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009381 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009382 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009383 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009384 }
Chris Lattner457dd822004-06-09 07:59:58 +00009385
Reid Spencere4d87aa2006-12-23 06:05:41 +00009386 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009387 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009388 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009389 // non-constant value, eliminate this whole mess. This corresponds to
9390 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009391 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009392 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009393 cast<Constant>(IC->getOperand(1))->isNullValue())
9394 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9395 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009396 isa<ConstantInt>(ICA->getOperand(1)) &&
9397 (ICA->getOperand(1) == TrueValC ||
9398 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009399 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9400 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009401 // know whether we have a icmp_ne or icmp_eq and whether the
9402 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009403 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009404 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009405 Value *V = ICA;
9406 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009407 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009408 Instruction::Xor, V, ICA->getOperand(1)), SI);
9409 return ReplaceInstUsesWith(SI, V);
9410 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009411 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009412 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009413
9414 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009415 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9416 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009417 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009418 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9419 // This is not safe in general for floating point:
9420 // consider X== -0, Y== +0.
9421 // It becomes safe if either operand is a nonzero constant.
9422 ConstantFP *CFPt, *CFPf;
9423 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9424 !CFPt->getValueAPF().isZero()) ||
9425 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9426 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009427 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009428 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009429 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009430 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009431 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009432 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009433
Reid Spencere4d87aa2006-12-23 06:05:41 +00009434 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009435 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009436 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9437 // This is not safe in general for floating point:
9438 // consider X== -0, Y== +0.
9439 // It becomes safe if either operand is a nonzero constant.
9440 ConstantFP *CFPt, *CFPf;
9441 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9442 !CFPt->getValueAPF().isZero()) ||
9443 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9444 !CFPf->getValueAPF().isZero()))
9445 return ReplaceInstUsesWith(SI, FalseVal);
9446 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009447 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009448 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9449 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009450 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009451 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009452 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009453 }
9454
9455 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009456 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9457 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9458 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009459
Chris Lattner87875da2005-01-13 22:52:24 +00009460 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9461 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9462 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009463 Instruction *AddOp = 0, *SubOp = 0;
9464
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009465 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9466 if (TI->getOpcode() == FI->getOpcode())
9467 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9468 return IV;
9469
9470 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9471 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009472 if ((TI->getOpcode() == Instruction::Sub &&
9473 FI->getOpcode() == Instruction::Add) ||
9474 (TI->getOpcode() == Instruction::FSub &&
9475 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009476 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009477 } else if ((FI->getOpcode() == Instruction::Sub &&
9478 TI->getOpcode() == Instruction::Add) ||
9479 (FI->getOpcode() == Instruction::FSub &&
9480 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009481 AddOp = TI; SubOp = FI;
9482 }
9483
9484 if (AddOp) {
9485 Value *OtherAddOp = 0;
9486 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9487 OtherAddOp = AddOp->getOperand(1);
9488 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9489 OtherAddOp = AddOp->getOperand(0);
9490 }
9491
9492 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009493 // So at this point we know we have (Y -> OtherAddOp):
9494 // select C, (add X, Y), (sub X, Z)
9495 Value *NegVal; // Compute -Z
9496 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009497 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009498 } else {
9499 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009500 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009501 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009502 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009503
9504 Value *NewTrueOp = OtherAddOp;
9505 Value *NewFalseOp = NegVal;
9506 if (AddOp != TI)
9507 std::swap(NewTrueOp, NewFalseOp);
9508 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009509 SelectInst::Create(CondVal, NewTrueOp,
9510 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009511
9512 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009513 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009514 }
9515 }
9516 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009517
Chris Lattnere576b912004-04-09 23:46:01 +00009518 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009519 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009520 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9521 if (FoldI)
9522 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009523 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009524
Chris Lattner7f239582009-10-22 00:17:26 +00009525 // See if we can fold the select into a phi node if the condition is a select.
9526 if (isa<PHINode>(SI.getCondition()))
9527 // The true/false values have to be live in the PHI predecessor's blocks.
9528 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9529 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9530 if (Instruction *NV = FoldOpIntoPhi(SI))
9531 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +00009532
Chris Lattnera1df33c2005-04-24 07:30:14 +00009533 if (BinaryOperator::isNot(CondVal)) {
9534 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9535 SI.setOperand(1, FalseVal);
9536 SI.setOperand(2, TrueVal);
9537 return &SI;
9538 }
9539
Chris Lattner3d69f462004-03-12 05:52:32 +00009540 return 0;
9541}
9542
Dan Gohmaneee962e2008-04-10 18:43:06 +00009543/// EnforceKnownAlignment - If the specified pointer points to an object that
9544/// we control, modify the object's alignment to PrefAlign. This isn't
9545/// often possible though. If alignment is important, a more reliable approach
9546/// is to simply align all global variables and allocation instructions to
9547/// their preferred alignment from the beginning.
9548///
9549static unsigned EnforceKnownAlignment(Value *V,
9550 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009551
Dan Gohmaneee962e2008-04-10 18:43:06 +00009552 User *U = dyn_cast<User>(V);
9553 if (!U) return Align;
9554
Dan Gohmanca178902009-07-17 20:47:02 +00009555 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009556 default: break;
9557 case Instruction::BitCast:
9558 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9559 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009560 // If all indexes are zero, it is just the alignment of the base pointer.
9561 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009562 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009563 if (!isa<Constant>(*i) ||
9564 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009565 AllZeroOperands = false;
9566 break;
9567 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009568
9569 if (AllZeroOperands) {
9570 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009571 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009572 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009573 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009574 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009575 }
9576
9577 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9578 // If there is a large requested alignment and we can, bump up the alignment
9579 // of the global.
9580 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009581 if (GV->getAlignment() >= PrefAlign)
9582 Align = GV->getAlignment();
9583 else {
9584 GV->setAlignment(PrefAlign);
9585 Align = PrefAlign;
9586 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009587 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009588 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9589 // If there is a requested alignment and if this is an alloca, round up.
9590 if (AI->getAlignment() >= PrefAlign)
9591 Align = AI->getAlignment();
9592 else {
9593 AI->setAlignment(PrefAlign);
9594 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009595 }
9596 }
9597
9598 return Align;
9599}
9600
9601/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9602/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9603/// and it is more than the alignment of the ultimate object, see if we can
9604/// increase the alignment of the ultimate object, making this check succeed.
9605unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9606 unsigned PrefAlign) {
9607 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9608 sizeof(PrefAlign) * CHAR_BIT;
9609 APInt Mask = APInt::getAllOnesValue(BitWidth);
9610 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9611 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9612 unsigned TrailZ = KnownZero.countTrailingOnes();
9613 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9614
9615 if (PrefAlign > Align)
9616 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9617
9618 // We don't need to make any adjustment.
9619 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009620}
9621
Chris Lattnerf497b022008-01-13 23:50:23 +00009622Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009623 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009624 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009625 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009626 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009627
9628 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009629 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009630 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009631 return MI;
9632 }
9633
9634 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9635 // load/store.
9636 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9637 if (MemOpLength == 0) return 0;
9638
Chris Lattner37ac6082008-01-14 00:28:35 +00009639 // Source and destination pointer types are always "i8*" for intrinsic. See
9640 // if the size is something we can handle with a single primitive load/store.
9641 // A single load+store correctly handles overlapping memory in the memmove
9642 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009643 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009644 if (Size == 0) return MI; // Delete this mem transfer.
9645
9646 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009647 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009648
Chris Lattner37ac6082008-01-14 00:28:35 +00009649 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009650 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009651 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009652
9653 // Memcpy forces the use of i8* for the source and destination. That means
9654 // that if you're using memcpy to move one double around, you'll get a cast
9655 // from double* to i8*. We'd much rather use a double load+store rather than
9656 // an i64 load+store, here because this improves the odds that the source or
9657 // dest address will be promotable. See if we can find a better type than the
9658 // integer datatype.
9659 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9660 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009661 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009662 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9663 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009664 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009665 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9666 if (STy->getNumElements() == 1)
9667 SrcETy = STy->getElementType(0);
9668 else
9669 break;
9670 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9671 if (ATy->getNumElements() == 1)
9672 SrcETy = ATy->getElementType();
9673 else
9674 break;
9675 } else
9676 break;
9677 }
9678
Dan Gohman8f8e2692008-05-23 01:52:21 +00009679 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009680 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009681 }
9682 }
9683
9684
Chris Lattnerf497b022008-01-13 23:50:23 +00009685 // If the memcpy/memmove provides better alignment info than we can
9686 // infer, use it.
9687 SrcAlign = std::max(SrcAlign, CopyAlign);
9688 DstAlign = std::max(DstAlign, CopyAlign);
9689
Chris Lattner08142f22009-08-30 19:47:22 +00009690 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9691 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009692 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9693 InsertNewInstBefore(L, *MI);
9694 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9695
9696 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009697 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009698 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009699}
Chris Lattner3d69f462004-03-12 05:52:32 +00009700
Chris Lattner69ea9d22008-04-30 06:39:11 +00009701Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9702 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009703 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009704 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009705 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009706 return MI;
9707 }
9708
9709 // Extract the length and alignment and fill if they are constant.
9710 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9711 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009712 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009713 return 0;
9714 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009715 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009716
9717 // If the length is zero, this is a no-op
9718 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9719
9720 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9721 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009722 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009723
9724 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009725 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009726
9727 // Alignment 0 is identity for alignment 1 for memset, but not store.
9728 if (Alignment == 0) Alignment = 1;
9729
9730 // Extract the fill value and store.
9731 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009732 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009733 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009734
9735 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009736 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009737 return MI;
9738 }
9739
9740 return 0;
9741}
9742
9743
Chris Lattner8b0ea312006-01-13 20:11:04 +00009744/// visitCallInst - CallInst simplification. This mostly only handles folding
9745/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9746/// the heavy lifting.
9747///
Chris Lattner9fe38862003-06-19 17:00:31 +00009748Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +00009749 if (isFreeCall(&CI))
9750 return visitFree(CI);
9751
Chris Lattneraab6ec42009-05-13 17:39:14 +00009752 // If the caller function is nounwind, mark the call as nounwind, even if the
9753 // callee isn't.
9754 if (CI.getParent()->getParent()->doesNotThrow() &&
9755 !CI.doesNotThrow()) {
9756 CI.setDoesNotThrow();
9757 return &CI;
9758 }
9759
Chris Lattner8b0ea312006-01-13 20:11:04 +00009760 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9761 if (!II) return visitCallSite(&CI);
9762
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009763 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9764 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009765 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009766 bool Changed = false;
9767
9768 // memmove/cpy/set of zero bytes is a noop.
9769 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9770 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9771
Chris Lattner35b9e482004-10-12 04:52:52 +00009772 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009773 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009774 // Replace the instruction with just byte operations. We would
9775 // transform other cases to loads/stores, but we don't know if
9776 // alignment is sufficient.
9777 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009778 }
9779
Chris Lattner35b9e482004-10-12 04:52:52 +00009780 // If we have a memmove and the source operation is a constant global,
9781 // then the source and dest pointers can't alias, so we can change this
9782 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009783 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009784 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9785 if (GVSrc->isConstant()) {
9786 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009787 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9788 const Type *Tys[1];
9789 Tys[0] = CI.getOperand(3)->getType();
9790 CI.setOperand(0,
9791 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009792 Changed = true;
9793 }
Chris Lattnera935db82008-05-28 05:30:41 +00009794
9795 // memmove(x,x,size) -> noop.
9796 if (MMI->getSource() == MMI->getDest())
9797 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009798 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009799
Chris Lattner95a959d2006-03-06 20:18:44 +00009800 // If we can determine a pointer alignment that is bigger than currently
9801 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009802 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009803 if (Instruction *I = SimplifyMemTransfer(MI))
9804 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009805 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9806 if (Instruction *I = SimplifyMemSet(MSI))
9807 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009808 }
9809
Chris Lattner8b0ea312006-01-13 20:11:04 +00009810 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009811 }
9812
9813 switch (II->getIntrinsicID()) {
9814 default: break;
9815 case Intrinsic::bswap:
9816 // bswap(bswap(x)) -> x
9817 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9818 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9819 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9820 break;
9821 case Intrinsic::ppc_altivec_lvx:
9822 case Intrinsic::ppc_altivec_lvxl:
9823 case Intrinsic::x86_sse_loadu_ps:
9824 case Intrinsic::x86_sse2_loadu_pd:
9825 case Intrinsic::x86_sse2_loadu_dq:
9826 // Turn PPC lvx -> load if the pointer is known aligned.
9827 // Turn X86 loadups -> load if the pointer is known aligned.
9828 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009829 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9830 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009831 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009832 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009833 break;
9834 case Intrinsic::ppc_altivec_stvx:
9835 case Intrinsic::ppc_altivec_stvxl:
9836 // Turn stvx -> store if the pointer is known aligned.
9837 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9838 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009839 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009840 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009841 return new StoreInst(II->getOperand(1), Ptr);
9842 }
9843 break;
9844 case Intrinsic::x86_sse_storeu_ps:
9845 case Intrinsic::x86_sse2_storeu_pd:
9846 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009847 // Turn X86 storeu -> store if the pointer is known aligned.
9848 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9849 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009850 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009851 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009852 return new StoreInst(II->getOperand(2), Ptr);
9853 }
9854 break;
9855
9856 case Intrinsic::x86_sse_cvttss2si: {
9857 // These intrinsics only demands the 0th element of its input vector. If
9858 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009859 unsigned VWidth =
9860 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9861 APInt DemandedElts(VWidth, 1);
9862 APInt UndefElts(VWidth, 0);
9863 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009864 UndefElts)) {
9865 II->setOperand(1, V);
9866 return II;
9867 }
9868 break;
9869 }
9870
9871 case Intrinsic::ppc_altivec_vperm:
9872 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9873 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9874 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009875
Chris Lattner0521e3c2008-06-18 04:33:20 +00009876 // Check that all of the elements are integer constants or undefs.
9877 bool AllEltsOk = true;
9878 for (unsigned i = 0; i != 16; ++i) {
9879 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9880 !isa<UndefValue>(Mask->getOperand(i))) {
9881 AllEltsOk = false;
9882 break;
9883 }
9884 }
9885
9886 if (AllEltsOk) {
9887 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009888 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9889 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009890 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009891
Chris Lattner0521e3c2008-06-18 04:33:20 +00009892 // Only extract each element once.
9893 Value *ExtractedElts[32];
9894 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9895
Chris Lattnere2ed0572006-04-06 19:19:17 +00009896 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009897 if (isa<UndefValue>(Mask->getOperand(i)))
9898 continue;
9899 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9900 Idx &= 31; // Match the hardware behavior.
9901
9902 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009903 ExtractedElts[Idx] =
9904 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9905 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9906 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009907 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009908
Chris Lattner0521e3c2008-06-18 04:33:20 +00009909 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009910 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9911 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9912 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009913 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009914 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009915 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009916 }
9917 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009918
Chris Lattner0521e3c2008-06-18 04:33:20 +00009919 case Intrinsic::stackrestore: {
9920 // If the save is right next to the restore, remove the restore. This can
9921 // happen when variable allocas are DCE'd.
9922 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9923 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9924 BasicBlock::iterator BI = SS;
9925 if (&*++BI == II)
9926 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009927 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009928 }
9929
9930 // Scan down this block to see if there is another stack restore in the
9931 // same block without an intervening call/alloca.
9932 BasicBlock::iterator BI = II;
9933 TerminatorInst *TI = II->getParent()->getTerminator();
9934 bool CannotRemove = false;
9935 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00009936 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009937 CannotRemove = true;
9938 break;
9939 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009940 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9941 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9942 // If there is a stackrestore below this one, remove this one.
9943 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9944 return EraseInstFromFunction(CI);
9945 // Otherwise, ignore the intrinsic.
9946 } else {
9947 // If we found a non-intrinsic call, we can't remove the stack
9948 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009949 CannotRemove = true;
9950 break;
9951 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009952 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009953 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009954
9955 // If the stack restore is in a return/unwind block and if there are no
9956 // allocas or calls between the restore and the return, nuke the restore.
9957 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9958 return EraseInstFromFunction(CI);
9959 break;
9960 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009961 }
9962
Chris Lattner8b0ea312006-01-13 20:11:04 +00009963 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009964}
9965
9966// InvokeInst simplification
9967//
9968Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009969 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009970}
9971
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009972/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9973/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009974static bool isSafeToEliminateVarargsCast(const CallSite CS,
9975 const CastInst * const CI,
9976 const TargetData * const TD,
9977 const int ix) {
9978 if (!CI->isLosslessCast())
9979 return false;
9980
9981 // The size of ByVal arguments is derived from the type, so we
9982 // can't change to a type with a different size. If the size were
9983 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009984 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009985 return true;
9986
9987 const Type* SrcTy =
9988 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9989 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9990 if (!SrcTy->isSized() || !DstTy->isSized())
9991 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009992 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009993 return false;
9994 return true;
9995}
9996
Chris Lattnera44d8a22003-10-07 22:32:43 +00009997// visitCallSite - Improvements for call and invoke instructions.
9998//
9999Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010000 bool Changed = false;
10001
10002 // If the callee is a constexpr cast of a function, attempt to move the cast
10003 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010004 if (transformConstExprCastCall(CS)) return 0;
10005
Chris Lattner6c266db2003-10-07 22:54:13 +000010006 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010007
Chris Lattner08b22ec2005-05-13 07:09:09 +000010008 if (Function *CalleeF = dyn_cast<Function>(Callee))
10009 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10010 Instruction *OldCall = CS.getInstruction();
10011 // If the call and callee calling conventions don't match, this call must
10012 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010013 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010014 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010015 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010016 // If OldCall dues not return void then replaceAllUsesWith undef.
10017 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010018 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010019 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010020 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10021 return EraseInstFromFunction(*OldCall);
10022 return 0;
10023 }
10024
Chris Lattner17be6352004-10-18 02:59:09 +000010025 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10026 // This instruction is not reachable, just remove it. We insert a store to
10027 // undef so that we know that this code is not reachable, despite the fact
10028 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010029 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010030 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +000010031 CS.getInstruction());
10032
Devang Patel228ebd02009-10-13 22:56:32 +000010033 // If CS dues not return void then replaceAllUsesWith undef.
10034 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010035 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010036 CS.getInstruction()->
10037 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010038
10039 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10040 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010041 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010042 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010043 }
Chris Lattner17be6352004-10-18 02:59:09 +000010044 return EraseInstFromFunction(*CS.getInstruction());
10045 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010046
Duncan Sandscdb6d922007-09-17 10:26:40 +000010047 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10048 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10049 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10050 return transformCallThroughTrampoline(CS);
10051
Chris Lattner6c266db2003-10-07 22:54:13 +000010052 const PointerType *PTy = cast<PointerType>(Callee->getType());
10053 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10054 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010055 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010056 // See if we can optimize any arguments passed through the varargs area of
10057 // the call.
10058 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010059 E = CS.arg_end(); I != E; ++I, ++ix) {
10060 CastInst *CI = dyn_cast<CastInst>(*I);
10061 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10062 *I = CI->getOperand(0);
10063 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010064 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010065 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010066 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010067
Duncan Sandsf0c33542007-12-19 21:13:37 +000010068 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010069 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010070 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010071 Changed = true;
10072 }
10073
Chris Lattner6c266db2003-10-07 22:54:13 +000010074 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010075}
10076
Chris Lattner9fe38862003-06-19 17:00:31 +000010077// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10078// attempt to move the cast to the arguments of the call/invoke.
10079//
10080bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10081 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10082 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010083 if (CE->getOpcode() != Instruction::BitCast ||
10084 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010085 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010086 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010087 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010088 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010089
10090 // Okay, this is a cast from a function to a different type. Unless doing so
10091 // would cause a type conversion of one of our arguments, change this call to
10092 // be a direct call with arguments casted to the appropriate types.
10093 //
10094 const FunctionType *FT = Callee->getFunctionType();
10095 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010096 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010097
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010098 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010099 return false; // TODO: Handle multiple return values.
10100
Chris Lattnerf78616b2004-01-14 06:06:08 +000010101 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010102 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010103 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010104 // Conversion is ok if changing from one pointer type to another or from
10105 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010106 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010107 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010108 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010109 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010110 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010111
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010112 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010113 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010114 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010115 return false; // Cannot transform this return value.
10116
Chris Lattner58d74912008-03-12 17:45:29 +000010117 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010118 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010119 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010120 return false; // Attribute not compatible with transformed value.
10121 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010122
Chris Lattnerf78616b2004-01-14 06:06:08 +000010123 // If the callsite is an invoke instruction, and the return value is used by
10124 // a PHI node in a successor, we cannot change the return type of the call
10125 // because there is no place to put the cast instruction (without breaking
10126 // the critical edge). Bail out in this case.
10127 if (!Caller->use_empty())
10128 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10129 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10130 UI != E; ++UI)
10131 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10132 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010133 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010134 return false;
10135 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010136
10137 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10138 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010139
Chris Lattner9fe38862003-06-19 17:00:31 +000010140 CallSite::arg_iterator AI = CS.arg_begin();
10141 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10142 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010143 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010144
10145 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010146 return false; // Cannot transform this parameter value.
10147
Devang Patel19c87462008-09-26 22:53:05 +000010148 if (CallerPAL.getParamAttributes(i + 1)
10149 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010150 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010151
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010152 // Converting from one pointer type to another or between a pointer and an
10153 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010154 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010155 (TD && ((isa<PointerType>(ParamTy) ||
10156 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10157 (isa<PointerType>(ActTy) ||
10158 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010159 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010160 }
10161
10162 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010163 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010164 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010165
Chris Lattner58d74912008-03-12 17:45:29 +000010166 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10167 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010168 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010169 // won't be dropping them. Check that these extra arguments have attributes
10170 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010171 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10172 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010173 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010174 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010175 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010176 return false;
10177 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010178
Chris Lattner9fe38862003-06-19 17:00:31 +000010179 // Okay, we decided that this is a safe thing to do: go ahead and start
10180 // inserting cast instructions as necessary...
10181 std::vector<Value*> Args;
10182 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010183 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010184 attrVec.reserve(NumCommonArgs);
10185
10186 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010187 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010188
10189 // If the return value is not being used, the type may not be compatible
10190 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010191 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010192
10193 // Add the new return attributes.
10194 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010195 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010196
10197 AI = CS.arg_begin();
10198 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10199 const Type *ParamTy = FT->getParamType(i);
10200 if ((*AI)->getType() == ParamTy) {
10201 Args.push_back(*AI);
10202 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010203 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010204 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010205 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010206 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010207
10208 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010209 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010210 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010211 }
10212
10213 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010214 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010215 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010216 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010217
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010218 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010219 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010220 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010221 errs() << "WARNING: While resolving call to function '"
10222 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010223 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010224 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010225 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10226 const Type *PTy = getPromotedType((*AI)->getType());
10227 if (PTy != (*AI)->getType()) {
10228 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010229 Instruction::CastOps opcode =
10230 CastInst::getCastOpcode(*AI, false, PTy, false);
10231 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010232 } else {
10233 Args.push_back(*AI);
10234 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010235
Duncan Sandse1e520f2008-01-13 08:02:44 +000010236 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010237 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010238 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010239 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010240 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010241 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010242
Devang Patel19c87462008-09-26 22:53:05 +000010243 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10244 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10245
Devang Patel9674d152009-10-14 17:29:00 +000010246 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010247 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010248
Eric Christophera66297a2009-07-25 02:45:27 +000010249 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10250 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010251
Chris Lattner9fe38862003-06-19 17:00:31 +000010252 Instruction *NC;
10253 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010254 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010255 Args.begin(), Args.end(),
10256 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010257 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010258 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010259 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010260 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10261 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010262 CallInst *CI = cast<CallInst>(Caller);
10263 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010264 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010265 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010266 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010267 }
10268
Chris Lattner6934a042007-02-11 01:23:03 +000010269 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010270 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010271 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000010272 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010273 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010274 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010275 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010276
10277 // If this is an invoke instruction, we should insert it after the first
10278 // non-phi, instruction in the normal successor block.
10279 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010280 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010281 InsertNewInstBefore(NC, *I);
10282 } else {
10283 // Otherwise, it's a call, just insert cast right after the call instr
10284 InsertNewInstBefore(NC, *Caller);
10285 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010286 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010287 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010288 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010289 }
10290 }
10291
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010292
Chris Lattner931f8f32009-08-31 05:17:58 +000010293 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010294 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010295
10296 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010297 return true;
10298}
10299
Duncan Sandscdb6d922007-09-17 10:26:40 +000010300// transformCallThroughTrampoline - Turn a call to a function created by the
10301// init_trampoline intrinsic into a direct call to the underlying function.
10302//
10303Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10304 Value *Callee = CS.getCalledValue();
10305 const PointerType *PTy = cast<PointerType>(Callee->getType());
10306 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010307 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010308
10309 // If the call already has the 'nest' attribute somewhere then give up -
10310 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010311 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010312 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010313
10314 IntrinsicInst *Tramp =
10315 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10316
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010317 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010318 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10319 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10320
Devang Patel05988662008-09-25 21:00:45 +000010321 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010322 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010323 unsigned NestIdx = 1;
10324 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010325 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010326
10327 // Look for a parameter marked with the 'nest' attribute.
10328 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10329 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010330 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010331 // Record the parameter type and any other attributes.
10332 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010333 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010334 break;
10335 }
10336
10337 if (NestTy) {
10338 Instruction *Caller = CS.getInstruction();
10339 std::vector<Value*> NewArgs;
10340 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10341
Devang Patel05988662008-09-25 21:00:45 +000010342 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010343 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010344
Duncan Sandscdb6d922007-09-17 10:26:40 +000010345 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010346 // mean appending it. Likewise for attributes.
10347
Devang Patel19c87462008-09-26 22:53:05 +000010348 // Add any result attributes.
10349 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010350 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010351
Duncan Sandscdb6d922007-09-17 10:26:40 +000010352 {
10353 unsigned Idx = 1;
10354 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10355 do {
10356 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010357 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010358 Value *NestVal = Tramp->getOperand(3);
10359 if (NestVal->getType() != NestTy)
10360 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10361 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010362 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010363 }
10364
10365 if (I == E)
10366 break;
10367
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010368 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010369 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010370 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010371 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010372 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010373
10374 ++Idx, ++I;
10375 } while (1);
10376 }
10377
Devang Patel19c87462008-09-26 22:53:05 +000010378 // Add any function attributes.
10379 if (Attributes Attr = Attrs.getFnAttributes())
10380 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10381
Duncan Sandscdb6d922007-09-17 10:26:40 +000010382 // The trampoline may have been bitcast to a bogus type (FTy).
10383 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010384 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010385
Duncan Sandscdb6d922007-09-17 10:26:40 +000010386 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010387 NewTypes.reserve(FTy->getNumParams()+1);
10388
Duncan Sandscdb6d922007-09-17 10:26:40 +000010389 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010390 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010391 {
10392 unsigned Idx = 1;
10393 FunctionType::param_iterator I = FTy->param_begin(),
10394 E = FTy->param_end();
10395
10396 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010397 if (Idx == NestIdx)
10398 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010399 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010400
10401 if (I == E)
10402 break;
10403
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010404 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010405 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010406
10407 ++Idx, ++I;
10408 } while (1);
10409 }
10410
10411 // Replace the trampoline call with a direct call. Let the generic
10412 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010413 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010414 FTy->isVarArg());
10415 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010416 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010417 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010418 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010419 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10420 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010421
10422 Instruction *NewCaller;
10423 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010424 NewCaller = InvokeInst::Create(NewCallee,
10425 II->getNormalDest(), II->getUnwindDest(),
10426 NewArgs.begin(), NewArgs.end(),
10427 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010428 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010429 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010430 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010431 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10432 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010433 if (cast<CallInst>(Caller)->isTailCall())
10434 cast<CallInst>(NewCaller)->setTailCall();
10435 cast<CallInst>(NewCaller)->
10436 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010437 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010438 }
Devang Patel9674d152009-10-14 17:29:00 +000010439 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010440 Caller->replaceAllUsesWith(NewCaller);
10441 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010442 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010443 return 0;
10444 }
10445 }
10446
10447 // Replace the trampoline call with a direct call. Since there is no 'nest'
10448 // parameter, there is no need to adjust the argument list. Let the generic
10449 // code sort out any function type mismatches.
10450 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010451 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010452 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010453 CS.setCalledFunction(NewCallee);
10454 return CS.getInstruction();
10455}
10456
Dan Gohman9ad29202009-09-16 16:50:24 +000010457/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10458/// and if a/b/c and the add's all have a single use, turn this into a phi
Chris Lattner7da52b22006-11-01 04:51:18 +000010459/// and a single binop.
10460Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10461 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010462 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010463 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010464 Value *LHSVal = FirstInst->getOperand(0);
10465 Value *RHSVal = FirstInst->getOperand(1);
10466
10467 const Type *LHSType = LHSVal->getType();
10468 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010469
Dan Gohman9ad29202009-09-16 16:50:24 +000010470 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010471 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010472 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010473 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010474 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010475 // types or GEP's with different index types.
10476 I->getOperand(0)->getType() != LHSType ||
10477 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010478 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010479
10480 // If they are CmpInst instructions, check their predicates
10481 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10482 if (cast<CmpInst>(I)->getPredicate() !=
10483 cast<CmpInst>(FirstInst)->getPredicate())
10484 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010485
10486 // Keep track of which operand needs a phi node.
10487 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10488 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010489 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010490
10491 // If both LHS and RHS would need a PHI, don't do this transformation,
10492 // because it would increase the number of PHIs entering the block,
10493 // which leads to higher register pressure. This is especially
10494 // bad when the PHIs are in the header of a loop.
10495 if (!LHSVal && !RHSVal)
10496 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010497
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010498 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010499
Chris Lattner7da52b22006-11-01 04:51:18 +000010500 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010501 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010502 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010503 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010504 NewLHS = PHINode::Create(LHSType,
10505 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010506 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10507 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010508 InsertNewInstBefore(NewLHS, PN);
10509 LHSVal = NewLHS;
10510 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010511
10512 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010513 NewRHS = PHINode::Create(RHSType,
10514 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010515 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10516 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010517 InsertNewInstBefore(NewRHS, PN);
10518 RHSVal = NewRHS;
10519 }
10520
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010521 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010522 if (NewLHS || NewRHS) {
10523 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10524 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10525 if (NewLHS) {
10526 Value *NewInLHS = InInst->getOperand(0);
10527 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10528 }
10529 if (NewRHS) {
10530 Value *NewInRHS = InInst->getOperand(1);
10531 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10532 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010533 }
10534 }
10535
Chris Lattner7da52b22006-11-01 04:51:18 +000010536 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010537 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010538 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010539 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010540 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010541}
10542
Chris Lattner05f18922008-12-01 02:34:36 +000010543Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10544 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10545
10546 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10547 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010548 // This is true if all GEP bases are allocas and if all indices into them are
10549 // constants.
10550 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010551
10552 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010553 // more than one phi, which leads to higher register pressure. This is
10554 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010555 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010556
Dan Gohman9ad29202009-09-16 16:50:24 +000010557 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010558 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10559 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10560 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10561 GEP->getNumOperands() != FirstInst->getNumOperands())
10562 return 0;
10563
Chris Lattner36d3e322009-02-21 00:46:50 +000010564 // Keep track of whether or not all GEPs are of alloca pointers.
10565 if (AllBasePointersAreAllocas &&
10566 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10567 !GEP->hasAllConstantIndices()))
10568 AllBasePointersAreAllocas = false;
10569
Chris Lattner05f18922008-12-01 02:34:36 +000010570 // Compare the operand lists.
10571 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10572 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10573 continue;
10574
10575 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10576 // if one of the PHIs has a constant for the index. The index may be
10577 // substantially cheaper to compute for the constants, so making it a
10578 // variable index could pessimize the path. This also handles the case
10579 // for struct indices, which must always be constant.
10580 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10581 isa<ConstantInt>(GEP->getOperand(op)))
10582 return 0;
10583
10584 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10585 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010586
10587 // If we already needed a PHI for an earlier operand, and another operand
10588 // also requires a PHI, we'd be introducing more PHIs than we're
10589 // eliminating, which increases register pressure on entry to the PHI's
10590 // block.
10591 if (NeededPhi)
10592 return 0;
10593
Chris Lattner05f18922008-12-01 02:34:36 +000010594 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010595 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010596 }
10597 }
10598
Chris Lattner36d3e322009-02-21 00:46:50 +000010599 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010600 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010601 // offset calculation, but all the predecessors will have to materialize the
10602 // stack address into a register anyway. We'd actually rather *clone* the
10603 // load up into the predecessors so that we have a load of a gep of an alloca,
10604 // which can usually all be folded into the load.
10605 if (AllBasePointersAreAllocas)
10606 return 0;
10607
Chris Lattner05f18922008-12-01 02:34:36 +000010608 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10609 // that is variable.
10610 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10611
10612 bool HasAnyPHIs = false;
10613 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10614 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10615 Value *FirstOp = FirstInst->getOperand(i);
10616 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10617 FirstOp->getName()+".pn");
10618 InsertNewInstBefore(NewPN, PN);
10619
10620 NewPN->reserveOperandSpace(e);
10621 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10622 OperandPhis[i] = NewPN;
10623 FixedOperands[i] = NewPN;
10624 HasAnyPHIs = true;
10625 }
10626
10627
10628 // Add all operands to the new PHIs.
10629 if (HasAnyPHIs) {
10630 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10631 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10632 BasicBlock *InBB = PN.getIncomingBlock(i);
10633
10634 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10635 if (PHINode *OpPhi = OperandPhis[op])
10636 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10637 }
10638 }
10639
10640 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010641 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10642 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10643 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010644 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10645 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010646}
10647
10648
Chris Lattner21550882009-02-23 05:56:17 +000010649/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10650/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010651/// obvious the value of the load is not changed from the point of the load to
10652/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010653///
10654/// Finally, it is safe, but not profitable, to sink a load targetting a
10655/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10656/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010657static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010658 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10659
10660 for (++BBI; BBI != E; ++BBI)
10661 if (BBI->mayWriteToMemory())
10662 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010663
10664 // Check for non-address taken alloca. If not address-taken already, it isn't
10665 // profitable to do this xform.
10666 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10667 bool isAddressTaken = false;
10668 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10669 UI != E; ++UI) {
10670 if (isa<LoadInst>(UI)) continue;
10671 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10672 // If storing TO the alloca, then the address isn't taken.
10673 if (SI->getOperand(1) == AI) continue;
10674 }
10675 isAddressTaken = true;
10676 break;
10677 }
10678
Chris Lattner36d3e322009-02-21 00:46:50 +000010679 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010680 return false;
10681 }
10682
Chris Lattner36d3e322009-02-21 00:46:50 +000010683 // If this load is a load from a GEP with a constant offset from an alloca,
10684 // then we don't want to sink it. In its present form, it will be
10685 // load [constant stack offset]. Sinking it will cause us to have to
10686 // materialize the stack addresses in each predecessor in a register only to
10687 // do a shared load from register in the successor.
10688 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10689 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10690 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10691 return false;
10692
Chris Lattner76c73142006-11-01 07:13:54 +000010693 return true;
10694}
10695
Chris Lattner751a3622009-11-01 20:04:24 +000010696Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10697 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10698
10699 // When processing loads, we need to propagate two bits of information to the
10700 // sunk load: whether it is volatile, and what its alignment is. We currently
10701 // don't sink loads when some have their alignment specified and some don't.
10702 // visitLoadInst will propagate an alignment onto the load when TD is around,
10703 // and if TD isn't around, we can't handle the mixed case.
10704 bool isVolatile = FirstLI->isVolatile();
10705 unsigned LoadAlignment = FirstLI->getAlignment();
10706
10707 // We can't sink the load if the loaded value could be modified between the
10708 // load and the PHI.
10709 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
10710 !isSafeAndProfitableToSinkLoad(FirstLI))
10711 return 0;
10712
10713 // If the PHI is of volatile loads and the load block has multiple
10714 // successors, sinking it would remove a load of the volatile value from
10715 // the path through the other successor.
10716 if (isVolatile &&
10717 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
10718 return 0;
10719
10720 // Check to see if all arguments are the same operation.
10721 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10722 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
10723 if (!LI || !LI->hasOneUse())
10724 return 0;
10725
10726 // We can't sink the load if the loaded value could be modified between
10727 // the load and the PHI.
10728 if (LI->isVolatile() != isVolatile ||
10729 LI->getParent() != PN.getIncomingBlock(i) ||
10730 !isSafeAndProfitableToSinkLoad(LI))
10731 return 0;
10732
10733 // If some of the loads have an alignment specified but not all of them,
10734 // we can't do the transformation.
10735 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
10736 return 0;
10737
Chris Lattnera664bb72009-11-01 20:07:07 +000010738 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +000010739
10740 // If the PHI is of volatile loads and the load block has multiple
10741 // successors, sinking it would remove a load of the volatile value from
10742 // the path through the other successor.
10743 if (isVolatile &&
10744 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10745 return 0;
10746 }
10747
10748 // Okay, they are all the same operation. Create a new PHI node of the
10749 // correct type, and PHI together all of the LHS's of the instructions.
10750 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
10751 PN.getName()+".in");
10752 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10753
10754 Value *InVal = FirstLI->getOperand(0);
10755 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10756
10757 // Add all operands to the new PHI.
10758 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10759 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
10760 if (NewInVal != InVal)
10761 InVal = 0;
10762 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10763 }
10764
10765 Value *PhiVal;
10766 if (InVal) {
10767 // The new PHI unions all of the same values together. This is really
10768 // common, so we handle it intelligently here for compile-time speed.
10769 PhiVal = InVal;
10770 delete NewPN;
10771 } else {
10772 InsertNewInstBefore(NewPN, PN);
10773 PhiVal = NewPN;
10774 }
10775
10776 // If this was a volatile load that we are merging, make sure to loop through
10777 // and mark all the input loads as non-volatile. If we don't do this, we will
10778 // insert a new volatile load and the old ones will not be deletable.
10779 if (isVolatile)
10780 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10781 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10782
10783 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
10784}
10785
Chris Lattner9fe38862003-06-19 17:00:31 +000010786
Chris Lattnerbac32862004-11-14 19:13:23 +000010787// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10788// operator and they all are only used by the PHI, PHI together their
10789// inputs, and do the operation once, to the result of the PHI.
10790Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10791 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10792
Chris Lattner751a3622009-11-01 20:04:24 +000010793 if (isa<GetElementPtrInst>(FirstInst))
10794 return FoldPHIArgGEPIntoPHI(PN);
10795 if (isa<LoadInst>(FirstInst))
10796 return FoldPHIArgLoadIntoPHI(PN);
10797
Chris Lattnerbac32862004-11-14 19:13:23 +000010798 // Scan the instruction, looking for input operations that can be folded away.
10799 // If all input operands to the phi are the same instruction (e.g. a cast from
10800 // the same type or "+42") we can pull the operation through the PHI, reducing
10801 // code size and simplifying code.
10802 Constant *ConstantOp = 0;
10803 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +000010804
Chris Lattnerbac32862004-11-14 19:13:23 +000010805 if (isa<CastInst>(FirstInst)) {
10806 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattnerbf382b52009-11-08 21:20:06 +000010807
10808 // Be careful about transforming integer PHIs. We don't want to pessimize
10809 // the code by turning an i32 into an i1293.
10810 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
10811 // If we don't have TD, we don't know if the original PHI was legal.
10812 if (!TD) return 0;
10813
10814 unsigned PHIWidth = PN.getType()->getPrimitiveSizeInBits();
10815 unsigned NewWidth = CastSrcTy->getPrimitiveSizeInBits();
10816 bool PHILegal = TD->isLegalInteger(PHIWidth);
10817 bool NewLegal = TD->isLegalInteger(NewWidth);
Chris Lattner9956c052009-11-08 19:23:30 +000010818
Chris Lattnerbf382b52009-11-08 21:20:06 +000010819 // If this is a legal integer PHI node, and pulling the operation through
10820 // would cause it to be an illegal integer PHI, don't do the
10821 // transformation.
10822 if (PHILegal && !NewLegal)
10823 return 0;
10824
10825 // Otherwise, if both are illegal, do not increase the size of the PHI. We
10826 // do allow things like i160 -> i64, but not i64 -> i160.
10827 if (!PHILegal && !NewLegal && NewWidth > PHIWidth)
10828 return 0;
10829 }
Reid Spencer832254e2007-02-02 02:16:23 +000010830 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010831 // Can fold binop, compare or shift here if the RHS is a constant,
10832 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010833 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010834 if (ConstantOp == 0)
10835 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010836 } else {
10837 return 0; // Cannot fold this operation.
10838 }
10839
10840 // Check to see if all arguments are the same operation.
10841 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +000010842 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10843 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010844 return 0;
10845 if (CastSrcTy) {
10846 if (I->getOperand(0)->getType() != CastSrcTy)
10847 return 0; // Cast operation must match.
10848 } else if (I->getOperand(1) != ConstantOp) {
10849 return 0;
10850 }
10851 }
10852
10853 // Okay, they are all the same operation. Create a new PHI node of the
10854 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010855 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10856 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010857 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010858
10859 Value *InVal = FirstInst->getOperand(0);
10860 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010861
10862 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010863 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10864 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10865 if (NewInVal != InVal)
10866 InVal = 0;
10867 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10868 }
10869
10870 Value *PhiVal;
10871 if (InVal) {
10872 // The new PHI unions all of the same values together. This is really
10873 // common, so we handle it intelligently here for compile-time speed.
10874 PhiVal = InVal;
10875 delete NewPN;
10876 } else {
10877 InsertNewInstBefore(NewPN, PN);
10878 PhiVal = NewPN;
10879 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010880
Chris Lattnerbac32862004-11-14 19:13:23 +000010881 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +000010882 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010883 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +000010884
Chris Lattner54545ac2008-04-29 17:13:43 +000010885 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010886 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +000010887
Chris Lattner751a3622009-11-01 20:04:24 +000010888 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10889 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10890 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +000010891}
Chris Lattnera1be5662002-05-02 17:06:02 +000010892
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010893/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10894/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010895static bool DeadPHICycle(PHINode *PN,
10896 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010897 if (PN->use_empty()) return true;
10898 if (!PN->hasOneUse()) return false;
10899
10900 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010901 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010902 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010903
10904 // Don't scan crazily complex things.
10905 if (PotentiallyDeadPHIs.size() == 16)
10906 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010907
10908 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10909 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010910
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010911 return false;
10912}
10913
Chris Lattnercf5008a2007-11-06 21:52:06 +000010914/// PHIsEqualValue - Return true if this phi node is always equal to
10915/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10916/// z = some value; x = phi (y, z); y = phi (x, z)
10917static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10918 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10919 // See if we already saw this PHI node.
10920 if (!ValueEqualPHIs.insert(PN))
10921 return true;
10922
10923 // Don't scan crazily complex things.
10924 if (ValueEqualPHIs.size() == 16)
10925 return false;
10926
10927 // Scan the operands to see if they are either phi nodes or are equal to
10928 // the value.
10929 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10930 Value *Op = PN->getIncomingValue(i);
10931 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10932 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10933 return false;
10934 } else if (Op != NonPhiInVal)
10935 return false;
10936 }
10937
10938 return true;
10939}
10940
10941
Chris Lattner9956c052009-11-08 19:23:30 +000010942namespace {
10943struct PHIUsageRecord {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010944 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner9956c052009-11-08 19:23:30 +000010945 unsigned Shift; // The amount shifted.
10946 Instruction *Inst; // The trunc instruction.
10947
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010948 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
10949 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner9956c052009-11-08 19:23:30 +000010950
10951 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010952 if (PHIId < RHS.PHIId) return true;
10953 if (PHIId > RHS.PHIId) return false;
Chris Lattner9956c052009-11-08 19:23:30 +000010954 if (Shift < RHS.Shift) return true;
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010955 if (Shift > RHS.Shift) return false;
10956 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner9956c052009-11-08 19:23:30 +000010957 RHS.Inst->getType()->getPrimitiveSizeInBits();
10958 }
10959};
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000010960
10961struct LoweredPHIRecord {
10962 PHINode *PN; // The PHI that was lowered.
10963 unsigned Shift; // The amount shifted.
10964 unsigned Width; // The width extracted.
10965
10966 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
10967 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
10968
10969 // Ctor form used by DenseMap.
10970 LoweredPHIRecord(PHINode *pn, unsigned Sh)
10971 : PN(pn), Shift(Sh), Width(0) {}
10972};
10973}
10974
10975namespace llvm {
10976 template<>
10977 struct DenseMapInfo<LoweredPHIRecord> {
10978 static inline LoweredPHIRecord getEmptyKey() {
10979 return LoweredPHIRecord(0, 0);
10980 }
10981 static inline LoweredPHIRecord getTombstoneKey() {
10982 return LoweredPHIRecord(0, 1);
10983 }
10984 static unsigned getHashValue(const LoweredPHIRecord &Val) {
10985 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
10986 (Val.Width>>3);
10987 }
10988 static bool isEqual(const LoweredPHIRecord &LHS,
10989 const LoweredPHIRecord &RHS) {
10990 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
10991 LHS.Width == RHS.Width;
10992 }
10993 static bool isPod() { return true; }
10994 };
Chris Lattner9956c052009-11-08 19:23:30 +000010995}
10996
10997
10998/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
10999/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11000/// so, we split the PHI into the various pieces being extracted. This sort of
11001/// thing is introduced when SROA promotes an aggregate to large integer values.
11002///
11003/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11004/// inttoptr. We should produce new PHIs in the right type.
11005///
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011006Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11007 // PHIUsers - Keep track of all of the truncated values extracted from a set
11008 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner9956c052009-11-08 19:23:30 +000011009 SmallVector<PHIUsageRecord, 16> PHIUsers;
11010
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011011 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11012 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11013 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11014 // check the uses of (to ensure they are all extracts).
11015 SmallVector<PHINode*, 8> PHIsToSlice;
11016 SmallPtrSet<PHINode*, 8> PHIsInspected;
11017
11018 PHIsToSlice.push_back(&FirstPhi);
11019 PHIsInspected.insert(&FirstPhi);
11020
11021 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11022 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011023
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011024 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11025 UI != E; ++UI) {
11026 Instruction *User = cast<Instruction>(*UI);
11027
11028 // If the user is a PHI, inspect its uses recursively.
11029 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11030 if (PHIsInspected.insert(UserPN))
11031 PHIsToSlice.push_back(UserPN);
11032 continue;
11033 }
11034
11035 // Truncates are always ok.
11036 if (isa<TruncInst>(User)) {
11037 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11038 continue;
11039 }
11040
11041 // Otherwise it must be a lshr which can only be used by one trunc.
11042 if (User->getOpcode() != Instruction::LShr ||
11043 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11044 !isa<ConstantInt>(User->getOperand(1)))
11045 return 0;
11046
11047 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11048 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner9956c052009-11-08 19:23:30 +000011049 }
Chris Lattner9956c052009-11-08 19:23:30 +000011050 }
11051
11052 // If we have no users, they must be all self uses, just nuke the PHI.
11053 if (PHIUsers.empty())
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011054 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner9956c052009-11-08 19:23:30 +000011055
11056 // If this phi node is transformable, create new PHIs for all the pieces
11057 // extracted out of it. First, sort the users by their offset and size.
11058 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11059
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011060 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11061 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11062 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11063 );
Chris Lattner9956c052009-11-08 19:23:30 +000011064
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011065 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11066 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner9956c052009-11-08 19:23:30 +000011067 DenseMap<BasicBlock*, Value*> PredValues;
11068
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011069 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11070 // introduce redundant PHIs.
11071 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11072
11073 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11074 unsigned PHIId = PHIUsers[UserI].PHIId;
11075 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011076 unsigned Offset = PHIUsers[UserI].Shift;
11077 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner9956c052009-11-08 19:23:30 +000011078
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011079 PHINode *EltPHI;
11080
11081 // If we've already lowered a user like this, reuse the previously lowered
11082 // value.
11083 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner9956c052009-11-08 19:23:30 +000011084
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011085 // Otherwise, Create the new PHI node for this user.
11086 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11087 assert(EltPHI->getType() != PN->getType() &&
11088 "Truncate didn't shrink phi?");
11089
11090 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11091 BasicBlock *Pred = PN->getIncomingBlock(i);
11092 Value *&PredVal = PredValues[Pred];
11093
11094 // If we already have a value for this predecessor, reuse it.
11095 if (PredVal) {
11096 EltPHI->addIncoming(PredVal, Pred);
11097 continue;
11098 }
Chris Lattner9956c052009-11-08 19:23:30 +000011099
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011100 // Handle the PHI self-reuse case.
11101 Value *InVal = PN->getIncomingValue(i);
11102 if (InVal == PN) {
11103 PredVal = EltPHI;
11104 EltPHI->addIncoming(PredVal, Pred);
11105 continue;
11106 } else if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
11107 // If the incoming value was a PHI, and if it was one of the PHIs we
11108 // already rewrote it, just use the lowered value.
11109 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11110 PredVal = Res;
11111 EltPHI->addIncoming(PredVal, Pred);
11112 continue;
11113 }
11114 }
11115
11116 // Otherwise, do an extract in the predecessor.
11117 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11118 Value *Res = InVal;
11119 if (Offset)
11120 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11121 Offset), "extract");
11122 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11123 PredVal = Res;
11124 EltPHI->addIncoming(Res, Pred);
11125
11126 // If the incoming value was a PHI, and if it was one of the PHIs we are
11127 // rewriting, we will ultimately delete the code we inserted. This
11128 // means we need to revisit that PHI to make sure we extract out the
11129 // needed piece.
11130 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11131 if (PHIsInspected.count(OldInVal)) {
11132 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11133 OldInVal)-PHIsToSlice.begin();
11134 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11135 cast<Instruction>(Res)));
11136 ++UserE;
11137 }
Chris Lattner9956c052009-11-08 19:23:30 +000011138 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011139 PredValues.clear();
Chris Lattner9956c052009-11-08 19:23:30 +000011140
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011141 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11142 << *EltPHI << '\n');
11143 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner9956c052009-11-08 19:23:30 +000011144 }
Chris Lattner9956c052009-11-08 19:23:30 +000011145
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011146 // Replace the use of this piece with the PHI node.
11147 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner9956c052009-11-08 19:23:30 +000011148 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011149
11150 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11151 // with undefs.
11152 Value *Undef = UndefValue::get(FirstPhi.getType());
11153 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11154 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11155 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner9956c052009-11-08 19:23:30 +000011156}
11157
Chris Lattner473945d2002-05-06 18:06:38 +000011158// PHINode simplification
11159//
Chris Lattner7e708292002-06-25 16:13:24 +000011160Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000011161 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000011162 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000011163
Owen Anderson7e057142006-07-10 22:03:18 +000011164 if (Value *V = PN.hasConstantValue())
11165 return ReplaceInstUsesWith(PN, V);
11166
Owen Anderson7e057142006-07-10 22:03:18 +000011167 // If all PHI operands are the same operation, pull them through the PHI,
11168 // reducing code size.
11169 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000011170 isa<Instruction>(PN.getIncomingValue(1)) &&
11171 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11172 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11173 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11174 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000011175 PN.getIncomingValue(0)->hasOneUse())
11176 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11177 return Result;
11178
11179 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11180 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11181 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011182 if (PN.hasOneUse()) {
11183 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11184 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000011185 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000011186 PotentiallyDeadPHIs.insert(&PN);
11187 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011188 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000011189 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011190
11191 // If this phi has a single use, and if that use just computes a value for
11192 // the next iteration of a loop, delete the phi. This occurs with unused
11193 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11194 // common case here is good because the only other things that catch this
11195 // are induction variable analysis (sometimes) and ADCE, which is only run
11196 // late.
11197 if (PHIUser->hasOneUse() &&
11198 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11199 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011200 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011201 }
11202 }
Owen Anderson7e057142006-07-10 22:03:18 +000011203
Chris Lattnercf5008a2007-11-06 21:52:06 +000011204 // We sometimes end up with phi cycles that non-obviously end up being the
11205 // same value, for example:
11206 // z = some value; x = phi (y, z); y = phi (x, z)
11207 // where the phi nodes don't necessarily need to be in the same block. Do a
11208 // quick check to see if the PHI node only contains a single non-phi value, if
11209 // so, scan to see if the phi cycle is actually equal to that value.
11210 {
11211 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11212 // Scan for the first non-phi operand.
11213 while (InValNo != NumOperandVals &&
11214 isa<PHINode>(PN.getIncomingValue(InValNo)))
11215 ++InValNo;
11216
11217 if (InValNo != NumOperandVals) {
11218 Value *NonPhiInVal = PN.getOperand(InValNo);
11219
11220 // Scan the rest of the operands to see if there are any conflicts, if so
11221 // there is no need to recursively scan other phis.
11222 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11223 Value *OpVal = PN.getIncomingValue(InValNo);
11224 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11225 break;
11226 }
11227
11228 // If we scanned over all operands, then we have one unique value plus
11229 // phi values. Scan PHI nodes to see if they all merge in each other or
11230 // the value.
11231 if (InValNo == NumOperandVals) {
11232 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11233 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11234 return ReplaceInstUsesWith(PN, NonPhiInVal);
11235 }
11236 }
11237 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011238
Dan Gohman5b097012009-10-31 14:22:52 +000011239 // If there are multiple PHIs, sort their operands so that they all list
11240 // the blocks in the same order. This will help identical PHIs be eliminated
11241 // by other passes. Other passes shouldn't depend on this for correctness
11242 // however.
11243 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11244 if (&PN != FirstPN)
11245 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011246 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +000011247 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11248 if (BBA != BBB) {
11249 Value *VA = PN.getIncomingValue(i);
11250 unsigned j = PN.getBasicBlockIndex(BBB);
11251 Value *VB = PN.getIncomingValue(j);
11252 PN.setIncomingBlock(i, BBB);
11253 PN.setIncomingValue(i, VB);
11254 PN.setIncomingBlock(j, BBA);
11255 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +000011256 // NOTE: Instcombine normally would want us to "return &PN" if we
11257 // modified any of the operands of an instruction. However, since we
11258 // aren't adding or removing uses (just rearranging them) we don't do
11259 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +000011260 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011261 }
11262
Chris Lattner9956c052009-11-08 19:23:30 +000011263 // If this is an integer PHI and we know that it has an illegal type, see if
11264 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11265 // PHI into the various pieces being extracted. This sort of thing is
11266 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattnerbf382b52009-11-08 21:20:06 +000011267 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner9956c052009-11-08 19:23:30 +000011268 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11269 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11270 return Res;
11271
Chris Lattner60921c92003-12-19 05:58:40 +000011272 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000011273}
11274
Chris Lattner7e708292002-06-25 16:13:24 +000011275Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000011276 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000011277 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011278 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000011279 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011280
Chris Lattnere87597f2004-10-16 18:11:37 +000011281 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011282 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011283
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011284 bool HasZeroPointerIndex = false;
11285 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11286 HasZeroPointerIndex = C->isNullValue();
11287
11288 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000011289 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000011290
Chris Lattner28977af2004-04-05 01:30:19 +000011291 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000011292 if (TD) {
11293 bool MadeChange = false;
11294 unsigned PtrSize = TD->getPointerSizeInBits();
11295
11296 gep_type_iterator GTI = gep_type_begin(GEP);
11297 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11298 I != E; ++I, ++GTI) {
11299 if (!isa<SequentialType>(*GTI)) continue;
11300
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011301 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011302 // to what we need. If narrower, sign-extend it to what we need. This
11303 // explicit cast can make subsequent optimizations more obvious.
11304 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000011305 if (OpBits == PtrSize)
11306 continue;
11307
Chris Lattner2345d1d2009-08-30 20:01:10 +000011308 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011309 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011310 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011311 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011312 }
Chris Lattner28977af2004-04-05 01:30:19 +000011313
Chris Lattner90ac28c2002-08-02 19:29:35 +000011314 // Combine Indices - If the source pointer to this getelementptr instruction
11315 // is a getelementptr instruction, combine the indices of the two
11316 // getelementptr instructions into a single instruction.
11317 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011318 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011319 // Note that if our source is a gep chain itself that we wait for that
11320 // chain to be resolved before we perform this transformation. This
11321 // avoids us creating a TON of code in some cases.
11322 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011323 if (GetElementPtrInst *SrcGEP =
11324 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11325 if (SrcGEP->getNumOperands() == 2)
11326 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000011327
Chris Lattner72588fc2007-02-15 22:48:32 +000011328 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000011329
11330 // Find out whether the last index in the source GEP is a sequential idx.
11331 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000011332 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11333 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000011334 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011335
Chris Lattner90ac28c2002-08-02 19:29:35 +000011336 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000011337 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000011338 // Replace: gep (gep %P, long B), long A, ...
11339 // With: T = long A+B; gep %P, T, ...
11340 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011341 Value *Sum;
11342 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11343 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000011344 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011345 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000011346 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000011347 Sum = SO1;
11348 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000011349 // If they aren't the same type, then the input hasn't been processed
11350 // by the loop above yet (which canonicalizes sequential index types to
11351 // intptr_t). Just avoid transforming this until the input has been
11352 // normalized.
11353 if (SO1->getType() != GO1->getType())
11354 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011355 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000011356 }
Chris Lattner620ce142004-05-07 22:09:22 +000011357
Chris Lattnerab984842009-08-30 05:30:55 +000011358 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011359 if (Src->getNumOperands() == 2) {
11360 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000011361 GEP.setOperand(1, Sum);
11362 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000011363 }
Chris Lattnerab984842009-08-30 05:30:55 +000011364 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011365 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000011366 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000011367 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000011368 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011369 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000011370 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000011371 Indices.append(Src->op_begin()+1, Src->op_end());
11372 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000011373 }
11374
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011375 if (!Indices.empty())
11376 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11377 Src->isInBounds()) ?
11378 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11379 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011380 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000011381 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000011382 }
11383
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000011384 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11385 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000011386 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000011387
Chris Lattner2de23192009-08-30 20:38:21 +000011388 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11389 // want to change the gep until the bitcasts are eliminated.
11390 if (getBitCastOperand(X)) {
11391 Worklist.AddValue(PtrOp);
11392 return 0;
11393 }
11394
Chris Lattner963f4ba2009-08-30 20:36:46 +000011395 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11396 // into : GEP [10 x i8]* X, i32 0, ...
11397 //
11398 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11399 // into : GEP i8* X, ...
11400 //
11401 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011402 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011403 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11404 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011405 if (const ArrayType *CATy =
11406 dyn_cast<ArrayType>(CPTy->getElementType())) {
11407 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11408 if (CATy->getElementType() == XTy->getElementType()) {
11409 // -> GEP i8* X, ...
11410 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011411 return cast<GEPOperator>(&GEP)->isInBounds() ?
11412 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11413 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011414 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11415 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011416 }
11417
11418 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011419 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011420 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011421 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011422 // At this point, we know that the cast source type is a pointer
11423 // to an array of the same type as the destination pointer
11424 // array. Because the array type is never stepped over (there
11425 // is a leading zero) we can fold the cast into this GEP.
11426 GEP.setOperand(0, X);
11427 return &GEP;
11428 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011429 }
11430 }
Chris Lattnereed48272005-09-13 00:40:14 +000011431 } else if (GEP.getNumOperands() == 2) {
11432 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011433 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11434 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011435 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11436 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011437 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011438 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11439 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011440 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011441 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011442 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011443 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11444 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011445 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011446 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011447 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011448 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011449
11450 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011451 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011452 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011453 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011454
Owen Anderson1d0be152009-08-13 21:58:54 +000011455 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011456 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011457 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011458
11459 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11460 // allow either a mul, shift, or constant here.
11461 Value *NewIdx = 0;
11462 ConstantInt *Scale = 0;
11463 if (ArrayEltSize == 1) {
11464 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011465 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011466 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011467 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011468 Scale = CI;
11469 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11470 if (Inst->getOpcode() == Instruction::Shl &&
11471 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011472 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11473 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011474 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011475 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011476 NewIdx = Inst->getOperand(0);
11477 } else if (Inst->getOpcode() == Instruction::Mul &&
11478 isa<ConstantInt>(Inst->getOperand(1))) {
11479 Scale = cast<ConstantInt>(Inst->getOperand(1));
11480 NewIdx = Inst->getOperand(0);
11481 }
11482 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011483
Chris Lattner7835cdd2005-09-13 18:36:04 +000011484 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011485 // out, perform the transformation. Note, we don't know whether Scale is
11486 // signed or not. We'll use unsigned version of division/modulo
11487 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011488 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011489 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011490 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011491 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011492 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011493 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11494 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011495 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011496 }
11497
11498 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011499 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011500 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011501 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011502 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11503 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11504 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011505 // The NewGEP must be pointer typed, so must the old one -> BitCast
11506 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011507 }
11508 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011509 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011510 }
Chris Lattner58407792009-01-09 04:53:57 +000011511
Chris Lattner46cd5a12009-01-09 05:44:56 +000011512 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011513 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011514 /// Y = gep X, <...constant indices...>
11515 /// into a gep of the original struct. This is important for SROA and alias
11516 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011517 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011518 if (TD &&
11519 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011520 // Determine how much the GEP moves the pointer. We are guaranteed to get
11521 // a constant back from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +000011522 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011523 int64_t Offset = OffsetV->getSExtValue();
11524
11525 // If this GEP instruction doesn't move the pointer, just replace the GEP
11526 // with a bitcast of the real input to the dest type.
11527 if (Offset == 0) {
11528 // If the bitcast is of an allocation, and the allocation will be
11529 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000011530 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000011531 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011532 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11533 if (Instruction *I = visitBitCast(*BCI)) {
11534 if (I != BCI) {
11535 I->takeName(BCI);
11536 BCI->getParent()->getInstList().insert(BCI, I);
11537 ReplaceInstUsesWith(*BCI, I);
11538 }
11539 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011540 }
Chris Lattner58407792009-01-09 04:53:57 +000011541 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011542 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011543 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011544
11545 // Otherwise, if the offset is non-zero, we need to find out if there is a
11546 // field at Offset in 'A's type. If so, we can pull the cast through the
11547 // GEP.
11548 SmallVector<Value*, 8> NewIndices;
11549 const Type *InTy =
11550 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011551 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011552 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11553 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11554 NewIndices.end()) :
11555 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11556 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011557
11558 if (NGEP->getType() == GEP.getType())
11559 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011560 NGEP->takeName(&GEP);
11561 return new BitCastInst(NGEP, GEP.getType());
11562 }
Chris Lattner58407792009-01-09 04:53:57 +000011563 }
11564 }
11565
Chris Lattner8a2a3112001-12-14 16:52:21 +000011566 return 0;
11567}
11568
Victor Hernandez7b929da2009-10-23 21:09:37 +000011569Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +000011570 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011571 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011572 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11573 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011574 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000011575 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000011576 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011577 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011578
Chris Lattner0864acf2002-11-04 16:18:53 +000011579 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011580 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011581 //
11582 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000011583 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011584
11585 // Now that I is pointing to the first non-allocation-inst in the block,
11586 // insert our getelementptr instruction...
11587 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011588 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011589 Value *Idx[2];
11590 Idx[0] = NullIdx;
11591 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011592 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11593 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011594
11595 // Now make everything use the getelementptr instead of the original
11596 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011597 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011598 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011599 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011600 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011601 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011602
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011603 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011604 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011605 // Note that we only do this for alloca's, because malloc should allocate
11606 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011607 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011608 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011609
11610 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11611 if (AI.getAlignment() == 0)
11612 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11613 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011614
Chris Lattner0864acf2002-11-04 16:18:53 +000011615 return 0;
11616}
11617
Victor Hernandez66284e02009-10-24 04:23:03 +000011618Instruction *InstCombiner::visitFree(Instruction &FI) {
11619 Value *Op = FI.getOperand(1);
11620
11621 // free undef -> unreachable.
11622 if (isa<UndefValue>(Op)) {
11623 // Insert a new store to null because we cannot modify the CFG here.
11624 new StoreInst(ConstantInt::getTrue(*Context),
11625 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11626 return EraseInstFromFunction(FI);
11627 }
11628
11629 // If we have 'free null' delete the instruction. This can happen in stl code
11630 // when lots of inlining happens.
11631 if (isa<ConstantPointerNull>(Op))
11632 return EraseInstFromFunction(FI);
11633
Victor Hernandez046e78c2009-10-26 23:43:48 +000011634 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000011635 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000011636 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11637 if (Op->hasOneUse() && CI->hasOneUse()) {
11638 EraseInstFromFunction(FI);
11639 EraseInstFromFunction(*CI);
11640 return EraseInstFromFunction(*cast<Instruction>(Op));
11641 }
11642 } else {
11643 // Op is a call to malloc
11644 if (Op->hasOneUse()) {
11645 EraseInstFromFunction(FI);
11646 return EraseInstFromFunction(*cast<Instruction>(Op));
11647 }
11648 }
Dan Gohman7f712a12009-10-27 00:11:02 +000011649 }
Victor Hernandez66284e02009-10-24 04:23:03 +000011650
11651 return 0;
11652}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011653
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011654/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011655static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011656 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011657 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011658 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011659 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011660
Mon P Wang6753f952009-02-07 22:19:29 +000011661 const PointerType *DestTy = cast<PointerType>(CI->getType());
11662 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011663 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011664
11665 // If the address spaces don't match, don't eliminate the cast.
11666 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11667 return 0;
11668
Chris Lattnerb89e0712004-07-13 01:49:43 +000011669 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011670
Reid Spencer42230162007-01-22 05:51:25 +000011671 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011672 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011673 // If the source is an array, the code below will not succeed. Check to
11674 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11675 // constants.
11676 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11677 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11678 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011679 Value *Idxs[2];
Chris Lattnere00c43f2009-10-22 06:44:07 +000011680 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11681 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000011682 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011683 SrcTy = cast<PointerType>(CastOp->getType());
11684 SrcPTy = SrcTy->getElementType();
11685 }
11686
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011687 if (IC.getTargetData() &&
11688 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011689 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011690 // Do not allow turning this into a load of an integer, which is then
11691 // casted to a pointer, this pessimizes pointer analysis a lot.
11692 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011693 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11694 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011695
Chris Lattnerf9527852005-01-31 04:50:46 +000011696 // Okay, we are casting from one integer or pointer type to another of
11697 // the same size. Instead of casting the pointer before the load, cast
11698 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011699 Value *NewLoad =
11700 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011701 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011702 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011703 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011704 }
11705 }
11706 return 0;
11707}
11708
Chris Lattner833b8a42003-06-26 05:06:25 +000011709Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11710 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011711
Dan Gohman9941f742007-07-20 16:34:21 +000011712 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011713 if (TD) {
11714 unsigned KnownAlign =
11715 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11716 if (KnownAlign >
11717 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11718 LI.getAlignment()))
11719 LI.setAlignment(KnownAlign);
11720 }
Dan Gohman9941f742007-07-20 16:34:21 +000011721
Chris Lattner963f4ba2009-08-30 20:36:46 +000011722 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011723 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011724 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011725 return Res;
11726
11727 // None of the following transforms are legal for volatile loads.
11728 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011729
Dan Gohman2276a7b2008-10-15 23:19:35 +000011730 // Do really simple store-to-load forwarding and load CSE, to catch cases
11731 // where there are several consequtive memory accesses to the same location,
11732 // separated by a few arithmetic operations.
11733 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011734 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11735 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011736
Chris Lattner878e4942009-10-22 06:25:11 +000011737 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000011738 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11739 const Value *GEPI0 = GEPI->getOperand(0);
11740 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011741 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011742 // Insert a new store to null instruction before the load to indicate
11743 // that this code is not reachable. We do this instead of inserting
11744 // an unreachable instruction directly because we cannot modify the
11745 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011746 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011747 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011748 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011749 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011750 }
Chris Lattner37366c12005-05-01 04:24:53 +000011751
Chris Lattner878e4942009-10-22 06:25:11 +000011752 // load null/undef -> unreachable
11753 // TODO: Consider a target hook for valid address spaces for this xform.
11754 if (isa<UndefValue>(Op) ||
11755 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11756 // Insert a new store to null instruction before the load to indicate that
11757 // this code is not reachable. We do this instead of inserting an
11758 // unreachable instruction directly because we cannot modify the CFG.
11759 new StoreInst(UndefValue::get(LI.getType()),
11760 Constant::getNullValue(Op->getType()), &LI);
11761 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011762 }
Chris Lattner878e4942009-10-22 06:25:11 +000011763
11764 // Instcombine load (constantexpr_cast global) -> cast (load global)
11765 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11766 if (CE->isCast())
11767 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11768 return Res;
11769
Chris Lattner37366c12005-05-01 04:24:53 +000011770 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011771 // Change select and PHI nodes to select values instead of addresses: this
11772 // helps alias analysis out a lot, allows many others simplifications, and
11773 // exposes redundancy in the code.
11774 //
11775 // Note that we cannot do the transformation unless we know that the
11776 // introduced loads cannot trap! Something like this is valid as long as
11777 // the condition is always false: load (select bool %C, int* null, int* %G),
11778 // but it would not be valid if we transformed it to load from null
11779 // unconditionally.
11780 //
11781 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11782 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011783 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11784 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011785 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11786 SI->getOperand(1)->getName()+".val");
11787 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11788 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011789 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011790 }
11791
Chris Lattner684fe212004-09-23 15:46:00 +000011792 // load (select (cond, null, P)) -> load P
11793 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11794 if (C->isNullValue()) {
11795 LI.setOperand(0, SI->getOperand(2));
11796 return &LI;
11797 }
11798
11799 // load (select (cond, P, null)) -> load P
11800 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11801 if (C->isNullValue()) {
11802 LI.setOperand(0, SI->getOperand(1));
11803 return &LI;
11804 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011805 }
11806 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011807 return 0;
11808}
11809
Reid Spencer55af2b52007-01-19 21:20:31 +000011810/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011811/// when possible. This makes it generally easy to do alias analysis and/or
11812/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011813static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11814 User *CI = cast<User>(SI.getOperand(1));
11815 Value *CastOp = CI->getOperand(0);
11816
11817 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011818 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11819 if (SrcTy == 0) return 0;
11820
11821 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011822
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011823 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11824 return 0;
11825
Chris Lattner3914f722009-01-24 01:00:13 +000011826 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11827 /// to its first element. This allows us to handle things like:
11828 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11829 /// on 32-bit hosts.
11830 SmallVector<Value*, 4> NewGEPIndices;
11831
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011832 // If the source is an array, the code below will not succeed. Check to
11833 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11834 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011835 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11836 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011837 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011838 NewGEPIndices.push_back(Zero);
11839
11840 while (1) {
11841 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011842 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011843 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011844 NewGEPIndices.push_back(Zero);
11845 SrcPTy = STy->getElementType(0);
11846 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11847 NewGEPIndices.push_back(Zero);
11848 SrcPTy = ATy->getElementType();
11849 } else {
11850 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011851 }
Chris Lattner3914f722009-01-24 01:00:13 +000011852 }
11853
Owen Andersondebcb012009-07-29 22:17:13 +000011854 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011855 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011856
11857 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11858 return 0;
11859
Chris Lattner71759c42009-01-16 20:12:52 +000011860 // If the pointers point into different address spaces or if they point to
11861 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011862 if (!IC.getTargetData() ||
11863 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011864 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011865 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11866 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011867 return 0;
11868
11869 // Okay, we are casting from one integer or pointer type to another of
11870 // the same size. Instead of casting the pointer before
11871 // the store, cast the value to be stored.
11872 Value *NewCast;
11873 Value *SIOp0 = SI.getOperand(0);
11874 Instruction::CastOps opcode = Instruction::BitCast;
11875 const Type* CastSrcTy = SIOp0->getType();
11876 const Type* CastDstTy = SrcPTy;
11877 if (isa<PointerType>(CastDstTy)) {
11878 if (CastSrcTy->isInteger())
11879 opcode = Instruction::IntToPtr;
11880 } else if (isa<IntegerType>(CastDstTy)) {
11881 if (isa<PointerType>(SIOp0->getType()))
11882 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011883 }
Chris Lattner3914f722009-01-24 01:00:13 +000011884
11885 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11886 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011887 if (!NewGEPIndices.empty())
11888 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11889 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011890
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011891 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11892 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011893 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011894}
11895
Chris Lattner4aebaee2008-11-27 08:56:30 +000011896/// equivalentAddressValues - Test if A and B will obviously have the same
11897/// value. This includes recognizing that %t0 and %t1 will have the same
11898/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011899/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011900/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011901/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011902/// %t2 = load i32* %t1
11903///
11904static bool equivalentAddressValues(Value *A, Value *B) {
11905 // Test if the values are trivially equivalent.
11906 if (A == B) return true;
11907
11908 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011909 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11910 // its only used to compare two uses within the same basic block, which
11911 // means that they'll always either have the same value or one of them
11912 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011913 if (isa<BinaryOperator>(A) ||
11914 isa<CastInst>(A) ||
11915 isa<PHINode>(A) ||
11916 isa<GetElementPtrInst>(A))
11917 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011918 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011919 return true;
11920
11921 // Otherwise they may not be equivalent.
11922 return false;
11923}
11924
Dale Johannesen4945c652009-03-03 21:26:39 +000011925// If this instruction has two uses, one of which is a llvm.dbg.declare,
11926// return the llvm.dbg.declare.
11927DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11928 if (!V->hasNUses(2))
11929 return 0;
11930 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11931 UI != E; ++UI) {
11932 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11933 return DI;
11934 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11935 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11936 return DI;
11937 }
11938 }
11939 return 0;
11940}
11941
Chris Lattner2f503e62005-01-31 05:36:43 +000011942Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11943 Value *Val = SI.getOperand(0);
11944 Value *Ptr = SI.getOperand(1);
11945
11946 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011947 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011948 ++NumCombined;
11949 return 0;
11950 }
Chris Lattner836692d2007-01-15 06:51:56 +000011951
11952 // If the RHS is an alloca with a single use, zapify the store, making the
11953 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011954 // If the RHS is an alloca with a two uses, the other one being a
11955 // llvm.dbg.declare, zapify the store and the declare, making the
11956 // alloca dead. We must do this to prevent declare's from affecting
11957 // codegen.
11958 if (!SI.isVolatile()) {
11959 if (Ptr->hasOneUse()) {
11960 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011961 EraseInstFromFunction(SI);
11962 ++NumCombined;
11963 return 0;
11964 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011965 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11966 if (isa<AllocaInst>(GEP->getOperand(0))) {
11967 if (GEP->getOperand(0)->hasOneUse()) {
11968 EraseInstFromFunction(SI);
11969 ++NumCombined;
11970 return 0;
11971 }
11972 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11973 EraseInstFromFunction(*DI);
11974 EraseInstFromFunction(SI);
11975 ++NumCombined;
11976 return 0;
11977 }
11978 }
11979 }
11980 }
11981 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11982 EraseInstFromFunction(*DI);
11983 EraseInstFromFunction(SI);
11984 ++NumCombined;
11985 return 0;
11986 }
Chris Lattner836692d2007-01-15 06:51:56 +000011987 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011988
Dan Gohman9941f742007-07-20 16:34:21 +000011989 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011990 if (TD) {
11991 unsigned KnownAlign =
11992 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11993 if (KnownAlign >
11994 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11995 SI.getAlignment()))
11996 SI.setAlignment(KnownAlign);
11997 }
Dan Gohman9941f742007-07-20 16:34:21 +000011998
Dale Johannesenacb51a32009-03-03 01:43:03 +000011999 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000012000 // stores to the same location, separated by a few arithmetic operations. This
12001 // situation often occurs with bitfield accesses.
12002 BasicBlock::iterator BBI = &SI;
12003 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12004 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000012005 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012006 // Don't count debug info directives, lest they affect codegen,
12007 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12008 // It is necessary for correctness to skip those that feed into a
12009 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000012010 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012011 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000012012 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000012013 continue;
12014 }
Chris Lattner9ca96412006-02-08 03:25:32 +000012015
12016 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12017 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000012018 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12019 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012020 ++NumDeadStore;
12021 ++BBI;
12022 EraseInstFromFunction(*PrevSI);
12023 continue;
12024 }
12025 break;
12026 }
12027
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012028 // If this is a load, we have to stop. However, if the loaded value is from
12029 // the pointer we're loading and is producing the pointer we're storing,
12030 // then *this* store is dead (X = load P; store X -> P).
12031 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000012032 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12033 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012034 EraseInstFromFunction(SI);
12035 ++NumCombined;
12036 return 0;
12037 }
12038 // Otherwise, this is a load from some other location. Stores before it
12039 // may not be dead.
12040 break;
12041 }
12042
Chris Lattner9ca96412006-02-08 03:25:32 +000012043 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000012044 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000012045 break;
12046 }
12047
12048
12049 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000012050
12051 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000012052 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000012053 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012054 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000012055 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000012056 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000012057 ++NumCombined;
12058 }
12059 return 0; // Do not modify these!
12060 }
12061
12062 // store undef, Ptr -> noop
12063 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012064 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000012065 ++NumCombined;
12066 return 0;
12067 }
12068
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012069 // If the pointer destination is a cast, see if we can fold the cast into the
12070 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012071 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012072 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12073 return Res;
12074 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000012075 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012076 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12077 return Res;
12078
Chris Lattner408902b2005-09-12 23:23:25 +000012079
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012080 // If this store is the last instruction in the basic block (possibly
12081 // excepting debug info instructions and the pointer bitcasts that feed
12082 // into them), and if the block ends with an unconditional branch, try
12083 // to move it to the successor block.
12084 BBI = &SI;
12085 do {
12086 ++BBI;
12087 } while (isa<DbgInfoIntrinsic>(BBI) ||
12088 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000012089 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012090 if (BI->isUnconditional())
12091 if (SimplifyStoreAtEndOfBlock(SI))
12092 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000012093
Chris Lattner2f503e62005-01-31 05:36:43 +000012094 return 0;
12095}
12096
Chris Lattner3284d1f2007-04-15 00:07:55 +000012097/// SimplifyStoreAtEndOfBlock - Turn things like:
12098/// if () { *P = v1; } else { *P = v2 }
12099/// into a phi node with a store in the successor.
12100///
Chris Lattner31755a02007-04-15 01:02:18 +000012101/// Simplify things like:
12102/// *P = v1; if () { *P = v2; }
12103/// into a phi node with a store in the successor.
12104///
Chris Lattner3284d1f2007-04-15 00:07:55 +000012105bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12106 BasicBlock *StoreBB = SI.getParent();
12107
12108 // Check to see if the successor block has exactly two incoming edges. If
12109 // so, see if the other predecessor contains a store to the same location.
12110 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012111 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012112
12113 // Determine whether Dest has exactly two predecessors and, if so, compute
12114 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012115 pred_iterator PI = pred_begin(DestBB);
12116 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012117 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012118 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012119 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012120 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012121 return false;
12122
12123 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012124 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012125 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012126 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012127 }
Chris Lattner31755a02007-04-15 01:02:18 +000012128 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012129 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012130
12131 // Bail out if all the relevant blocks aren't distinct (this can happen,
12132 // for example, if SI is in an infinite loop)
12133 if (StoreBB == DestBB || OtherBB == DestBB)
12134 return false;
12135
Chris Lattner31755a02007-04-15 01:02:18 +000012136 // Verify that the other block ends in a branch and is not otherwise empty.
12137 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012138 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012139 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012140 return false;
12141
Chris Lattner31755a02007-04-15 01:02:18 +000012142 // If the other block ends in an unconditional branch, check for the 'if then
12143 // else' case. there is an instruction before the branch.
12144 StoreInst *OtherStore = 0;
12145 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012146 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012147 // Skip over debugging info.
12148 while (isa<DbgInfoIntrinsic>(BBI) ||
12149 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12150 if (BBI==OtherBB->begin())
12151 return false;
12152 --BBI;
12153 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012154 // If this isn't a store, isn't a store to the same location, or if the
12155 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012156 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012157 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12158 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012159 return false;
12160 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012161 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012162 // destinations is StoreBB, then we have the if/then case.
12163 if (OtherBr->getSuccessor(0) != StoreBB &&
12164 OtherBr->getSuccessor(1) != StoreBB)
12165 return false;
12166
12167 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012168 // if/then triangle. See if there is a store to the same ptr as SI that
12169 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012170 for (;; --BBI) {
12171 // Check to see if we find the matching store.
12172 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012173 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12174 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012175 return false;
12176 break;
12177 }
Eli Friedman6903a242008-06-13 22:02:12 +000012178 // If we find something that may be using or overwriting the stored
12179 // value, or if we run out of instructions, we can't do the xform.
12180 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012181 BBI == OtherBB->begin())
12182 return false;
12183 }
12184
12185 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012186 // make sure nothing reads or overwrites the stored value in
12187 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012188 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12189 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012190 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012191 return false;
12192 }
12193 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012194
Chris Lattner31755a02007-04-15 01:02:18 +000012195 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012196 Value *MergedVal = OtherStore->getOperand(0);
12197 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012198 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012199 PN->reserveOperandSpace(2);
12200 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012201 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12202 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012203 }
12204
12205 // Advance to a place where it is safe to insert the new store and
12206 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012207 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012208 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012209 OtherStore->isVolatile(),
12210 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012211
12212 // Nuke the old stores.
12213 EraseInstFromFunction(SI);
12214 EraseInstFromFunction(*OtherStore);
12215 ++NumCombined;
12216 return true;
12217}
12218
Chris Lattner2f503e62005-01-31 05:36:43 +000012219
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012220Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12221 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012222 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012223 BasicBlock *TrueDest;
12224 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012225 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012226 !isa<Constant>(X)) {
12227 // Swap Destinations and condition...
12228 BI.setCondition(X);
12229 BI.setSuccessor(0, FalseDest);
12230 BI.setSuccessor(1, TrueDest);
12231 return &BI;
12232 }
12233
Reid Spencere4d87aa2006-12-23 06:05:41 +000012234 // Cannonicalize fcmp_one -> fcmp_oeq
12235 FCmpInst::Predicate FPred; Value *Y;
12236 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012237 TrueDest, FalseDest)) &&
12238 BI.getCondition()->hasOneUse())
12239 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12240 FPred == FCmpInst::FCMP_OGE) {
12241 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12242 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12243
12244 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000012245 BI.setSuccessor(0, FalseDest);
12246 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012247 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012248 return &BI;
12249 }
12250
12251 // Cannonicalize icmp_ne -> icmp_eq
12252 ICmpInst::Predicate IPred;
12253 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012254 TrueDest, FalseDest)) &&
12255 BI.getCondition()->hasOneUse())
12256 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12257 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12258 IPred == ICmpInst::ICMP_SGE) {
12259 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12260 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12261 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000012262 BI.setSuccessor(0, FalseDest);
12263 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012264 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000012265 return &BI;
12266 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012267
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012268 return 0;
12269}
Chris Lattner0864acf2002-11-04 16:18:53 +000012270
Chris Lattner46238a62004-07-03 00:26:11 +000012271Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12272 Value *Cond = SI.getCondition();
12273 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12274 if (I->getOpcode() == Instruction::Add)
12275 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12276 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12277 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012278 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012279 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012280 AddRHS));
12281 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012282 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012283 return &SI;
12284 }
12285 }
12286 return 0;
12287}
12288
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012289Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012290 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012291
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012292 if (!EV.hasIndices())
12293 return ReplaceInstUsesWith(EV, Agg);
12294
12295 if (Constant *C = dyn_cast<Constant>(Agg)) {
12296 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012297 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012298
12299 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012300 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012301
12302 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12303 // Extract the element indexed by the first index out of the constant
12304 Value *V = C->getOperand(*EV.idx_begin());
12305 if (EV.getNumIndices() > 1)
12306 // Extract the remaining indices out of the constant indexed by the
12307 // first index
12308 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12309 else
12310 return ReplaceInstUsesWith(EV, V);
12311 }
12312 return 0; // Can't handle other constants
12313 }
12314 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12315 // We're extracting from an insertvalue instruction, compare the indices
12316 const unsigned *exti, *exte, *insi, *inse;
12317 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12318 exte = EV.idx_end(), inse = IV->idx_end();
12319 exti != exte && insi != inse;
12320 ++exti, ++insi) {
12321 if (*insi != *exti)
12322 // The insert and extract both reference distinctly different elements.
12323 // This means the extract is not influenced by the insert, and we can
12324 // replace the aggregate operand of the extract with the aggregate
12325 // operand of the insert. i.e., replace
12326 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12327 // %E = extractvalue { i32, { i32 } } %I, 0
12328 // with
12329 // %E = extractvalue { i32, { i32 } } %A, 0
12330 return ExtractValueInst::Create(IV->getAggregateOperand(),
12331 EV.idx_begin(), EV.idx_end());
12332 }
12333 if (exti == exte && insi == inse)
12334 // Both iterators are at the end: Index lists are identical. Replace
12335 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12336 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12337 // with "i32 42"
12338 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12339 if (exti == exte) {
12340 // The extract list is a prefix of the insert list. i.e. replace
12341 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12342 // %E = extractvalue { i32, { i32 } } %I, 1
12343 // with
12344 // %X = extractvalue { i32, { i32 } } %A, 1
12345 // %E = insertvalue { i32 } %X, i32 42, 0
12346 // by switching the order of the insert and extract (though the
12347 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012348 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12349 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012350 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12351 insi, inse);
12352 }
12353 if (insi == inse)
12354 // The insert list is a prefix of the extract list
12355 // We can simply remove the common indices from the extract and make it
12356 // operate on the inserted value instead of the insertvalue result.
12357 // i.e., replace
12358 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12359 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12360 // with
12361 // %E extractvalue { i32 } { i32 42 }, 0
12362 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12363 exti, exte);
12364 }
Chris Lattner7e606e22009-11-09 07:07:56 +000012365 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12366 // We're extracting from an intrinsic, see if we're the only user, which
12367 // allows us to simplify multiple result intrinsics to simpler things that
12368 // just get one value..
12369 if (II->hasOneUse()) {
12370 // Check if we're grabbing the overflow bit or the result of a 'with
12371 // overflow' intrinsic. If it's the latter we can remove the intrinsic
12372 // and replace it with a traditional binary instruction.
12373 switch (II->getIntrinsicID()) {
12374 case Intrinsic::uadd_with_overflow:
12375 case Intrinsic::sadd_with_overflow:
12376 if (*EV.idx_begin() == 0) { // Normal result.
12377 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12378 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12379 EraseInstFromFunction(*II);
12380 return BinaryOperator::CreateAdd(LHS, RHS);
12381 }
12382 break;
12383 case Intrinsic::usub_with_overflow:
12384 case Intrinsic::ssub_with_overflow:
12385 if (*EV.idx_begin() == 0) { // Normal result.
12386 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12387 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12388 EraseInstFromFunction(*II);
12389 return BinaryOperator::CreateSub(LHS, RHS);
12390 }
12391 break;
12392 case Intrinsic::umul_with_overflow:
12393 case Intrinsic::smul_with_overflow:
12394 if (*EV.idx_begin() == 0) { // Normal result.
12395 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12396 II->replaceAllUsesWith(UndefValue::get(II->getType()));
12397 EraseInstFromFunction(*II);
12398 return BinaryOperator::CreateMul(LHS, RHS);
12399 }
12400 break;
12401 default:
12402 break;
12403 }
12404 }
12405 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012406 // Can't simplify extracts from other values. Note that nested extracts are
12407 // already simplified implicitely by the above (extract ( extract (insert) )
12408 // will be translated into extract ( insert ( extract ) ) first and then just
12409 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012410 return 0;
12411}
12412
Chris Lattner220b0cf2006-03-05 00:22:33 +000012413/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12414/// is to leave as a vector operation.
12415static bool CheapToScalarize(Value *V, bool isConstant) {
12416 if (isa<ConstantAggregateZero>(V))
12417 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012418 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012419 if (isConstant) return true;
12420 // If all elts are the same, we can extract.
12421 Constant *Op0 = C->getOperand(0);
12422 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12423 if (C->getOperand(i) != Op0)
12424 return false;
12425 return true;
12426 }
12427 Instruction *I = dyn_cast<Instruction>(V);
12428 if (!I) return false;
12429
12430 // Insert element gets simplified to the inserted element or is deleted if
12431 // this is constant idx extract element and its a constant idx insertelt.
12432 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12433 isa<ConstantInt>(I->getOperand(2)))
12434 return true;
12435 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12436 return true;
12437 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12438 if (BO->hasOneUse() &&
12439 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12440 CheapToScalarize(BO->getOperand(1), isConstant)))
12441 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012442 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12443 if (CI->hasOneUse() &&
12444 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12445 CheapToScalarize(CI->getOperand(1), isConstant)))
12446 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012447
12448 return false;
12449}
12450
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012451/// Read and decode a shufflevector mask.
12452///
12453/// It turns undef elements into values that are larger than the number of
12454/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012455static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12456 unsigned NElts = SVI->getType()->getNumElements();
12457 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12458 return std::vector<unsigned>(NElts, 0);
12459 if (isa<UndefValue>(SVI->getOperand(2)))
12460 return std::vector<unsigned>(NElts, 2*NElts);
12461
12462 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012463 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012464 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12465 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012466 Result.push_back(NElts*2); // undef -> 8
12467 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012468 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012469 return Result;
12470}
12471
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012472/// FindScalarElement - Given a vector and an element number, see if the scalar
12473/// value is already around as a register, for example if it were inserted then
12474/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012475static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012476 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012477 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12478 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012479 unsigned Width = PTy->getNumElements();
12480 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012481 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012482
12483 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012484 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012485 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012486 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012487 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012488 return CP->getOperand(EltNo);
12489 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12490 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012491 if (!isa<ConstantInt>(III->getOperand(2)))
12492 return 0;
12493 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012494
12495 // If this is an insert to the element we are looking for, return the
12496 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012497 if (EltNo == IIElt)
12498 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012499
12500 // Otherwise, the insertelement doesn't modify the value, recurse on its
12501 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012502 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012503 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012504 unsigned LHSWidth =
12505 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012506 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012507 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012508 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012509 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012510 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012511 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012512 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012513 }
12514
12515 // Otherwise, we don't know.
12516 return 0;
12517}
12518
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012519Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012520 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012521 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012522 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012523
Dan Gohman07a96762007-07-16 14:29:03 +000012524 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012525 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012526 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012527
Reid Spencer9d6565a2007-02-15 02:26:10 +000012528 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012529 // If vector val is constant with all elements the same, replace EI with
12530 // that element. When the elements are not identical, we cannot replace yet
12531 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012532 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012533 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012534 if (C->getOperand(i) != op0) {
12535 op0 = 0;
12536 break;
12537 }
12538 if (op0)
12539 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012540 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012541
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012542 // If extracting a specified index from the vector, see if we can recursively
12543 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012544 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012545 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012546 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012547
12548 // If this is extracting an invalid index, turn this into undef, to avoid
12549 // crashing the code below.
12550 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012551 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012552
Chris Lattner867b99f2006-10-05 06:55:50 +000012553 // This instruction only demands the single element from the input vector.
12554 // If the input vector has a single use, simplify it based on this use
12555 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012556 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012557 APInt UndefElts(VectorWidth, 0);
12558 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012559 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012560 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012561 EI.setOperand(0, V);
12562 return &EI;
12563 }
12564 }
12565
Owen Andersond672ecb2009-07-03 00:17:18 +000012566 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012567 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012568
12569 // If the this extractelement is directly using a bitcast from a vector of
12570 // the same number of elements, see if we can find the source element from
12571 // it. In this case, we will end up needing to bitcast the scalars.
12572 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12573 if (const VectorType *VT =
12574 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12575 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012576 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12577 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012578 return new BitCastInst(Elt, EI.getType());
12579 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012580 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012581
Chris Lattner73fa49d2006-05-25 22:53:38 +000012582 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012583 // Push extractelement into predecessor operation if legal and
12584 // profitable to do so
12585 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12586 if (I->hasOneUse() &&
12587 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12588 Value *newEI0 =
12589 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12590 EI.getName()+".lhs");
12591 Value *newEI1 =
12592 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12593 EI.getName()+".rhs");
12594 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012595 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012596 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012597 // Extracting the inserted element?
12598 if (IE->getOperand(2) == EI.getOperand(1))
12599 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12600 // If the inserted and extracted elements are constants, they must not
12601 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012602 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012603 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012604 EI.setOperand(0, IE->getOperand(0));
12605 return &EI;
12606 }
12607 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12608 // If this is extracting an element from a shufflevector, figure out where
12609 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012610 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12611 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012612 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012613 unsigned LHSWidth =
12614 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12615
12616 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012617 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012618 else if (SrcIdx < LHSWidth*2) {
12619 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012620 Src = SVI->getOperand(1);
12621 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012622 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012623 }
Eric Christophera3500da2009-07-25 02:28:41 +000012624 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012625 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12626 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012627 }
12628 }
Eli Friedman2451a642009-07-18 23:06:53 +000012629 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012630 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012631 return 0;
12632}
12633
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012634/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12635/// elements from either LHS or RHS, return the shuffle mask and true.
12636/// Otherwise, return false.
12637static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012638 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012639 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012640 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12641 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012642 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012643
12644 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012645 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012646 return true;
12647 } else if (V == LHS) {
12648 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012649 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012650 return true;
12651 } else if (V == RHS) {
12652 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012653 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012654 return true;
12655 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12656 // If this is an insert of an extract from some other vector, include it.
12657 Value *VecOp = IEI->getOperand(0);
12658 Value *ScalarOp = IEI->getOperand(1);
12659 Value *IdxOp = IEI->getOperand(2);
12660
Chris Lattnerd929f062006-04-27 21:14:21 +000012661 if (!isa<ConstantInt>(IdxOp))
12662 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012663 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012664
12665 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12666 // Okay, we can handle this if the vector we are insertinting into is
12667 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012668 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012669 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012670 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012671 return true;
12672 }
12673 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12674 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012675 EI->getOperand(0)->getType() == V->getType()) {
12676 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012677 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012678
12679 // This must be extracting from either LHS or RHS.
12680 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12681 // Okay, we can handle this if the vector we are insertinting into is
12682 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012683 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012684 // If so, update the mask to reflect the inserted value.
12685 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012686 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012687 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012688 } else {
12689 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012690 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012691 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012692
12693 }
12694 return true;
12695 }
12696 }
12697 }
12698 }
12699 }
12700 // TODO: Handle shufflevector here!
12701
12702 return false;
12703}
12704
12705/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12706/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12707/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012708static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012709 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012710 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012711 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012712 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012713 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012714
12715 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012716 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012717 return V;
12718 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012719 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012720 return V;
12721 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12722 // If this is an insert of an extract from some other vector, include it.
12723 Value *VecOp = IEI->getOperand(0);
12724 Value *ScalarOp = IEI->getOperand(1);
12725 Value *IdxOp = IEI->getOperand(2);
12726
12727 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12728 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12729 EI->getOperand(0)->getType() == V->getType()) {
12730 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012731 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12732 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012733
12734 // Either the extracted from or inserted into vector must be RHSVec,
12735 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012736 if (EI->getOperand(0) == RHS || RHS == 0) {
12737 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012738 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012739 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012740 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012741 return V;
12742 }
12743
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012744 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012745 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12746 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012747 // Everything but the extracted element is replaced with the RHS.
12748 for (unsigned i = 0; i != NumElts; ++i) {
12749 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012750 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012751 }
12752 return V;
12753 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012754
12755 // If this insertelement is a chain that comes from exactly these two
12756 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012757 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12758 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012759 return EI->getOperand(0);
12760
Chris Lattnerefb47352006-04-15 01:39:45 +000012761 }
12762 }
12763 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012764 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012765
12766 // Otherwise, can't do anything fancy. Return an identity vector.
12767 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012768 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012769 return V;
12770}
12771
12772Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12773 Value *VecOp = IE.getOperand(0);
12774 Value *ScalarOp = IE.getOperand(1);
12775 Value *IdxOp = IE.getOperand(2);
12776
Chris Lattner599ded12007-04-09 01:11:16 +000012777 // Inserting an undef or into an undefined place, remove this.
12778 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12779 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012780
Chris Lattnerefb47352006-04-15 01:39:45 +000012781 // If the inserted element was extracted from some other vector, and if the
12782 // indexes are constant, try to turn this into a shufflevector operation.
12783 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12784 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12785 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012786 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012787 unsigned ExtractedIdx =
12788 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012789 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012790
12791 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12792 return ReplaceInstUsesWith(IE, VecOp);
12793
12794 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012795 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012796
12797 // If we are extracting a value from a vector, then inserting it right
12798 // back into the same place, just use the input vector.
12799 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12800 return ReplaceInstUsesWith(IE, VecOp);
12801
Chris Lattnerefb47352006-04-15 01:39:45 +000012802 // If this insertelement isn't used by some other insertelement, turn it
12803 // (and any insertelements it points to), into one big shuffle.
12804 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12805 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012806 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012807 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012808 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012809 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012810 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012811 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012812 }
12813 }
12814 }
12815
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012816 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12817 APInt UndefElts(VWidth, 0);
12818 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12819 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12820 return &IE;
12821
Chris Lattnerefb47352006-04-15 01:39:45 +000012822 return 0;
12823}
12824
12825
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012826Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12827 Value *LHS = SVI.getOperand(0);
12828 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012829 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012830
12831 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012832
Chris Lattner867b99f2006-10-05 06:55:50 +000012833 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012834 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012835 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012836
Dan Gohman488fbfc2008-09-09 18:11:14 +000012837 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012838
12839 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12840 return 0;
12841
Evan Cheng388df622009-02-03 10:05:09 +000012842 APInt UndefElts(VWidth, 0);
12843 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12844 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012845 LHS = SVI.getOperand(0);
12846 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012847 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012848 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012849
Chris Lattner863bcff2006-05-25 23:48:38 +000012850 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12851 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12852 if (LHS == RHS || isa<UndefValue>(LHS)) {
12853 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012854 // shuffle(undef,undef,mask) -> undef.
12855 return ReplaceInstUsesWith(SVI, LHS);
12856 }
12857
Chris Lattner863bcff2006-05-25 23:48:38 +000012858 // Remap any references to RHS to use LHS.
12859 std::vector<Constant*> Elts;
12860 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012861 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012862 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012863 else {
12864 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012865 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012866 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012867 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012868 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012869 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012870 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012871 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012872 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012873 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012874 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012875 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012876 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012877 LHS = SVI.getOperand(0);
12878 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012879 MadeChange = true;
12880 }
12881
Chris Lattner7b2e27922006-05-26 00:29:06 +000012882 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012883 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012884
Chris Lattner863bcff2006-05-25 23:48:38 +000012885 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12886 if (Mask[i] >= e*2) continue; // Ignore undef values.
12887 // Is this an identity shuffle of the LHS value?
12888 isLHSID &= (Mask[i] == i);
12889
12890 // Is this an identity shuffle of the RHS value?
12891 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012892 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012893
Chris Lattner863bcff2006-05-25 23:48:38 +000012894 // Eliminate identity shuffles.
12895 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12896 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012897
Chris Lattner7b2e27922006-05-26 00:29:06 +000012898 // If the LHS is a shufflevector itself, see if we can combine it with this
12899 // one without producing an unusual shuffle. Here we are really conservative:
12900 // we are absolutely afraid of producing a shuffle mask not in the input
12901 // program, because the code gen may not be smart enough to turn a merged
12902 // shuffle into two specific shuffles: it may produce worse code. As such,
12903 // we only merge two shuffles if the result is one of the two input shuffle
12904 // masks. In this case, merging the shuffles just removes one instruction,
12905 // which we know is safe. This is good for things like turning:
12906 // (splat(splat)) -> splat.
12907 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12908 if (isa<UndefValue>(RHS)) {
12909 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12910
12911 std::vector<unsigned> NewMask;
12912 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12913 if (Mask[i] >= 2*e)
12914 NewMask.push_back(2*e);
12915 else
12916 NewMask.push_back(LHSMask[Mask[i]]);
12917
12918 // If the result mask is equal to the src shuffle or this shuffle mask, do
12919 // the replacement.
12920 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012921 unsigned LHSInNElts =
12922 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012923 std::vector<Constant*> Elts;
12924 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012925 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012926 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012927 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012928 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012929 }
12930 }
12931 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12932 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012933 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012934 }
12935 }
12936 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012937
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012938 return MadeChange ? &SVI : 0;
12939}
12940
12941
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012942
Chris Lattnerea1c4542004-12-08 23:43:58 +000012943
12944/// TryToSinkInstruction - Try to move the specified instruction from its
12945/// current block into the beginning of DestBlock, which can only happen if it's
12946/// safe to move the instruction past all of the instructions between it and the
12947/// end of its block.
12948static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12949 assert(I->hasOneUse() && "Invariants didn't hold!");
12950
Chris Lattner108e9022005-10-27 17:13:11 +000012951 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012952 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012953 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012954
Chris Lattnerea1c4542004-12-08 23:43:58 +000012955 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012956 if (isa<AllocaInst>(I) && I->getParent() ==
12957 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012958 return false;
12959
Chris Lattner96a52a62004-12-09 07:14:34 +000012960 // We can only sink load instructions if there is nothing between the load and
12961 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012962 if (I->mayReadFromMemory()) {
12963 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012964 Scan != E; ++Scan)
12965 if (Scan->mayWriteToMemory())
12966 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012967 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012968
Dan Gohman02dea8b2008-05-23 21:05:58 +000012969 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012970
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012971 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012972 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012973 ++NumSunkInst;
12974 return true;
12975}
12976
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012977
12978/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12979/// all reachable code to the worklist.
12980///
12981/// This has a couple of tricks to make the code faster and more powerful. In
12982/// particular, we constant fold and DCE instructions as we go, to avoid adding
12983/// them to the worklist (this significantly speeds up instcombine on code where
12984/// many instructions are dead or constant). Additionally, if we find a branch
12985/// whose condition is a known constant, we only visit the reachable successors.
12986///
Chris Lattner2ee743b2009-10-15 04:59:28 +000012987static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012988 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012989 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012990 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000012991 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000012992 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012993 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000012994
12995 std::vector<Instruction*> InstrsForInstCombineWorklist;
12996 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012997
Chris Lattner2ee743b2009-10-15 04:59:28 +000012998 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
12999
Chris Lattner2c7718a2007-03-23 19:17:18 +000013000 while (!Worklist.empty()) {
13001 BB = Worklist.back();
13002 Worklist.pop_back();
13003
13004 // We have now visited this block! If we've already been here, ignore it.
13005 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000013006
Chris Lattner2c7718a2007-03-23 19:17:18 +000013007 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13008 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013009
Chris Lattner2c7718a2007-03-23 19:17:18 +000013010 // DCE instruction if trivially dead.
13011 if (isInstructionTriviallyDead(Inst)) {
13012 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000013013 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000013014 Inst->eraseFromParent();
13015 continue;
13016 }
13017
13018 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013019 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013020 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013021 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13022 << *Inst << '\n');
13023 Inst->replaceAllUsesWith(C);
13024 ++NumConstProp;
13025 Inst->eraseFromParent();
13026 continue;
13027 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000013028
13029
13030
13031 if (TD) {
13032 // See if we can constant fold its operands.
13033 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13034 i != e; ++i) {
13035 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13036 if (CE == 0) continue;
13037
13038 // If we already folded this constant, don't try again.
13039 if (!FoldedConstants.insert(CE))
13040 continue;
13041
Chris Lattner7b550cc2009-11-06 04:27:31 +000013042 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +000013043 if (NewC && NewC != CE) {
13044 *i = NewC;
13045 MadeIRChange = true;
13046 }
13047 }
13048 }
13049
Devang Patel7fe1dec2008-11-19 18:56:50 +000013050
Chris Lattner67f7d542009-10-12 03:58:40 +000013051 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013052 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000013053
13054 // Recursively visit successors. If this is a branch or switch on a
13055 // constant, only visit the reachable successor.
13056 TerminatorInst *TI = BB->getTerminator();
13057 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13058 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13059 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000013060 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013061 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013062 continue;
13063 }
13064 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13065 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13066 // See if this is an explicit destination.
13067 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13068 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000013069 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013070 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013071 continue;
13072 }
13073
13074 // Otherwise it is the default destination.
13075 Worklist.push_back(SI->getSuccessor(0));
13076 continue;
13077 }
13078 }
13079
13080 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13081 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013082 }
Chris Lattner67f7d542009-10-12 03:58:40 +000013083
13084 // Once we've found all of the instructions to add to instcombine's worklist,
13085 // add them in reverse order. This way instcombine will visit from the top
13086 // of the function down. This jives well with the way that it adds all uses
13087 // of instructions to the worklist after doing a transformation, thus avoiding
13088 // some N^2 behavior in pathological cases.
13089 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13090 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000013091
13092 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013093}
13094
Chris Lattnerec9c3582007-03-03 02:04:50 +000013095bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013096 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013097
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000013098 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13099 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000013100
Chris Lattnerb3d59702005-07-07 20:40:38 +000013101 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013102 // Do a depth-first traversal of the function, populate the worklist with
13103 // the reachable instructions. Ignore blocks that are not reachable. Keep
13104 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000013105 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000013106 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000013107
Chris Lattnerb3d59702005-07-07 20:40:38 +000013108 // Do a quick scan over the function. If we find any blocks that are
13109 // unreachable, remove any instructions inside of them. This prevents
13110 // the instcombine code from having to deal with some bad special cases.
13111 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13112 if (!Visited.count(BB)) {
13113 Instruction *Term = BB->getTerminator();
13114 while (Term != BB->begin()) { // Remove instrs bottom-up
13115 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000013116
Chris Lattnerbdff5482009-08-23 04:37:46 +000013117 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000013118 // A debug intrinsic shouldn't force another iteration if we weren't
13119 // going to do one without it.
13120 if (!isa<DbgInfoIntrinsic>(I)) {
13121 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013122 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000013123 }
Devang Patel228ebd02009-10-13 22:56:32 +000013124
Devang Patel228ebd02009-10-13 22:56:32 +000013125 // If I is not void type then replaceAllUsesWith undef.
13126 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000013127 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000013128 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000013129 I->eraseFromParent();
13130 }
13131 }
13132 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013133
Chris Lattner873ff012009-08-30 05:55:36 +000013134 while (!Worklist.isEmpty()) {
13135 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013136 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013137
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013138 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013139 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013140 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000013141 EraseInstFromFunction(*I);
13142 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013143 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013144 continue;
13145 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013146
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013147 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013148 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013149 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013150 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000013151
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013152 // Add operands to the worklist.
13153 ReplaceInstUsesWith(*I, C);
13154 ++NumConstProp;
13155 EraseInstFromFunction(*I);
13156 MadeIRChange = true;
13157 continue;
13158 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013159
Chris Lattnerea1c4542004-12-08 23:43:58 +000013160 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013161 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013162 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000013163 Instruction *UserInst = cast<Instruction>(I->use_back());
13164 BasicBlock *UserParent;
13165
13166 // Get the block the use occurs in.
13167 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13168 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13169 else
13170 UserParent = UserInst->getParent();
13171
Chris Lattnerea1c4542004-12-08 23:43:58 +000013172 if (UserParent != BB) {
13173 bool UserIsSuccessor = false;
13174 // See if the user is one of our successors.
13175 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13176 if (*SI == UserParent) {
13177 UserIsSuccessor = true;
13178 break;
13179 }
13180
13181 // If the user is one of our immediate successors, and if that successor
13182 // only has us as a predecessors (we'd have to split the critical edge
13183 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000013184 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013185 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013186 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013187 }
13188 }
13189
Chris Lattner74381062009-08-30 07:44:24 +000013190 // Now that we have an instruction, try combining it to simplify it.
13191 Builder->SetInsertPoint(I->getParent(), I);
13192
Reid Spencera9b81012007-03-26 17:44:01 +000013193#ifndef NDEBUG
13194 std::string OrigI;
13195#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000013196 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000013197 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13198
Chris Lattner90ac28c2002-08-02 19:29:35 +000013199 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013200 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013201 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013202 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013203 DEBUG(errs() << "IC: Old = " << *I << '\n'
13204 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013205
Chris Lattnerf523d062004-06-09 05:08:07 +000013206 // Everything uses the new instruction now.
13207 I->replaceAllUsesWith(Result);
13208
13209 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000013210 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013211 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013212
Chris Lattner6934a042007-02-11 01:23:03 +000013213 // Move the name to the new instruction first.
13214 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013215
13216 // Insert the new instruction into the basic block...
13217 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013218 BasicBlock::iterator InsertPos = I;
13219
13220 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13221 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13222 ++InsertPos;
13223
13224 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013225
Chris Lattner7a1e9242009-08-30 06:13:40 +000013226 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000013227 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013228#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000013229 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13230 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000013231#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013232
Chris Lattner90ac28c2002-08-02 19:29:35 +000013233 // If the instruction was modified, it's possible that it is now dead.
13234 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013235 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013236 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000013237 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013238 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013239 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013240 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013241 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013242 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013243 }
13244 }
13245
Chris Lattner873ff012009-08-30 05:55:36 +000013246 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013247 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013248}
13249
Chris Lattnerec9c3582007-03-03 02:04:50 +000013250
13251bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013252 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013253 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013254 TD = getAnalysisIfAvailable<TargetData>();
13255
Chris Lattner74381062009-08-30 07:44:24 +000013256
13257 /// Builder - This is an IRBuilder that automatically inserts new
13258 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013259 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +000013260 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +000013261 InstCombineIRInserter(Worklist));
13262 Builder = &TheBuilder;
13263
Chris Lattnerec9c3582007-03-03 02:04:50 +000013264 bool EverMadeChange = false;
13265
13266 // Iterate while there is work to do.
13267 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013268 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013269 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000013270
13271 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013272 return EverMadeChange;
13273}
13274
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013275FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013276 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013277}