blob: f33946cdcc650dfcf237878f7cc88b355946a2e6 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11// both before and after the DAG is legalized.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "dagcombine"
16#include "llvm/CodeGen/SelectionDAG.h"
Chris Lattner4e137af2008-01-25 07:20:16 +000017#include "llvm/CodeGen/MachineFunction.h"
18#include "llvm/CodeGen/MachineFrameInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000019#include "llvm/Analysis/AliasAnalysis.h"
20#include "llvm/Target/TargetData.h"
Chris Lattner1e3362f2008-01-26 19:45:50 +000021#include "llvm/Target/TargetFrameInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#include "llvm/Target/TargetLowering.h"
23#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/TargetOptions.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/MathExtras.h"
31#include <algorithm>
32using namespace llvm;
33
34STATISTIC(NodesCombined , "Number of dag nodes combined");
35STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
36STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
37
38namespace {
39#ifndef NDEBUG
40 static cl::opt<bool>
41 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
42 cl::desc("Pop up a window to show dags before the first "
43 "dag combine pass"));
44 static cl::opt<bool>
45 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
46 cl::desc("Pop up a window to show dags before the second "
47 "dag combine pass"));
48#else
49 static const bool ViewDAGCombine1 = false;
50 static const bool ViewDAGCombine2 = false;
51#endif
52
53 static cl::opt<bool>
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Turn on alias analysis during testing"));
56
57 static cl::opt<bool>
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Include global information in alias analysis"));
60
61//------------------------------ DAGCombiner ---------------------------------//
62
63 class VISIBILITY_HIDDEN DAGCombiner {
64 SelectionDAG &DAG;
65 TargetLowering &TLI;
66 bool AfterLegalize;
67
68 // Worklist of all of the nodes that need to be simplified.
69 std::vector<SDNode*> WorkList;
70
71 // AA - Used for DAG load/store alias analysis.
72 AliasAnalysis &AA;
73
74 /// AddUsersToWorkList - When an instruction is simplified, add all users of
75 /// the instruction to the work lists because they might get more simplified
76 /// now.
77 ///
78 void AddUsersToWorkList(SDNode *N) {
79 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
80 UI != UE; ++UI)
81 AddToWorkList(*UI);
82 }
83
Dan Gohman6c89ea72007-10-08 17:57:15 +000084 /// visit - call the node-specific routine that knows how to fold each
85 /// particular type of node.
86 SDOperand visit(SDNode *N);
87
Dan Gohmanf17a25c2007-07-18 16:29:46 +000088 public:
89 /// AddToWorkList - Add to the work list making sure it's instance is at the
90 /// the back (next to be processed.)
91 void AddToWorkList(SDNode *N) {
92 removeFromWorkList(N);
93 WorkList.push_back(N);
94 }
95
Chris Lattner7bcb18f2008-02-03 06:49:24 +000096 /// removeFromWorkList - remove all instances of N from the worklist.
97 ///
98 void removeFromWorkList(SDNode *N) {
99 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
100 WorkList.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000101 }
102
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000103 SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
104 bool AddTo = true);
105
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000106 SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
107 return CombineTo(N, &Res, 1, AddTo);
108 }
109
110 SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
111 bool AddTo = true) {
112 SDOperand To[] = { Res0, Res1 };
113 return CombineTo(N, To, 2, AddTo);
114 }
Chris Lattner5872a362008-01-17 07:00:52 +0000115
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000116 private:
117
118 /// SimplifyDemandedBits - Check the specified integer node value to see if
119 /// it can be simplified or if things it uses can be simplified by bit
120 /// propagation. If so, return true.
Dan Gohman11607792008-02-27 00:25:32 +0000121 bool SimplifyDemandedBits(SDOperand Op) {
122 APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
123 return SimplifyDemandedBits(Op, Demanded);
124 }
125
126 bool SimplifyDemandedBits(SDOperand Op, const APInt &Demanded);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127
128 bool CombineToPreIndexedLoadStore(SDNode *N);
129 bool CombineToPostIndexedLoadStore(SDNode *N);
130
131
Dan Gohman6c89ea72007-10-08 17:57:15 +0000132 /// combine - call the node-specific routine that knows how to fold each
133 /// particular type of node. If that doesn't do anything, try the
134 /// target-specific DAG combines.
135 SDOperand combine(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136
137 // Visitation implementation - Implement dag node combining for different
138 // node types. The semantics are as follows:
139 // Return Value:
140 // SDOperand.Val == 0 - No change was made
141 // SDOperand.Val == N - N was replaced, is dead, and is already handled.
142 // otherwise - N should be replaced by the returned Operand.
143 //
144 SDOperand visitTokenFactor(SDNode *N);
Chris Lattnerf32fa7f2008-02-13 07:25:05 +0000145 SDOperand visitMERGE_VALUES(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146 SDOperand visitADD(SDNode *N);
147 SDOperand visitSUB(SDNode *N);
148 SDOperand visitADDC(SDNode *N);
149 SDOperand visitADDE(SDNode *N);
150 SDOperand visitMUL(SDNode *N);
151 SDOperand visitSDIV(SDNode *N);
152 SDOperand visitUDIV(SDNode *N);
153 SDOperand visitSREM(SDNode *N);
154 SDOperand visitUREM(SDNode *N);
155 SDOperand visitMULHU(SDNode *N);
156 SDOperand visitMULHS(SDNode *N);
Dan Gohman6c89ea72007-10-08 17:57:15 +0000157 SDOperand visitSMUL_LOHI(SDNode *N);
158 SDOperand visitUMUL_LOHI(SDNode *N);
159 SDOperand visitSDIVREM(SDNode *N);
160 SDOperand visitUDIVREM(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 SDOperand visitAND(SDNode *N);
162 SDOperand visitOR(SDNode *N);
163 SDOperand visitXOR(SDNode *N);
164 SDOperand SimplifyVBinOp(SDNode *N);
165 SDOperand visitSHL(SDNode *N);
166 SDOperand visitSRA(SDNode *N);
167 SDOperand visitSRL(SDNode *N);
168 SDOperand visitCTLZ(SDNode *N);
169 SDOperand visitCTTZ(SDNode *N);
170 SDOperand visitCTPOP(SDNode *N);
171 SDOperand visitSELECT(SDNode *N);
172 SDOperand visitSELECT_CC(SDNode *N);
173 SDOperand visitSETCC(SDNode *N);
174 SDOperand visitSIGN_EXTEND(SDNode *N);
175 SDOperand visitZERO_EXTEND(SDNode *N);
176 SDOperand visitANY_EXTEND(SDNode *N);
177 SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
178 SDOperand visitTRUNCATE(SDNode *N);
179 SDOperand visitBIT_CONVERT(SDNode *N);
180 SDOperand visitFADD(SDNode *N);
181 SDOperand visitFSUB(SDNode *N);
182 SDOperand visitFMUL(SDNode *N);
183 SDOperand visitFDIV(SDNode *N);
184 SDOperand visitFREM(SDNode *N);
185 SDOperand visitFCOPYSIGN(SDNode *N);
186 SDOperand visitSINT_TO_FP(SDNode *N);
187 SDOperand visitUINT_TO_FP(SDNode *N);
188 SDOperand visitFP_TO_SINT(SDNode *N);
189 SDOperand visitFP_TO_UINT(SDNode *N);
190 SDOperand visitFP_ROUND(SDNode *N);
191 SDOperand visitFP_ROUND_INREG(SDNode *N);
192 SDOperand visitFP_EXTEND(SDNode *N);
193 SDOperand visitFNEG(SDNode *N);
194 SDOperand visitFABS(SDNode *N);
195 SDOperand visitBRCOND(SDNode *N);
196 SDOperand visitBR_CC(SDNode *N);
197 SDOperand visitLOAD(SDNode *N);
198 SDOperand visitSTORE(SDNode *N);
199 SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
Evan Chengd7ba7ed2007-10-06 08:19:55 +0000200 SDOperand visitEXTRACT_VECTOR_ELT(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201 SDOperand visitBUILD_VECTOR(SDNode *N);
202 SDOperand visitCONCAT_VECTORS(SDNode *N);
203 SDOperand visitVECTOR_SHUFFLE(SDNode *N);
204
205 SDOperand XformToShuffleWithZero(SDNode *N);
206 SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
207
Chris Lattner91ed3c32007-12-06 07:33:36 +0000208 SDOperand visitShiftByConstant(SDNode *N, unsigned Amt);
209
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
211 SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
212 SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
213 SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
214 SDOperand N3, ISD::CondCode CC,
215 bool NotExtCompare = false);
216 SDOperand SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
217 ISD::CondCode Cond, bool foldBooleans = true);
Chris Lattner4a7c8452008-01-26 01:09:19 +0000218 SDOperand SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
219 unsigned HiOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 SDOperand ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT::ValueType);
221 SDOperand BuildSDIV(SDNode *N);
222 SDOperand BuildUDIV(SDNode *N);
223 SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
224 SDOperand ReduceLoadWidth(SDNode *N);
225
Dan Gohman07961cd2008-02-25 21:11:39 +0000226 SDOperand GetDemandedBits(SDOperand V, const APInt &Mask);
Chris Lattnere8671c52007-10-13 06:35:54 +0000227
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
229 /// looking for aliasing nodes and adding them to the Aliases vector.
230 void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
231 SmallVector<SDOperand, 8> &Aliases);
232
233 /// isAlias - Return true if there is any possibility that the two addresses
234 /// overlap.
235 bool isAlias(SDOperand Ptr1, int64_t Size1,
236 const Value *SrcValue1, int SrcValueOffset1,
237 SDOperand Ptr2, int64_t Size2,
238 const Value *SrcValue2, int SrcValueOffset2);
239
240 /// FindAliasInfo - Extracts the relevant alias information from the memory
241 /// node. Returns true if the operand was a load.
242 bool FindAliasInfo(SDNode *N,
243 SDOperand &Ptr, int64_t &Size,
244 const Value *&SrcValue, int &SrcValueOffset);
245
246 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
247 /// looking for a better chain (aliasing node.)
248 SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
249
250public:
251 DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
252 : DAG(D),
253 TLI(D.getTargetLoweringInfo()),
254 AfterLegalize(false),
255 AA(A) {}
256
257 /// Run - runs the dag combiner on all nodes in the work list
258 void Run(bool RunningAfterLegalize);
259 };
260}
261
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000262
263namespace {
264/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
265/// nodes from the worklist.
266class VISIBILITY_HIDDEN WorkListRemover :
267 public SelectionDAG::DAGUpdateListener {
268 DAGCombiner &DC;
269public:
Dan Gohmana789bff2008-02-20 16:44:09 +0000270 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000271
272 virtual void NodeDeleted(SDNode *N) {
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000273 DC.removeFromWorkList(N);
274 }
275
276 virtual void NodeUpdated(SDNode *N) {
277 // Ignore updates.
278 }
279};
280}
281
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000282//===----------------------------------------------------------------------===//
283// TargetLowering::DAGCombinerInfo implementation
284//===----------------------------------------------------------------------===//
285
286void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
287 ((DAGCombiner*)DC)->AddToWorkList(N);
288}
289
290SDOperand TargetLowering::DAGCombinerInfo::
291CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
292 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
293}
294
295SDOperand TargetLowering::DAGCombinerInfo::
296CombineTo(SDNode *N, SDOperand Res) {
297 return ((DAGCombiner*)DC)->CombineTo(N, Res);
298}
299
300
301SDOperand TargetLowering::DAGCombinerInfo::
302CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
303 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
304}
305
306
307//===----------------------------------------------------------------------===//
308// Helper Functions
309//===----------------------------------------------------------------------===//
310
311/// isNegatibleForFree - Return 1 if we can compute the negated form of the
312/// specified expression for the same cost as the expression itself, or 2 if we
313/// can compute the negated form more cheaply than the expression itself.
Chris Lattnere0992b82008-02-26 07:04:54 +0000314static char isNegatibleForFree(SDOperand Op, bool AfterLegalize,
315 unsigned Depth = 0) {
Dale Johannesenb89072e2007-10-16 23:38:29 +0000316 // No compile time optimizations on this type.
317 if (Op.getValueType() == MVT::ppcf128)
318 return 0;
319
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000320 // fneg is removable even if it has multiple uses.
321 if (Op.getOpcode() == ISD::FNEG) return 2;
322
323 // Don't allow anything with multiple uses.
324 if (!Op.hasOneUse()) return 0;
325
326 // Don't recurse exponentially.
327 if (Depth > 6) return 0;
328
329 switch (Op.getOpcode()) {
330 default: return false;
331 case ISD::ConstantFP:
Chris Lattnere0992b82008-02-26 07:04:54 +0000332 // Don't invert constant FP values after legalize. The negated constant
333 // isn't necessarily legal.
334 return AfterLegalize ? 0 : 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000335 case ISD::FADD:
336 // FIXME: determine better conditions for this xform.
337 if (!UnsafeFPMath) return 0;
338
339 // -(A+B) -> -A - B
Chris Lattnere0992b82008-02-26 07:04:54 +0000340 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341 return V;
342 // -(A+B) -> -B - A
Chris Lattnere0992b82008-02-26 07:04:54 +0000343 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 case ISD::FSUB:
345 // We can't turn -(A-B) into B-A when we honor signed zeros.
346 if (!UnsafeFPMath) return 0;
347
348 // -(A-B) -> B-A
349 return 1;
350
351 case ISD::FMUL:
352 case ISD::FDIV:
353 if (HonorSignDependentRoundingFPMath()) return 0;
354
355 // -(X*Y) -> (-X * Y) or (X*-Y)
Chris Lattnere0992b82008-02-26 07:04:54 +0000356 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357 return V;
358
Chris Lattnere0992b82008-02-26 07:04:54 +0000359 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360
361 case ISD::FP_EXTEND:
362 case ISD::FP_ROUND:
363 case ISD::FSIN:
Chris Lattnere0992b82008-02-26 07:04:54 +0000364 return isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000365 }
366}
367
368/// GetNegatedExpression - If isNegatibleForFree returns true, this function
369/// returns the newly negated expression.
370static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
Chris Lattnere0992b82008-02-26 07:04:54 +0000371 bool AfterLegalize, unsigned Depth = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372 // fneg is removable even if it has multiple uses.
373 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
374
375 // Don't allow anything with multiple uses.
376 assert(Op.hasOneUse() && "Unknown reuse!");
377
378 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
379 switch (Op.getOpcode()) {
380 default: assert(0 && "Unknown code");
Dale Johannesen7604c1b2007-08-31 23:34:27 +0000381 case ISD::ConstantFP: {
382 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
383 V.changeSign();
384 return DAG.getConstantFP(V, Op.getValueType());
385 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386 case ISD::FADD:
387 // FIXME: determine better conditions for this xform.
388 assert(UnsafeFPMath);
389
390 // -(A+B) -> -A - B
Chris Lattnere0992b82008-02-26 07:04:54 +0000391 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392 return DAG.getNode(ISD::FSUB, Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000393 GetNegatedExpression(Op.getOperand(0), DAG,
394 AfterLegalize, Depth+1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000395 Op.getOperand(1));
396 // -(A+B) -> -B - A
397 return DAG.getNode(ISD::FSUB, Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000398 GetNegatedExpression(Op.getOperand(1), DAG,
399 AfterLegalize, Depth+1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000400 Op.getOperand(0));
401 case ISD::FSUB:
402 // We can't turn -(A-B) into B-A when we honor signed zeros.
403 assert(UnsafeFPMath);
404
405 // -(0-B) -> B
406 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen7604c1b2007-08-31 23:34:27 +0000407 if (N0CFP->getValueAPF().isZero())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408 return Op.getOperand(1);
409
410 // -(A-B) -> B-A
411 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1),
412 Op.getOperand(0));
413
414 case ISD::FMUL:
415 case ISD::FDIV:
416 assert(!HonorSignDependentRoundingFPMath());
417
418 // -(X*Y) -> -X * Y
Chris Lattner46360032008-02-26 17:09:59 +0000419 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000421 GetNegatedExpression(Op.getOperand(0), DAG,
422 AfterLegalize, Depth+1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000423 Op.getOperand(1));
424
425 // -(X*Y) -> X * -Y
426 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
427 Op.getOperand(0),
Chris Lattnere0992b82008-02-26 07:04:54 +0000428 GetNegatedExpression(Op.getOperand(1), DAG,
429 AfterLegalize, Depth+1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000430
431 case ISD::FP_EXTEND:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432 case ISD::FSIN:
433 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000434 GetNegatedExpression(Op.getOperand(0), DAG,
435 AfterLegalize, Depth+1));
Chris Lattner5872a362008-01-17 07:00:52 +0000436 case ISD::FP_ROUND:
437 return DAG.getNode(ISD::FP_ROUND, Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000438 GetNegatedExpression(Op.getOperand(0), DAG,
439 AfterLegalize, Depth+1),
Chris Lattner5872a362008-01-17 07:00:52 +0000440 Op.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000441 }
442}
443
444
445// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
446// that selects between the values 1 and 0, making it equivalent to a setcc.
447// Also, set the incoming LHS, RHS, and CC references to the appropriate
448// nodes based on the type of node we are checking. This simplifies life a
449// bit for the callers.
450static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
451 SDOperand &CC) {
452 if (N.getOpcode() == ISD::SETCC) {
453 LHS = N.getOperand(0);
454 RHS = N.getOperand(1);
455 CC = N.getOperand(2);
456 return true;
457 }
458 if (N.getOpcode() == ISD::SELECT_CC &&
459 N.getOperand(2).getOpcode() == ISD::Constant &&
460 N.getOperand(3).getOpcode() == ISD::Constant &&
Dan Gohman9d24dc72008-03-13 22:13:53 +0000461 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000462 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
463 LHS = N.getOperand(0);
464 RHS = N.getOperand(1);
465 CC = N.getOperand(4);
466 return true;
467 }
468 return false;
469}
470
471// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
472// one use. If this is true, it allows the users to invert the operation for
473// free when it is profitable to do so.
474static bool isOneUseSetCC(SDOperand N) {
475 SDOperand N0, N1, N2;
476 if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
477 return true;
478 return false;
479}
480
481SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
482 MVT::ValueType VT = N0.getValueType();
483 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
484 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
485 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
486 if (isa<ConstantSDNode>(N1)) {
487 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
488 AddToWorkList(OpNode.Val);
489 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
490 } else if (N0.hasOneUse()) {
491 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
492 AddToWorkList(OpNode.Val);
493 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
494 }
495 }
496 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
497 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
498 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
499 if (isa<ConstantSDNode>(N0)) {
500 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
501 AddToWorkList(OpNode.Val);
502 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
503 } else if (N1.hasOneUse()) {
504 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
505 AddToWorkList(OpNode.Val);
506 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
507 }
508 }
509 return SDOperand();
510}
511
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000512SDOperand DAGCombiner::CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
513 bool AddTo) {
514 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
515 ++NodesCombined;
516 DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
517 DOUT << "\nWith: "; DEBUG(To[0].Val->dump(&DAG));
518 DOUT << " and " << NumTo-1 << " other values\n";
519 WorkListRemover DeadNodes(*this);
520 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
521
522 if (AddTo) {
523 // Push the new nodes and any users onto the worklist
524 for (unsigned i = 0, e = NumTo; i != e; ++i) {
525 AddToWorkList(To[i].Val);
526 AddUsersToWorkList(To[i].Val);
527 }
528 }
529
530 // Nodes can be reintroduced into the worklist. Make sure we do not
531 // process a node that has been replaced.
532 removeFromWorkList(N);
533
534 // Finally, since the node is now dead, remove it from the graph.
535 DAG.DeleteNode(N);
536 return SDOperand(N, 0);
537}
538
539/// SimplifyDemandedBits - Check the specified integer node value to see if
540/// it can be simplified or if things it uses can be simplified by bit
541/// propagation. If so, return true.
Dan Gohman11607792008-02-27 00:25:32 +0000542bool DAGCombiner::SimplifyDemandedBits(SDOperand Op, const APInt &Demanded) {
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000543 TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize);
Dan Gohman11607792008-02-27 00:25:32 +0000544 APInt KnownZero, KnownOne;
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000545 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
546 return false;
547
548 // Revisit the node.
549 AddToWorkList(Op.Val);
550
551 // Replace the old value with the new one.
552 ++NodesCombined;
553 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.Val->dump(&DAG));
554 DOUT << "\nWith: "; DEBUG(TLO.New.Val->dump(&DAG));
555 DOUT << '\n';
556
557 // Replace all uses. If any nodes become isomorphic to other nodes and
558 // are deleted, make sure to remove them from our worklist.
559 WorkListRemover DeadNodes(*this);
560 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
561
562 // Push the new node and any (possibly new) users onto the worklist.
563 AddToWorkList(TLO.New.Val);
564 AddUsersToWorkList(TLO.New.Val);
565
566 // Finally, if the node is now dead, remove it from the graph. The node
567 // may not be dead if the replacement process recursively simplified to
568 // something else needing this node.
569 if (TLO.Old.Val->use_empty()) {
570 removeFromWorkList(TLO.Old.Val);
571
572 // If the operands of this node are only used by the node, they will now
573 // be dead. Make sure to visit them first to delete dead nodes early.
574 for (unsigned i = 0, e = TLO.Old.Val->getNumOperands(); i != e; ++i)
575 if (TLO.Old.Val->getOperand(i).Val->hasOneUse())
576 AddToWorkList(TLO.Old.Val->getOperand(i).Val);
577
578 DAG.DeleteNode(TLO.Old.Val);
579 }
580 return true;
581}
582
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583//===----------------------------------------------------------------------===//
584// Main DAG Combiner implementation
585//===----------------------------------------------------------------------===//
586
587void DAGCombiner::Run(bool RunningAfterLegalize) {
588 // set the instance variable, so that the various visit routines may use it.
589 AfterLegalize = RunningAfterLegalize;
590
591 // Add all the dag nodes to the worklist.
592 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
593 E = DAG.allnodes_end(); I != E; ++I)
594 WorkList.push_back(I);
595
596 // Create a dummy node (which is not added to allnodes), that adds a reference
597 // to the root node, preventing it from being deleted, and tracking any
598 // changes of the root.
599 HandleSDNode Dummy(DAG.getRoot());
600
601 // The root of the dag may dangle to deleted nodes until the dag combiner is
602 // done. Set it to null to avoid confusion.
603 DAG.setRoot(SDOperand());
604
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000605 // while the worklist isn't empty, inspect the node on the end of it and
606 // try and combine it.
607 while (!WorkList.empty()) {
608 SDNode *N = WorkList.back();
609 WorkList.pop_back();
610
611 // If N has no uses, it is dead. Make sure to revisit all N's operands once
612 // N is deleted from the DAG, since they too may now be dead or may have a
613 // reduced number of uses, allowing other xforms.
614 if (N->use_empty() && N != &Dummy) {
615 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
616 AddToWorkList(N->getOperand(i).Val);
617
618 DAG.DeleteNode(N);
619 continue;
620 }
621
Dan Gohman6c89ea72007-10-08 17:57:15 +0000622 SDOperand RV = combine(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000623
Chris Lattner20e53902008-01-25 23:34:24 +0000624 if (RV.Val == 0)
625 continue;
626
627 ++NodesCombined;
Chris Lattner4a7c8452008-01-26 01:09:19 +0000628
Chris Lattner20e53902008-01-25 23:34:24 +0000629 // If we get back the same node we passed in, rather than a new node or
630 // zero, we know that the node must have defined multiple values and
631 // CombineTo was used. Since CombineTo takes care of the worklist
632 // mechanics for us, we have no work to do in this case.
633 if (RV.Val == N)
634 continue;
635
636 assert(N->getOpcode() != ISD::DELETED_NODE &&
637 RV.Val->getOpcode() != ISD::DELETED_NODE &&
638 "Node was deleted but visit returned new node!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000639
Chris Lattner20e53902008-01-25 23:34:24 +0000640 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
641 DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
642 DOUT << '\n';
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000643 WorkListRemover DeadNodes(*this);
Chris Lattner20e53902008-01-25 23:34:24 +0000644 if (N->getNumValues() == RV.Val->getNumValues())
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000645 DAG.ReplaceAllUsesWith(N, RV.Val, &DeadNodes);
Chris Lattner20e53902008-01-25 23:34:24 +0000646 else {
Chris Lattner4a7c8452008-01-26 01:09:19 +0000647 assert(N->getValueType(0) == RV.getValueType() &&
648 N->getNumValues() == 1 && "Type mismatch");
Chris Lattner20e53902008-01-25 23:34:24 +0000649 SDOperand OpV = RV;
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000650 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000651 }
Chris Lattner20e53902008-01-25 23:34:24 +0000652
653 // Push the new node and any users onto the worklist
654 AddToWorkList(RV.Val);
655 AddUsersToWorkList(RV.Val);
656
657 // Add any uses of the old node to the worklist in case this node is the
658 // last one that uses them. They may become dead after this node is
659 // deleted.
660 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
661 AddToWorkList(N->getOperand(i).Val);
662
663 // Nodes can be reintroduced into the worklist. Make sure we do not
664 // process a node that has been replaced.
665 removeFromWorkList(N);
Chris Lattner20e53902008-01-25 23:34:24 +0000666
667 // Finally, since the node is now dead, remove it from the graph.
668 DAG.DeleteNode(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 }
670
671 // If the root changed (e.g. it was a dead load, update the root).
672 DAG.setRoot(Dummy.getValue());
673}
674
675SDOperand DAGCombiner::visit(SDNode *N) {
676 switch(N->getOpcode()) {
677 default: break;
678 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattnerf32fa7f2008-02-13 07:25:05 +0000679 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000680 case ISD::ADD: return visitADD(N);
681 case ISD::SUB: return visitSUB(N);
682 case ISD::ADDC: return visitADDC(N);
683 case ISD::ADDE: return visitADDE(N);
684 case ISD::MUL: return visitMUL(N);
685 case ISD::SDIV: return visitSDIV(N);
686 case ISD::UDIV: return visitUDIV(N);
687 case ISD::SREM: return visitSREM(N);
688 case ISD::UREM: return visitUREM(N);
689 case ISD::MULHU: return visitMULHU(N);
690 case ISD::MULHS: return visitMULHS(N);
Dan Gohman6c89ea72007-10-08 17:57:15 +0000691 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
692 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
693 case ISD::SDIVREM: return visitSDIVREM(N);
694 case ISD::UDIVREM: return visitUDIVREM(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000695 case ISD::AND: return visitAND(N);
696 case ISD::OR: return visitOR(N);
697 case ISD::XOR: return visitXOR(N);
698 case ISD::SHL: return visitSHL(N);
699 case ISD::SRA: return visitSRA(N);
700 case ISD::SRL: return visitSRL(N);
701 case ISD::CTLZ: return visitCTLZ(N);
702 case ISD::CTTZ: return visitCTTZ(N);
703 case ISD::CTPOP: return visitCTPOP(N);
704 case ISD::SELECT: return visitSELECT(N);
705 case ISD::SELECT_CC: return visitSELECT_CC(N);
706 case ISD::SETCC: return visitSETCC(N);
707 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
708 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
709 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
710 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
711 case ISD::TRUNCATE: return visitTRUNCATE(N);
712 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
713 case ISD::FADD: return visitFADD(N);
714 case ISD::FSUB: return visitFSUB(N);
715 case ISD::FMUL: return visitFMUL(N);
716 case ISD::FDIV: return visitFDIV(N);
717 case ISD::FREM: return visitFREM(N);
718 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
719 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
720 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
721 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
722 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
723 case ISD::FP_ROUND: return visitFP_ROUND(N);
724 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
725 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
726 case ISD::FNEG: return visitFNEG(N);
727 case ISD::FABS: return visitFABS(N);
728 case ISD::BRCOND: return visitBRCOND(N);
729 case ISD::BR_CC: return visitBR_CC(N);
730 case ISD::LOAD: return visitLOAD(N);
731 case ISD::STORE: return visitSTORE(N);
732 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Chengd7ba7ed2007-10-06 08:19:55 +0000733 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
735 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
736 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
737 }
738 return SDOperand();
739}
740
Dan Gohman6c89ea72007-10-08 17:57:15 +0000741SDOperand DAGCombiner::combine(SDNode *N) {
742
743 SDOperand RV = visit(N);
744
745 // If nothing happened, try a target-specific DAG combine.
746 if (RV.Val == 0) {
747 assert(N->getOpcode() != ISD::DELETED_NODE &&
748 "Node was deleted but visit returned NULL!");
749
750 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
751 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
752
753 // Expose the DAG combiner to the target combiner impls.
754 TargetLowering::DAGCombinerInfo
755 DagCombineInfo(DAG, !AfterLegalize, false, this);
756
757 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
758 }
759 }
760
761 return RV;
762}
763
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000764/// getInputChainForNode - Given a node, return its input chain if it has one,
765/// otherwise return a null sd operand.
766static SDOperand getInputChainForNode(SDNode *N) {
767 if (unsigned NumOps = N->getNumOperands()) {
768 if (N->getOperand(0).getValueType() == MVT::Other)
769 return N->getOperand(0);
770 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
771 return N->getOperand(NumOps-1);
772 for (unsigned i = 1; i < NumOps-1; ++i)
773 if (N->getOperand(i).getValueType() == MVT::Other)
774 return N->getOperand(i);
775 }
776 return SDOperand(0, 0);
777}
778
779SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
780 // If N has two operands, where one has an input chain equal to the other,
781 // the 'other' chain is redundant.
782 if (N->getNumOperands() == 2) {
783 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
784 return N->getOperand(0);
785 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
786 return N->getOperand(1);
787 }
788
789 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
790 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
791 SmallPtrSet<SDNode*, 16> SeenOps;
792 bool Changed = false; // If we should replace this token factor.
793
794 // Start out with this token factor.
795 TFs.push_back(N);
796
797 // Iterate through token factors. The TFs grows when new token factors are
798 // encountered.
799 for (unsigned i = 0; i < TFs.size(); ++i) {
800 SDNode *TF = TFs[i];
801
802 // Check each of the operands.
803 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
804 SDOperand Op = TF->getOperand(i);
805
806 switch (Op.getOpcode()) {
807 case ISD::EntryToken:
808 // Entry tokens don't need to be added to the list. They are
809 // rededundant.
810 Changed = true;
811 break;
812
813 case ISD::TokenFactor:
814 if ((CombinerAA || Op.hasOneUse()) &&
815 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
816 // Queue up for processing.
817 TFs.push_back(Op.Val);
818 // Clean up in case the token factor is removed.
819 AddToWorkList(Op.Val);
820 Changed = true;
821 break;
822 }
823 // Fall thru
824
825 default:
826 // Only add if it isn't already in the list.
827 if (SeenOps.insert(Op.Val))
828 Ops.push_back(Op);
829 else
830 Changed = true;
831 break;
832 }
833 }
834 }
835
836 SDOperand Result;
837
838 // If we've change things around then replace token factor.
839 if (Changed) {
Dan Gohman301f4052008-01-29 13:02:09 +0000840 if (Ops.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841 // The entry token is the only possible outcome.
842 Result = DAG.getEntryNode();
843 } else {
844 // New and improved token factor.
845 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
846 }
847
848 // Don't add users to work list.
849 return CombineTo(N, Result, false);
850 }
851
852 return Result;
853}
854
Chris Lattnerf32fa7f2008-02-13 07:25:05 +0000855/// MERGE_VALUES can always be eliminated.
856SDOperand DAGCombiner::visitMERGE_VALUES(SDNode *N) {
857 WorkListRemover DeadNodes(*this);
858 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
859 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, i), N->getOperand(i),
860 &DeadNodes);
861 removeFromWorkList(N);
862 DAG.DeleteNode(N);
863 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
864}
865
866
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867static
868SDOperand combineShlAddConstant(SDOperand N0, SDOperand N1, SelectionDAG &DAG) {
869 MVT::ValueType VT = N0.getValueType();
870 SDOperand N00 = N0.getOperand(0);
871 SDOperand N01 = N0.getOperand(1);
872 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
873 if (N01C && N00.getOpcode() == ISD::ADD && N00.Val->hasOneUse() &&
874 isa<ConstantSDNode>(N00.getOperand(1))) {
875 N0 = DAG.getNode(ISD::ADD, VT,
876 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
877 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
878 return DAG.getNode(ISD::ADD, VT, N0, N1);
879 }
880 return SDOperand();
881}
882
883static
884SDOperand combineSelectAndUse(SDNode *N, SDOperand Slct, SDOperand OtherOp,
885 SelectionDAG &DAG) {
886 MVT::ValueType VT = N->getValueType(0);
887 unsigned Opc = N->getOpcode();
888 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
889 SDOperand LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
890 SDOperand RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
891 ISD::CondCode CC = ISD::SETCC_INVALID;
892 if (isSlctCC)
893 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
894 else {
895 SDOperand CCOp = Slct.getOperand(0);
896 if (CCOp.getOpcode() == ISD::SETCC)
897 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
898 }
899
900 bool DoXform = false;
901 bool InvCC = false;
902 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
903 "Bad input!");
904 if (LHS.getOpcode() == ISD::Constant &&
905 cast<ConstantSDNode>(LHS)->isNullValue())
906 DoXform = true;
907 else if (CC != ISD::SETCC_INVALID &&
908 RHS.getOpcode() == ISD::Constant &&
909 cast<ConstantSDNode>(RHS)->isNullValue()) {
910 std::swap(LHS, RHS);
Chris Lattner667f9c12008-01-17 07:20:38 +0000911 SDOperand Op0 = Slct.getOperand(0);
912 bool isInt = MVT::isInteger(isSlctCC ? Op0.getValueType()
913 : Op0.getOperand(0).getValueType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000914 CC = ISD::getSetCCInverse(CC, isInt);
915 DoXform = true;
916 InvCC = true;
917 }
918
919 if (DoXform) {
920 SDOperand Result = DAG.getNode(Opc, VT, OtherOp, RHS);
921 if (isSlctCC)
922 return DAG.getSelectCC(OtherOp, Result,
923 Slct.getOperand(0), Slct.getOperand(1), CC);
924 SDOperand CCOp = Slct.getOperand(0);
925 if (InvCC)
926 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
927 CCOp.getOperand(1), CC);
928 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
929 }
930 return SDOperand();
931}
932
933SDOperand DAGCombiner::visitADD(SDNode *N) {
934 SDOperand N0 = N->getOperand(0);
935 SDOperand N1 = N->getOperand(1);
936 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
937 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
938 MVT::ValueType VT = N0.getValueType();
939
940 // fold vector ops
941 if (MVT::isVector(VT)) {
942 SDOperand FoldedVOp = SimplifyVBinOp(N);
943 if (FoldedVOp.Val) return FoldedVOp;
944 }
945
946 // fold (add x, undef) -> undef
947 if (N0.getOpcode() == ISD::UNDEF)
948 return N0;
949 if (N1.getOpcode() == ISD::UNDEF)
950 return N1;
951 // fold (add c1, c2) -> c1+c2
952 if (N0C && N1C)
Dan Gohman9d24dc72008-03-13 22:13:53 +0000953 return DAG.getConstant(N0C->getAPIntValue() + N1C->getAPIntValue(), VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000954 // canonicalize constant to RHS
955 if (N0C && !N1C)
956 return DAG.getNode(ISD::ADD, VT, N1, N0);
957 // fold (add x, 0) -> x
958 if (N1C && N1C->isNullValue())
959 return N0;
960 // fold ((c1-A)+c2) -> (c1+c2)-A
961 if (N1C && N0.getOpcode() == ISD::SUB)
962 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
963 return DAG.getNode(ISD::SUB, VT,
Dan Gohman9d24dc72008-03-13 22:13:53 +0000964 DAG.getConstant(N1C->getAPIntValue()+
965 N0C->getAPIntValue(), VT),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966 N0.getOperand(1));
967 // reassociate add
968 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
969 if (RADD.Val != 0)
970 return RADD;
971 // fold ((0-A) + B) -> B-A
972 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
973 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
974 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
975 // fold (A + (0-B)) -> A-B
976 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
977 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
978 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
979 // fold (A+(B-A)) -> B
980 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
981 return N1.getOperand(0);
982
983 if (!MVT::isVector(VT) && SimplifyDemandedBits(SDOperand(N, 0)))
984 return SDOperand(N, 0);
985
986 // fold (a+b) -> (a|b) iff a and b share no bits.
987 if (MVT::isInteger(VT) && !MVT::isVector(VT)) {
Dan Gohmanbea075f2008-02-20 16:33:30 +0000988 APInt LHSZero, LHSOne;
989 APInt RHSZero, RHSOne;
990 APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000991 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
Dan Gohmanbea075f2008-02-20 16:33:30 +0000992 if (LHSZero.getBoolValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
994
995 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
996 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
997 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
998 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
999 return DAG.getNode(ISD::OR, VT, N0, N1);
1000 }
1001 }
1002
1003 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1004 if (N0.getOpcode() == ISD::SHL && N0.Val->hasOneUse()) {
1005 SDOperand Result = combineShlAddConstant(N0, N1, DAG);
1006 if (Result.Val) return Result;
1007 }
1008 if (N1.getOpcode() == ISD::SHL && N1.Val->hasOneUse()) {
1009 SDOperand Result = combineShlAddConstant(N1, N0, DAG);
1010 if (Result.Val) return Result;
1011 }
1012
1013 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1014 if (N0.getOpcode() == ISD::SELECT && N0.Val->hasOneUse()) {
1015 SDOperand Result = combineSelectAndUse(N, N0, N1, DAG);
1016 if (Result.Val) return Result;
1017 }
1018 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1019 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1020 if (Result.Val) return Result;
1021 }
1022
1023 return SDOperand();
1024}
1025
1026SDOperand DAGCombiner::visitADDC(SDNode *N) {
1027 SDOperand N0 = N->getOperand(0);
1028 SDOperand N1 = N->getOperand(1);
1029 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1030 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1031 MVT::ValueType VT = N0.getValueType();
1032
1033 // If the flag result is dead, turn this into an ADD.
1034 if (N->hasNUsesOfValue(0, 1))
1035 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
1036 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1037
1038 // canonicalize constant to RHS.
1039 if (N0C && !N1C) {
1040 SDOperand Ops[] = { N1, N0 };
1041 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
1042 }
1043
1044 // fold (addc x, 0) -> x + no carry out
1045 if (N1C && N1C->isNullValue())
1046 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1047
1048 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmanbea075f2008-02-20 16:33:30 +00001049 APInt LHSZero, LHSOne;
1050 APInt RHSZero, RHSOne;
1051 APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001052 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
Dan Gohmanbea075f2008-02-20 16:33:30 +00001053 if (LHSZero.getBoolValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001054 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1055
1056 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1057 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1058 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1059 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1060 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
1061 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1062 }
1063
1064 return SDOperand();
1065}
1066
1067SDOperand DAGCombiner::visitADDE(SDNode *N) {
1068 SDOperand N0 = N->getOperand(0);
1069 SDOperand N1 = N->getOperand(1);
1070 SDOperand CarryIn = N->getOperand(2);
1071 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1072 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1073 //MVT::ValueType VT = N0.getValueType();
1074
1075 // canonicalize constant to RHS
1076 if (N0C && !N1C) {
1077 SDOperand Ops[] = { N1, N0, CarryIn };
1078 return DAG.getNode(ISD::ADDE, N->getVTList(), Ops, 3);
1079 }
1080
1081 // fold (adde x, y, false) -> (addc x, y)
1082 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) {
1083 SDOperand Ops[] = { N1, N0 };
1084 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
1085 }
1086
1087 return SDOperand();
1088}
1089
1090
1091
1092SDOperand DAGCombiner::visitSUB(SDNode *N) {
1093 SDOperand N0 = N->getOperand(0);
1094 SDOperand N1 = N->getOperand(1);
1095 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1096 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1097 MVT::ValueType VT = N0.getValueType();
1098
1099 // fold vector ops
1100 if (MVT::isVector(VT)) {
1101 SDOperand FoldedVOp = SimplifyVBinOp(N);
1102 if (FoldedVOp.Val) return FoldedVOp;
1103 }
1104
1105 // fold (sub x, x) -> 0
Evan Chenga15896e2008-03-12 07:02:50 +00001106 if (N0 == N1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001107 return DAG.getConstant(0, N->getValueType(0));
1108 // fold (sub c1, c2) -> c1-c2
1109 if (N0C && N1C)
1110 return DAG.getNode(ISD::SUB, VT, N0, N1);
1111 // fold (sub x, c) -> (add x, -c)
1112 if (N1C)
Dan Gohman9d24dc72008-03-13 22:13:53 +00001113 return DAG.getNode(ISD::ADD, VT, N0,
1114 DAG.getConstant(-N1C->getAPIntValue(), VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001115 // fold (A+B)-A -> B
1116 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1117 return N0.getOperand(1);
1118 // fold (A+B)-B -> A
1119 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1120 return N0.getOperand(0);
1121 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1122 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1123 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1124 if (Result.Val) return Result;
1125 }
1126 // If either operand of a sub is undef, the result is undef
1127 if (N0.getOpcode() == ISD::UNDEF)
1128 return N0;
1129 if (N1.getOpcode() == ISD::UNDEF)
1130 return N1;
1131
1132 return SDOperand();
1133}
1134
1135SDOperand DAGCombiner::visitMUL(SDNode *N) {
1136 SDOperand N0 = N->getOperand(0);
1137 SDOperand N1 = N->getOperand(1);
1138 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1139 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1140 MVT::ValueType VT = N0.getValueType();
1141
1142 // fold vector ops
1143 if (MVT::isVector(VT)) {
1144 SDOperand FoldedVOp = SimplifyVBinOp(N);
1145 if (FoldedVOp.Val) return FoldedVOp;
1146 }
1147
1148 // fold (mul x, undef) -> 0
1149 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1150 return DAG.getConstant(0, VT);
1151 // fold (mul c1, c2) -> c1*c2
1152 if (N0C && N1C)
1153 return DAG.getNode(ISD::MUL, VT, N0, N1);
1154 // canonicalize constant to RHS
1155 if (N0C && !N1C)
1156 return DAG.getNode(ISD::MUL, VT, N1, N0);
1157 // fold (mul x, 0) -> 0
1158 if (N1C && N1C->isNullValue())
1159 return N1;
1160 // fold (mul x, -1) -> 0-x
1161 if (N1C && N1C->isAllOnesValue())
1162 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1163 // fold (mul x, (1 << c)) -> x << c
Dan Gohman9d24dc72008-03-13 22:13:53 +00001164 if (N1C && N1C->getAPIntValue().isPowerOf2())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001165 return DAG.getNode(ISD::SHL, VT, N0,
Dan Gohman9d24dc72008-03-13 22:13:53 +00001166 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001167 TLI.getShiftAmountTy()));
1168 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1169 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
1170 // FIXME: If the input is something that is easily negated (e.g. a
1171 // single-use add), we should put the negate there.
1172 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1173 DAG.getNode(ISD::SHL, VT, N0,
1174 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
1175 TLI.getShiftAmountTy())));
1176 }
1177
1178 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1179 if (N1C && N0.getOpcode() == ISD::SHL &&
1180 isa<ConstantSDNode>(N0.getOperand(1))) {
1181 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1182 AddToWorkList(C3.Val);
1183 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1184 }
1185
1186 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1187 // use.
1188 {
1189 SDOperand Sh(0,0), Y(0,0);
1190 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1191 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1192 N0.Val->hasOneUse()) {
1193 Sh = N0; Y = N1;
1194 } else if (N1.getOpcode() == ISD::SHL &&
1195 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1196 Sh = N1; Y = N0;
1197 }
1198 if (Sh.Val) {
1199 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1200 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1201 }
1202 }
1203 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1204 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1205 isa<ConstantSDNode>(N0.getOperand(1))) {
1206 return DAG.getNode(ISD::ADD, VT,
1207 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1208 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1209 }
1210
1211 // reassociate mul
1212 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1213 if (RMUL.Val != 0)
1214 return RMUL;
1215
1216 return SDOperand();
1217}
1218
1219SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1220 SDOperand N0 = N->getOperand(0);
1221 SDOperand N1 = N->getOperand(1);
1222 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1223 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1224 MVT::ValueType VT = N->getValueType(0);
1225
1226 // fold vector ops
1227 if (MVT::isVector(VT)) {
1228 SDOperand FoldedVOp = SimplifyVBinOp(N);
1229 if (FoldedVOp.Val) return FoldedVOp;
1230 }
1231
1232 // fold (sdiv c1, c2) -> c1/c2
1233 if (N0C && N1C && !N1C->isNullValue())
1234 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1235 // fold (sdiv X, 1) -> X
1236 if (N1C && N1C->getSignExtended() == 1LL)
1237 return N0;
1238 // fold (sdiv X, -1) -> 0-X
1239 if (N1C && N1C->isAllOnesValue())
1240 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1241 // If we know the sign bits of both operands are zero, strength reduce to a
1242 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Chris Lattner336672f2008-01-27 23:32:17 +00001243 if (!MVT::isVector(VT)) {
Dan Gohman07961cd2008-02-25 21:11:39 +00001244 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Chris Lattner336672f2008-01-27 23:32:17 +00001245 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1246 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001247 // fold (sdiv X, pow2) -> simple ops after legalize
Dan Gohman9d24dc72008-03-13 22:13:53 +00001248 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001249 (isPowerOf2_64(N1C->getSignExtended()) ||
1250 isPowerOf2_64(-N1C->getSignExtended()))) {
1251 // If dividing by powers of two is cheap, then don't perform the following
1252 // fold.
1253 if (TLI.isPow2DivCheap())
1254 return SDOperand();
1255 int64_t pow2 = N1C->getSignExtended();
1256 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1257 unsigned lg2 = Log2_64(abs2);
1258 // Splat the sign bit into the register
1259 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1260 DAG.getConstant(MVT::getSizeInBits(VT)-1,
1261 TLI.getShiftAmountTy()));
1262 AddToWorkList(SGN.Val);
1263 // Add (N0 < 0) ? abs2 - 1 : 0;
1264 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1265 DAG.getConstant(MVT::getSizeInBits(VT)-lg2,
1266 TLI.getShiftAmountTy()));
1267 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1268 AddToWorkList(SRL.Val);
1269 AddToWorkList(ADD.Val); // Divide by pow2
1270 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1271 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1272 // If we're dividing by a positive value, we're done. Otherwise, we must
1273 // negate the result.
1274 if (pow2 > 0)
1275 return SRA;
1276 AddToWorkList(SRA.Val);
1277 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1278 }
1279 // if integer divide is expensive and we satisfy the requirements, emit an
1280 // alternate sequence.
1281 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1282 !TLI.isIntDivCheap()) {
1283 SDOperand Op = BuildSDIV(N);
1284 if (Op.Val) return Op;
1285 }
1286
1287 // undef / X -> 0
1288 if (N0.getOpcode() == ISD::UNDEF)
1289 return DAG.getConstant(0, VT);
1290 // X / undef -> undef
1291 if (N1.getOpcode() == ISD::UNDEF)
1292 return N1;
1293
1294 return SDOperand();
1295}
1296
1297SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1298 SDOperand N0 = N->getOperand(0);
1299 SDOperand N1 = N->getOperand(1);
1300 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1301 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1302 MVT::ValueType VT = N->getValueType(0);
1303
1304 // fold vector ops
1305 if (MVT::isVector(VT)) {
1306 SDOperand FoldedVOp = SimplifyVBinOp(N);
1307 if (FoldedVOp.Val) return FoldedVOp;
1308 }
1309
1310 // fold (udiv c1, c2) -> c1/c2
1311 if (N0C && N1C && !N1C->isNullValue())
1312 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1313 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohman9d24dc72008-03-13 22:13:53 +00001314 if (N1C && N1C->getAPIntValue().isPowerOf2())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001315 return DAG.getNode(ISD::SRL, VT, N0,
Dan Gohman9d24dc72008-03-13 22:13:53 +00001316 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001317 TLI.getShiftAmountTy()));
1318 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1319 if (N1.getOpcode() == ISD::SHL) {
1320 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00001321 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322 MVT::ValueType ADDVT = N1.getOperand(1).getValueType();
1323 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
Dan Gohman9d24dc72008-03-13 22:13:53 +00001324 DAG.getConstant(SHC->getAPIntValue()
1325 .logBase2(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001326 ADDVT));
1327 AddToWorkList(Add.Val);
1328 return DAG.getNode(ISD::SRL, VT, N0, Add);
1329 }
1330 }
1331 }
1332 // fold (udiv x, c) -> alternate
Dan Gohman9d24dc72008-03-13 22:13:53 +00001333 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001334 SDOperand Op = BuildUDIV(N);
1335 if (Op.Val) return Op;
1336 }
1337
1338 // undef / X -> 0
1339 if (N0.getOpcode() == ISD::UNDEF)
1340 return DAG.getConstant(0, VT);
1341 // X / undef -> undef
1342 if (N1.getOpcode() == ISD::UNDEF)
1343 return N1;
1344
1345 return SDOperand();
1346}
1347
1348SDOperand DAGCombiner::visitSREM(SDNode *N) {
1349 SDOperand N0 = N->getOperand(0);
1350 SDOperand N1 = N->getOperand(1);
1351 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1352 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1353 MVT::ValueType VT = N->getValueType(0);
1354
1355 // fold (srem c1, c2) -> c1%c2
1356 if (N0C && N1C && !N1C->isNullValue())
1357 return DAG.getNode(ISD::SREM, VT, N0, N1);
1358 // If we know the sign bits of both operands are zero, strength reduce to a
1359 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Chris Lattnerce602f52008-01-27 23:21:58 +00001360 if (!MVT::isVector(VT)) {
Dan Gohman07961cd2008-02-25 21:11:39 +00001361 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Chris Lattnerce602f52008-01-27 23:21:58 +00001362 return DAG.getNode(ISD::UREM, VT, N0, N1);
1363 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001364
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001365 // If X/C can be simplified by the division-by-constant logic, lower
1366 // X%C to the equivalent of X-X/C*C.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001367 if (N1C && !N1C->isNullValue()) {
1368 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
Chris Lattner4a7c8452008-01-26 01:09:19 +00001369 AddToWorkList(Div.Val);
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001370 SDOperand OptimizedDiv = combine(Div.Val);
1371 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1372 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1373 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1374 AddToWorkList(Mul.Val);
1375 return Sub;
1376 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001377 }
1378
1379 // undef % X -> 0
1380 if (N0.getOpcode() == ISD::UNDEF)
1381 return DAG.getConstant(0, VT);
1382 // X % undef -> undef
1383 if (N1.getOpcode() == ISD::UNDEF)
1384 return N1;
1385
1386 return SDOperand();
1387}
1388
1389SDOperand DAGCombiner::visitUREM(SDNode *N) {
1390 SDOperand N0 = N->getOperand(0);
1391 SDOperand N1 = N->getOperand(1);
1392 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1393 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1394 MVT::ValueType VT = N->getValueType(0);
1395
1396 // fold (urem c1, c2) -> c1%c2
1397 if (N0C && N1C && !N1C->isNullValue())
1398 return DAG.getNode(ISD::UREM, VT, N0, N1);
1399 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohman9d24dc72008-03-13 22:13:53 +00001400 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1401 return DAG.getNode(ISD::AND, VT, N0,
1402 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001403 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1404 if (N1.getOpcode() == ISD::SHL) {
1405 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00001406 if (SHC->getAPIntValue().isPowerOf2()) {
1407 SDOperand Add =
1408 DAG.getNode(ISD::ADD, VT, N1,
1409 DAG.getConstant(APInt::getAllOnesValue(MVT::getSizeInBits(VT)),
1410 VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001411 AddToWorkList(Add.Val);
1412 return DAG.getNode(ISD::AND, VT, N0, Add);
1413 }
1414 }
1415 }
1416
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001417 // If X/C can be simplified by the division-by-constant logic, lower
1418 // X%C to the equivalent of X-X/C*C.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001419 if (N1C && !N1C->isNullValue()) {
1420 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001421 SDOperand OptimizedDiv = combine(Div.Val);
1422 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1423 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1424 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1425 AddToWorkList(Mul.Val);
1426 return Sub;
1427 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001428 }
1429
1430 // undef % X -> 0
1431 if (N0.getOpcode() == ISD::UNDEF)
1432 return DAG.getConstant(0, VT);
1433 // X % undef -> undef
1434 if (N1.getOpcode() == ISD::UNDEF)
1435 return N1;
1436
1437 return SDOperand();
1438}
1439
1440SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1441 SDOperand N0 = N->getOperand(0);
1442 SDOperand N1 = N->getOperand(1);
1443 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1444 MVT::ValueType VT = N->getValueType(0);
1445
1446 // fold (mulhs x, 0) -> 0
1447 if (N1C && N1C->isNullValue())
1448 return N1;
1449 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohman9d24dc72008-03-13 22:13:53 +00001450 if (N1C && N1C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001451 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1452 DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
1453 TLI.getShiftAmountTy()));
1454 // fold (mulhs x, undef) -> 0
1455 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1456 return DAG.getConstant(0, VT);
1457
1458 return SDOperand();
1459}
1460
1461SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1462 SDOperand N0 = N->getOperand(0);
1463 SDOperand N1 = N->getOperand(1);
1464 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1465 MVT::ValueType VT = N->getValueType(0);
1466
1467 // fold (mulhu x, 0) -> 0
1468 if (N1C && N1C->isNullValue())
1469 return N1;
1470 // fold (mulhu x, 1) -> 0
Dan Gohman9d24dc72008-03-13 22:13:53 +00001471 if (N1C && N1C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001472 return DAG.getConstant(0, N0.getValueType());
1473 // fold (mulhu x, undef) -> 0
1474 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1475 return DAG.getConstant(0, VT);
1476
1477 return SDOperand();
1478}
1479
Dan Gohman6c89ea72007-10-08 17:57:15 +00001480/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1481/// compute two values. LoOp and HiOp give the opcodes for the two computations
1482/// that are being performed. Return true if a simplification was made.
1483///
Chris Lattner4a7c8452008-01-26 01:09:19 +00001484SDOperand DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1485 unsigned HiOp) {
Dan Gohman6c89ea72007-10-08 17:57:15 +00001486 // If the high half is not needed, just compute the low half.
Evan Chengddfa8c72007-11-08 09:25:29 +00001487 bool HiExists = N->hasAnyUseOfValue(1);
1488 if (!HiExists &&
Dan Gohman6c89ea72007-10-08 17:57:15 +00001489 (!AfterLegalize ||
1490 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001491 SDOperand Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(),
1492 N->getNumOperands());
1493 return CombineTo(N, Res, Res);
Dan Gohman6c89ea72007-10-08 17:57:15 +00001494 }
1495
1496 // If the low half is not needed, just compute the high half.
Evan Chengddfa8c72007-11-08 09:25:29 +00001497 bool LoExists = N->hasAnyUseOfValue(0);
1498 if (!LoExists &&
Dan Gohman6c89ea72007-10-08 17:57:15 +00001499 (!AfterLegalize ||
1500 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001501 SDOperand Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(),
1502 N->getNumOperands());
1503 return CombineTo(N, Res, Res);
Dan Gohman6c89ea72007-10-08 17:57:15 +00001504 }
1505
Evan Chengddfa8c72007-11-08 09:25:29 +00001506 // If both halves are used, return as it is.
1507 if (LoExists && HiExists)
Chris Lattner4a7c8452008-01-26 01:09:19 +00001508 return SDOperand();
Evan Chengddfa8c72007-11-08 09:25:29 +00001509
1510 // If the two computed results can be simplified separately, separate them.
Evan Chengddfa8c72007-11-08 09:25:29 +00001511 if (LoExists) {
1512 SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
1513 N->op_begin(), N->getNumOperands());
Chris Lattner4a7c8452008-01-26 01:09:19 +00001514 AddToWorkList(Lo.Val);
Evan Chengddfa8c72007-11-08 09:25:29 +00001515 SDOperand LoOpt = combine(Lo.Val);
Chris Lattner4a7c8452008-01-26 01:09:19 +00001516 if (LoOpt.Val && LoOpt.Val != Lo.Val &&
1517 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))
1518 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman6c89ea72007-10-08 17:57:15 +00001519 }
1520
Evan Chengddfa8c72007-11-08 09:25:29 +00001521 if (HiExists) {
1522 SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
1523 N->op_begin(), N->getNumOperands());
Chris Lattner4a7c8452008-01-26 01:09:19 +00001524 AddToWorkList(Hi.Val);
Evan Chengddfa8c72007-11-08 09:25:29 +00001525 SDOperand HiOpt = combine(Hi.Val);
1526 if (HiOpt.Val && HiOpt != Hi &&
Chris Lattner4a7c8452008-01-26 01:09:19 +00001527 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))
1528 return CombineTo(N, HiOpt, HiOpt);
Evan Chengddfa8c72007-11-08 09:25:29 +00001529 }
Chris Lattner4a7c8452008-01-26 01:09:19 +00001530 return SDOperand();
Dan Gohman6c89ea72007-10-08 17:57:15 +00001531}
1532
1533SDOperand DAGCombiner::visitSMUL_LOHI(SDNode *N) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001534 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1535 if (Res.Val) return Res;
Dan Gohman6c89ea72007-10-08 17:57:15 +00001536
1537 return SDOperand();
1538}
1539
1540SDOperand DAGCombiner::visitUMUL_LOHI(SDNode *N) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001541 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1542 if (Res.Val) return Res;
Dan Gohman6c89ea72007-10-08 17:57:15 +00001543
1544 return SDOperand();
1545}
1546
1547SDOperand DAGCombiner::visitSDIVREM(SDNode *N) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001548 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1549 if (Res.Val) return Res;
Dan Gohman6c89ea72007-10-08 17:57:15 +00001550
1551 return SDOperand();
1552}
1553
1554SDOperand DAGCombiner::visitUDIVREM(SDNode *N) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001555 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1556 if (Res.Val) return Res;
Dan Gohman6c89ea72007-10-08 17:57:15 +00001557
1558 return SDOperand();
1559}
1560
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001561/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1562/// two operands of the same opcode, try to simplify it.
1563SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1564 SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1565 MVT::ValueType VT = N0.getValueType();
1566 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1567
1568 // For each of OP in AND/OR/XOR:
1569 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1570 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1571 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1572 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1573 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1574 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1575 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1576 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1577 N0.getOperand(0).getValueType(),
1578 N0.getOperand(0), N1.getOperand(0));
1579 AddToWorkList(ORNode.Val);
1580 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1581 }
1582
1583 // For each of OP in SHL/SRL/SRA/AND...
1584 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1585 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1586 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1587 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1588 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1589 N0.getOperand(1) == N1.getOperand(1)) {
1590 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1591 N0.getOperand(0).getValueType(),
1592 N0.getOperand(0), N1.getOperand(0));
1593 AddToWorkList(ORNode.Val);
1594 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1595 }
1596
1597 return SDOperand();
1598}
1599
1600SDOperand DAGCombiner::visitAND(SDNode *N) {
1601 SDOperand N0 = N->getOperand(0);
1602 SDOperand N1 = N->getOperand(1);
1603 SDOperand LL, LR, RL, RR, CC0, CC1;
1604 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1605 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1606 MVT::ValueType VT = N1.getValueType();
Dan Gohman07961cd2008-02-25 21:11:39 +00001607 unsigned BitWidth = MVT::getSizeInBits(VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001608
1609 // fold vector ops
1610 if (MVT::isVector(VT)) {
1611 SDOperand FoldedVOp = SimplifyVBinOp(N);
1612 if (FoldedVOp.Val) return FoldedVOp;
1613 }
1614
1615 // fold (and x, undef) -> 0
1616 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1617 return DAG.getConstant(0, VT);
1618 // fold (and c1, c2) -> c1&c2
1619 if (N0C && N1C)
1620 return DAG.getNode(ISD::AND, VT, N0, N1);
1621 // canonicalize constant to RHS
1622 if (N0C && !N1C)
1623 return DAG.getNode(ISD::AND, VT, N1, N0);
1624 // fold (and x, -1) -> x
1625 if (N1C && N1C->isAllOnesValue())
1626 return N0;
1627 // if (and x, c) is known to be zero, return 0
Dan Gohman07961cd2008-02-25 21:11:39 +00001628 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
1629 APInt::getAllOnesValue(BitWidth)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001630 return DAG.getConstant(0, VT);
1631 // reassociate and
1632 SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1633 if (RAND.Val != 0)
1634 return RAND;
1635 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1636 if (N1C && N0.getOpcode() == ISD::OR)
1637 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman9d24dc72008-03-13 22:13:53 +00001638 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001639 return N1;
1640 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1641 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman07961cd2008-02-25 21:11:39 +00001642 SDOperand N0Op0 = N0.getOperand(0);
1643 APInt Mask = ~N1C->getAPIntValue();
1644 Mask.trunc(N0Op0.getValueSizeInBits());
1645 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001646 SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
Dan Gohman07961cd2008-02-25 21:11:39 +00001647 N0Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001648
1649 // Replace uses of the AND with uses of the Zero extend node.
1650 CombineTo(N, Zext);
1651
1652 // We actually want to replace all uses of the any_extend with the
1653 // zero_extend, to avoid duplicating things. This will later cause this
1654 // AND to be folded.
1655 CombineTo(N0.Val, Zext);
1656 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1657 }
1658 }
1659 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1660 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1661 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1662 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1663
1664 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1665 MVT::isInteger(LL.getValueType())) {
1666 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
Dan Gohman9d24dc72008-03-13 22:13:53 +00001667 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001668 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1669 AddToWorkList(ORNode.Val);
1670 return DAG.getSetCC(VT, ORNode, LR, Op1);
1671 }
1672 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1673 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1674 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1675 AddToWorkList(ANDNode.Val);
1676 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1677 }
1678 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1679 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1680 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1681 AddToWorkList(ORNode.Val);
1682 return DAG.getSetCC(VT, ORNode, LR, Op1);
1683 }
1684 }
1685 // canonicalize equivalent to ll == rl
1686 if (LL == RR && LR == RL) {
1687 Op1 = ISD::getSetCCSwappedOperands(Op1);
1688 std::swap(RL, RR);
1689 }
1690 if (LL == RL && LR == RR) {
1691 bool isInteger = MVT::isInteger(LL.getValueType());
1692 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1693 if (Result != ISD::SETCC_INVALID)
1694 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1695 }
1696 }
1697
1698 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1699 if (N0.getOpcode() == N1.getOpcode()) {
1700 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1701 if (Tmp.Val) return Tmp;
1702 }
1703
1704 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1705 // fold (and (sra)) -> (and (srl)) when possible.
1706 if (!MVT::isVector(VT) &&
1707 SimplifyDemandedBits(SDOperand(N, 0)))
1708 return SDOperand(N, 0);
1709 // fold (zext_inreg (extload x)) -> (zextload x)
1710 if (ISD::isEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val)) {
1711 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman9a4c92c2008-01-30 00:15:11 +00001712 MVT::ValueType EVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001713 // If we zero all the possible extended bits, then we can turn this into
1714 // a zextload if we are running before legalize or the operation is legal.
Dan Gohman07961cd2008-02-25 21:11:39 +00001715 unsigned BitWidth = N1.getValueSizeInBits();
1716 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1717 BitWidth - MVT::getSizeInBits(EVT))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001718 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1719 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1720 LN0->getBasePtr(), LN0->getSrcValue(),
1721 LN0->getSrcValueOffset(), EVT,
1722 LN0->isVolatile(),
1723 LN0->getAlignment());
1724 AddToWorkList(N);
1725 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1726 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1727 }
1728 }
1729 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1730 if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
1731 N0.hasOneUse()) {
1732 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman9a4c92c2008-01-30 00:15:11 +00001733 MVT::ValueType EVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001734 // If we zero all the possible extended bits, then we can turn this into
1735 // a zextload if we are running before legalize or the operation is legal.
Dan Gohman07961cd2008-02-25 21:11:39 +00001736 unsigned BitWidth = N1.getValueSizeInBits();
1737 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1738 BitWidth - MVT::getSizeInBits(EVT))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001739 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1740 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1741 LN0->getBasePtr(), LN0->getSrcValue(),
1742 LN0->getSrcValueOffset(), EVT,
1743 LN0->isVolatile(),
1744 LN0->getAlignment());
1745 AddToWorkList(N);
1746 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1747 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1748 }
1749 }
1750
1751 // fold (and (load x), 255) -> (zextload x, i8)
1752 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1753 if (N1C && N0.getOpcode() == ISD::LOAD) {
1754 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1755 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Chris Lattner3bc08502008-01-17 19:59:44 +00001756 LN0->isUnindexed() && N0.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001757 MVT::ValueType EVT, LoadedVT;
Dan Gohman9d24dc72008-03-13 22:13:53 +00001758 if (N1C->getAPIntValue() == 255)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001759 EVT = MVT::i8;
Dan Gohman9d24dc72008-03-13 22:13:53 +00001760 else if (N1C->getAPIntValue() == 65535)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001761 EVT = MVT::i16;
Dan Gohman9d24dc72008-03-13 22:13:53 +00001762 else if (N1C->getAPIntValue() == ~0U)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001763 EVT = MVT::i32;
1764 else
1765 EVT = MVT::Other;
1766
Dan Gohman9a4c92c2008-01-30 00:15:11 +00001767 LoadedVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001768 if (EVT != MVT::Other && LoadedVT > EVT &&
1769 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1770 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1771 // For big endian targets, we need to add an offset to the pointer to
1772 // load the correct bytes. For little endian systems, we merely need to
1773 // read fewer bytes from the same pointer.
Duncan Sands4f18d4f2007-11-09 08:57:19 +00001774 unsigned LVTStoreBytes = MVT::getStoreSizeInBits(LoadedVT)/8;
1775 unsigned EVTStoreBytes = MVT::getStoreSizeInBits(EVT)/8;
1776 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Duncan Sandsa3691432007-10-28 12:59:45 +00001777 unsigned Alignment = LN0->getAlignment();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001778 SDOperand NewPtr = LN0->getBasePtr();
Duncan Sands9ff8fbf2008-02-11 10:37:04 +00001779 if (TLI.isBigEndian()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001780 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1781 DAG.getConstant(PtrOff, PtrType));
Duncan Sandsa3691432007-10-28 12:59:45 +00001782 Alignment = MinAlign(Alignment, PtrOff);
1783 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001784 AddToWorkList(NewPtr.Val);
1785 SDOperand Load =
1786 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1787 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
Duncan Sandsa3691432007-10-28 12:59:45 +00001788 LN0->isVolatile(), Alignment);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001789 AddToWorkList(N);
1790 CombineTo(N0.Val, Load, Load.getValue(1));
1791 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1792 }
1793 }
1794 }
1795
1796 return SDOperand();
1797}
1798
1799SDOperand DAGCombiner::visitOR(SDNode *N) {
1800 SDOperand N0 = N->getOperand(0);
1801 SDOperand N1 = N->getOperand(1);
1802 SDOperand LL, LR, RL, RR, CC0, CC1;
1803 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1804 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1805 MVT::ValueType VT = N1.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001806
1807 // fold vector ops
1808 if (MVT::isVector(VT)) {
1809 SDOperand FoldedVOp = SimplifyVBinOp(N);
1810 if (FoldedVOp.Val) return FoldedVOp;
1811 }
1812
1813 // fold (or x, undef) -> -1
1814 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1815 return DAG.getConstant(~0ULL, VT);
1816 // fold (or c1, c2) -> c1|c2
1817 if (N0C && N1C)
1818 return DAG.getNode(ISD::OR, VT, N0, N1);
1819 // canonicalize constant to RHS
1820 if (N0C && !N1C)
1821 return DAG.getNode(ISD::OR, VT, N1, N0);
1822 // fold (or x, 0) -> x
1823 if (N1C && N1C->isNullValue())
1824 return N0;
1825 // fold (or x, -1) -> -1
1826 if (N1C && N1C->isAllOnesValue())
1827 return N1;
1828 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman07961cd2008-02-25 21:11:39 +00001829 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001830 return N1;
1831 // reassociate or
1832 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1833 if (ROR.Val != 0)
1834 return ROR;
1835 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1836 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1837 isa<ConstantSDNode>(N0.getOperand(1))) {
1838 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1839 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1840 N1),
Dan Gohman9d24dc72008-03-13 22:13:53 +00001841 DAG.getConstant(N1C->getAPIntValue() |
1842 C1->getAPIntValue(), VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001843 }
1844 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1845 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1846 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1847 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1848
1849 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1850 MVT::isInteger(LL.getValueType())) {
1851 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1852 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
Dan Gohman9d24dc72008-03-13 22:13:53 +00001853 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001854 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1855 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1856 AddToWorkList(ORNode.Val);
1857 return DAG.getSetCC(VT, ORNode, LR, Op1);
1858 }
1859 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1860 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1861 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1862 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1863 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1864 AddToWorkList(ANDNode.Val);
1865 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1866 }
1867 }
1868 // canonicalize equivalent to ll == rl
1869 if (LL == RR && LR == RL) {
1870 Op1 = ISD::getSetCCSwappedOperands(Op1);
1871 std::swap(RL, RR);
1872 }
1873 if (LL == RL && LR == RR) {
1874 bool isInteger = MVT::isInteger(LL.getValueType());
1875 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1876 if (Result != ISD::SETCC_INVALID)
1877 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1878 }
1879 }
1880
1881 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1882 if (N0.getOpcode() == N1.getOpcode()) {
1883 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1884 if (Tmp.Val) return Tmp;
1885 }
1886
1887 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1888 if (N0.getOpcode() == ISD::AND &&
1889 N1.getOpcode() == ISD::AND &&
1890 N0.getOperand(1).getOpcode() == ISD::Constant &&
1891 N1.getOperand(1).getOpcode() == ISD::Constant &&
1892 // Don't increase # computations.
1893 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1894 // We can only do this xform if we know that bits from X that are set in C2
1895 // but not in C1 are already zero. Likewise for Y.
Dan Gohman07961cd2008-02-25 21:11:39 +00001896 const APInt &LHSMask =
1897 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1898 const APInt &RHSMask =
1899 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001900
1901 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1902 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1903 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1904 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1905 }
1906 }
1907
1908
1909 // See if this is some rotate idiom.
1910 if (SDNode *Rot = MatchRotate(N0, N1))
1911 return SDOperand(Rot, 0);
1912
1913 return SDOperand();
1914}
1915
1916
1917/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1918static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1919 if (Op.getOpcode() == ISD::AND) {
1920 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1921 Mask = Op.getOperand(1);
1922 Op = Op.getOperand(0);
1923 } else {
1924 return false;
1925 }
1926 }
1927
1928 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1929 Shift = Op;
1930 return true;
1931 }
1932 return false;
1933}
1934
1935
1936// MatchRotate - Handle an 'or' of two operands. If this is one of the many
1937// idioms for rotate, and if the target supports rotation instructions, generate
1938// a rot[lr].
1939SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1940 // Must be a legal type. Expanded an promoted things won't work with rotates.
1941 MVT::ValueType VT = LHS.getValueType();
1942 if (!TLI.isTypeLegal(VT)) return 0;
1943
1944 // The target must have at least one rotate flavor.
1945 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1946 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1947 if (!HasROTL && !HasROTR) return 0;
1948
1949 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1950 SDOperand LHSShift; // The shift.
1951 SDOperand LHSMask; // AND value if any.
1952 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1953 return 0; // Not part of a rotate.
1954
1955 SDOperand RHSShift; // The shift.
1956 SDOperand RHSMask; // AND value if any.
1957 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1958 return 0; // Not part of a rotate.
1959
1960 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1961 return 0; // Not shifting the same value.
1962
1963 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1964 return 0; // Shifts must disagree.
1965
1966 // Canonicalize shl to left side in a shl/srl pair.
1967 if (RHSShift.getOpcode() == ISD::SHL) {
1968 std::swap(LHS, RHS);
1969 std::swap(LHSShift, RHSShift);
1970 std::swap(LHSMask , RHSMask );
1971 }
1972
1973 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1974 SDOperand LHSShiftArg = LHSShift.getOperand(0);
1975 SDOperand LHSShiftAmt = LHSShift.getOperand(1);
1976 SDOperand RHSShiftAmt = RHSShift.getOperand(1);
1977
1978 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1979 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1980 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
1981 RHSShiftAmt.getOpcode() == ISD::Constant) {
1982 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue();
1983 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue();
1984 if ((LShVal + RShVal) != OpSizeInBits)
1985 return 0;
1986
1987 SDOperand Rot;
1988 if (HasROTL)
1989 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
1990 else
1991 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
1992
1993 // If there is an AND of either shifted operand, apply it to the result.
1994 if (LHSMask.Val || RHSMask.Val) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00001995 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001996
1997 if (LHSMask.Val) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00001998 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
1999 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002000 }
2001 if (RHSMask.Val) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00002002 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2003 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002004 }
2005
2006 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
2007 }
2008
2009 return Rot.Val;
2010 }
2011
2012 // If there is a mask here, and we have a variable shift, we can't be sure
2013 // that we're masking out the right stuff.
2014 if (LHSMask.Val || RHSMask.Val)
2015 return 0;
2016
2017 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2018 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2019 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2020 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2021 if (ConstantSDNode *SUBC =
2022 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00002023 if (SUBC->getAPIntValue() == OpSizeInBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002024 if (HasROTL)
2025 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2026 else
2027 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002028 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002029 }
2030 }
2031
2032 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2033 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2034 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2035 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2036 if (ConstantSDNode *SUBC =
2037 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00002038 if (SUBC->getAPIntValue() == OpSizeInBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002039 if (HasROTL)
2040 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2041 else
2042 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002043 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002044 }
2045 }
2046
2047 // Look for sign/zext/any-extended cases:
2048 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2049 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2050 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) &&
2051 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2052 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2053 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) {
2054 SDOperand LExtOp0 = LHSShiftAmt.getOperand(0);
2055 SDOperand RExtOp0 = RHSShiftAmt.getOperand(0);
2056 if (RExtOp0.getOpcode() == ISD::SUB &&
2057 RExtOp0.getOperand(1) == LExtOp0) {
2058 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2059 // (rotr x, y)
2060 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2061 // (rotl x, (sub 32, y))
2062 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00002063 if (SUBC->getAPIntValue() == OpSizeInBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002064 if (HasROTL)
2065 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2066 else
2067 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2068 }
2069 }
2070 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2071 RExtOp0 == LExtOp0.getOperand(1)) {
2072 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2073 // (rotl x, y)
2074 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2075 // (rotr x, (sub 32, y))
2076 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00002077 if (SUBC->getAPIntValue() == OpSizeInBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002078 if (HasROTL)
2079 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
2080 else
2081 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2082 }
2083 }
2084 }
2085 }
2086
2087 return 0;
2088}
2089
2090
2091SDOperand DAGCombiner::visitXOR(SDNode *N) {
2092 SDOperand N0 = N->getOperand(0);
2093 SDOperand N1 = N->getOperand(1);
2094 SDOperand LHS, RHS, CC;
2095 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2096 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2097 MVT::ValueType VT = N0.getValueType();
2098
2099 // fold vector ops
2100 if (MVT::isVector(VT)) {
2101 SDOperand FoldedVOp = SimplifyVBinOp(N);
2102 if (FoldedVOp.Val) return FoldedVOp;
2103 }
2104
2105 // fold (xor x, undef) -> undef
2106 if (N0.getOpcode() == ISD::UNDEF)
2107 return N0;
2108 if (N1.getOpcode() == ISD::UNDEF)
2109 return N1;
2110 // fold (xor c1, c2) -> c1^c2
2111 if (N0C && N1C)
2112 return DAG.getNode(ISD::XOR, VT, N0, N1);
2113 // canonicalize constant to RHS
2114 if (N0C && !N1C)
2115 return DAG.getNode(ISD::XOR, VT, N1, N0);
2116 // fold (xor x, 0) -> x
2117 if (N1C && N1C->isNullValue())
2118 return N0;
2119 // reassociate xor
2120 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
2121 if (RXOR.Val != 0)
2122 return RXOR;
2123 // fold !(x cc y) -> (x !cc y)
Dan Gohman9d24dc72008-03-13 22:13:53 +00002124 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002125 bool isInt = MVT::isInteger(LHS.getValueType());
2126 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2127 isInt);
2128 if (N0.getOpcode() == ISD::SETCC)
2129 return DAG.getSetCC(VT, LHS, RHS, NotCC);
2130 if (N0.getOpcode() == ISD::SELECT_CC)
2131 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
2132 assert(0 && "Unhandled SetCC Equivalent!");
2133 abort();
2134 }
Chris Lattnere27cd502007-09-10 21:39:07 +00002135 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohman9d24dc72008-03-13 22:13:53 +00002136 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Chris Lattnere27cd502007-09-10 21:39:07 +00002137 N0.Val->hasOneUse() && isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2138 SDOperand V = N0.getOperand(0);
2139 V = DAG.getNode(ISD::XOR, V.getValueType(), V,
Duncan Sandsbed21472007-10-10 09:54:50 +00002140 DAG.getConstant(1, V.getValueType()));
Chris Lattnere27cd502007-09-10 21:39:07 +00002141 AddToWorkList(V.Val);
2142 return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2143 }
2144
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002145 // fold !(x or y) -> (!x and !y) iff x or y are setcc
Dan Gohman9d24dc72008-03-13 22:13:53 +00002146 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002147 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2148 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2149 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2150 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2151 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2152 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2153 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2154 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2155 }
2156 }
2157 // fold !(x or y) -> (!x and !y) iff x or y are constants
2158 if (N1C && N1C->isAllOnesValue() &&
2159 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2160 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2161 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2162 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2163 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2164 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2165 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2166 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2167 }
2168 }
2169 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2170 if (N1C && N0.getOpcode() == ISD::XOR) {
2171 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2172 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2173 if (N00C)
2174 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
Dan Gohman9d24dc72008-03-13 22:13:53 +00002175 DAG.getConstant(N1C->getAPIntValue()^
2176 N00C->getAPIntValue(), VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002177 if (N01C)
2178 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
Dan Gohman9d24dc72008-03-13 22:13:53 +00002179 DAG.getConstant(N1C->getAPIntValue()^
2180 N01C->getAPIntValue(), VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002181 }
2182 // fold (xor x, x) -> 0
2183 if (N0 == N1) {
2184 if (!MVT::isVector(VT)) {
2185 return DAG.getConstant(0, VT);
2186 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
2187 // Produce a vector of zeros.
2188 SDOperand El = DAG.getConstant(0, MVT::getVectorElementType(VT));
2189 std::vector<SDOperand> Ops(MVT::getVectorNumElements(VT), El);
2190 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2191 }
2192 }
2193
2194 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2195 if (N0.getOpcode() == N1.getOpcode()) {
2196 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2197 if (Tmp.Val) return Tmp;
2198 }
2199
2200 // Simplify the expression using non-local knowledge.
2201 if (!MVT::isVector(VT) &&
2202 SimplifyDemandedBits(SDOperand(N, 0)))
2203 return SDOperand(N, 0);
2204
2205 return SDOperand();
2206}
2207
Chris Lattner91ed3c32007-12-06 07:33:36 +00002208/// visitShiftByConstant - Handle transforms common to the three shifts, when
2209/// the shift amount is a constant.
2210SDOperand DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2211 SDNode *LHS = N->getOperand(0).Val;
2212 if (!LHS->hasOneUse()) return SDOperand();
2213
2214 // We want to pull some binops through shifts, so that we have (and (shift))
2215 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2216 // thing happens with address calculations, so it's important to canonicalize
2217 // it.
2218 bool HighBitSet = false; // Can we transform this if the high bit is set?
2219
2220 switch (LHS->getOpcode()) {
2221 default: return SDOperand();
2222 case ISD::OR:
2223 case ISD::XOR:
2224 HighBitSet = false; // We can only transform sra if the high bit is clear.
2225 break;
2226 case ISD::AND:
2227 HighBitSet = true; // We can only transform sra if the high bit is set.
2228 break;
2229 case ISD::ADD:
2230 if (N->getOpcode() != ISD::SHL)
2231 return SDOperand(); // only shl(add) not sr[al](add).
2232 HighBitSet = false; // We can only transform sra if the high bit is clear.
2233 break;
2234 }
2235
2236 // We require the RHS of the binop to be a constant as well.
2237 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2238 if (!BinOpCst) return SDOperand();
2239
Chris Lattnerdcd19762007-12-06 07:47:55 +00002240
2241 // FIXME: disable this for unless the input to the binop is a shift by a
2242 // constant. If it is not a shift, it pessimizes some common cases like:
2243 //
2244 //void foo(int *X, int i) { X[i & 1235] = 1; }
2245 //int bar(int *X, int i) { return X[i & 255]; }
2246 SDNode *BinOpLHSVal = LHS->getOperand(0).Val;
2247 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2248 BinOpLHSVal->getOpcode() != ISD::SRA &&
2249 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2250 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2251 return SDOperand();
2252
Chris Lattner91ed3c32007-12-06 07:33:36 +00002253 MVT::ValueType VT = N->getValueType(0);
2254
2255 // If this is a signed shift right, and the high bit is modified
2256 // by the logical operation, do not perform the transformation.
2257 // The highBitSet boolean indicates the value of the high bit of
2258 // the constant which would cause it to be modified for this
2259 // operation.
2260 if (N->getOpcode() == ISD::SRA) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00002261 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2262 if (BinOpRHSSignSet != HighBitSet)
Chris Lattner91ed3c32007-12-06 07:33:36 +00002263 return SDOperand();
2264 }
2265
2266 // Fold the constants, shifting the binop RHS by the shift amount.
2267 SDOperand NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
2268 LHS->getOperand(1), N->getOperand(1));
2269
2270 // Create the new shift.
2271 SDOperand NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
2272 N->getOperand(1));
2273
2274 // Create the new binop.
2275 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
2276}
2277
2278
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002279SDOperand DAGCombiner::visitSHL(SDNode *N) {
2280 SDOperand N0 = N->getOperand(0);
2281 SDOperand N1 = N->getOperand(1);
2282 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2283 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2284 MVT::ValueType VT = N0.getValueType();
2285 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2286
2287 // fold (shl c1, c2) -> c1<<c2
2288 if (N0C && N1C)
2289 return DAG.getNode(ISD::SHL, VT, N0, N1);
2290 // fold (shl 0, x) -> 0
2291 if (N0C && N0C->isNullValue())
2292 return N0;
2293 // fold (shl x, c >= size(x)) -> undef
2294 if (N1C && N1C->getValue() >= OpSizeInBits)
2295 return DAG.getNode(ISD::UNDEF, VT);
2296 // fold (shl x, 0) -> x
2297 if (N1C && N1C->isNullValue())
2298 return N0;
2299 // if (shl x, c) is known to be zero, return 0
Dan Gohman07961cd2008-02-25 21:11:39 +00002300 if (DAG.MaskedValueIsZero(SDOperand(N, 0),
2301 APInt::getAllOnesValue(MVT::getSizeInBits(VT))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002302 return DAG.getConstant(0, VT);
2303 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2304 return SDOperand(N, 0);
2305 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2306 if (N1C && N0.getOpcode() == ISD::SHL &&
2307 N0.getOperand(1).getOpcode() == ISD::Constant) {
2308 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2309 uint64_t c2 = N1C->getValue();
2310 if (c1 + c2 > OpSizeInBits)
2311 return DAG.getConstant(0, VT);
2312 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2313 DAG.getConstant(c1 + c2, N1.getValueType()));
2314 }
2315 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2316 // (srl (and x, -1 << c1), c1-c2)
2317 if (N1C && N0.getOpcode() == ISD::SRL &&
2318 N0.getOperand(1).getOpcode() == ISD::Constant) {
2319 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2320 uint64_t c2 = N1C->getValue();
2321 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2322 DAG.getConstant(~0ULL << c1, VT));
2323 if (c2 > c1)
2324 return DAG.getNode(ISD::SHL, VT, Mask,
2325 DAG.getConstant(c2-c1, N1.getValueType()));
2326 else
2327 return DAG.getNode(ISD::SRL, VT, Mask,
2328 DAG.getConstant(c1-c2, N1.getValueType()));
2329 }
2330 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2331 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2332 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2333 DAG.getConstant(~0ULL << N1C->getValue(), VT));
Chris Lattner91ed3c32007-12-06 07:33:36 +00002334
2335 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002336}
2337
2338SDOperand DAGCombiner::visitSRA(SDNode *N) {
2339 SDOperand N0 = N->getOperand(0);
2340 SDOperand N1 = N->getOperand(1);
2341 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2342 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2343 MVT::ValueType VT = N0.getValueType();
2344
2345 // fold (sra c1, c2) -> c1>>c2
2346 if (N0C && N1C)
2347 return DAG.getNode(ISD::SRA, VT, N0, N1);
2348 // fold (sra 0, x) -> 0
2349 if (N0C && N0C->isNullValue())
2350 return N0;
2351 // fold (sra -1, x) -> -1
2352 if (N0C && N0C->isAllOnesValue())
2353 return N0;
2354 // fold (sra x, c >= size(x)) -> undef
2355 if (N1C && N1C->getValue() >= MVT::getSizeInBits(VT))
2356 return DAG.getNode(ISD::UNDEF, VT);
2357 // fold (sra x, 0) -> x
2358 if (N1C && N1C->isNullValue())
2359 return N0;
2360 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2361 // sext_inreg.
2362 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2363 unsigned LowBits = MVT::getSizeInBits(VT) - (unsigned)N1C->getValue();
2364 MVT::ValueType EVT;
2365 switch (LowBits) {
2366 default: EVT = MVT::Other; break;
2367 case 1: EVT = MVT::i1; break;
2368 case 8: EVT = MVT::i8; break;
2369 case 16: EVT = MVT::i16; break;
2370 case 32: EVT = MVT::i32; break;
2371 }
2372 if (EVT > MVT::Other && TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))
2373 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2374 DAG.getValueType(EVT));
2375 }
2376
2377 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2378 if (N1C && N0.getOpcode() == ISD::SRA) {
2379 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2380 unsigned Sum = N1C->getValue() + C1->getValue();
2381 if (Sum >= MVT::getSizeInBits(VT)) Sum = MVT::getSizeInBits(VT)-1;
2382 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2383 DAG.getConstant(Sum, N1C->getValueType(0)));
2384 }
2385 }
Christopher Lambfc5c1642008-03-19 08:30:06 +00002386
2387 // fold sra (shl X, m), result_size - n
2388 // -> (sign_extend (trunc (shl X, result_size - n - m))) for
2389 // result_size - n != m. If truncate is free for the target sext(shl) is
2390 // likely to result in better code.
2391 if (N0.getOpcode() == ISD::SHL) {
2392 // Get the two constanst of the shifts, CN0 = m, CN = n.
2393 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2394 if (N01C && N1C) {
2395 // Determine if the truncate type's bitsize would correspond to
2396 // an integer type for this target.
2397 unsigned VTValSize = MVT::getSizeInBits(VT);
2398 MVT::ValueType TruncVT = MVT::getIntegerType(VTValSize - N1C->getValue());
2399 unsigned ShiftAmt = N1C->getValue() - N01C->getValue();
2400
2401 // If the shift wouldn't be a noop, the truncated type is an actual type,
2402 // and the truncate is free, then proceed with the transform.
2403 if (ShiftAmt != 0 && TLI.isTruncateFree(VT, TruncVT)) {
2404 SDOperand Amt = DAG.getConstant(ShiftAmt, TLI.getShiftAmountTy());
2405 SDOperand Shift = DAG.getNode(ISD::SRL, VT, N0.getOperand(0), Amt);
2406 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, TruncVT, Shift);
2407 return DAG.getNode(ISD::SIGN_EXTEND, N->getValueType(0), Trunc);
2408 }
2409 }
2410 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002411
2412 // Simplify, based on bits shifted out of the LHS.
2413 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2414 return SDOperand(N, 0);
2415
2416
2417 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman07961cd2008-02-25 21:11:39 +00002418 if (DAG.SignBitIsZero(N0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002419 return DAG.getNode(ISD::SRL, VT, N0, N1);
Chris Lattner91ed3c32007-12-06 07:33:36 +00002420
2421 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002422}
2423
2424SDOperand DAGCombiner::visitSRL(SDNode *N) {
2425 SDOperand N0 = N->getOperand(0);
2426 SDOperand N1 = N->getOperand(1);
2427 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2428 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2429 MVT::ValueType VT = N0.getValueType();
2430 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2431
2432 // fold (srl c1, c2) -> c1 >>u c2
2433 if (N0C && N1C)
2434 return DAG.getNode(ISD::SRL, VT, N0, N1);
2435 // fold (srl 0, x) -> 0
2436 if (N0C && N0C->isNullValue())
2437 return N0;
2438 // fold (srl x, c >= size(x)) -> undef
2439 if (N1C && N1C->getValue() >= OpSizeInBits)
2440 return DAG.getNode(ISD::UNDEF, VT);
2441 // fold (srl x, 0) -> x
2442 if (N1C && N1C->isNullValue())
2443 return N0;
2444 // if (srl x, c) is known to be zero, return 0
Dan Gohman07961cd2008-02-25 21:11:39 +00002445 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
2446 APInt::getAllOnesValue(OpSizeInBits)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002447 return DAG.getConstant(0, VT);
2448
2449 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2450 if (N1C && N0.getOpcode() == ISD::SRL &&
2451 N0.getOperand(1).getOpcode() == ISD::Constant) {
2452 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2453 uint64_t c2 = N1C->getValue();
2454 if (c1 + c2 > OpSizeInBits)
2455 return DAG.getConstant(0, VT);
2456 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2457 DAG.getConstant(c1 + c2, N1.getValueType()));
2458 }
2459
2460 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2461 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2462 // Shifting in all undef bits?
2463 MVT::ValueType SmallVT = N0.getOperand(0).getValueType();
2464 if (N1C->getValue() >= MVT::getSizeInBits(SmallVT))
2465 return DAG.getNode(ISD::UNDEF, VT);
2466
2467 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2468 AddToWorkList(SmallShift.Val);
2469 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2470 }
2471
2472 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2473 // bit, which is unmodified by sra.
2474 if (N1C && N1C->getValue()+1 == MVT::getSizeInBits(VT)) {
2475 if (N0.getOpcode() == ISD::SRA)
2476 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2477 }
2478
2479 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2480 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Dan Gohman9d24dc72008-03-13 22:13:53 +00002481 N1C->getAPIntValue() == Log2_32(MVT::getSizeInBits(VT))) {
Dan Gohmanbea075f2008-02-20 16:33:30 +00002482 APInt KnownZero, KnownOne;
2483 APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002484 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2485
2486 // If any of the input bits are KnownOne, then the input couldn't be all
2487 // zeros, thus the result of the srl will always be zero.
Dan Gohmanbea075f2008-02-20 16:33:30 +00002488 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002489
2490 // If all of the bits input the to ctlz node are known to be zero, then
2491 // the result of the ctlz is "32" and the result of the shift is one.
Dan Gohmanbea075f2008-02-20 16:33:30 +00002492 APInt UnknownBits = ~KnownZero & Mask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002493 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2494
2495 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2496 if ((UnknownBits & (UnknownBits-1)) == 0) {
2497 // Okay, we know that only that the single bit specified by UnknownBits
2498 // could be set on input to the CTLZ node. If this bit is set, the SRL
2499 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2500 // to an SRL,XOR pair, which is likely to simplify more.
Dan Gohmanbea075f2008-02-20 16:33:30 +00002501 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002502 SDOperand Op = N0.getOperand(0);
2503 if (ShAmt) {
2504 Op = DAG.getNode(ISD::SRL, VT, Op,
2505 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2506 AddToWorkList(Op.Val);
2507 }
2508 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2509 }
2510 }
2511
2512 // fold operands of srl based on knowledge that the low bits are not
2513 // demanded.
2514 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2515 return SDOperand(N, 0);
2516
Chris Lattner91ed3c32007-12-06 07:33:36 +00002517 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002518}
2519
2520SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2521 SDOperand N0 = N->getOperand(0);
2522 MVT::ValueType VT = N->getValueType(0);
2523
2524 // fold (ctlz c1) -> c2
2525 if (isa<ConstantSDNode>(N0))
2526 return DAG.getNode(ISD::CTLZ, VT, N0);
2527 return SDOperand();
2528}
2529
2530SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2531 SDOperand N0 = N->getOperand(0);
2532 MVT::ValueType VT = N->getValueType(0);
2533
2534 // fold (cttz c1) -> c2
2535 if (isa<ConstantSDNode>(N0))
2536 return DAG.getNode(ISD::CTTZ, VT, N0);
2537 return SDOperand();
2538}
2539
2540SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2541 SDOperand N0 = N->getOperand(0);
2542 MVT::ValueType VT = N->getValueType(0);
2543
2544 // fold (ctpop c1) -> c2
2545 if (isa<ConstantSDNode>(N0))
2546 return DAG.getNode(ISD::CTPOP, VT, N0);
2547 return SDOperand();
2548}
2549
2550SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2551 SDOperand N0 = N->getOperand(0);
2552 SDOperand N1 = N->getOperand(1);
2553 SDOperand N2 = N->getOperand(2);
2554 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2555 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2556 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2557 MVT::ValueType VT = N->getValueType(0);
Evan Chengff601dc2007-08-18 05:57:05 +00002558 MVT::ValueType VT0 = N0.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002559
2560 // fold select C, X, X -> X
2561 if (N1 == N2)
2562 return N1;
2563 // fold select true, X, Y -> X
2564 if (N0C && !N0C->isNullValue())
2565 return N1;
2566 // fold select false, X, Y -> Y
2567 if (N0C && N0C->isNullValue())
2568 return N2;
2569 // fold select C, 1, X -> C | X
Dan Gohman9d24dc72008-03-13 22:13:53 +00002570 if (MVT::i1 == VT && N1C && N1C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002571 return DAG.getNode(ISD::OR, VT, N0, N2);
Evan Chengff601dc2007-08-18 05:57:05 +00002572 // fold select C, 0, 1 -> ~C
2573 if (MVT::isInteger(VT) && MVT::isInteger(VT0) &&
Dan Gohman9d24dc72008-03-13 22:13:53 +00002574 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Evan Chengff601dc2007-08-18 05:57:05 +00002575 SDOperand XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2576 if (VT == VT0)
2577 return XORNode;
2578 AddToWorkList(XORNode.Val);
2579 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(VT0))
2580 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2581 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2582 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002583 // fold select C, 0, X -> ~C & X
Dale Johannesen53e0ad72007-12-06 17:53:31 +00002584 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2585 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002586 AddToWorkList(XORNode.Val);
2587 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2588 }
2589 // fold select C, X, 1 -> ~C | X
Dan Gohman9d24dc72008-03-13 22:13:53 +00002590 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Dale Johannesen53e0ad72007-12-06 17:53:31 +00002591 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002592 AddToWorkList(XORNode.Val);
2593 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2594 }
2595 // fold select C, X, 0 -> C & X
2596 // FIXME: this should check for C type == X type, not i1?
2597 if (MVT::i1 == VT && N2C && N2C->isNullValue())
2598 return DAG.getNode(ISD::AND, VT, N0, N1);
2599 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2600 if (MVT::i1 == VT && N0 == N1)
2601 return DAG.getNode(ISD::OR, VT, N0, N2);
2602 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2603 if (MVT::i1 == VT && N0 == N2)
2604 return DAG.getNode(ISD::AND, VT, N0, N1);
2605
2606 // If we can fold this based on the true/false value, do so.
2607 if (SimplifySelectOps(N, N1, N2))
2608 return SDOperand(N, 0); // Don't revisit N.
2609
2610 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002611 if (N0.getOpcode() == ISD::SETCC) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002612 // FIXME:
2613 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2614 // having to say they don't support SELECT_CC on every type the DAG knows
2615 // about, since there is no way to mark an opcode illegal at all value types
2616 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2617 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2618 N1, N2, N0.getOperand(2));
2619 else
2620 return SimplifySelect(N0, N1, N2);
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002621 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002622 return SDOperand();
2623}
2624
2625SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2626 SDOperand N0 = N->getOperand(0);
2627 SDOperand N1 = N->getOperand(1);
2628 SDOperand N2 = N->getOperand(2);
2629 SDOperand N3 = N->getOperand(3);
2630 SDOperand N4 = N->getOperand(4);
2631 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2632
2633 // fold select_cc lhs, rhs, x, x, cc -> x
2634 if (N2 == N3)
2635 return N2;
2636
2637 // Determine if the condition we're dealing with is constant
Scott Michel502151f2008-03-10 15:42:14 +00002638 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002639 if (SCC.Val) AddToWorkList(SCC.Val);
2640
2641 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
Dan Gohman9d24dc72008-03-13 22:13:53 +00002642 if (!SCCC->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002643 return N2; // cond always true -> true val
2644 else
2645 return N3; // cond always false -> false val
2646 }
2647
2648 // Fold to a simpler select_cc
2649 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2650 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2651 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2652 SCC.getOperand(2));
2653
2654 // If we can fold this based on the true/false value, do so.
2655 if (SimplifySelectOps(N, N2, N3))
2656 return SDOperand(N, 0); // Don't revisit N.
2657
2658 // fold select_cc into other things, such as min/max/abs
2659 return SimplifySelectCC(N0, N1, N2, N3, CC);
2660}
2661
2662SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2663 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2664 cast<CondCodeSDNode>(N->getOperand(2))->get());
2665}
2666
Evan Cheng9decb332007-10-29 19:58:20 +00002667// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2668// "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
2669// transformation. Returns true if extension are possible and the above
2670// mentioned transformation is profitable.
2671static bool ExtendUsesToFormExtLoad(SDNode *N, SDOperand N0,
2672 unsigned ExtOpc,
2673 SmallVector<SDNode*, 4> &ExtendNodes,
2674 TargetLowering &TLI) {
2675 bool HasCopyToRegUses = false;
2676 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2677 for (SDNode::use_iterator UI = N0.Val->use_begin(), UE = N0.Val->use_end();
2678 UI != UE; ++UI) {
2679 SDNode *User = *UI;
2680 if (User == N)
2681 continue;
2682 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2683 if (User->getOpcode() == ISD::SETCC) {
2684 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2685 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2686 // Sign bits will be lost after a zext.
2687 return false;
2688 bool Add = false;
2689 for (unsigned i = 0; i != 2; ++i) {
2690 SDOperand UseOp = User->getOperand(i);
2691 if (UseOp == N0)
2692 continue;
2693 if (!isa<ConstantSDNode>(UseOp))
2694 return false;
2695 Add = true;
2696 }
2697 if (Add)
2698 ExtendNodes.push_back(User);
2699 } else {
2700 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2701 SDOperand UseOp = User->getOperand(i);
2702 if (UseOp == N0) {
2703 // If truncate from extended type to original load type is free
2704 // on this target, then it's ok to extend a CopyToReg.
2705 if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
2706 HasCopyToRegUses = true;
2707 else
2708 return false;
2709 }
2710 }
2711 }
2712 }
2713
2714 if (HasCopyToRegUses) {
2715 bool BothLiveOut = false;
2716 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2717 UI != UE; ++UI) {
2718 SDNode *User = *UI;
2719 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2720 SDOperand UseOp = User->getOperand(i);
2721 if (UseOp.Val == N && UseOp.ResNo == 0) {
2722 BothLiveOut = true;
2723 break;
2724 }
2725 }
2726 }
2727 if (BothLiveOut)
2728 // Both unextended and extended values are live out. There had better be
2729 // good a reason for the transformation.
2730 return ExtendNodes.size();
2731 }
2732 return true;
2733}
2734
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002735SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2736 SDOperand N0 = N->getOperand(0);
2737 MVT::ValueType VT = N->getValueType(0);
2738
2739 // fold (sext c1) -> c1
2740 if (isa<ConstantSDNode>(N0))
2741 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2742
2743 // fold (sext (sext x)) -> (sext x)
2744 // fold (sext (aext x)) -> (sext x)
2745 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2746 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2747
2748 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2749 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2750 if (N0.getOpcode() == ISD::TRUNCATE) {
2751 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2752 if (NarrowLoad.Val) {
2753 if (NarrowLoad.Val != N0.Val)
2754 CombineTo(N0.Val, NarrowLoad);
2755 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2756 }
2757 }
2758
2759 // See if the value being truncated is already sign extended. If so, just
2760 // eliminate the trunc/sext pair.
2761 if (N0.getOpcode() == ISD::TRUNCATE) {
2762 SDOperand Op = N0.getOperand(0);
2763 unsigned OpBits = MVT::getSizeInBits(Op.getValueType());
2764 unsigned MidBits = MVT::getSizeInBits(N0.getValueType());
2765 unsigned DestBits = MVT::getSizeInBits(VT);
2766 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2767
2768 if (OpBits == DestBits) {
2769 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2770 // bits, it is already ready.
2771 if (NumSignBits > DestBits-MidBits)
2772 return Op;
2773 } else if (OpBits < DestBits) {
2774 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2775 // bits, just sext from i32.
2776 if (NumSignBits > OpBits-MidBits)
2777 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2778 } else {
2779 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2780 // bits, just truncate to i32.
2781 if (NumSignBits > OpBits-MidBits)
2782 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2783 }
2784
2785 // fold (sext (truncate x)) -> (sextinreg x).
2786 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2787 N0.getValueType())) {
2788 if (Op.getValueType() < VT)
2789 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2790 else if (Op.getValueType() > VT)
2791 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2792 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2793 DAG.getValueType(N0.getValueType()));
2794 }
2795 }
2796
2797 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Evan Cheng9decb332007-10-29 19:58:20 +00002798 if (ISD::isNON_EXTLoad(N0.Val) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002799 (!AfterLegalize||TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))){
Evan Cheng9decb332007-10-29 19:58:20 +00002800 bool DoXform = true;
2801 SmallVector<SDNode*, 4> SetCCs;
2802 if (!N0.hasOneUse())
2803 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
2804 if (DoXform) {
2805 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2806 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2807 LN0->getBasePtr(), LN0->getSrcValue(),
2808 LN0->getSrcValueOffset(),
2809 N0.getValueType(),
2810 LN0->isVolatile(),
2811 LN0->getAlignment());
2812 CombineTo(N, ExtLoad);
2813 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2814 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2815 // Extend SetCC uses if necessary.
2816 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2817 SDNode *SetCC = SetCCs[i];
2818 SmallVector<SDOperand, 4> Ops;
2819 for (unsigned j = 0; j != 2; ++j) {
2820 SDOperand SOp = SetCC->getOperand(j);
2821 if (SOp == Trunc)
2822 Ops.push_back(ExtLoad);
2823 else
2824 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
2825 }
2826 Ops.push_back(SetCC->getOperand(2));
2827 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2828 &Ops[0], Ops.size()));
2829 }
2830 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2831 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002832 }
2833
2834 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2835 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2836 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2837 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2838 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman9a4c92c2008-01-30 00:15:11 +00002839 MVT::ValueType EVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002840 if (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
2841 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2842 LN0->getBasePtr(), LN0->getSrcValue(),
2843 LN0->getSrcValueOffset(), EVT,
2844 LN0->isVolatile(),
2845 LN0->getAlignment());
2846 CombineTo(N, ExtLoad);
2847 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2848 ExtLoad.getValue(1));
2849 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2850 }
2851 }
2852
2853 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2854 if (N0.getOpcode() == ISD::SETCC) {
2855 SDOperand SCC =
2856 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2857 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2858 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2859 if (SCC.Val) return SCC;
2860 }
2861
2862 return SDOperand();
2863}
2864
2865SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2866 SDOperand N0 = N->getOperand(0);
2867 MVT::ValueType VT = N->getValueType(0);
2868
2869 // fold (zext c1) -> c1
2870 if (isa<ConstantSDNode>(N0))
2871 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2872 // fold (zext (zext x)) -> (zext x)
2873 // fold (zext (aext x)) -> (zext x)
2874 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2875 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2876
2877 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2878 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2879 if (N0.getOpcode() == ISD::TRUNCATE) {
2880 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2881 if (NarrowLoad.Val) {
2882 if (NarrowLoad.Val != N0.Val)
2883 CombineTo(N0.Val, NarrowLoad);
2884 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2885 }
2886 }
2887
2888 // fold (zext (truncate x)) -> (and x, mask)
2889 if (N0.getOpcode() == ISD::TRUNCATE &&
2890 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2891 SDOperand Op = N0.getOperand(0);
2892 if (Op.getValueType() < VT) {
2893 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2894 } else if (Op.getValueType() > VT) {
2895 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2896 }
2897 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2898 }
2899
2900 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2901 if (N0.getOpcode() == ISD::AND &&
2902 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2903 N0.getOperand(1).getOpcode() == ISD::Constant) {
2904 SDOperand X = N0.getOperand(0).getOperand(0);
2905 if (X.getValueType() < VT) {
2906 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2907 } else if (X.getValueType() > VT) {
2908 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2909 }
Dan Gohmand047c3e2008-03-03 23:51:38 +00002910 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2911 Mask.zext(MVT::getSizeInBits(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002912 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2913 }
2914
2915 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Evan Cheng9decb332007-10-29 19:58:20 +00002916 if (ISD::isNON_EXTLoad(N0.Val) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002917 (!AfterLegalize||TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Cheng9decb332007-10-29 19:58:20 +00002918 bool DoXform = true;
2919 SmallVector<SDNode*, 4> SetCCs;
2920 if (!N0.hasOneUse())
2921 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
2922 if (DoXform) {
2923 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2924 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2925 LN0->getBasePtr(), LN0->getSrcValue(),
2926 LN0->getSrcValueOffset(),
2927 N0.getValueType(),
2928 LN0->isVolatile(),
2929 LN0->getAlignment());
2930 CombineTo(N, ExtLoad);
2931 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2932 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2933 // Extend SetCC uses if necessary.
2934 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2935 SDNode *SetCC = SetCCs[i];
2936 SmallVector<SDOperand, 4> Ops;
2937 for (unsigned j = 0; j != 2; ++j) {
2938 SDOperand SOp = SetCC->getOperand(j);
2939 if (SOp == Trunc)
2940 Ops.push_back(ExtLoad);
2941 else
Evan Cheng06aaf4c2007-10-30 20:11:21 +00002942 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
Evan Cheng9decb332007-10-29 19:58:20 +00002943 }
2944 Ops.push_back(SetCC->getOperand(2));
2945 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2946 &Ops[0], Ops.size()));
2947 }
2948 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2949 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002950 }
2951
2952 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2953 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2954 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2955 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2956 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman9a4c92c2008-01-30 00:15:11 +00002957 MVT::ValueType EVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002958 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2959 LN0->getBasePtr(), LN0->getSrcValue(),
2960 LN0->getSrcValueOffset(), EVT,
2961 LN0->isVolatile(),
2962 LN0->getAlignment());
2963 CombineTo(N, ExtLoad);
2964 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2965 ExtLoad.getValue(1));
2966 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2967 }
2968
2969 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
2970 if (N0.getOpcode() == ISD::SETCC) {
2971 SDOperand SCC =
2972 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2973 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2974 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2975 if (SCC.Val) return SCC;
2976 }
2977
2978 return SDOperand();
2979}
2980
2981SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
2982 SDOperand N0 = N->getOperand(0);
2983 MVT::ValueType VT = N->getValueType(0);
2984
2985 // fold (aext c1) -> c1
2986 if (isa<ConstantSDNode>(N0))
2987 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
2988 // fold (aext (aext x)) -> (aext x)
2989 // fold (aext (zext x)) -> (zext x)
2990 // fold (aext (sext x)) -> (sext x)
2991 if (N0.getOpcode() == ISD::ANY_EXTEND ||
2992 N0.getOpcode() == ISD::ZERO_EXTEND ||
2993 N0.getOpcode() == ISD::SIGN_EXTEND)
2994 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2995
2996 // fold (aext (truncate (load x))) -> (aext (smaller load x))
2997 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
2998 if (N0.getOpcode() == ISD::TRUNCATE) {
2999 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
3000 if (NarrowLoad.Val) {
3001 if (NarrowLoad.Val != N0.Val)
3002 CombineTo(N0.Val, NarrowLoad);
3003 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
3004 }
3005 }
3006
3007 // fold (aext (truncate x))
3008 if (N0.getOpcode() == ISD::TRUNCATE) {
3009 SDOperand TruncOp = N0.getOperand(0);
3010 if (TruncOp.getValueType() == VT)
3011 return TruncOp; // x iff x size == zext size.
3012 if (TruncOp.getValueType() > VT)
3013 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
3014 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
3015 }
3016
3017 // fold (aext (and (trunc x), cst)) -> (and x, cst).
3018 if (N0.getOpcode() == ISD::AND &&
3019 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3020 N0.getOperand(1).getOpcode() == ISD::Constant) {
3021 SDOperand X = N0.getOperand(0).getOperand(0);
3022 if (X.getValueType() < VT) {
3023 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
3024 } else if (X.getValueType() > VT) {
3025 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3026 }
Dan Gohmand047c3e2008-03-03 23:51:38 +00003027 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3028 Mask.zext(MVT::getSizeInBits(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003029 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
3030 }
3031
3032 // fold (aext (load x)) -> (aext (truncate (extload x)))
3033 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3034 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3035 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3036 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3037 LN0->getBasePtr(), LN0->getSrcValue(),
3038 LN0->getSrcValueOffset(),
3039 N0.getValueType(),
3040 LN0->isVolatile(),
3041 LN0->getAlignment());
3042 CombineTo(N, ExtLoad);
3043 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3044 ExtLoad.getValue(1));
3045 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3046 }
3047
3048 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3049 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3050 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3051 if (N0.getOpcode() == ISD::LOAD &&
3052 !ISD::isNON_EXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3053 N0.hasOneUse()) {
3054 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman9a4c92c2008-01-30 00:15:11 +00003055 MVT::ValueType EVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003056 SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
3057 LN0->getChain(), LN0->getBasePtr(),
3058 LN0->getSrcValue(),
3059 LN0->getSrcValueOffset(), EVT,
3060 LN0->isVolatile(),
3061 LN0->getAlignment());
3062 CombineTo(N, ExtLoad);
3063 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3064 ExtLoad.getValue(1));
3065 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3066 }
3067
3068 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3069 if (N0.getOpcode() == ISD::SETCC) {
3070 SDOperand SCC =
3071 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3072 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3073 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3074 if (SCC.Val)
3075 return SCC;
3076 }
3077
3078 return SDOperand();
3079}
3080
Chris Lattnere8671c52007-10-13 06:35:54 +00003081/// GetDemandedBits - See if the specified operand can be simplified with the
3082/// knowledge that only the bits specified by Mask are used. If so, return the
3083/// simpler operand, otherwise return a null SDOperand.
Dan Gohman07961cd2008-02-25 21:11:39 +00003084SDOperand DAGCombiner::GetDemandedBits(SDOperand V, const APInt &Mask) {
Chris Lattnere8671c52007-10-13 06:35:54 +00003085 switch (V.getOpcode()) {
3086 default: break;
3087 case ISD::OR:
3088 case ISD::XOR:
3089 // If the LHS or RHS don't contribute bits to the or, drop them.
3090 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3091 return V.getOperand(1);
3092 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3093 return V.getOperand(0);
3094 break;
Chris Lattnerb77ea552007-10-13 06:58:48 +00003095 case ISD::SRL:
3096 // Only look at single-use SRLs.
3097 if (!V.Val->hasOneUse())
3098 break;
3099 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3100 // See if we can recursively simplify the LHS.
3101 unsigned Amt = RHSC->getValue();
Dan Gohman07961cd2008-02-25 21:11:39 +00003102 APInt NewMask = Mask << Amt;
3103 SDOperand SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Chris Lattnerb77ea552007-10-13 06:58:48 +00003104 if (SimplifyLHS.Val) {
3105 return DAG.getNode(ISD::SRL, V.getValueType(),
3106 SimplifyLHS, V.getOperand(1));
3107 }
3108 }
Chris Lattnere8671c52007-10-13 06:35:54 +00003109 }
3110 return SDOperand();
3111}
3112
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003113/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3114/// bits and then truncated to a narrower type and where N is a multiple
3115/// of number of bits of the narrower type, transform it to a narrower load
3116/// from address + N / num of bits of new type. If the result is to be
3117/// extended, also fold the extension to form a extending load.
3118SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
3119 unsigned Opc = N->getOpcode();
3120 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3121 SDOperand N0 = N->getOperand(0);
3122 MVT::ValueType VT = N->getValueType(0);
3123 MVT::ValueType EVT = N->getValueType(0);
3124
3125 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3126 // extended to VT.
3127 if (Opc == ISD::SIGN_EXTEND_INREG) {
3128 ExtType = ISD::SEXTLOAD;
3129 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3130 if (AfterLegalize && !TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))
3131 return SDOperand();
3132 }
3133
3134 unsigned EVTBits = MVT::getSizeInBits(EVT);
3135 unsigned ShAmt = 0;
3136 bool CombineSRL = false;
3137 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3138 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3139 ShAmt = N01->getValue();
3140 // Is the shift amount a multiple of size of VT?
3141 if ((ShAmt & (EVTBits-1)) == 0) {
3142 N0 = N0.getOperand(0);
3143 if (MVT::getSizeInBits(N0.getValueType()) <= EVTBits)
3144 return SDOperand();
3145 CombineSRL = true;
3146 }
3147 }
3148 }
3149
3150 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3151 // Do not allow folding to i1 here. i1 is implicitly stored in memory in
3152 // zero extended form: by shrinking the load, we lose track of the fact
3153 // that it is already zero extended.
3154 // FIXME: This should be reevaluated.
3155 VT != MVT::i1) {
3156 assert(MVT::getSizeInBits(N0.getValueType()) > EVTBits &&
3157 "Cannot truncate to larger type!");
3158 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3159 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
3160 // For big endian targets, we need to adjust the offset to the pointer to
3161 // load the correct bytes.
Duncan Sands9ff8fbf2008-02-11 10:37:04 +00003162 if (TLI.isBigEndian()) {
Duncan Sands4f18d4f2007-11-09 08:57:19 +00003163 unsigned LVTStoreBits = MVT::getStoreSizeInBits(N0.getValueType());
3164 unsigned EVTStoreBits = MVT::getStoreSizeInBits(EVT);
3165 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3166 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003167 uint64_t PtrOff = ShAmt / 8;
Duncan Sandsa3691432007-10-28 12:59:45 +00003168 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003169 SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
3170 DAG.getConstant(PtrOff, PtrType));
3171 AddToWorkList(NewPtr.Val);
3172 SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
3173 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
3174 LN0->getSrcValue(), LN0->getSrcValueOffset(),
Duncan Sandsa3691432007-10-28 12:59:45 +00003175 LN0->isVolatile(), NewAlign)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003176 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
3177 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
Duncan Sandsa3691432007-10-28 12:59:45 +00003178 LN0->isVolatile(), NewAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003179 AddToWorkList(N);
3180 if (CombineSRL) {
Chris Lattner7bcb18f2008-02-03 06:49:24 +00003181 WorkListRemover DeadNodes(*this);
3182 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3183 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003184 CombineTo(N->getOperand(0).Val, Load);
3185 } else
3186 CombineTo(N0.Val, Load, Load.getValue(1));
3187 if (ShAmt) {
3188 if (Opc == ISD::SIGN_EXTEND_INREG)
3189 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
3190 else
3191 return DAG.getNode(Opc, VT, Load);
3192 }
3193 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3194 }
3195
3196 return SDOperand();
3197}
3198
3199
3200SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3201 SDOperand N0 = N->getOperand(0);
3202 SDOperand N1 = N->getOperand(1);
3203 MVT::ValueType VT = N->getValueType(0);
3204 MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman07961cd2008-02-25 21:11:39 +00003205 unsigned VTBits = MVT::getSizeInBits(VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003206 unsigned EVTBits = MVT::getSizeInBits(EVT);
3207
3208 // fold (sext_in_reg c1) -> c1
3209 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3210 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
3211
3212 // If the input is already sign extended, just drop the extension.
3213 if (DAG.ComputeNumSignBits(N0) >= MVT::getSizeInBits(VT)-EVTBits+1)
3214 return N0;
3215
3216 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3217 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3218 EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
3219 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
3220 }
3221
3222 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman07961cd2008-02-25 21:11:39 +00003223 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003224 return DAG.getZeroExtendInReg(N0, EVT);
3225
3226 // fold operands of sext_in_reg based on knowledge that the top bits are not
3227 // demanded.
3228 if (SimplifyDemandedBits(SDOperand(N, 0)))
3229 return SDOperand(N, 0);
3230
3231 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3232 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3233 SDOperand NarrowLoad = ReduceLoadWidth(N);
3234 if (NarrowLoad.Val)
3235 return NarrowLoad;
3236
3237 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
3238 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
3239 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3240 if (N0.getOpcode() == ISD::SRL) {
3241 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3242 if (ShAmt->getValue()+EVTBits <= MVT::getSizeInBits(VT)) {
3243 // We can turn this into an SRA iff the input to the SRL is already sign
3244 // extended enough.
3245 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3246 if (MVT::getSizeInBits(VT)-(ShAmt->getValue()+EVTBits) < InSignBits)
3247 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
3248 }
3249 }
3250
3251 // fold (sext_inreg (extload x)) -> (sextload x)
3252 if (ISD::isEXTLoad(N0.Val) &&
3253 ISD::isUNINDEXEDLoad(N0.Val) &&
Dan Gohman9a4c92c2008-01-30 00:15:11 +00003254 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003255 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3256 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3257 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3258 LN0->getBasePtr(), LN0->getSrcValue(),
3259 LN0->getSrcValueOffset(), EVT,
3260 LN0->isVolatile(),
3261 LN0->getAlignment());
3262 CombineTo(N, ExtLoad);
3263 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3264 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3265 }
3266 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3267 if (ISD::isZEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3268 N0.hasOneUse() &&
Dan Gohman9a4c92c2008-01-30 00:15:11 +00003269 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003270 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3271 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3272 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3273 LN0->getBasePtr(), LN0->getSrcValue(),
3274 LN0->getSrcValueOffset(), EVT,
3275 LN0->isVolatile(),
3276 LN0->getAlignment());
3277 CombineTo(N, ExtLoad);
3278 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3279 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3280 }
3281 return SDOperand();
3282}
3283
3284SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
3285 SDOperand N0 = N->getOperand(0);
3286 MVT::ValueType VT = N->getValueType(0);
3287
3288 // noop truncate
3289 if (N0.getValueType() == N->getValueType(0))
3290 return N0;
3291 // fold (truncate c1) -> c1
3292 if (isa<ConstantSDNode>(N0))
3293 return DAG.getNode(ISD::TRUNCATE, VT, N0);
3294 // fold (truncate (truncate x)) -> (truncate x)
3295 if (N0.getOpcode() == ISD::TRUNCATE)
3296 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3297 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3298 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3299 N0.getOpcode() == ISD::ANY_EXTEND) {
3300 if (N0.getOperand(0).getValueType() < VT)
3301 // if the source is smaller than the dest, we still need an extend
3302 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3303 else if (N0.getOperand(0).getValueType() > VT)
3304 // if the source is larger than the dest, than we just need the truncate
3305 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3306 else
3307 // if the source and dest are the same type, we can drop both the extend
3308 // and the truncate
3309 return N0.getOperand(0);
3310 }
3311
Chris Lattnere8671c52007-10-13 06:35:54 +00003312 // See if we can simplify the input to this truncate through knowledge that
3313 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3314 // -> trunc y
Dan Gohman07961cd2008-02-25 21:11:39 +00003315 SDOperand Shorter =
3316 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3317 MVT::getSizeInBits(VT)));
Chris Lattnere8671c52007-10-13 06:35:54 +00003318 if (Shorter.Val)
3319 return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3320
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003321 // fold (truncate (load x)) -> (smaller load x)
3322 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3323 return ReduceLoadWidth(N);
3324}
3325
3326SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3327 SDOperand N0 = N->getOperand(0);
3328 MVT::ValueType VT = N->getValueType(0);
3329
3330 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3331 // Only do this before legalize, since afterward the target may be depending
3332 // on the bitconvert.
3333 // First check to see if this is all constant.
3334 if (!AfterLegalize &&
3335 N0.getOpcode() == ISD::BUILD_VECTOR && N0.Val->hasOneUse() &&
3336 MVT::isVector(VT)) {
3337 bool isSimple = true;
3338 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3339 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3340 N0.getOperand(i).getOpcode() != ISD::Constant &&
3341 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3342 isSimple = false;
3343 break;
3344 }
3345
3346 MVT::ValueType DestEltVT = MVT::getVectorElementType(N->getValueType(0));
3347 assert(!MVT::isVector(DestEltVT) &&
3348 "Element type of vector ValueType must not be vector!");
3349 if (isSimple) {
3350 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.Val, DestEltVT);
3351 }
3352 }
3353
3354 // If the input is a constant, let getNode() fold it.
3355 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3356 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3357 if (Res.Val != N) return Res;
3358 }
3359
3360 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
3361 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3362
3363 // fold (conv (load x)) -> (load (conv*)x)
Evan Chengd7ba7ed2007-10-06 08:19:55 +00003364 // If the resultant load doesn't need a higher alignment than the original!
3365 if (ISD::isNormalLoad(N0.Val) && N0.hasOneUse() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003366 TLI.isOperationLegal(ISD::LOAD, VT)) {
3367 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3368 unsigned Align = TLI.getTargetMachine().getTargetData()->
3369 getABITypeAlignment(MVT::getTypeForValueType(VT));
3370 unsigned OrigAlign = LN0->getAlignment();
3371 if (Align <= OrigAlign) {
3372 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3373 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3374 LN0->isVolatile(), Align);
3375 AddToWorkList(N);
3376 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3377 Load.getValue(1));
3378 return Load;
3379 }
3380 }
3381
Chris Lattneref26cbc2008-01-27 17:42:27 +00003382 // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit)
3383 // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit)
3384 // This often reduces constant pool loads.
3385 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3386 N0.Val->hasOneUse() && MVT::isInteger(VT) && !MVT::isVector(VT)) {
3387 SDOperand NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3388 AddToWorkList(NewConv.Val);
3389
Dan Gohmand047c3e2008-03-03 23:51:38 +00003390 APInt SignBit = APInt::getSignBit(MVT::getSizeInBits(VT));
Chris Lattneref26cbc2008-01-27 17:42:27 +00003391 if (N0.getOpcode() == ISD::FNEG)
3392 return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT));
3393 assert(N0.getOpcode() == ISD::FABS);
3394 return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT));
3395 }
3396
3397 // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign'
3398 // Note that we don't handle copysign(x,cst) because this can always be folded
3399 // to an fneg or fabs.
3400 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse() &&
Chris Lattner336672f2008-01-27 23:32:17 +00003401 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3402 MVT::isInteger(VT) && !MVT::isVector(VT)) {
Chris Lattneref26cbc2008-01-27 17:42:27 +00003403 unsigned OrigXWidth = MVT::getSizeInBits(N0.getOperand(1).getValueType());
3404 SDOperand X = DAG.getNode(ISD::BIT_CONVERT, MVT::getIntegerType(OrigXWidth),
3405 N0.getOperand(1));
3406 AddToWorkList(X.Val);
3407
3408 // If X has a different width than the result/lhs, sext it or truncate it.
3409 unsigned VTWidth = MVT::getSizeInBits(VT);
3410 if (OrigXWidth < VTWidth) {
3411 X = DAG.getNode(ISD::SIGN_EXTEND, VT, X);
3412 AddToWorkList(X.Val);
3413 } else if (OrigXWidth > VTWidth) {
3414 // To get the sign bit in the right place, we have to shift it right
3415 // before truncating.
3416 X = DAG.getNode(ISD::SRL, X.getValueType(), X,
3417 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3418 AddToWorkList(X.Val);
3419 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3420 AddToWorkList(X.Val);
3421 }
3422
Dan Gohmand047c3e2008-03-03 23:51:38 +00003423 APInt SignBit = APInt::getSignBit(MVT::getSizeInBits(VT));
Chris Lattneref26cbc2008-01-27 17:42:27 +00003424 X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT));
3425 AddToWorkList(X.Val);
3426
3427 SDOperand Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3428 Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT));
3429 AddToWorkList(Cst.Val);
3430
3431 return DAG.getNode(ISD::OR, VT, X, Cst);
3432 }
3433
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003434 return SDOperand();
3435}
3436
3437/// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3438/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3439/// destination element value type.
3440SDOperand DAGCombiner::
3441ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
3442 MVT::ValueType SrcEltVT = BV->getOperand(0).getValueType();
3443
3444 // If this is already the right type, we're done.
3445 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
3446
3447 unsigned SrcBitSize = MVT::getSizeInBits(SrcEltVT);
3448 unsigned DstBitSize = MVT::getSizeInBits(DstEltVT);
3449
3450 // If this is a conversion of N elements of one type to N elements of another
3451 // type, convert each element. This handles FP<->INT cases.
3452 if (SrcBitSize == DstBitSize) {
3453 SmallVector<SDOperand, 8> Ops;
3454 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3455 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3456 AddToWorkList(Ops.back().Val);
3457 }
3458 MVT::ValueType VT =
3459 MVT::getVectorType(DstEltVT,
3460 MVT::getVectorNumElements(BV->getValueType(0)));
3461 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3462 }
3463
3464 // Otherwise, we're growing or shrinking the elements. To avoid having to
3465 // handle annoying details of growing/shrinking FP values, we convert them to
3466 // int first.
3467 if (MVT::isFloatingPoint(SrcEltVT)) {
3468 // Convert the input float vector to a int vector where the elements are the
3469 // same sizes.
3470 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3471 MVT::ValueType IntVT = SrcEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
3472 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).Val;
3473 SrcEltVT = IntVT;
3474 }
3475
3476 // Now we know the input is an integer vector. If the output is a FP type,
3477 // convert to integer first, then to FP of the right size.
3478 if (MVT::isFloatingPoint(DstEltVT)) {
3479 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3480 MVT::ValueType TmpVT = DstEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
3481 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).Val;
3482
3483 // Next, convert to FP elements of the same size.
3484 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3485 }
3486
3487 // Okay, we know the src/dst types are both integers of differing types.
3488 // Handling growing first.
3489 assert(MVT::isInteger(SrcEltVT) && MVT::isInteger(DstEltVT));
3490 if (SrcBitSize < DstBitSize) {
3491 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3492
3493 SmallVector<SDOperand, 8> Ops;
3494 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3495 i += NumInputsPerOutput) {
3496 bool isLE = TLI.isLittleEndian();
Dan Gohmand047c3e2008-03-03 23:51:38 +00003497 APInt NewBits = APInt(DstBitSize, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003498 bool EltIsUndef = true;
3499 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3500 // Shift the previously computed bits over.
3501 NewBits <<= SrcBitSize;
3502 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3503 if (Op.getOpcode() == ISD::UNDEF) continue;
3504 EltIsUndef = false;
3505
Dan Gohmand047c3e2008-03-03 23:51:38 +00003506 NewBits |=
3507 APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).zext(DstBitSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003508 }
3509
3510 if (EltIsUndef)
3511 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3512 else
3513 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3514 }
3515
Evan Chengd1045a62008-02-18 23:04:32 +00003516 MVT::ValueType VT = MVT::getVectorType(DstEltVT, Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003517 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3518 }
3519
3520 // Finally, this must be the case where we are shrinking elements: each input
3521 // turns into multiple outputs.
Evan Chengd1045a62008-02-18 23:04:32 +00003522 bool isS2V = ISD::isScalarToVector(BV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003523 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Evan Chengd1045a62008-02-18 23:04:32 +00003524 MVT::ValueType VT = MVT::getVectorType(DstEltVT,
3525 NumOutputsPerInput * BV->getNumOperands());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003526 SmallVector<SDOperand, 8> Ops;
3527 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3528 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3529 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3530 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3531 continue;
3532 }
Dan Gohmand047c3e2008-03-03 23:51:38 +00003533 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getAPIntValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003534 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00003535 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003536 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Dan Gohmand047c3e2008-03-03 23:51:38 +00003537 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
Evan Chengd1045a62008-02-18 23:04:32 +00003538 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3539 return DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Ops[0]);
Dan Gohmand047c3e2008-03-03 23:51:38 +00003540 OpVal = OpVal.lshr(DstBitSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003541 }
3542
3543 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands9ff8fbf2008-02-11 10:37:04 +00003544 if (TLI.isBigEndian())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003545 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3546 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003547 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3548}
3549
3550
3551
3552SDOperand DAGCombiner::visitFADD(SDNode *N) {
3553 SDOperand N0 = N->getOperand(0);
3554 SDOperand N1 = N->getOperand(1);
3555 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3556 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3557 MVT::ValueType VT = N->getValueType(0);
3558
3559 // fold vector ops
3560 if (MVT::isVector(VT)) {
3561 SDOperand FoldedVOp = SimplifyVBinOp(N);
3562 if (FoldedVOp.Val) return FoldedVOp;
3563 }
3564
3565 // fold (fadd c1, c2) -> c1+c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003566 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003567 return DAG.getNode(ISD::FADD, VT, N0, N1);
3568 // canonicalize constant to RHS
3569 if (N0CFP && !N1CFP)
3570 return DAG.getNode(ISD::FADD, VT, N1, N0);
3571 // fold (A + (-B)) -> A-B
Chris Lattnere0992b82008-02-26 07:04:54 +00003572 if (isNegatibleForFree(N1, AfterLegalize) == 2)
3573 return DAG.getNode(ISD::FSUB, VT, N0,
3574 GetNegatedExpression(N1, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003575 // fold ((-A) + B) -> B-A
Chris Lattnere0992b82008-02-26 07:04:54 +00003576 if (isNegatibleForFree(N0, AfterLegalize) == 2)
3577 return DAG.getNode(ISD::FSUB, VT, N1,
3578 GetNegatedExpression(N0, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003579
3580 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3581 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3582 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3583 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3584 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3585
3586 return SDOperand();
3587}
3588
3589SDOperand DAGCombiner::visitFSUB(SDNode *N) {
3590 SDOperand N0 = N->getOperand(0);
3591 SDOperand N1 = N->getOperand(1);
3592 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3593 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3594 MVT::ValueType VT = N->getValueType(0);
3595
3596 // fold vector ops
3597 if (MVT::isVector(VT)) {
3598 SDOperand FoldedVOp = SimplifyVBinOp(N);
3599 if (FoldedVOp.Val) return FoldedVOp;
3600 }
3601
3602 // fold (fsub c1, c2) -> c1-c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003603 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003604 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3605 // fold (0-B) -> -B
Dale Johannesen7604c1b2007-08-31 23:34:27 +00003606 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
Chris Lattnere0992b82008-02-26 07:04:54 +00003607 if (isNegatibleForFree(N1, AfterLegalize))
3608 return GetNegatedExpression(N1, DAG, AfterLegalize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003609 return DAG.getNode(ISD::FNEG, VT, N1);
3610 }
3611 // fold (A-(-B)) -> A+B
Chris Lattnere0992b82008-02-26 07:04:54 +00003612 if (isNegatibleForFree(N1, AfterLegalize))
3613 return DAG.getNode(ISD::FADD, VT, N0,
3614 GetNegatedExpression(N1, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003615
3616 return SDOperand();
3617}
3618
3619SDOperand DAGCombiner::visitFMUL(SDNode *N) {
3620 SDOperand N0 = N->getOperand(0);
3621 SDOperand N1 = N->getOperand(1);
3622 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3623 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3624 MVT::ValueType VT = N->getValueType(0);
3625
3626 // fold vector ops
3627 if (MVT::isVector(VT)) {
3628 SDOperand FoldedVOp = SimplifyVBinOp(N);
3629 if (FoldedVOp.Val) return FoldedVOp;
3630 }
3631
3632 // fold (fmul c1, c2) -> c1*c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003633 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003634 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3635 // canonicalize constant to RHS
3636 if (N0CFP && !N1CFP)
3637 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3638 // fold (fmul X, 2.0) -> (fadd X, X)
3639 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3640 return DAG.getNode(ISD::FADD, VT, N0, N0);
3641 // fold (fmul X, -1.0) -> (fneg X)
3642 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3643 return DAG.getNode(ISD::FNEG, VT, N0);
3644
3645 // -X * -Y -> X*Y
Chris Lattnere0992b82008-02-26 07:04:54 +00003646 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3647 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003648 // Both can be negated for free, check to see if at least one is cheaper
3649 // negated.
3650 if (LHSNeg == 2 || RHSNeg == 2)
Chris Lattnere0992b82008-02-26 07:04:54 +00003651 return DAG.getNode(ISD::FMUL, VT,
3652 GetNegatedExpression(N0, DAG, AfterLegalize),
3653 GetNegatedExpression(N1, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003654 }
3655 }
3656
3657 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3658 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3659 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3660 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3661 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3662
3663 return SDOperand();
3664}
3665
3666SDOperand DAGCombiner::visitFDIV(SDNode *N) {
3667 SDOperand N0 = N->getOperand(0);
3668 SDOperand N1 = N->getOperand(1);
3669 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3670 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3671 MVT::ValueType VT = N->getValueType(0);
3672
3673 // fold vector ops
3674 if (MVT::isVector(VT)) {
3675 SDOperand FoldedVOp = SimplifyVBinOp(N);
3676 if (FoldedVOp.Val) return FoldedVOp;
3677 }
3678
3679 // fold (fdiv c1, c2) -> c1/c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003680 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003681 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3682
3683
3684 // -X / -Y -> X*Y
Chris Lattnere0992b82008-02-26 07:04:54 +00003685 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3686 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003687 // Both can be negated for free, check to see if at least one is cheaper
3688 // negated.
3689 if (LHSNeg == 2 || RHSNeg == 2)
Chris Lattnere0992b82008-02-26 07:04:54 +00003690 return DAG.getNode(ISD::FDIV, VT,
3691 GetNegatedExpression(N0, DAG, AfterLegalize),
3692 GetNegatedExpression(N1, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003693 }
3694 }
3695
3696 return SDOperand();
3697}
3698
3699SDOperand DAGCombiner::visitFREM(SDNode *N) {
3700 SDOperand N0 = N->getOperand(0);
3701 SDOperand N1 = N->getOperand(1);
3702 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3703 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3704 MVT::ValueType VT = N->getValueType(0);
3705
3706 // fold (frem c1, c2) -> fmod(c1,c2)
Dale Johannesenb89072e2007-10-16 23:38:29 +00003707 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003708 return DAG.getNode(ISD::FREM, VT, N0, N1);
3709
3710 return SDOperand();
3711}
3712
3713SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3714 SDOperand N0 = N->getOperand(0);
3715 SDOperand N1 = N->getOperand(1);
3716 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3717 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3718 MVT::ValueType VT = N->getValueType(0);
3719
Dale Johannesenb89072e2007-10-16 23:38:29 +00003720 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003721 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3722
3723 if (N1CFP) {
Dale Johannesenc53301c2007-08-26 01:18:27 +00003724 const APFloat& V = N1CFP->getValueAPF();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003725 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3726 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dale Johannesen7f2c1d12007-08-25 22:10:57 +00003727 if (!V.isNegative())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003728 return DAG.getNode(ISD::FABS, VT, N0);
3729 else
3730 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3731 }
3732
3733 // copysign(fabs(x), y) -> copysign(x, y)
3734 // copysign(fneg(x), y) -> copysign(x, y)
3735 // copysign(copysign(x,z), y) -> copysign(x, y)
3736 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3737 N0.getOpcode() == ISD::FCOPYSIGN)
3738 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3739
3740 // copysign(x, abs(y)) -> abs(x)
3741 if (N1.getOpcode() == ISD::FABS)
3742 return DAG.getNode(ISD::FABS, VT, N0);
3743
3744 // copysign(x, copysign(y,z)) -> copysign(x, z)
3745 if (N1.getOpcode() == ISD::FCOPYSIGN)
3746 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3747
3748 // copysign(x, fp_extend(y)) -> copysign(x, y)
3749 // copysign(x, fp_round(y)) -> copysign(x, y)
3750 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3751 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3752
3753 return SDOperand();
3754}
3755
3756
3757
3758SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3759 SDOperand N0 = N->getOperand(0);
3760 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3761 MVT::ValueType VT = N->getValueType(0);
3762
3763 // fold (sint_to_fp c1) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003764 if (N0C && N0.getValueType() != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003765 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3766 return SDOperand();
3767}
3768
3769SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3770 SDOperand N0 = N->getOperand(0);
3771 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3772 MVT::ValueType VT = N->getValueType(0);
3773
3774 // fold (uint_to_fp c1) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003775 if (N0C && N0.getValueType() != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003776 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3777 return SDOperand();
3778}
3779
3780SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3781 SDOperand N0 = N->getOperand(0);
3782 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3783 MVT::ValueType VT = N->getValueType(0);
3784
3785 // fold (fp_to_sint c1fp) -> c1
3786 if (N0CFP)
3787 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3788 return SDOperand();
3789}
3790
3791SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3792 SDOperand N0 = N->getOperand(0);
3793 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3794 MVT::ValueType VT = N->getValueType(0);
3795
3796 // fold (fp_to_uint c1fp) -> c1
Dale Johannesenb89072e2007-10-16 23:38:29 +00003797 if (N0CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003798 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3799 return SDOperand();
3800}
3801
3802SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
3803 SDOperand N0 = N->getOperand(0);
Chris Lattner5872a362008-01-17 07:00:52 +00003804 SDOperand N1 = N->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003805 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3806 MVT::ValueType VT = N->getValueType(0);
3807
3808 // fold (fp_round c1fp) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003809 if (N0CFP && N0.getValueType() != MVT::ppcf128)
Chris Lattner5872a362008-01-17 07:00:52 +00003810 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003811
3812 // fold (fp_round (fp_extend x)) -> x
3813 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3814 return N0.getOperand(0);
3815
Chris Lattner7afb8552008-01-24 06:45:35 +00003816 // fold (fp_round (fp_round x)) -> (fp_round x)
3817 if (N0.getOpcode() == ISD::FP_ROUND) {
3818 // This is a value preserving truncation if both round's are.
3819 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
3820 N0.Val->getConstantOperandVal(1) == 1;
3821 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
3822 DAG.getIntPtrConstant(IsTrunc));
3823 }
3824
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003825 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3826 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
Chris Lattner5872a362008-01-17 07:00:52 +00003827 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003828 AddToWorkList(Tmp.Val);
3829 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
3830 }
3831
3832 return SDOperand();
3833}
3834
3835SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
3836 SDOperand N0 = N->getOperand(0);
3837 MVT::ValueType VT = N->getValueType(0);
3838 MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3839 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3840
3841 // fold (fp_round_inreg c1fp) -> c1fp
3842 if (N0CFP) {
Dale Johannesen7604c1b2007-08-31 23:34:27 +00003843 SDOperand Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003844 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
3845 }
3846 return SDOperand();
3847}
3848
3849SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
3850 SDOperand N0 = N->getOperand(0);
3851 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3852 MVT::ValueType VT = N->getValueType(0);
3853
Chris Lattner6f981fc2007-12-29 06:55:23 +00003854 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
3855 if (N->hasOneUse() && (*N->use_begin())->getOpcode() == ISD::FP_ROUND)
3856 return SDOperand();
Chris Lattner5872a362008-01-17 07:00:52 +00003857
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003858 // fold (fp_extend c1fp) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003859 if (N0CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003860 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
Chris Lattner5872a362008-01-17 07:00:52 +00003861
3862 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
3863 // value of X.
3864 if (N0.getOpcode() == ISD::FP_ROUND && N0.Val->getConstantOperandVal(1) == 1){
3865 SDOperand In = N0.getOperand(0);
3866 if (In.getValueType() == VT) return In;
3867 if (VT < In.getValueType())
3868 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
3869 return DAG.getNode(ISD::FP_EXTEND, VT, In);
3870 }
3871
3872 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Dale Johannesen2550e3a2007-10-19 20:29:00 +00003873 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003874 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3875 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3876 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3877 LN0->getBasePtr(), LN0->getSrcValue(),
3878 LN0->getSrcValueOffset(),
3879 N0.getValueType(),
3880 LN0->isVolatile(),
3881 LN0->getAlignment());
3882 CombineTo(N, ExtLoad);
Chris Lattner5872a362008-01-17 07:00:52 +00003883 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad,
3884 DAG.getIntPtrConstant(1)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003885 ExtLoad.getValue(1));
3886 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3887 }
3888
3889
3890 return SDOperand();
3891}
3892
3893SDOperand DAGCombiner::visitFNEG(SDNode *N) {
3894 SDOperand N0 = N->getOperand(0);
3895
Chris Lattnere0992b82008-02-26 07:04:54 +00003896 if (isNegatibleForFree(N0, AfterLegalize))
3897 return GetNegatedExpression(N0, DAG, AfterLegalize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003898
Chris Lattneref26cbc2008-01-27 17:42:27 +00003899 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
3900 // constant pool values.
Chris Lattner336672f2008-01-27 23:32:17 +00003901 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
3902 MVT::isInteger(N0.getOperand(0).getValueType()) &&
3903 !MVT::isVector(N0.getOperand(0).getValueType())) {
Chris Lattneref26cbc2008-01-27 17:42:27 +00003904 SDOperand Int = N0.getOperand(0);
3905 MVT::ValueType IntVT = Int.getValueType();
3906 if (MVT::isInteger(IntVT) && !MVT::isVector(IntVT)) {
3907 Int = DAG.getNode(ISD::XOR, IntVT, Int,
3908 DAG.getConstant(MVT::getIntVTSignBit(IntVT), IntVT));
3909 AddToWorkList(Int.Val);
3910 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
3911 }
3912 }
3913
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003914 return SDOperand();
3915}
3916
3917SDOperand DAGCombiner::visitFABS(SDNode *N) {
3918 SDOperand N0 = N->getOperand(0);
3919 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3920 MVT::ValueType VT = N->getValueType(0);
3921
3922 // fold (fabs c1) -> fabs(c1)
Dale Johannesenb89072e2007-10-16 23:38:29 +00003923 if (N0CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003924 return DAG.getNode(ISD::FABS, VT, N0);
3925 // fold (fabs (fabs x)) -> (fabs x)
3926 if (N0.getOpcode() == ISD::FABS)
3927 return N->getOperand(0);
3928 // fold (fabs (fneg x)) -> (fabs x)
3929 // fold (fabs (fcopysign x, y)) -> (fabs x)
3930 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
3931 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
3932
Chris Lattneref26cbc2008-01-27 17:42:27 +00003933 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
3934 // constant pool values.
Chris Lattner336672f2008-01-27 23:32:17 +00003935 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
3936 MVT::isInteger(N0.getOperand(0).getValueType()) &&
3937 !MVT::isVector(N0.getOperand(0).getValueType())) {
Chris Lattneref26cbc2008-01-27 17:42:27 +00003938 SDOperand Int = N0.getOperand(0);
3939 MVT::ValueType IntVT = Int.getValueType();
3940 if (MVT::isInteger(IntVT) && !MVT::isVector(IntVT)) {
3941 Int = DAG.getNode(ISD::AND, IntVT, Int,
3942 DAG.getConstant(~MVT::getIntVTSignBit(IntVT), IntVT));
3943 AddToWorkList(Int.Val);
3944 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
3945 }
3946 }
3947
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003948 return SDOperand();
3949}
3950
3951SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
3952 SDOperand Chain = N->getOperand(0);
3953 SDOperand N1 = N->getOperand(1);
3954 SDOperand N2 = N->getOperand(2);
3955 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3956
3957 // never taken branch, fold to chain
3958 if (N1C && N1C->isNullValue())
3959 return Chain;
3960 // unconditional branch
Dan Gohman9d24dc72008-03-13 22:13:53 +00003961 if (N1C && N1C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003962 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
3963 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
3964 // on the target.
3965 if (N1.getOpcode() == ISD::SETCC &&
3966 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
3967 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
3968 N1.getOperand(0), N1.getOperand(1), N2);
3969 }
3970 return SDOperand();
3971}
3972
3973// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
3974//
3975SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
3976 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
3977 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
3978
3979 // Use SimplifySetCC to simplify SETCC's.
3980 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
3981 if (Simp.Val) AddToWorkList(Simp.Val);
3982
3983 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
3984
3985 // fold br_cc true, dest -> br dest (unconditional branch)
Dan Gohman9d24dc72008-03-13 22:13:53 +00003986 if (SCCC && !SCCC->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003987 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
3988 N->getOperand(4));
3989 // fold br_cc false, dest -> unconditional fall through
3990 if (SCCC && SCCC->isNullValue())
3991 return N->getOperand(0);
3992
3993 // fold to a simpler setcc
3994 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
3995 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
3996 Simp.getOperand(2), Simp.getOperand(0),
3997 Simp.getOperand(1), N->getOperand(4));
3998 return SDOperand();
3999}
4000
4001
4002/// CombineToPreIndexedLoadStore - Try turning a load / store and a
4003/// pre-indexed load / store when the base pointer is a add or subtract
4004/// and it has other uses besides the load / store. After the
4005/// transformation, the new indexed load / store has effectively folded
4006/// the add / subtract in and all of its other uses are redirected to the
4007/// new load / store.
4008bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4009 if (!AfterLegalize)
4010 return false;
4011
4012 bool isLoad = true;
4013 SDOperand Ptr;
4014 MVT::ValueType VT;
4015 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004016 if (LD->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004017 return false;
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004018 VT = LD->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004019 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4020 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4021 return false;
4022 Ptr = LD->getBasePtr();
4023 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004024 if (ST->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004025 return false;
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004026 VT = ST->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004027 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4028 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4029 return false;
4030 Ptr = ST->getBasePtr();
4031 isLoad = false;
4032 } else
4033 return false;
4034
4035 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4036 // out. There is no reason to make this a preinc/predec.
4037 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4038 Ptr.Val->hasOneUse())
4039 return false;
4040
4041 // Ask the target to do addressing mode selection.
4042 SDOperand BasePtr;
4043 SDOperand Offset;
4044 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4045 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4046 return false;
4047 // Don't create a indexed load / store with zero offset.
4048 if (isa<ConstantSDNode>(Offset) &&
Dan Gohman9d24dc72008-03-13 22:13:53 +00004049 cast<ConstantSDNode>(Offset)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004050 return false;
4051
4052 // Try turning it into a pre-indexed load / store except when:
4053 // 1) The new base ptr is a frame index.
4054 // 2) If N is a store and the new base ptr is either the same as or is a
4055 // predecessor of the value being stored.
4056 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4057 // that would create a cycle.
4058 // 4) All uses are load / store ops that use it as old base ptr.
4059
4060 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4061 // (plus the implicit offset) to a register to preinc anyway.
4062 if (isa<FrameIndexSDNode>(BasePtr))
4063 return false;
4064
4065 // Check #2.
4066 if (!isLoad) {
4067 SDOperand Val = cast<StoreSDNode>(N)->getValue();
Evan Chengd9387682008-03-04 00:41:45 +00004068 if (Val == BasePtr || BasePtr.Val->isPredecessorOf(Val.Val))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004069 return false;
4070 }
4071
4072 // Now check for #3 and #4.
4073 bool RealUse = false;
4074 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4075 E = Ptr.Val->use_end(); I != E; ++I) {
4076 SDNode *Use = *I;
4077 if (Use == N)
4078 continue;
Evan Chengd9387682008-03-04 00:41:45 +00004079 if (Use->isPredecessorOf(N))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004080 return false;
4081
4082 if (!((Use->getOpcode() == ISD::LOAD &&
4083 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
Anton Korobeynikov53422f62008-02-20 11:10:28 +00004084 (Use->getOpcode() == ISD::STORE &&
4085 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004086 RealUse = true;
4087 }
4088 if (!RealUse)
4089 return false;
4090
4091 SDOperand Result;
4092 if (isLoad)
4093 Result = DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
4094 else
4095 Result = DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4096 ++PreIndexedNodes;
4097 ++NodesCombined;
4098 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
4099 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4100 DOUT << '\n';
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004101 WorkListRemover DeadNodes(*this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004102 if (isLoad) {
4103 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004104 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004105 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004106 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004107 } else {
4108 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004109 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004110 }
4111
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004112 // Finally, since the node is now dead, remove it from the graph.
4113 DAG.DeleteNode(N);
4114
4115 // Replace the uses of Ptr with uses of the updated base value.
4116 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004117 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004118 removeFromWorkList(Ptr.Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004119 DAG.DeleteNode(Ptr.Val);
4120
4121 return true;
4122}
4123
4124/// CombineToPostIndexedLoadStore - Try combine a load / store with a
4125/// add / sub of the base pointer node into a post-indexed load / store.
4126/// The transformation folded the add / subtract into the new indexed
4127/// load / store effectively and all of its uses are redirected to the
4128/// new load / store.
4129bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4130 if (!AfterLegalize)
4131 return false;
4132
4133 bool isLoad = true;
4134 SDOperand Ptr;
4135 MVT::ValueType VT;
4136 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004137 if (LD->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004138 return false;
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004139 VT = LD->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004140 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4141 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4142 return false;
4143 Ptr = LD->getBasePtr();
4144 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004145 if (ST->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004146 return false;
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004147 VT = ST->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004148 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4149 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4150 return false;
4151 Ptr = ST->getBasePtr();
4152 isLoad = false;
4153 } else
4154 return false;
4155
4156 if (Ptr.Val->hasOneUse())
4157 return false;
4158
4159 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4160 E = Ptr.Val->use_end(); I != E; ++I) {
4161 SDNode *Op = *I;
4162 if (Op == N ||
4163 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4164 continue;
4165
4166 SDOperand BasePtr;
4167 SDOperand Offset;
4168 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4169 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4170 if (Ptr == Offset)
4171 std::swap(BasePtr, Offset);
4172 if (Ptr != BasePtr)
4173 continue;
4174 // Don't create a indexed load / store with zero offset.
4175 if (isa<ConstantSDNode>(Offset) &&
Dan Gohman9d24dc72008-03-13 22:13:53 +00004176 cast<ConstantSDNode>(Offset)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004177 continue;
4178
4179 // Try turning it into a post-indexed load / store except when
4180 // 1) All uses are load / store ops that use it as base ptr.
4181 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4182 // nor a successor of N. Otherwise, if Op is folded that would
4183 // create a cycle.
4184
4185 // Check for #1.
4186 bool TryNext = false;
4187 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
4188 EE = BasePtr.Val->use_end(); II != EE; ++II) {
4189 SDNode *Use = *II;
4190 if (Use == Ptr.Val)
4191 continue;
4192
4193 // If all the uses are load / store addresses, then don't do the
4194 // transformation.
4195 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4196 bool RealUse = false;
4197 for (SDNode::use_iterator III = Use->use_begin(),
4198 EEE = Use->use_end(); III != EEE; ++III) {
4199 SDNode *UseUse = *III;
4200 if (!((UseUse->getOpcode() == ISD::LOAD &&
4201 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
Anton Korobeynikov53422f62008-02-20 11:10:28 +00004202 (UseUse->getOpcode() == ISD::STORE &&
4203 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004204 RealUse = true;
4205 }
4206
4207 if (!RealUse) {
4208 TryNext = true;
4209 break;
4210 }
4211 }
4212 }
4213 if (TryNext)
4214 continue;
4215
4216 // Check for #2
Evan Chengd9387682008-03-04 00:41:45 +00004217 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004218 SDOperand Result = isLoad
4219 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
4220 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4221 ++PostIndexedNodes;
4222 ++NodesCombined;
4223 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
4224 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4225 DOUT << '\n';
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004226 WorkListRemover DeadNodes(*this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004227 if (isLoad) {
4228 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004229 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004230 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004231 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004232 } else {
4233 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004234 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004235 }
4236
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004237 // Finally, since the node is now dead, remove it from the graph.
4238 DAG.DeleteNode(N);
4239
4240 // Replace the uses of Use with uses of the updated base value.
4241 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
4242 Result.getValue(isLoad ? 1 : 0),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004243 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004244 removeFromWorkList(Op);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004245 DAG.DeleteNode(Op);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004246 return true;
4247 }
4248 }
4249 }
4250 return false;
4251}
4252
Chris Lattner4e137af2008-01-25 07:20:16 +00004253/// InferAlignment - If we can infer some alignment information from this
4254/// pointer, return it.
4255static unsigned InferAlignment(SDOperand Ptr, SelectionDAG &DAG) {
4256 // If this is a direct reference to a stack slot, use information about the
4257 // stack slot's alignment.
Chris Lattner1e3362f2008-01-26 19:45:50 +00004258 int FrameIdx = 1 << 31;
4259 int64_t FrameOffset = 0;
Chris Lattner4e137af2008-01-25 07:20:16 +00004260 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
Chris Lattner1e3362f2008-01-26 19:45:50 +00004261 FrameIdx = FI->getIndex();
4262 } else if (Ptr.getOpcode() == ISD::ADD &&
4263 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4264 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4265 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4266 FrameOffset = Ptr.getConstantOperandVal(1);
Chris Lattner4e137af2008-01-25 07:20:16 +00004267 }
Chris Lattner1e3362f2008-01-26 19:45:50 +00004268
4269 if (FrameIdx != (1 << 31)) {
4270 // FIXME: Handle FI+CST.
4271 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
4272 if (MFI.isFixedObjectIndex(FrameIdx)) {
4273 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx);
4274
4275 // The alignment of the frame index can be determined from its offset from
4276 // the incoming frame position. If the frame object is at offset 32 and
4277 // the stack is guaranteed to be 16-byte aligned, then we know that the
4278 // object is 16-byte aligned.
4279 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
4280 unsigned Align = MinAlign(ObjectOffset, StackAlign);
4281
4282 // Finally, the frame object itself may have a known alignment. Factor
4283 // the alignment + offset into a new alignment. For example, if we know
4284 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
4285 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
4286 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
4287 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
4288 FrameOffset);
4289 return std::max(Align, FIInfoAlign);
4290 }
4291 }
Chris Lattner4e137af2008-01-25 07:20:16 +00004292
4293 return 0;
4294}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004295
4296SDOperand DAGCombiner::visitLOAD(SDNode *N) {
4297 LoadSDNode *LD = cast<LoadSDNode>(N);
4298 SDOperand Chain = LD->getChain();
4299 SDOperand Ptr = LD->getBasePtr();
Chris Lattner4e137af2008-01-25 07:20:16 +00004300
4301 // Try to infer better alignment information than the load already has.
4302 if (LD->isUnindexed()) {
4303 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4304 if (Align > LD->getAlignment())
4305 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
4306 Chain, Ptr, LD->getSrcValue(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004307 LD->getSrcValueOffset(), LD->getMemoryVT(),
Chris Lattner4e137af2008-01-25 07:20:16 +00004308 LD->isVolatile(), Align);
4309 }
4310 }
4311
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004312
4313 // If load is not volatile and there are no uses of the loaded value (and
4314 // the updated indexed value in case of indexed loads), change uses of the
4315 // chain value into uses of the chain input (i.e. delete the dead load).
4316 if (!LD->isVolatile()) {
4317 if (N->getValueType(1) == MVT::Other) {
4318 // Unindexed loads.
Evan Chenge8b886a2008-01-16 23:11:54 +00004319 if (N->hasNUsesOfValue(0, 0)) {
4320 // It's not safe to use the two value CombineTo variant here. e.g.
4321 // v1, chain2 = load chain1, loc
4322 // v2, chain3 = load chain2, loc
4323 // v3 = add v2, c
Chris Lattnerbb67c192008-01-24 07:57:06 +00004324 // Now we replace use of chain2 with chain1. This makes the second load
4325 // isomorphic to the one we are deleting, and thus makes this load live.
Evan Chenge8b886a2008-01-16 23:11:54 +00004326 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
Chris Lattnerbb67c192008-01-24 07:57:06 +00004327 DOUT << "\nWith chain: "; DEBUG(Chain.Val->dump(&DAG));
4328 DOUT << "\n";
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004329 WorkListRemover DeadNodes(*this);
4330 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Chain, &DeadNodes);
Chris Lattnerbb67c192008-01-24 07:57:06 +00004331 if (N->use_empty()) {
4332 removeFromWorkList(N);
4333 DAG.DeleteNode(N);
4334 }
Evan Chenge8b886a2008-01-16 23:11:54 +00004335 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4336 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004337 } else {
4338 // Indexed loads.
4339 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4340 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
Evan Chenge8b886a2008-01-16 23:11:54 +00004341 SDOperand Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
4342 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4343 DOUT << "\nWith: "; DEBUG(Undef.Val->dump(&DAG));
4344 DOUT << " and 2 other values\n";
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004345 WorkListRemover DeadNodes(*this);
4346 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Undef, &DeadNodes);
Evan Chenge8b886a2008-01-16 23:11:54 +00004347 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
Chris Lattner667f9c12008-01-17 07:20:38 +00004348 DAG.getNode(ISD::UNDEF, N->getValueType(1)),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004349 &DeadNodes);
4350 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 2), Chain, &DeadNodes);
Evan Chenge8b886a2008-01-16 23:11:54 +00004351 removeFromWorkList(N);
Evan Chenge8b886a2008-01-16 23:11:54 +00004352 DAG.DeleteNode(N);
4353 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004354 }
4355 }
4356 }
4357
4358 // If this load is directly stored, replace the load value with the stored
4359 // value.
4360 // TODO: Handle store large -> read small portion.
4361 // TODO: Handle TRUNCSTORE/LOADEXT
4362 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4363 if (ISD::isNON_TRUNCStore(Chain.Val)) {
4364 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4365 if (PrevST->getBasePtr() == Ptr &&
4366 PrevST->getValue().getValueType() == N->getValueType(0))
4367 return CombineTo(N, Chain.getOperand(1), Chain);
4368 }
4369 }
4370
4371 if (CombinerAA) {
4372 // Walk up chain skipping non-aliasing memory nodes.
4373 SDOperand BetterChain = FindBetterChain(N, Chain);
4374
4375 // If there is a better chain.
4376 if (Chain != BetterChain) {
4377 SDOperand ReplLoad;
4378
4379 // Replace the chain to void dependency.
4380 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4381 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
Duncan Sandsa3691432007-10-28 12:59:45 +00004382 LD->getSrcValue(), LD->getSrcValueOffset(),
4383 LD->isVolatile(), LD->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004384 } else {
4385 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
4386 LD->getValueType(0),
4387 BetterChain, Ptr, LD->getSrcValue(),
4388 LD->getSrcValueOffset(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004389 LD->getMemoryVT(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004390 LD->isVolatile(),
4391 LD->getAlignment());
4392 }
4393
4394 // Create token factor to keep old chain connected.
4395 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
4396 Chain, ReplLoad.getValue(1));
4397
4398 // Replace uses with load result and token factor. Don't add users
4399 // to work list.
4400 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4401 }
4402 }
4403
4404 // Try transforming N to an indexed load.
4405 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4406 return SDOperand(N, 0);
4407
4408 return SDOperand();
4409}
4410
Chris Lattner2e023772008-01-08 23:08:06 +00004411
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004412SDOperand DAGCombiner::visitSTORE(SDNode *N) {
4413 StoreSDNode *ST = cast<StoreSDNode>(N);
4414 SDOperand Chain = ST->getChain();
4415 SDOperand Value = ST->getValue();
4416 SDOperand Ptr = ST->getBasePtr();
4417
Chris Lattner4e137af2008-01-25 07:20:16 +00004418 // Try to infer better alignment information than the store already has.
4419 if (ST->isUnindexed()) {
4420 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4421 if (Align > ST->getAlignment())
4422 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004423 ST->getSrcValueOffset(), ST->getMemoryVT(),
Chris Lattner4e137af2008-01-25 07:20:16 +00004424 ST->isVolatile(), Align);
4425 }
4426 }
4427
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004428 // If this is a store of a bit convert, store the input value if the
4429 // resultant store does not need a higher alignment than the original.
4430 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
Chris Lattner3bc08502008-01-17 19:59:44 +00004431 ST->isUnindexed()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004432 unsigned Align = ST->getAlignment();
4433 MVT::ValueType SVT = Value.getOperand(0).getValueType();
4434 unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
4435 getABITypeAlignment(MVT::getTypeForValueType(SVT));
4436 if (Align <= OrigAlign && TLI.isOperationLegal(ISD::STORE, SVT))
4437 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4438 ST->getSrcValueOffset(), ST->isVolatile(), Align);
4439 }
4440
4441 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
4442 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
4443 if (Value.getOpcode() != ISD::TargetConstantFP) {
4444 SDOperand Tmp;
4445 switch (CFP->getValueType(0)) {
4446 default: assert(0 && "Unknown FP type");
Dale Johannesen1b4181d2007-09-18 18:36:59 +00004447 case MVT::f80: // We don't do this for these yet.
4448 case MVT::f128:
4449 case MVT::ppcf128:
4450 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004451 case MVT::f32:
4452 if (!AfterLegalize || TLI.isTypeLegal(MVT::i32)) {
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00004453 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
4454 convertToAPInt().getZExtValue(), MVT::i32);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004455 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4456 ST->getSrcValueOffset(), ST->isVolatile(),
4457 ST->getAlignment());
4458 }
4459 break;
4460 case MVT::f64:
4461 if (!AfterLegalize || TLI.isTypeLegal(MVT::i64)) {
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00004462 Tmp = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
4463 getZExtValue(), MVT::i64);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004464 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4465 ST->getSrcValueOffset(), ST->isVolatile(),
4466 ST->getAlignment());
4467 } else if (TLI.isTypeLegal(MVT::i32)) {
Duncan Sandsa3691432007-10-28 12:59:45 +00004468 // Many FP stores are not made apparent until after legalize, e.g. for
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004469 // argument passing. Since this is so common, custom legalize the
4470 // 64-bit integer store into two 32-bit stores.
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00004471 uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004472 SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
4473 SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands9ff8fbf2008-02-11 10:37:04 +00004474 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004475
4476 int SVOffset = ST->getSrcValueOffset();
4477 unsigned Alignment = ST->getAlignment();
4478 bool isVolatile = ST->isVolatile();
4479
4480 SDOperand St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4481 ST->getSrcValueOffset(),
4482 isVolatile, ST->getAlignment());
4483 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4484 DAG.getConstant(4, Ptr.getValueType()));
4485 SVOffset += 4;
Duncan Sandsa3691432007-10-28 12:59:45 +00004486 Alignment = MinAlign(Alignment, 4U);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004487 SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4488 SVOffset, isVolatile, Alignment);
4489 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4490 }
4491 break;
4492 }
4493 }
4494 }
4495
4496 if (CombinerAA) {
4497 // Walk up chain skipping non-aliasing memory nodes.
4498 SDOperand BetterChain = FindBetterChain(N, Chain);
4499
4500 // If there is a better chain.
4501 if (Chain != BetterChain) {
4502 // Replace the chain to avoid dependency.
4503 SDOperand ReplStore;
4504 if (ST->isTruncatingStore()) {
4505 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
Chris Lattner667f9c12008-01-17 07:20:38 +00004506 ST->getSrcValue(),ST->getSrcValueOffset(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004507 ST->getMemoryVT(),
Chris Lattner667f9c12008-01-17 07:20:38 +00004508 ST->isVolatile(), ST->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004509 } else {
4510 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
Chris Lattner667f9c12008-01-17 07:20:38 +00004511 ST->getSrcValue(), ST->getSrcValueOffset(),
4512 ST->isVolatile(), ST->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004513 }
4514
4515 // Create token to keep both nodes around.
4516 SDOperand Token =
4517 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4518
4519 // Don't add users to work list.
4520 return CombineTo(N, Token, false);
4521 }
4522 }
4523
4524 // Try transforming N to an indexed store.
4525 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4526 return SDOperand(N, 0);
4527
Chris Lattner447d8e82007-12-29 06:26:16 +00004528 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner3bc08502008-01-17 19:59:44 +00004529 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Chris Lattnere8671c52007-10-13 06:35:54 +00004530 MVT::isInteger(Value.getValueType())) {
4531 // See if we can simplify the input to this truncstore with knowledge that
4532 // only the low bits are being used. For example:
4533 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
4534 SDOperand Shorter =
Dan Gohman07961cd2008-02-25 21:11:39 +00004535 GetDemandedBits(Value,
4536 APInt::getLowBitsSet(Value.getValueSizeInBits(),
4537 MVT::getSizeInBits(ST->getMemoryVT())));
Chris Lattnere8671c52007-10-13 06:35:54 +00004538 AddToWorkList(Value.Val);
4539 if (Shorter.Val)
4540 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004541 ST->getSrcValueOffset(), ST->getMemoryVT(),
Chris Lattnere8671c52007-10-13 06:35:54 +00004542 ST->isVolatile(), ST->getAlignment());
Chris Lattnerb77ea552007-10-13 06:58:48 +00004543
4544 // Otherwise, see if we can simplify the operation with
4545 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohman11607792008-02-27 00:25:32 +00004546 if (SimplifyDemandedBits(Value,
4547 APInt::getLowBitsSet(
4548 Value.getValueSizeInBits(),
4549 MVT::getSizeInBits(ST->getMemoryVT()))))
Chris Lattnerb77ea552007-10-13 06:58:48 +00004550 return SDOperand(N, 0);
Chris Lattnere8671c52007-10-13 06:35:54 +00004551 }
4552
Chris Lattner447d8e82007-12-29 06:26:16 +00004553 // If this is a load followed by a store to the same location, then the store
4554 // is dead/noop.
4555 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004556 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner3bc08502008-01-17 19:59:44 +00004557 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner2e023772008-01-08 23:08:06 +00004558 // There can't be any side effects between the load and store, such as
4559 // a call or store.
Chris Lattner10d94f92008-01-16 05:49:24 +00004560 Chain.reachesChainWithoutSideEffects(SDOperand(Ld, 1))) {
Chris Lattner447d8e82007-12-29 06:26:16 +00004561 // The store is dead, remove it.
4562 return Chain;
4563 }
4564 }
4565
Chris Lattner3bc08502008-01-17 19:59:44 +00004566 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
4567 // truncating store. We can do this even if this is already a truncstore.
4568 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
4569 && TLI.isTypeLegal(Value.getOperand(0).getValueType()) &&
4570 Value.Val->hasOneUse() && ST->isUnindexed() &&
4571 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004572 ST->getMemoryVT())) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004573 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004574 ST->getSrcValueOffset(), ST->getMemoryVT(),
Chris Lattner3bc08502008-01-17 19:59:44 +00004575 ST->isVolatile(), ST->getAlignment());
4576 }
4577
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004578 return SDOperand();
4579}
4580
4581SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4582 SDOperand InVec = N->getOperand(0);
4583 SDOperand InVal = N->getOperand(1);
4584 SDOperand EltNo = N->getOperand(2);
4585
4586 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4587 // vector with the inserted element.
4588 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4589 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4590 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
4591 if (Elt < Ops.size())
4592 Ops[Elt] = InVal;
4593 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4594 &Ops[0], Ops.size());
4595 }
4596
4597 return SDOperand();
4598}
4599
Evan Chengd7ba7ed2007-10-06 08:19:55 +00004600SDOperand DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
4601 SDOperand InVec = N->getOperand(0);
4602 SDOperand EltNo = N->getOperand(1);
4603
4604 // (vextract (v4f32 s2v (f32 load $addr)), 0) -> (f32 load $addr)
4605 // (vextract (v4i32 bc (v4f32 s2v (f32 load $addr))), 0) -> (i32 load $addr)
4606 if (isa<ConstantSDNode>(EltNo)) {
4607 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4608 bool NewLoad = false;
4609 if (Elt == 0) {
4610 MVT::ValueType VT = InVec.getValueType();
4611 MVT::ValueType EVT = MVT::getVectorElementType(VT);
4612 MVT::ValueType LVT = EVT;
4613 unsigned NumElts = MVT::getVectorNumElements(VT);
4614 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
4615 MVT::ValueType BCVT = InVec.getOperand(0).getValueType();
Dan Gohmana3591d92007-10-29 20:44:42 +00004616 if (!MVT::isVector(BCVT) ||
4617 NumElts != MVT::getVectorNumElements(BCVT))
Evan Chengd7ba7ed2007-10-06 08:19:55 +00004618 return SDOperand();
4619 InVec = InVec.getOperand(0);
4620 EVT = MVT::getVectorElementType(BCVT);
4621 NewLoad = true;
4622 }
4623 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4624 InVec.getOperand(0).getValueType() == EVT &&
4625 ISD::isNormalLoad(InVec.getOperand(0).Val) &&
4626 InVec.getOperand(0).hasOneUse()) {
4627 LoadSDNode *LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4628 unsigned Align = LN0->getAlignment();
4629 if (NewLoad) {
4630 // Check the resultant load doesn't need a higher alignment than the
4631 // original load.
4632 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
4633 getABITypeAlignment(MVT::getTypeForValueType(LVT));
4634 if (!TLI.isOperationLegal(ISD::LOAD, LVT) || NewAlign > Align)
4635 return SDOperand();
4636 Align = NewAlign;
4637 }
4638
4639 return DAG.getLoad(LVT, LN0->getChain(), LN0->getBasePtr(),
4640 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4641 LN0->isVolatile(), Align);
4642 }
4643 }
4644 }
4645 return SDOperand();
4646}
4647
4648
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004649SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4650 unsigned NumInScalars = N->getNumOperands();
4651 MVT::ValueType VT = N->getValueType(0);
4652 unsigned NumElts = MVT::getVectorNumElements(VT);
4653 MVT::ValueType EltType = MVT::getVectorElementType(VT);
4654
4655 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4656 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4657 // at most two distinct vectors, turn this into a shuffle node.
4658 SDOperand VecIn1, VecIn2;
4659 for (unsigned i = 0; i != NumInScalars; ++i) {
4660 // Ignore undef inputs.
4661 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4662
4663 // If this input is something other than a EXTRACT_VECTOR_ELT with a
4664 // constant index, bail out.
4665 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4666 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4667 VecIn1 = VecIn2 = SDOperand(0, 0);
4668 break;
4669 }
4670
4671 // If the input vector type disagrees with the result of the build_vector,
4672 // we can't make a shuffle.
4673 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
4674 if (ExtractedFromVec.getValueType() != VT) {
4675 VecIn1 = VecIn2 = SDOperand(0, 0);
4676 break;
4677 }
4678
4679 // Otherwise, remember this. We allow up to two distinct input vectors.
4680 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
4681 continue;
4682
4683 if (VecIn1.Val == 0) {
4684 VecIn1 = ExtractedFromVec;
4685 } else if (VecIn2.Val == 0) {
4686 VecIn2 = ExtractedFromVec;
4687 } else {
4688 // Too many inputs.
4689 VecIn1 = VecIn2 = SDOperand(0, 0);
4690 break;
4691 }
4692 }
4693
4694 // If everything is good, we can make a shuffle operation.
4695 if (VecIn1.Val) {
4696 SmallVector<SDOperand, 8> BuildVecIndices;
4697 for (unsigned i = 0; i != NumInScalars; ++i) {
4698 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
4699 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
4700 continue;
4701 }
4702
4703 SDOperand Extract = N->getOperand(i);
4704
4705 // If extracting from the first vector, just use the index directly.
4706 if (Extract.getOperand(0) == VecIn1) {
4707 BuildVecIndices.push_back(Extract.getOperand(1));
4708 continue;
4709 }
4710
4711 // Otherwise, use InIdx + VecSize
4712 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
Chris Lattner5872a362008-01-17 07:00:52 +00004713 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004714 }
4715
4716 // Add count and size info.
Chris Lattner5872a362008-01-17 07:00:52 +00004717 MVT::ValueType BuildVecVT = MVT::getVectorType(TLI.getPointerTy(), NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004718
4719 // Return the new VECTOR_SHUFFLE node.
4720 SDOperand Ops[5];
4721 Ops[0] = VecIn1;
4722 if (VecIn2.Val) {
4723 Ops[1] = VecIn2;
4724 } else {
4725 // Use an undef build_vector as input for the second operand.
4726 std::vector<SDOperand> UnOps(NumInScalars,
4727 DAG.getNode(ISD::UNDEF,
4728 EltType));
4729 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
4730 &UnOps[0], UnOps.size());
4731 AddToWorkList(Ops[1].Val);
4732 }
4733 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
4734 &BuildVecIndices[0], BuildVecIndices.size());
4735 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
4736 }
4737
4738 return SDOperand();
4739}
4740
4741SDOperand DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
4742 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
4743 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
4744 // inputs come from at most two distinct vectors, turn this into a shuffle
4745 // node.
4746
4747 // If we only have one input vector, we don't need to do any concatenation.
4748 if (N->getNumOperands() == 1) {
4749 return N->getOperand(0);
4750 }
4751
4752 return SDOperand();
4753}
4754
4755SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
4756 SDOperand ShufMask = N->getOperand(2);
4757 unsigned NumElts = ShufMask.getNumOperands();
4758
4759 // If the shuffle mask is an identity operation on the LHS, return the LHS.
4760 bool isIdentity = true;
4761 for (unsigned i = 0; i != NumElts; ++i) {
4762 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4763 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
4764 isIdentity = false;
4765 break;
4766 }
4767 }
4768 if (isIdentity) return N->getOperand(0);
4769
4770 // If the shuffle mask is an identity operation on the RHS, return the RHS.
4771 isIdentity = true;
4772 for (unsigned i = 0; i != NumElts; ++i) {
4773 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4774 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
4775 isIdentity = false;
4776 break;
4777 }
4778 }
4779 if (isIdentity) return N->getOperand(1);
4780
4781 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
4782 // needed at all.
4783 bool isUnary = true;
4784 bool isSplat = true;
4785 int VecNum = -1;
4786 unsigned BaseIdx = 0;
4787 for (unsigned i = 0; i != NumElts; ++i)
4788 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
4789 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
4790 int V = (Idx < NumElts) ? 0 : 1;
4791 if (VecNum == -1) {
4792 VecNum = V;
4793 BaseIdx = Idx;
4794 } else {
4795 if (BaseIdx != Idx)
4796 isSplat = false;
4797 if (VecNum != V) {
4798 isUnary = false;
4799 break;
4800 }
4801 }
4802 }
4803
4804 SDOperand N0 = N->getOperand(0);
4805 SDOperand N1 = N->getOperand(1);
4806 // Normalize unary shuffle so the RHS is undef.
4807 if (isUnary && VecNum == 1)
4808 std::swap(N0, N1);
4809
4810 // If it is a splat, check if the argument vector is a build_vector with
4811 // all scalar elements the same.
4812 if (isSplat) {
4813 SDNode *V = N0.Val;
4814
4815 // If this is a bit convert that changes the element type of the vector but
4816 // not the number of vector elements, look through it. Be careful not to
4817 // look though conversions that change things like v4f32 to v2f64.
4818 if (V->getOpcode() == ISD::BIT_CONVERT) {
4819 SDOperand ConvInput = V->getOperand(0);
4820 if (MVT::getVectorNumElements(ConvInput.getValueType()) == NumElts)
4821 V = ConvInput.Val;
4822 }
4823
4824 if (V->getOpcode() == ISD::BUILD_VECTOR) {
4825 unsigned NumElems = V->getNumOperands();
4826 if (NumElems > BaseIdx) {
4827 SDOperand Base;
4828 bool AllSame = true;
4829 for (unsigned i = 0; i != NumElems; ++i) {
4830 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
4831 Base = V->getOperand(i);
4832 break;
4833 }
4834 }
4835 // Splat of <u, u, u, u>, return <u, u, u, u>
4836 if (!Base.Val)
4837 return N0;
4838 for (unsigned i = 0; i != NumElems; ++i) {
Evan Cheng8d68c2b2007-09-18 21:54:37 +00004839 if (V->getOperand(i) != Base) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004840 AllSame = false;
4841 break;
4842 }
4843 }
4844 // Splat of <x, x, x, x>, return <x, x, x, x>
4845 if (AllSame)
4846 return N0;
4847 }
4848 }
4849 }
4850
4851 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
4852 // into an undef.
4853 if (isUnary || N0 == N1) {
4854 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
4855 // first operand.
4856 SmallVector<SDOperand, 8> MappedOps;
4857 for (unsigned i = 0; i != NumElts; ++i) {
4858 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
4859 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
4860 MappedOps.push_back(ShufMask.getOperand(i));
4861 } else {
4862 unsigned NewIdx =
4863 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
4864 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
4865 }
4866 }
4867 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
4868 &MappedOps[0], MappedOps.size());
4869 AddToWorkList(ShufMask.Val);
4870 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
4871 N0,
4872 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
4873 ShufMask);
4874 }
4875
4876 return SDOperand();
4877}
4878
4879/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
4880/// an AND to a vector_shuffle with the destination vector and a zero vector.
4881/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
4882/// vector_shuffle V, Zero, <0, 4, 2, 4>
4883SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
4884 SDOperand LHS = N->getOperand(0);
4885 SDOperand RHS = N->getOperand(1);
4886 if (N->getOpcode() == ISD::AND) {
4887 if (RHS.getOpcode() == ISD::BIT_CONVERT)
4888 RHS = RHS.getOperand(0);
4889 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
4890 std::vector<SDOperand> IdxOps;
4891 unsigned NumOps = RHS.getNumOperands();
4892 unsigned NumElts = NumOps;
4893 MVT::ValueType EVT = MVT::getVectorElementType(RHS.getValueType());
4894 for (unsigned i = 0; i != NumElts; ++i) {
4895 SDOperand Elt = RHS.getOperand(i);
4896 if (!isa<ConstantSDNode>(Elt))
4897 return SDOperand();
4898 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
4899 IdxOps.push_back(DAG.getConstant(i, EVT));
4900 else if (cast<ConstantSDNode>(Elt)->isNullValue())
4901 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
4902 else
4903 return SDOperand();
4904 }
4905
4906 // Let's see if the target supports this vector_shuffle.
4907 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
4908 return SDOperand();
4909
4910 // Return the new VECTOR_SHUFFLE node.
4911 MVT::ValueType VT = MVT::getVectorType(EVT, NumElts);
4912 std::vector<SDOperand> Ops;
4913 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
4914 Ops.push_back(LHS);
4915 AddToWorkList(LHS.Val);
4916 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
4917 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4918 &ZeroOps[0], ZeroOps.size()));
4919 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4920 &IdxOps[0], IdxOps.size()));
4921 SDOperand Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
4922 &Ops[0], Ops.size());
4923 if (VT != LHS.getValueType()) {
4924 Result = DAG.getNode(ISD::BIT_CONVERT, LHS.getValueType(), Result);
4925 }
4926 return Result;
4927 }
4928 }
4929 return SDOperand();
4930}
4931
4932/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
4933SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
4934 // After legalize, the target may be depending on adds and other
4935 // binary ops to provide legal ways to construct constants or other
4936 // things. Simplifying them may result in a loss of legality.
4937 if (AfterLegalize) return SDOperand();
4938
4939 MVT::ValueType VT = N->getValueType(0);
4940 assert(MVT::isVector(VT) && "SimplifyVBinOp only works on vectors!");
4941
4942 MVT::ValueType EltType = MVT::getVectorElementType(VT);
4943 SDOperand LHS = N->getOperand(0);
4944 SDOperand RHS = N->getOperand(1);
4945 SDOperand Shuffle = XformToShuffleWithZero(N);
4946 if (Shuffle.Val) return Shuffle;
4947
4948 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
4949 // this operation.
4950 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
4951 RHS.getOpcode() == ISD::BUILD_VECTOR) {
4952 SmallVector<SDOperand, 8> Ops;
4953 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
4954 SDOperand LHSOp = LHS.getOperand(i);
4955 SDOperand RHSOp = RHS.getOperand(i);
4956 // If these two elements can't be folded, bail out.
4957 if ((LHSOp.getOpcode() != ISD::UNDEF &&
4958 LHSOp.getOpcode() != ISD::Constant &&
4959 LHSOp.getOpcode() != ISD::ConstantFP) ||
4960 (RHSOp.getOpcode() != ISD::UNDEF &&
4961 RHSOp.getOpcode() != ISD::Constant &&
4962 RHSOp.getOpcode() != ISD::ConstantFP))
4963 break;
4964 // Can't fold divide by zero.
4965 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
4966 N->getOpcode() == ISD::FDIV) {
4967 if ((RHSOp.getOpcode() == ISD::Constant &&
4968 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
4969 (RHSOp.getOpcode() == ISD::ConstantFP &&
Dale Johannesen7604c1b2007-08-31 23:34:27 +00004970 cast<ConstantFPSDNode>(RHSOp.Val)->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004971 break;
4972 }
4973 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
4974 AddToWorkList(Ops.back().Val);
4975 assert((Ops.back().getOpcode() == ISD::UNDEF ||
4976 Ops.back().getOpcode() == ISD::Constant ||
4977 Ops.back().getOpcode() == ISD::ConstantFP) &&
4978 "Scalar binop didn't fold!");
4979 }
4980
4981 if (Ops.size() == LHS.getNumOperands()) {
4982 MVT::ValueType VT = LHS.getValueType();
4983 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
4984 }
4985 }
4986
4987 return SDOperand();
4988}
4989
4990SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
4991 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
4992
4993 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
4994 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4995 // If we got a simplified select_cc node back from SimplifySelectCC, then
4996 // break it down into a new SETCC node, and a new SELECT node, and then return
4997 // the SELECT node, since we were called with a SELECT node.
4998 if (SCC.Val) {
4999 // Check to see if we got a select_cc back (to turn into setcc/select).
5000 // Otherwise, just return whatever node we got back, like fabs.
5001 if (SCC.getOpcode() == ISD::SELECT_CC) {
5002 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
5003 SCC.getOperand(0), SCC.getOperand(1),
5004 SCC.getOperand(4));
5005 AddToWorkList(SETCC.Val);
5006 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
5007 SCC.getOperand(3), SETCC);
5008 }
5009 return SCC;
5010 }
5011 return SDOperand();
5012}
5013
5014/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5015/// are the two values being selected between, see if we can simplify the
5016/// select. Callers of this should assume that TheSelect is deleted if this
5017/// returns true. As such, they should return the appropriate thing (e.g. the
5018/// node) back to the top-level of the DAG combiner loop to avoid it being
5019/// looked at.
5020///
5021bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
5022 SDOperand RHS) {
5023
5024 // If this is a select from two identical things, try to pull the operation
5025 // through the select.
5026 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5027 // If this is a load and the token chain is identical, replace the select
5028 // of two loads with a load through a select of the address to load from.
5029 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5030 // constants have been dropped into the constant pool.
5031 if (LHS.getOpcode() == ISD::LOAD &&
5032 // Token chains must be identical.
5033 LHS.getOperand(0) == RHS.getOperand(0)) {
5034 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5035 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5036
5037 // If this is an EXTLOAD, the VT's must match.
Dan Gohman9a4c92c2008-01-30 00:15:11 +00005038 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005039 // FIXME: this conflates two src values, discarding one. This is not
5040 // the right thing to do, but nothing uses srcvalues now. When they do,
5041 // turn SrcValue into a list of locations.
5042 SDOperand Addr;
5043 if (TheSelect->getOpcode() == ISD::SELECT) {
5044 // Check that the condition doesn't reach either load. If so, folding
5045 // this will induce a cycle into the DAG.
Evan Chengd9387682008-03-04 00:41:45 +00005046 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5047 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005048 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
5049 TheSelect->getOperand(0), LLD->getBasePtr(),
5050 RLD->getBasePtr());
5051 }
5052 } else {
5053 // Check that the condition doesn't reach either load. If so, folding
5054 // this will induce a cycle into the DAG.
Evan Chengd9387682008-03-04 00:41:45 +00005055 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5056 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5057 !LLD->isPredecessorOf(TheSelect->getOperand(1).Val) &&
5058 !RLD->isPredecessorOf(TheSelect->getOperand(1).Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005059 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
5060 TheSelect->getOperand(0),
5061 TheSelect->getOperand(1),
5062 LLD->getBasePtr(), RLD->getBasePtr(),
5063 TheSelect->getOperand(4));
5064 }
5065 }
5066
5067 if (Addr.Val) {
5068 SDOperand Load;
5069 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
5070 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
5071 Addr,LLD->getSrcValue(),
5072 LLD->getSrcValueOffset(),
5073 LLD->isVolatile(),
5074 LLD->getAlignment());
5075 else {
5076 Load = DAG.getExtLoad(LLD->getExtensionType(),
5077 TheSelect->getValueType(0),
5078 LLD->getChain(), Addr, LLD->getSrcValue(),
5079 LLD->getSrcValueOffset(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00005080 LLD->getMemoryVT(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005081 LLD->isVolatile(),
5082 LLD->getAlignment());
5083 }
5084 // Users of the select now use the result of the load.
5085 CombineTo(TheSelect, Load);
5086
5087 // Users of the old loads now use the new load's chain. We know the
5088 // old-load value is dead now.
5089 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
5090 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
5091 return true;
5092 }
5093 }
5094 }
5095 }
5096
5097 return false;
5098}
5099
5100SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
5101 SDOperand N2, SDOperand N3,
5102 ISD::CondCode CC, bool NotExtCompare) {
5103
5104 MVT::ValueType VT = N2.getValueType();
5105 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
5106 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
5107 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
5108
5109 // Determine if the condition we're dealing with is constant
Scott Michel502151f2008-03-10 15:42:14 +00005110 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005111 if (SCC.Val) AddToWorkList(SCC.Val);
5112 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
5113
5114 // fold select_cc true, x, y -> x
Dan Gohman9d24dc72008-03-13 22:13:53 +00005115 if (SCCC && !SCCC->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005116 return N2;
5117 // fold select_cc false, x, y -> y
Dan Gohman9d24dc72008-03-13 22:13:53 +00005118 if (SCCC && SCCC->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005119 return N3;
5120
5121 // Check to see if we can simplify the select into an fabs node
5122 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5123 // Allow either -0.0 or 0.0
Dale Johannesen7f2c1d12007-08-25 22:10:57 +00005124 if (CFP->getValueAPF().isZero()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005125 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5126 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5127 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5128 N2 == N3.getOperand(0))
5129 return DAG.getNode(ISD::FABS, VT, N0);
5130
5131 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5132 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5133 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5134 N2.getOperand(0) == N3)
5135 return DAG.getNode(ISD::FABS, VT, N3);
5136 }
5137 }
5138
5139 // Check to see if we can perform the "gzip trick", transforming
5140 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
5141 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5142 MVT::isInteger(N0.getValueType()) &&
5143 MVT::isInteger(N2.getValueType()) &&
Dan Gohman9d24dc72008-03-13 22:13:53 +00005144 (N1C->isNullValue() || // (a < 0) ? b : 0
5145 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005146 MVT::ValueType XType = N0.getValueType();
5147 MVT::ValueType AType = N2.getValueType();
5148 if (XType >= AType) {
5149 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5150 // single-bit constant.
Dan Gohman9d24dc72008-03-13 22:13:53 +00005151 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
5152 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005153 ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
5154 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
5155 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
5156 AddToWorkList(Shift.Val);
5157 if (XType > AType) {
5158 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5159 AddToWorkList(Shift.Val);
5160 }
5161 return DAG.getNode(ISD::AND, AType, Shift, N2);
5162 }
5163 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5164 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5165 TLI.getShiftAmountTy()));
5166 AddToWorkList(Shift.Val);
5167 if (XType > AType) {
5168 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5169 AddToWorkList(Shift.Val);
5170 }
5171 return DAG.getNode(ISD::AND, AType, Shift, N2);
5172 }
5173 }
5174
5175 // fold select C, 16, 0 -> shl C, 4
Dan Gohman9d24dc72008-03-13 22:13:53 +00005176 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005177 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
5178
5179 // If the caller doesn't want us to simplify this into a zext of a compare,
5180 // don't do it.
Dan Gohman9d24dc72008-03-13 22:13:53 +00005181 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005182 return SDOperand();
5183
5184 // Get a SetCC of the condition
5185 // FIXME: Should probably make sure that setcc is legal if we ever have a
5186 // target where it isn't.
5187 SDOperand Temp, SCC;
5188 // cast from setcc result type to select result type
5189 if (AfterLegalize) {
Scott Michel502151f2008-03-10 15:42:14 +00005190 SCC = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005191 if (N2.getValueType() < SCC.getValueType())
5192 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
5193 else
5194 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5195 } else {
5196 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
5197 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5198 }
5199 AddToWorkList(SCC.Val);
5200 AddToWorkList(Temp.Val);
5201
Dan Gohman9d24dc72008-03-13 22:13:53 +00005202 if (N2C->getAPIntValue() == 1)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005203 return Temp;
5204 // shl setcc result by log2 n2c
5205 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
Dan Gohman9d24dc72008-03-13 22:13:53 +00005206 DAG.getConstant(N2C->getAPIntValue().logBase2(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005207 TLI.getShiftAmountTy()));
5208 }
5209
5210 // Check to see if this is the equivalent of setcc
5211 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5212 // otherwise, go ahead with the folds.
Dan Gohman9d24dc72008-03-13 22:13:53 +00005213 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005214 MVT::ValueType XType = N0.getValueType();
Scott Michel502151f2008-03-10 15:42:14 +00005215 if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(N0))) {
5216 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005217 if (Res.getValueType() != VT)
5218 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
5219 return Res;
5220 }
5221
5222 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
5223 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5224 TLI.isOperationLegal(ISD::CTLZ, XType)) {
5225 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
5226 return DAG.getNode(ISD::SRL, XType, Ctlz,
5227 DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
5228 TLI.getShiftAmountTy()));
5229 }
5230 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
5231 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5232 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
5233 N0);
5234 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
5235 DAG.getConstant(~0ULL, XType));
5236 return DAG.getNode(ISD::SRL, XType,
5237 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
5238 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5239 TLI.getShiftAmountTy()));
5240 }
5241 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
5242 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5243 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
5244 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5245 TLI.getShiftAmountTy()));
5246 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
5247 }
5248 }
5249
5250 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5251 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5252 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5253 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5254 N2.getOperand(0) == N1 && MVT::isInteger(N0.getValueType())) {
5255 MVT::ValueType XType = N0.getValueType();
5256 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5257 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5258 TLI.getShiftAmountTy()));
5259 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5260 AddToWorkList(Shift.Val);
5261 AddToWorkList(Add.Val);
5262 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5263 }
5264 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5265 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5266 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5267 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5268 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5269 MVT::ValueType XType = N0.getValueType();
5270 if (SubC->isNullValue() && MVT::isInteger(XType)) {
5271 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5272 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5273 TLI.getShiftAmountTy()));
5274 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5275 AddToWorkList(Shift.Val);
5276 AddToWorkList(Add.Val);
5277 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5278 }
5279 }
5280 }
5281
5282 return SDOperand();
5283}
5284
5285/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
5286SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
5287 SDOperand N1, ISD::CondCode Cond,
5288 bool foldBooleans) {
5289 TargetLowering::DAGCombinerInfo
5290 DagCombineInfo(DAG, !AfterLegalize, false, this);
5291 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
5292}
5293
5294/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
5295/// return a DAG expression to select that will generate the same value by
5296/// multiplying by a magic number. See:
5297/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5298SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
5299 std::vector<SDNode*> Built;
5300 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
5301
5302 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5303 ii != ee; ++ii)
5304 AddToWorkList(*ii);
5305 return S;
5306}
5307
5308/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
5309/// return a DAG expression to select that will generate the same value by
5310/// multiplying by a magic number. See:
5311/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5312SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
5313 std::vector<SDNode*> Built;
5314 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
5315
5316 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5317 ii != ee; ++ii)
5318 AddToWorkList(*ii);
5319 return S;
5320}
5321
5322/// FindBaseOffset - Return true if base is known not to alias with anything
5323/// but itself. Provides base object and offset as results.
5324static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
5325 // Assume it is a primitive operation.
5326 Base = Ptr; Offset = 0;
5327
5328 // If it's an adding a simple constant then integrate the offset.
5329 if (Base.getOpcode() == ISD::ADD) {
5330 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
5331 Base = Base.getOperand(0);
5332 Offset += C->getValue();
5333 }
5334 }
5335
5336 // If it's any of the following then it can't alias with anything but itself.
5337 return isa<FrameIndexSDNode>(Base) ||
5338 isa<ConstantPoolSDNode>(Base) ||
5339 isa<GlobalAddressSDNode>(Base);
5340}
5341
5342/// isAlias - Return true if there is any possibility that the two addresses
5343/// overlap.
5344bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
5345 const Value *SrcValue1, int SrcValueOffset1,
5346 SDOperand Ptr2, int64_t Size2,
5347 const Value *SrcValue2, int SrcValueOffset2)
5348{
5349 // If they are the same then they must be aliases.
5350 if (Ptr1 == Ptr2) return true;
5351
5352 // Gather base node and offset information.
5353 SDOperand Base1, Base2;
5354 int64_t Offset1, Offset2;
5355 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
5356 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
5357
5358 // If they have a same base address then...
5359 if (Base1 == Base2) {
5360 // Check to see if the addresses overlap.
5361 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
5362 }
5363
5364 // If we know both bases then they can't alias.
5365 if (KnownBase1 && KnownBase2) return false;
5366
5367 if (CombinerGlobalAA) {
5368 // Use alias analysis information.
Dan Gohmane142c2e2007-08-27 16:32:11 +00005369 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
5370 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
5371 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005372 AliasAnalysis::AliasResult AAResult =
5373 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
5374 if (AAResult == AliasAnalysis::NoAlias)
5375 return false;
5376 }
5377
5378 // Otherwise we have to assume they alias.
5379 return true;
5380}
5381
5382/// FindAliasInfo - Extracts the relevant alias information from the memory
5383/// node. Returns true if the operand was a load.
5384bool DAGCombiner::FindAliasInfo(SDNode *N,
5385 SDOperand &Ptr, int64_t &Size,
5386 const Value *&SrcValue, int &SrcValueOffset) {
5387 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5388 Ptr = LD->getBasePtr();
Dan Gohman9a4c92c2008-01-30 00:15:11 +00005389 Size = MVT::getSizeInBits(LD->getMemoryVT()) >> 3;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005390 SrcValue = LD->getSrcValue();
5391 SrcValueOffset = LD->getSrcValueOffset();
5392 return true;
5393 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5394 Ptr = ST->getBasePtr();
Dan Gohman9a4c92c2008-01-30 00:15:11 +00005395 Size = MVT::getSizeInBits(ST->getMemoryVT()) >> 3;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005396 SrcValue = ST->getSrcValue();
5397 SrcValueOffset = ST->getSrcValueOffset();
5398 } else {
5399 assert(0 && "FindAliasInfo expected a memory operand");
5400 }
5401
5402 return false;
5403}
5404
5405/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
5406/// looking for aliasing nodes and adding them to the Aliases vector.
5407void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
5408 SmallVector<SDOperand, 8> &Aliases) {
5409 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
5410 std::set<SDNode *> Visited; // Visited node set.
5411
5412 // Get alias information for node.
5413 SDOperand Ptr;
5414 int64_t Size;
5415 const Value *SrcValue;
5416 int SrcValueOffset;
5417 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
5418
5419 // Starting off.
5420 Chains.push_back(OriginalChain);
5421
5422 // Look at each chain and determine if it is an alias. If so, add it to the
5423 // aliases list. If not, then continue up the chain looking for the next
5424 // candidate.
5425 while (!Chains.empty()) {
5426 SDOperand Chain = Chains.back();
5427 Chains.pop_back();
5428
5429 // Don't bother if we've been before.
5430 if (Visited.find(Chain.Val) != Visited.end()) continue;
5431 Visited.insert(Chain.Val);
5432
5433 switch (Chain.getOpcode()) {
5434 case ISD::EntryToken:
5435 // Entry token is ideal chain operand, but handled in FindBetterChain.
5436 break;
5437
5438 case ISD::LOAD:
5439 case ISD::STORE: {
5440 // Get alias information for Chain.
5441 SDOperand OpPtr;
5442 int64_t OpSize;
5443 const Value *OpSrcValue;
5444 int OpSrcValueOffset;
5445 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
5446 OpSrcValue, OpSrcValueOffset);
5447
5448 // If chain is alias then stop here.
5449 if (!(IsLoad && IsOpLoad) &&
5450 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
5451 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
5452 Aliases.push_back(Chain);
5453 } else {
5454 // Look further up the chain.
5455 Chains.push_back(Chain.getOperand(0));
5456 // Clean up old chain.
5457 AddToWorkList(Chain.Val);
5458 }
5459 break;
5460 }
5461
5462 case ISD::TokenFactor:
5463 // We have to check each of the operands of the token factor, so we queue
5464 // then up. Adding the operands to the queue (stack) in reverse order
5465 // maintains the original order and increases the likelihood that getNode
5466 // will find a matching token factor (CSE.)
5467 for (unsigned n = Chain.getNumOperands(); n;)
5468 Chains.push_back(Chain.getOperand(--n));
5469 // Eliminate the token factor if we can.
5470 AddToWorkList(Chain.Val);
5471 break;
5472
5473 default:
5474 // For all other instructions we will just have to take what we can get.
5475 Aliases.push_back(Chain);
5476 break;
5477 }
5478 }
5479}
5480
5481/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
5482/// for a better chain (aliasing node.)
5483SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
5484 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
5485
5486 // Accumulate all the aliases to this node.
5487 GatherAllAliases(N, OldChain, Aliases);
5488
5489 if (Aliases.size() == 0) {
5490 // If no operands then chain to entry token.
5491 return DAG.getEntryNode();
5492 } else if (Aliases.size() == 1) {
5493 // If a single operand then chain to it. We don't need to revisit it.
5494 return Aliases[0];
5495 }
5496
5497 // Construct a custom tailored token factor.
5498 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5499 &Aliases[0], Aliases.size());
5500
5501 // Make sure the old chain gets cleaned up.
5502 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
5503
5504 return NewChain;
5505}
5506
5507// SelectionDAG::Combine - This is the entry point for the file.
5508//
5509void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
5510 if (!RunningAfterLegalize && ViewDAGCombine1)
5511 viewGraph();
5512 if (RunningAfterLegalize && ViewDAGCombine2)
5513 viewGraph();
5514 /// run - This is the main entry point to this class.
5515 ///
5516 DAGCombiner(*this, AA).Run(RunningAfterLegalize);
5517}