1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "dagcombine"
16 #include "llvm/CodeGen/SelectionDAG.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Target/TargetFrameInfo.h"
22 #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"
34 STATISTIC(NodesCombined , "Number of dag nodes combined");
35 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
36 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
41 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
42 cl::desc("Pop up a window to show dags before the first "
45 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
46 cl::desc("Pop up a window to show dags before the second "
49 static const bool ViewDAGCombine1 = false;
50 static const bool ViewDAGCombine2 = false;
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Turn on alias analysis during testing"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Include global information in alias analysis"));
61 //------------------------------ DAGCombiner ---------------------------------//
63 class VISIBILITY_HIDDEN DAGCombiner {
68 // Worklist of all of the nodes that need to be simplified.
69 std::vector<SDNode*> WorkList;
71 // AA - Used for DAG load/store alias analysis.
74 /// AddUsersToWorkList - When an instruction is simplified, add all users of
75 /// the instruction to the work lists because they might get more simplified
78 void AddUsersToWorkList(SDNode *N) {
79 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
84 /// visit - call the node-specific routine that knows how to fold each
85 /// particular type of node.
86 SDOperand visit(SDNode *N);
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);
96 /// removeFromWorkList - remove all instances of N from the worklist.
98 void removeFromWorkList(SDNode *N) {
99 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
103 SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
106 SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
107 return CombineTo(N, &Res, 1, AddTo);
110 SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
112 SDOperand To[] = { Res0, Res1 };
113 return CombineTo(N, To, 2, AddTo);
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.
121 bool SimplifyDemandedBits(SDOperand Op) {
122 APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
123 return SimplifyDemandedBits(Op, Demanded);
126 bool SimplifyDemandedBits(SDOperand Op, const APInt &Demanded);
128 bool CombineToPreIndexedLoadStore(SDNode *N);
129 bool CombineToPostIndexedLoadStore(SDNode *N);
132 /// 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);
137 // Visitation implementation - Implement dag node combining for different
138 // node types. The semantics are as follows:
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.
144 SDOperand visitTokenFactor(SDNode *N);
145 SDOperand visitMERGE_VALUES(SDNode *N);
146 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);
157 SDOperand visitSMUL_LOHI(SDNode *N);
158 SDOperand visitUMUL_LOHI(SDNode *N);
159 SDOperand visitSDIVREM(SDNode *N);
160 SDOperand visitUDIVREM(SDNode *N);
161 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);
200 SDOperand visitEXTRACT_VECTOR_ELT(SDNode *N);
201 SDOperand visitBUILD_VECTOR(SDNode *N);
202 SDOperand visitCONCAT_VECTORS(SDNode *N);
203 SDOperand visitVECTOR_SHUFFLE(SDNode *N);
205 SDOperand XformToShuffleWithZero(SDNode *N);
206 SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
208 SDOperand visitShiftByConstant(SDNode *N, unsigned Amt);
210 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);
218 SDOperand SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
220 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);
226 SDOperand GetDemandedBits(SDOperand V, const APInt &Mask);
228 /// 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);
233 /// isAlias - Return true if there is any possibility that the two addresses
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);
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);
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);
251 DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
253 TLI(D.getTargetLoweringInfo()),
254 AfterLegalize(false),
257 /// Run - runs the dag combiner on all nodes in the work list
258 void Run(bool RunningAfterLegalize);
264 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
265 /// nodes from the worklist.
266 class VISIBILITY_HIDDEN WorkListRemover :
267 public SelectionDAG::DAGUpdateListener {
270 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
272 virtual void NodeDeleted(SDNode *N) {
273 DC.removeFromWorkList(N);
276 virtual void NodeUpdated(SDNode *N) {
282 //===----------------------------------------------------------------------===//
283 // TargetLowering::DAGCombinerInfo implementation
284 //===----------------------------------------------------------------------===//
286 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
287 ((DAGCombiner*)DC)->AddToWorkList(N);
290 SDOperand TargetLowering::DAGCombinerInfo::
291 CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
292 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
295 SDOperand TargetLowering::DAGCombinerInfo::
296 CombineTo(SDNode *N, SDOperand Res) {
297 return ((DAGCombiner*)DC)->CombineTo(N, Res);
301 SDOperand TargetLowering::DAGCombinerInfo::
302 CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
303 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
307 //===----------------------------------------------------------------------===//
309 //===----------------------------------------------------------------------===//
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.
314 static char isNegatibleForFree(SDOperand Op, bool AfterLegalize,
315 unsigned Depth = 0) {
316 // No compile time optimizations on this type.
317 if (Op.getValueType() == MVT::ppcf128)
320 // fneg is removable even if it has multiple uses.
321 if (Op.getOpcode() == ISD::FNEG) return 2;
323 // Don't allow anything with multiple uses.
324 if (!Op.hasOneUse()) return 0;
326 // Don't recurse exponentially.
327 if (Depth > 6) return 0;
329 switch (Op.getOpcode()) {
330 default: return false;
331 case ISD::ConstantFP:
332 // Don't invert constant FP values after legalize. The negated constant
333 // isn't necessarily legal.
334 return AfterLegalize ? 0 : 1;
336 // FIXME: determine better conditions for this xform.
337 if (!UnsafeFPMath) return 0;
340 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
343 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
345 // We can't turn -(A-B) into B-A when we honor signed zeros.
346 if (!UnsafeFPMath) return 0;
353 if (HonorSignDependentRoundingFPMath()) return 0;
355 // -(X*Y) -> (-X * Y) or (X*-Y)
356 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
359 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
364 return isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1);
368 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
369 /// returns the newly negated expression.
370 static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
371 bool AfterLegalize, unsigned Depth = 0) {
372 // fneg is removable even if it has multiple uses.
373 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
375 // Don't allow anything with multiple uses.
376 assert(Op.hasOneUse() && "Unknown reuse!");
378 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
379 switch (Op.getOpcode()) {
380 default: assert(0 && "Unknown code");
381 case ISD::ConstantFP: {
382 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
384 return DAG.getConstantFP(V, Op.getValueType());
387 // FIXME: determine better conditions for this xform.
388 assert(UnsafeFPMath);
391 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
392 return DAG.getNode(ISD::FSUB, Op.getValueType(),
393 GetNegatedExpression(Op.getOperand(0), DAG,
394 AfterLegalize, Depth+1),
397 return DAG.getNode(ISD::FSUB, Op.getValueType(),
398 GetNegatedExpression(Op.getOperand(1), DAG,
399 AfterLegalize, Depth+1),
402 // We can't turn -(A-B) into B-A when we honor signed zeros.
403 assert(UnsafeFPMath);
406 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
407 if (N0CFP->getValueAPF().isZero())
408 return Op.getOperand(1);
411 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1),
416 assert(!HonorSignDependentRoundingFPMath());
419 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
420 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
421 GetNegatedExpression(Op.getOperand(0), DAG,
422 AfterLegalize, Depth+1),
426 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
428 GetNegatedExpression(Op.getOperand(1), DAG,
429 AfterLegalize, Depth+1));
433 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
434 GetNegatedExpression(Op.getOperand(0), DAG,
435 AfterLegalize, Depth+1));
437 return DAG.getNode(ISD::FP_ROUND, Op.getValueType(),
438 GetNegatedExpression(Op.getOperand(0), DAG,
439 AfterLegalize, Depth+1),
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.
450 static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
452 if (N.getOpcode() == ISD::SETCC) {
453 LHS = N.getOperand(0);
454 RHS = N.getOperand(1);
455 CC = N.getOperand(2);
458 if (N.getOpcode() == ISD::SELECT_CC &&
459 N.getOperand(2).getOpcode() == ISD::Constant &&
460 N.getOperand(3).getOpcode() == ISD::Constant &&
461 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
462 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
463 LHS = N.getOperand(0);
464 RHS = N.getOperand(1);
465 CC = N.getOperand(4);
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.
474 static bool isOneUseSetCC(SDOperand N) {
475 SDOperand N0, N1, N2;
476 if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
481 SDOperand 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));
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));
512 SDOperand DAGCombiner::CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
514 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
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);
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);
530 // Nodes can be reintroduced into the worklist. Make sure we do not
531 // process a node that has been replaced.
532 removeFromWorkList(N);
534 // Finally, since the node is now dead, remove it from the graph.
536 return SDOperand(N, 0);
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.
542 bool DAGCombiner::SimplifyDemandedBits(SDOperand Op, const APInt &Demanded) {
543 TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize);
544 APInt KnownZero, KnownOne;
545 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
549 AddToWorkList(Op.Val);
551 // Replace the old value with the new one.
553 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.Val->dump(&DAG));
554 DOUT << "\nWith: "; DEBUG(TLO.New.Val->dump(&DAG));
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);
562 // Push the new node and any (possibly new) users onto the worklist.
563 AddToWorkList(TLO.New.Val);
564 AddUsersToWorkList(TLO.New.Val);
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);
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);
578 DAG.DeleteNode(TLO.Old.Val);
583 //===----------------------------------------------------------------------===//
584 // Main DAG Combiner implementation
585 //===----------------------------------------------------------------------===//
587 void DAGCombiner::Run(bool RunningAfterLegalize) {
588 // set the instance variable, so that the various visit routines may use it.
589 AfterLegalize = RunningAfterLegalize;
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);
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());
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());
605 // 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();
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);
622 SDOperand RV = combine(N);
629 // 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.
636 assert(N->getOpcode() != ISD::DELETED_NODE &&
637 RV.Val->getOpcode() != ISD::DELETED_NODE &&
638 "Node was deleted but visit returned new node!");
640 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
641 DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
643 WorkListRemover DeadNodes(*this);
644 if (N->getNumValues() == RV.Val->getNumValues())
645 DAG.ReplaceAllUsesWith(N, RV.Val, &DeadNodes);
647 assert(N->getValueType(0) == RV.getValueType() &&
648 N->getNumValues() == 1 && "Type mismatch");
650 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
653 // Push the new node and any users onto the worklist
654 AddToWorkList(RV.Val);
655 AddUsersToWorkList(RV.Val);
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
660 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
661 AddToWorkList(N->getOperand(i).Val);
663 // Nodes can be reintroduced into the worklist. Make sure we do not
664 // process a node that has been replaced.
665 removeFromWorkList(N);
667 // Finally, since the node is now dead, remove it from the graph.
671 // If the root changed (e.g. it was a dead load, update the root).
672 DAG.setRoot(Dummy.getValue());
675 SDOperand DAGCombiner::visit(SDNode *N) {
676 switch(N->getOpcode()) {
678 case ISD::TokenFactor: return visitTokenFactor(N);
679 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
680 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);
691 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);
695 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);
733 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
734 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);
741 SDOperand DAGCombiner::combine(SDNode *N) {
743 SDOperand RV = visit(N);
745 // If nothing happened, try a target-specific DAG combine.
747 assert(N->getOpcode() != ISD::DELETED_NODE &&
748 "Node was deleted but visit returned NULL!");
750 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
751 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
753 // Expose the DAG combiner to the target combiner impls.
754 TargetLowering::DAGCombinerInfo
755 DagCombineInfo(DAG, !AfterLegalize, false, this);
757 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
761 // If N is a commutative binary node, try commuting it to enable more
764 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
765 N->getNumValues() == 1) {
766 SDOperand N0 = N->getOperand(0);
767 SDOperand N1 = N->getOperand(1);
768 // Constant operands are canonicalized to RHS.
769 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
770 SDOperand Ops[] = { N1, N0 };
771 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
774 return SDOperand(CSENode, 0);
781 /// getInputChainForNode - Given a node, return its input chain if it has one,
782 /// otherwise return a null sd operand.
783 static SDOperand getInputChainForNode(SDNode *N) {
784 if (unsigned NumOps = N->getNumOperands()) {
785 if (N->getOperand(0).getValueType() == MVT::Other)
786 return N->getOperand(0);
787 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
788 return N->getOperand(NumOps-1);
789 for (unsigned i = 1; i < NumOps-1; ++i)
790 if (N->getOperand(i).getValueType() == MVT::Other)
791 return N->getOperand(i);
793 return SDOperand(0, 0);
796 SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
797 // If N has two operands, where one has an input chain equal to the other,
798 // the 'other' chain is redundant.
799 if (N->getNumOperands() == 2) {
800 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
801 return N->getOperand(0);
802 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
803 return N->getOperand(1);
806 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
807 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
808 SmallPtrSet<SDNode*, 16> SeenOps;
809 bool Changed = false; // If we should replace this token factor.
811 // Start out with this token factor.
814 // Iterate through token factors. The TFs grows when new token factors are
816 for (unsigned i = 0; i < TFs.size(); ++i) {
819 // Check each of the operands.
820 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
821 SDOperand Op = TF->getOperand(i);
823 switch (Op.getOpcode()) {
824 case ISD::EntryToken:
825 // Entry tokens don't need to be added to the list. They are
830 case ISD::TokenFactor:
831 if ((CombinerAA || Op.hasOneUse()) &&
832 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
833 // Queue up for processing.
834 TFs.push_back(Op.Val);
835 // Clean up in case the token factor is removed.
836 AddToWorkList(Op.Val);
843 // Only add if it isn't already in the list.
844 if (SeenOps.insert(Op.Val))
855 // If we've change things around then replace token factor.
858 // The entry token is the only possible outcome.
859 Result = DAG.getEntryNode();
861 // New and improved token factor.
862 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
865 // Don't add users to work list.
866 return CombineTo(N, Result, false);
872 /// MERGE_VALUES can always be eliminated.
873 SDOperand DAGCombiner::visitMERGE_VALUES(SDNode *N) {
874 WorkListRemover DeadNodes(*this);
875 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
876 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, i), N->getOperand(i),
878 removeFromWorkList(N);
880 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
885 SDOperand combineShlAddConstant(SDOperand N0, SDOperand N1, SelectionDAG &DAG) {
886 MVT::ValueType VT = N0.getValueType();
887 SDOperand N00 = N0.getOperand(0);
888 SDOperand N01 = N0.getOperand(1);
889 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
890 if (N01C && N00.getOpcode() == ISD::ADD && N00.Val->hasOneUse() &&
891 isa<ConstantSDNode>(N00.getOperand(1))) {
892 N0 = DAG.getNode(ISD::ADD, VT,
893 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
894 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
895 return DAG.getNode(ISD::ADD, VT, N0, N1);
901 SDOperand combineSelectAndUse(SDNode *N, SDOperand Slct, SDOperand OtherOp,
903 MVT::ValueType VT = N->getValueType(0);
904 unsigned Opc = N->getOpcode();
905 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
906 SDOperand LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
907 SDOperand RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
908 ISD::CondCode CC = ISD::SETCC_INVALID;
910 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
912 SDOperand CCOp = Slct.getOperand(0);
913 if (CCOp.getOpcode() == ISD::SETCC)
914 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
917 bool DoXform = false;
919 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
921 if (LHS.getOpcode() == ISD::Constant &&
922 cast<ConstantSDNode>(LHS)->isNullValue())
924 else if (CC != ISD::SETCC_INVALID &&
925 RHS.getOpcode() == ISD::Constant &&
926 cast<ConstantSDNode>(RHS)->isNullValue()) {
928 SDOperand Op0 = Slct.getOperand(0);
929 bool isInt = MVT::isInteger(isSlctCC ? Op0.getValueType()
930 : Op0.getOperand(0).getValueType());
931 CC = ISD::getSetCCInverse(CC, isInt);
937 SDOperand Result = DAG.getNode(Opc, VT, OtherOp, RHS);
939 return DAG.getSelectCC(OtherOp, Result,
940 Slct.getOperand(0), Slct.getOperand(1), CC);
941 SDOperand CCOp = Slct.getOperand(0);
943 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
944 CCOp.getOperand(1), CC);
945 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
950 SDOperand DAGCombiner::visitADD(SDNode *N) {
951 SDOperand N0 = N->getOperand(0);
952 SDOperand N1 = N->getOperand(1);
953 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
954 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
955 MVT::ValueType VT = N0.getValueType();
958 if (MVT::isVector(VT)) {
959 SDOperand FoldedVOp = SimplifyVBinOp(N);
960 if (FoldedVOp.Val) return FoldedVOp;
963 // fold (add x, undef) -> undef
964 if (N0.getOpcode() == ISD::UNDEF)
966 if (N1.getOpcode() == ISD::UNDEF)
968 // fold (add c1, c2) -> c1+c2
970 return DAG.getConstant(N0C->getAPIntValue() + N1C->getAPIntValue(), VT);
971 // canonicalize constant to RHS
973 return DAG.getNode(ISD::ADD, VT, N1, N0);
974 // fold (add x, 0) -> x
975 if (N1C && N1C->isNullValue())
977 // fold ((c1-A)+c2) -> (c1+c2)-A
978 if (N1C && N0.getOpcode() == ISD::SUB)
979 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
980 return DAG.getNode(ISD::SUB, VT,
981 DAG.getConstant(N1C->getAPIntValue()+
982 N0C->getAPIntValue(), VT),
985 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
988 // fold ((0-A) + B) -> B-A
989 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
990 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
991 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
992 // fold (A + (0-B)) -> A-B
993 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
994 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
995 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
996 // fold (A+(B-A)) -> B
997 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
998 return N1.getOperand(0);
1000 if (!MVT::isVector(VT) && SimplifyDemandedBits(SDOperand(N, 0)))
1001 return SDOperand(N, 0);
1003 // fold (a+b) -> (a|b) iff a and b share no bits.
1004 if (MVT::isInteger(VT) && !MVT::isVector(VT)) {
1005 APInt LHSZero, LHSOne;
1006 APInt RHSZero, RHSOne;
1007 APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
1008 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1009 if (LHSZero.getBoolValue()) {
1010 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1012 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1013 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1014 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1015 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1016 return DAG.getNode(ISD::OR, VT, N0, N1);
1020 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1021 if (N0.getOpcode() == ISD::SHL && N0.Val->hasOneUse()) {
1022 SDOperand Result = combineShlAddConstant(N0, N1, DAG);
1023 if (Result.Val) return Result;
1025 if (N1.getOpcode() == ISD::SHL && N1.Val->hasOneUse()) {
1026 SDOperand Result = combineShlAddConstant(N1, N0, DAG);
1027 if (Result.Val) return Result;
1030 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1031 if (N0.getOpcode() == ISD::SELECT && N0.Val->hasOneUse()) {
1032 SDOperand Result = combineSelectAndUse(N, N0, N1, DAG);
1033 if (Result.Val) return Result;
1035 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1036 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1037 if (Result.Val) return Result;
1043 SDOperand DAGCombiner::visitADDC(SDNode *N) {
1044 SDOperand N0 = N->getOperand(0);
1045 SDOperand N1 = N->getOperand(1);
1046 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1047 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1048 MVT::ValueType VT = N0.getValueType();
1050 // If the flag result is dead, turn this into an ADD.
1051 if (N->hasNUsesOfValue(0, 1))
1052 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
1053 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1055 // canonicalize constant to RHS.
1057 SDOperand Ops[] = { N1, N0 };
1058 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
1061 // fold (addc x, 0) -> x + no carry out
1062 if (N1C && N1C->isNullValue())
1063 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1065 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1066 APInt LHSZero, LHSOne;
1067 APInt RHSZero, RHSOne;
1068 APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
1069 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1070 if (LHSZero.getBoolValue()) {
1071 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1073 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1074 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1075 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1076 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1077 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
1078 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1084 SDOperand DAGCombiner::visitADDE(SDNode *N) {
1085 SDOperand N0 = N->getOperand(0);
1086 SDOperand N1 = N->getOperand(1);
1087 SDOperand CarryIn = N->getOperand(2);
1088 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1089 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1090 //MVT::ValueType VT = N0.getValueType();
1092 // canonicalize constant to RHS
1094 SDOperand Ops[] = { N1, N0, CarryIn };
1095 return DAG.getNode(ISD::ADDE, N->getVTList(), Ops, 3);
1098 // fold (adde x, y, false) -> (addc x, y)
1099 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) {
1100 SDOperand Ops[] = { N1, N0 };
1101 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
1109 SDOperand DAGCombiner::visitSUB(SDNode *N) {
1110 SDOperand N0 = N->getOperand(0);
1111 SDOperand N1 = N->getOperand(1);
1112 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1113 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1114 MVT::ValueType VT = N0.getValueType();
1117 if (MVT::isVector(VT)) {
1118 SDOperand FoldedVOp = SimplifyVBinOp(N);
1119 if (FoldedVOp.Val) return FoldedVOp;
1122 // fold (sub x, x) -> 0
1124 return DAG.getConstant(0, N->getValueType(0));
1125 // fold (sub c1, c2) -> c1-c2
1127 return DAG.getNode(ISD::SUB, VT, N0, N1);
1128 // fold (sub x, c) -> (add x, -c)
1130 return DAG.getNode(ISD::ADD, VT, N0,
1131 DAG.getConstant(-N1C->getAPIntValue(), VT));
1132 // fold (A+B)-A -> B
1133 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1134 return N0.getOperand(1);
1135 // fold (A+B)-B -> A
1136 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1137 return N0.getOperand(0);
1138 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1139 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1140 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1141 if (Result.Val) return Result;
1143 // If either operand of a sub is undef, the result is undef
1144 if (N0.getOpcode() == ISD::UNDEF)
1146 if (N1.getOpcode() == ISD::UNDEF)
1152 SDOperand DAGCombiner::visitMUL(SDNode *N) {
1153 SDOperand N0 = N->getOperand(0);
1154 SDOperand N1 = N->getOperand(1);
1155 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1156 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1157 MVT::ValueType VT = N0.getValueType();
1160 if (MVT::isVector(VT)) {
1161 SDOperand FoldedVOp = SimplifyVBinOp(N);
1162 if (FoldedVOp.Val) return FoldedVOp;
1165 // fold (mul x, undef) -> 0
1166 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1167 return DAG.getConstant(0, VT);
1168 // fold (mul c1, c2) -> c1*c2
1170 return DAG.getNode(ISD::MUL, VT, N0, N1);
1171 // canonicalize constant to RHS
1173 return DAG.getNode(ISD::MUL, VT, N1, N0);
1174 // fold (mul x, 0) -> 0
1175 if (N1C && N1C->isNullValue())
1177 // fold (mul x, -1) -> 0-x
1178 if (N1C && N1C->isAllOnesValue())
1179 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1180 // fold (mul x, (1 << c)) -> x << c
1181 if (N1C && N1C->getAPIntValue().isPowerOf2())
1182 return DAG.getNode(ISD::SHL, VT, N0,
1183 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1184 TLI.getShiftAmountTy()));
1185 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1186 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
1187 // FIXME: If the input is something that is easily negated (e.g. a
1188 // single-use add), we should put the negate there.
1189 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1190 DAG.getNode(ISD::SHL, VT, N0,
1191 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
1192 TLI.getShiftAmountTy())));
1195 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1196 if (N1C && N0.getOpcode() == ISD::SHL &&
1197 isa<ConstantSDNode>(N0.getOperand(1))) {
1198 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1199 AddToWorkList(C3.Val);
1200 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1203 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1206 SDOperand Sh(0,0), Y(0,0);
1207 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1208 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1209 N0.Val->hasOneUse()) {
1211 } else if (N1.getOpcode() == ISD::SHL &&
1212 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1216 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1217 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1220 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1221 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1222 isa<ConstantSDNode>(N0.getOperand(1))) {
1223 return DAG.getNode(ISD::ADD, VT,
1224 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1225 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1229 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1236 SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1237 SDOperand N0 = N->getOperand(0);
1238 SDOperand N1 = N->getOperand(1);
1239 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1240 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1241 MVT::ValueType VT = N->getValueType(0);
1244 if (MVT::isVector(VT)) {
1245 SDOperand FoldedVOp = SimplifyVBinOp(N);
1246 if (FoldedVOp.Val) return FoldedVOp;
1249 // fold (sdiv c1, c2) -> c1/c2
1250 if (N0C && N1C && !N1C->isNullValue())
1251 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1252 // fold (sdiv X, 1) -> X
1253 if (N1C && N1C->getSignExtended() == 1LL)
1255 // fold (sdiv X, -1) -> 0-X
1256 if (N1C && N1C->isAllOnesValue())
1257 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1258 // If we know the sign bits of both operands are zero, strength reduce to a
1259 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1260 if (!MVT::isVector(VT)) {
1261 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1262 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1264 // fold (sdiv X, pow2) -> simple ops after legalize
1265 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1266 (isPowerOf2_64(N1C->getSignExtended()) ||
1267 isPowerOf2_64(-N1C->getSignExtended()))) {
1268 // If dividing by powers of two is cheap, then don't perform the following
1270 if (TLI.isPow2DivCheap())
1272 int64_t pow2 = N1C->getSignExtended();
1273 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1274 unsigned lg2 = Log2_64(abs2);
1275 // Splat the sign bit into the register
1276 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1277 DAG.getConstant(MVT::getSizeInBits(VT)-1,
1278 TLI.getShiftAmountTy()));
1279 AddToWorkList(SGN.Val);
1280 // Add (N0 < 0) ? abs2 - 1 : 0;
1281 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1282 DAG.getConstant(MVT::getSizeInBits(VT)-lg2,
1283 TLI.getShiftAmountTy()));
1284 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1285 AddToWorkList(SRL.Val);
1286 AddToWorkList(ADD.Val); // Divide by pow2
1287 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1288 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1289 // If we're dividing by a positive value, we're done. Otherwise, we must
1290 // negate the result.
1293 AddToWorkList(SRA.Val);
1294 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1296 // if integer divide is expensive and we satisfy the requirements, emit an
1297 // alternate sequence.
1298 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1299 !TLI.isIntDivCheap()) {
1300 SDOperand Op = BuildSDIV(N);
1301 if (Op.Val) return Op;
1305 if (N0.getOpcode() == ISD::UNDEF)
1306 return DAG.getConstant(0, VT);
1307 // X / undef -> undef
1308 if (N1.getOpcode() == ISD::UNDEF)
1314 SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1315 SDOperand N0 = N->getOperand(0);
1316 SDOperand N1 = N->getOperand(1);
1317 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1318 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1319 MVT::ValueType VT = N->getValueType(0);
1322 if (MVT::isVector(VT)) {
1323 SDOperand FoldedVOp = SimplifyVBinOp(N);
1324 if (FoldedVOp.Val) return FoldedVOp;
1327 // fold (udiv c1, c2) -> c1/c2
1328 if (N0C && N1C && !N1C->isNullValue())
1329 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1330 // fold (udiv x, (1 << c)) -> x >>u c
1331 if (N1C && N1C->getAPIntValue().isPowerOf2())
1332 return DAG.getNode(ISD::SRL, VT, N0,
1333 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1334 TLI.getShiftAmountTy()));
1335 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1336 if (N1.getOpcode() == ISD::SHL) {
1337 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1338 if (SHC->getAPIntValue().isPowerOf2()) {
1339 MVT::ValueType ADDVT = N1.getOperand(1).getValueType();
1340 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1341 DAG.getConstant(SHC->getAPIntValue()
1344 AddToWorkList(Add.Val);
1345 return DAG.getNode(ISD::SRL, VT, N0, Add);
1349 // fold (udiv x, c) -> alternate
1350 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1351 SDOperand Op = BuildUDIV(N);
1352 if (Op.Val) return Op;
1356 if (N0.getOpcode() == ISD::UNDEF)
1357 return DAG.getConstant(0, VT);
1358 // X / undef -> undef
1359 if (N1.getOpcode() == ISD::UNDEF)
1365 SDOperand DAGCombiner::visitSREM(SDNode *N) {
1366 SDOperand N0 = N->getOperand(0);
1367 SDOperand N1 = N->getOperand(1);
1368 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1369 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1370 MVT::ValueType VT = N->getValueType(0);
1372 // fold (srem c1, c2) -> c1%c2
1373 if (N0C && N1C && !N1C->isNullValue())
1374 return DAG.getNode(ISD::SREM, VT, N0, N1);
1375 // If we know the sign bits of both operands are zero, strength reduce to a
1376 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1377 if (!MVT::isVector(VT)) {
1378 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1379 return DAG.getNode(ISD::UREM, VT, N0, N1);
1382 // If X/C can be simplified by the division-by-constant logic, lower
1383 // X%C to the equivalent of X-X/C*C.
1384 if (N1C && !N1C->isNullValue()) {
1385 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1386 AddToWorkList(Div.Val);
1387 SDOperand OptimizedDiv = combine(Div.Val);
1388 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1389 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1390 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1391 AddToWorkList(Mul.Val);
1397 if (N0.getOpcode() == ISD::UNDEF)
1398 return DAG.getConstant(0, VT);
1399 // X % undef -> undef
1400 if (N1.getOpcode() == ISD::UNDEF)
1406 SDOperand DAGCombiner::visitUREM(SDNode *N) {
1407 SDOperand N0 = N->getOperand(0);
1408 SDOperand N1 = N->getOperand(1);
1409 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1410 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1411 MVT::ValueType VT = N->getValueType(0);
1413 // fold (urem c1, c2) -> c1%c2
1414 if (N0C && N1C && !N1C->isNullValue())
1415 return DAG.getNode(ISD::UREM, VT, N0, N1);
1416 // fold (urem x, pow2) -> (and x, pow2-1)
1417 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1418 return DAG.getNode(ISD::AND, VT, N0,
1419 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1420 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1421 if (N1.getOpcode() == ISD::SHL) {
1422 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1423 if (SHC->getAPIntValue().isPowerOf2()) {
1425 DAG.getNode(ISD::ADD, VT, N1,
1426 DAG.getConstant(APInt::getAllOnesValue(MVT::getSizeInBits(VT)),
1428 AddToWorkList(Add.Val);
1429 return DAG.getNode(ISD::AND, VT, N0, Add);
1434 // If X/C can be simplified by the division-by-constant logic, lower
1435 // X%C to the equivalent of X-X/C*C.
1436 if (N1C && !N1C->isNullValue()) {
1437 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1438 SDOperand OptimizedDiv = combine(Div.Val);
1439 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1440 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1441 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1442 AddToWorkList(Mul.Val);
1448 if (N0.getOpcode() == ISD::UNDEF)
1449 return DAG.getConstant(0, VT);
1450 // X % undef -> undef
1451 if (N1.getOpcode() == ISD::UNDEF)
1457 SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1458 SDOperand N0 = N->getOperand(0);
1459 SDOperand N1 = N->getOperand(1);
1460 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1461 MVT::ValueType VT = N->getValueType(0);
1463 // fold (mulhs x, 0) -> 0
1464 if (N1C && N1C->isNullValue())
1466 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1467 if (N1C && N1C->getAPIntValue() == 1)
1468 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1469 DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
1470 TLI.getShiftAmountTy()));
1471 // fold (mulhs x, undef) -> 0
1472 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1473 return DAG.getConstant(0, VT);
1478 SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1479 SDOperand N0 = N->getOperand(0);
1480 SDOperand N1 = N->getOperand(1);
1481 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1482 MVT::ValueType VT = N->getValueType(0);
1484 // fold (mulhu x, 0) -> 0
1485 if (N1C && N1C->isNullValue())
1487 // fold (mulhu x, 1) -> 0
1488 if (N1C && N1C->getAPIntValue() == 1)
1489 return DAG.getConstant(0, N0.getValueType());
1490 // fold (mulhu x, undef) -> 0
1491 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1492 return DAG.getConstant(0, VT);
1497 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1498 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1499 /// that are being performed. Return true if a simplification was made.
1501 SDOperand DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1503 // If the high half is not needed, just compute the low half.
1504 bool HiExists = N->hasAnyUseOfValue(1);
1507 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1508 SDOperand Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(),
1509 N->getNumOperands());
1510 return CombineTo(N, Res, Res);
1513 // If the low half is not needed, just compute the high half.
1514 bool LoExists = N->hasAnyUseOfValue(0);
1517 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1518 SDOperand Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(),
1519 N->getNumOperands());
1520 return CombineTo(N, Res, Res);
1523 // If both halves are used, return as it is.
1524 if (LoExists && HiExists)
1527 // If the two computed results can be simplified separately, separate them.
1529 SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
1530 N->op_begin(), N->getNumOperands());
1531 AddToWorkList(Lo.Val);
1532 SDOperand LoOpt = combine(Lo.Val);
1533 if (LoOpt.Val && LoOpt.Val != Lo.Val &&
1534 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))
1535 return CombineTo(N, LoOpt, LoOpt);
1539 SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
1540 N->op_begin(), N->getNumOperands());
1541 AddToWorkList(Hi.Val);
1542 SDOperand HiOpt = combine(Hi.Val);
1543 if (HiOpt.Val && HiOpt != Hi &&
1544 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))
1545 return CombineTo(N, HiOpt, HiOpt);
1550 SDOperand DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1551 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1552 if (Res.Val) return Res;
1557 SDOperand DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1558 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1559 if (Res.Val) return Res;
1564 SDOperand DAGCombiner::visitSDIVREM(SDNode *N) {
1565 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1566 if (Res.Val) return Res;
1571 SDOperand DAGCombiner::visitUDIVREM(SDNode *N) {
1572 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1573 if (Res.Val) return Res;
1578 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1579 /// two operands of the same opcode, try to simplify it.
1580 SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1581 SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1582 MVT::ValueType VT = N0.getValueType();
1583 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1585 // For each of OP in AND/OR/XOR:
1586 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1587 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1588 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1589 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1590 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1591 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1592 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1593 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1594 N0.getOperand(0).getValueType(),
1595 N0.getOperand(0), N1.getOperand(0));
1596 AddToWorkList(ORNode.Val);
1597 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1600 // For each of OP in SHL/SRL/SRA/AND...
1601 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1602 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1603 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1604 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1605 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1606 N0.getOperand(1) == N1.getOperand(1)) {
1607 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1608 N0.getOperand(0).getValueType(),
1609 N0.getOperand(0), N1.getOperand(0));
1610 AddToWorkList(ORNode.Val);
1611 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1617 SDOperand DAGCombiner::visitAND(SDNode *N) {
1618 SDOperand N0 = N->getOperand(0);
1619 SDOperand N1 = N->getOperand(1);
1620 SDOperand LL, LR, RL, RR, CC0, CC1;
1621 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1622 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1623 MVT::ValueType VT = N1.getValueType();
1624 unsigned BitWidth = MVT::getSizeInBits(VT);
1627 if (MVT::isVector(VT)) {
1628 SDOperand FoldedVOp = SimplifyVBinOp(N);
1629 if (FoldedVOp.Val) return FoldedVOp;
1632 // fold (and x, undef) -> 0
1633 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1634 return DAG.getConstant(0, VT);
1635 // fold (and c1, c2) -> c1&c2
1637 return DAG.getNode(ISD::AND, VT, N0, N1);
1638 // canonicalize constant to RHS
1640 return DAG.getNode(ISD::AND, VT, N1, N0);
1641 // fold (and x, -1) -> x
1642 if (N1C && N1C->isAllOnesValue())
1644 // if (and x, c) is known to be zero, return 0
1645 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
1646 APInt::getAllOnesValue(BitWidth)))
1647 return DAG.getConstant(0, VT);
1649 SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1652 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1653 if (N1C && N0.getOpcode() == ISD::OR)
1654 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1655 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
1657 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1658 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1659 SDOperand N0Op0 = N0.getOperand(0);
1660 APInt Mask = ~N1C->getAPIntValue();
1661 Mask.trunc(N0Op0.getValueSizeInBits());
1662 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
1663 SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1666 // Replace uses of the AND with uses of the Zero extend node.
1669 // We actually want to replace all uses of the any_extend with the
1670 // zero_extend, to avoid duplicating things. This will later cause this
1671 // AND to be folded.
1672 CombineTo(N0.Val, Zext);
1673 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1676 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1677 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1678 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1679 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1681 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1682 MVT::isInteger(LL.getValueType())) {
1683 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1684 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
1685 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1686 AddToWorkList(ORNode.Val);
1687 return DAG.getSetCC(VT, ORNode, LR, Op1);
1689 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1690 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1691 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1692 AddToWorkList(ANDNode.Val);
1693 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1695 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1696 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1697 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1698 AddToWorkList(ORNode.Val);
1699 return DAG.getSetCC(VT, ORNode, LR, Op1);
1702 // canonicalize equivalent to ll == rl
1703 if (LL == RR && LR == RL) {
1704 Op1 = ISD::getSetCCSwappedOperands(Op1);
1707 if (LL == RL && LR == RR) {
1708 bool isInteger = MVT::isInteger(LL.getValueType());
1709 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1710 if (Result != ISD::SETCC_INVALID)
1711 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1715 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1716 if (N0.getOpcode() == N1.getOpcode()) {
1717 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1718 if (Tmp.Val) return Tmp;
1721 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1722 // fold (and (sra)) -> (and (srl)) when possible.
1723 if (!MVT::isVector(VT) &&
1724 SimplifyDemandedBits(SDOperand(N, 0)))
1725 return SDOperand(N, 0);
1726 // fold (zext_inreg (extload x)) -> (zextload x)
1727 if (ISD::isEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val)) {
1728 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1729 MVT::ValueType EVT = LN0->getMemoryVT();
1730 // If we zero all the possible extended bits, then we can turn this into
1731 // a zextload if we are running before legalize or the operation is legal.
1732 unsigned BitWidth = N1.getValueSizeInBits();
1733 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1734 BitWidth - MVT::getSizeInBits(EVT))) &&
1735 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1736 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1737 LN0->getBasePtr(), LN0->getSrcValue(),
1738 LN0->getSrcValueOffset(), EVT,
1740 LN0->getAlignment());
1742 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1743 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1746 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1747 if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
1749 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1750 MVT::ValueType EVT = LN0->getMemoryVT();
1751 // If we zero all the possible extended bits, then we can turn this into
1752 // a zextload if we are running before legalize or the operation is legal.
1753 unsigned BitWidth = N1.getValueSizeInBits();
1754 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1755 BitWidth - MVT::getSizeInBits(EVT))) &&
1756 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1757 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1758 LN0->getBasePtr(), LN0->getSrcValue(),
1759 LN0->getSrcValueOffset(), EVT,
1761 LN0->getAlignment());
1763 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1764 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1768 // fold (and (load x), 255) -> (zextload x, i8)
1769 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1770 if (N1C && N0.getOpcode() == ISD::LOAD) {
1771 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1772 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1773 LN0->isUnindexed() && N0.hasOneUse()) {
1774 MVT::ValueType EVT, LoadedVT;
1775 if (N1C->getAPIntValue() == 255)
1777 else if (N1C->getAPIntValue() == 65535)
1779 else if (N1C->getAPIntValue() == ~0U)
1784 LoadedVT = LN0->getMemoryVT();
1785 if (EVT != MVT::Other && LoadedVT > EVT &&
1786 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1787 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1788 // For big endian targets, we need to add an offset to the pointer to
1789 // load the correct bytes. For little endian systems, we merely need to
1790 // read fewer bytes from the same pointer.
1791 unsigned LVTStoreBytes = MVT::getStoreSizeInBits(LoadedVT)/8;
1792 unsigned EVTStoreBytes = MVT::getStoreSizeInBits(EVT)/8;
1793 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
1794 unsigned Alignment = LN0->getAlignment();
1795 SDOperand NewPtr = LN0->getBasePtr();
1796 if (TLI.isBigEndian()) {
1797 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1798 DAG.getConstant(PtrOff, PtrType));
1799 Alignment = MinAlign(Alignment, PtrOff);
1801 AddToWorkList(NewPtr.Val);
1803 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1804 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
1805 LN0->isVolatile(), Alignment);
1807 CombineTo(N0.Val, Load, Load.getValue(1));
1808 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1816 SDOperand DAGCombiner::visitOR(SDNode *N) {
1817 SDOperand N0 = N->getOperand(0);
1818 SDOperand N1 = N->getOperand(1);
1819 SDOperand LL, LR, RL, RR, CC0, CC1;
1820 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1821 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1822 MVT::ValueType VT = N1.getValueType();
1825 if (MVT::isVector(VT)) {
1826 SDOperand FoldedVOp = SimplifyVBinOp(N);
1827 if (FoldedVOp.Val) return FoldedVOp;
1830 // fold (or x, undef) -> -1
1831 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1832 return DAG.getConstant(~0ULL, VT);
1833 // fold (or c1, c2) -> c1|c2
1835 return DAG.getNode(ISD::OR, VT, N0, N1);
1836 // canonicalize constant to RHS
1838 return DAG.getNode(ISD::OR, VT, N1, N0);
1839 // fold (or x, 0) -> x
1840 if (N1C && N1C->isNullValue())
1842 // fold (or x, -1) -> -1
1843 if (N1C && N1C->isAllOnesValue())
1845 // fold (or x, c) -> c iff (x & ~c) == 0
1846 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
1849 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1852 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1853 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1854 isa<ConstantSDNode>(N0.getOperand(1))) {
1855 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1856 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1858 DAG.getConstant(N1C->getAPIntValue() |
1859 C1->getAPIntValue(), VT));
1861 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1862 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1863 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1864 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1866 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1867 MVT::isInteger(LL.getValueType())) {
1868 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1869 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1870 if (cast<ConstantSDNode>(LR)->isNullValue() &&
1871 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1872 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1873 AddToWorkList(ORNode.Val);
1874 return DAG.getSetCC(VT, ORNode, LR, Op1);
1876 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1877 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1878 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1879 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1880 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1881 AddToWorkList(ANDNode.Val);
1882 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1885 // canonicalize equivalent to ll == rl
1886 if (LL == RR && LR == RL) {
1887 Op1 = ISD::getSetCCSwappedOperands(Op1);
1890 if (LL == RL && LR == RR) {
1891 bool isInteger = MVT::isInteger(LL.getValueType());
1892 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1893 if (Result != ISD::SETCC_INVALID)
1894 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1898 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1899 if (N0.getOpcode() == N1.getOpcode()) {
1900 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1901 if (Tmp.Val) return Tmp;
1904 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1905 if (N0.getOpcode() == ISD::AND &&
1906 N1.getOpcode() == ISD::AND &&
1907 N0.getOperand(1).getOpcode() == ISD::Constant &&
1908 N1.getOperand(1).getOpcode() == ISD::Constant &&
1909 // Don't increase # computations.
1910 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1911 // We can only do this xform if we know that bits from X that are set in C2
1912 // but not in C1 are already zero. Likewise for Y.
1913 const APInt &LHSMask =
1914 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1915 const APInt &RHSMask =
1916 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
1918 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1919 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1920 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1921 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1926 // See if this is some rotate idiom.
1927 if (SDNode *Rot = MatchRotate(N0, N1))
1928 return SDOperand(Rot, 0);
1934 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1935 static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1936 if (Op.getOpcode() == ISD::AND) {
1937 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1938 Mask = Op.getOperand(1);
1939 Op = Op.getOperand(0);
1945 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1953 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
1954 // idioms for rotate, and if the target supports rotation instructions, generate
1956 SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1957 // Must be a legal type. Expanded an promoted things won't work with rotates.
1958 MVT::ValueType VT = LHS.getValueType();
1959 if (!TLI.isTypeLegal(VT)) return 0;
1961 // The target must have at least one rotate flavor.
1962 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1963 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1964 if (!HasROTL && !HasROTR) return 0;
1966 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1967 SDOperand LHSShift; // The shift.
1968 SDOperand LHSMask; // AND value if any.
1969 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1970 return 0; // Not part of a rotate.
1972 SDOperand RHSShift; // The shift.
1973 SDOperand RHSMask; // AND value if any.
1974 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1975 return 0; // Not part of a rotate.
1977 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1978 return 0; // Not shifting the same value.
1980 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1981 return 0; // Shifts must disagree.
1983 // Canonicalize shl to left side in a shl/srl pair.
1984 if (RHSShift.getOpcode() == ISD::SHL) {
1985 std::swap(LHS, RHS);
1986 std::swap(LHSShift, RHSShift);
1987 std::swap(LHSMask , RHSMask );
1990 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1991 SDOperand LHSShiftArg = LHSShift.getOperand(0);
1992 SDOperand LHSShiftAmt = LHSShift.getOperand(1);
1993 SDOperand RHSShiftAmt = RHSShift.getOperand(1);
1995 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1996 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1997 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
1998 RHSShiftAmt.getOpcode() == ISD::Constant) {
1999 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue();
2000 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue();
2001 if ((LShVal + RShVal) != OpSizeInBits)
2006 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
2008 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
2010 // If there is an AND of either shifted operand, apply it to the result.
2011 if (LHSMask.Val || RHSMask.Val) {
2012 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2015 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2016 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2019 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2020 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2023 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
2029 // If there is a mask here, and we have a variable shift, we can't be sure
2030 // that we're masking out the right stuff.
2031 if (LHSMask.Val || RHSMask.Val)
2034 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2035 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2036 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2037 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2038 if (ConstantSDNode *SUBC =
2039 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2040 if (SUBC->getAPIntValue() == OpSizeInBits) {
2042 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2044 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2049 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2050 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2051 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2052 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2053 if (ConstantSDNode *SUBC =
2054 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2055 if (SUBC->getAPIntValue() == OpSizeInBits) {
2057 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2059 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2064 // Look for sign/zext/any-extended cases:
2065 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2066 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2067 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) &&
2068 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2069 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2070 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) {
2071 SDOperand LExtOp0 = LHSShiftAmt.getOperand(0);
2072 SDOperand RExtOp0 = RHSShiftAmt.getOperand(0);
2073 if (RExtOp0.getOpcode() == ISD::SUB &&
2074 RExtOp0.getOperand(1) == LExtOp0) {
2075 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2077 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2078 // (rotl x, (sub 32, y))
2079 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2080 if (SUBC->getAPIntValue() == OpSizeInBits) {
2082 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2084 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2087 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2088 RExtOp0 == LExtOp0.getOperand(1)) {
2089 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2091 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2092 // (rotr x, (sub 32, y))
2093 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2094 if (SUBC->getAPIntValue() == OpSizeInBits) {
2096 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
2098 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2108 SDOperand DAGCombiner::visitXOR(SDNode *N) {
2109 SDOperand N0 = N->getOperand(0);
2110 SDOperand N1 = N->getOperand(1);
2111 SDOperand LHS, RHS, CC;
2112 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2113 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2114 MVT::ValueType VT = N0.getValueType();
2117 if (MVT::isVector(VT)) {
2118 SDOperand FoldedVOp = SimplifyVBinOp(N);
2119 if (FoldedVOp.Val) return FoldedVOp;
2122 // fold (xor x, undef) -> undef
2123 if (N0.getOpcode() == ISD::UNDEF)
2125 if (N1.getOpcode() == ISD::UNDEF)
2127 // fold (xor c1, c2) -> c1^c2
2129 return DAG.getNode(ISD::XOR, VT, N0, N1);
2130 // canonicalize constant to RHS
2132 return DAG.getNode(ISD::XOR, VT, N1, N0);
2133 // fold (xor x, 0) -> x
2134 if (N1C && N1C->isNullValue())
2137 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
2140 // fold !(x cc y) -> (x !cc y)
2141 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2142 bool isInt = MVT::isInteger(LHS.getValueType());
2143 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2145 if (N0.getOpcode() == ISD::SETCC)
2146 return DAG.getSetCC(VT, LHS, RHS, NotCC);
2147 if (N0.getOpcode() == ISD::SELECT_CC)
2148 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
2149 assert(0 && "Unhandled SetCC Equivalent!");
2152 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2153 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2154 N0.Val->hasOneUse() && isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2155 SDOperand V = N0.getOperand(0);
2156 V = DAG.getNode(ISD::XOR, V.getValueType(), V,
2157 DAG.getConstant(1, V.getValueType()));
2158 AddToWorkList(V.Val);
2159 return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2162 // fold !(x or y) -> (!x and !y) iff x or y are setcc
2163 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2164 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2165 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2166 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2167 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2168 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2169 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2170 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2171 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2174 // fold !(x or y) -> (!x and !y) iff x or y are constants
2175 if (N1C && N1C->isAllOnesValue() &&
2176 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2177 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2178 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2179 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2180 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2181 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2182 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2183 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2186 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2187 if (N1C && N0.getOpcode() == ISD::XOR) {
2188 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2189 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2191 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
2192 DAG.getConstant(N1C->getAPIntValue()^
2193 N00C->getAPIntValue(), VT));
2195 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
2196 DAG.getConstant(N1C->getAPIntValue()^
2197 N01C->getAPIntValue(), VT));
2199 // fold (xor x, x) -> 0
2201 if (!MVT::isVector(VT)) {
2202 return DAG.getConstant(0, VT);
2203 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
2204 // Produce a vector of zeros.
2205 SDOperand El = DAG.getConstant(0, MVT::getVectorElementType(VT));
2206 std::vector<SDOperand> Ops(MVT::getVectorNumElements(VT), El);
2207 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2211 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2212 if (N0.getOpcode() == N1.getOpcode()) {
2213 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2214 if (Tmp.Val) return Tmp;
2217 // Simplify the expression using non-local knowledge.
2218 if (!MVT::isVector(VT) &&
2219 SimplifyDemandedBits(SDOperand(N, 0)))
2220 return SDOperand(N, 0);
2225 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2226 /// the shift amount is a constant.
2227 SDOperand DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2228 SDNode *LHS = N->getOperand(0).Val;
2229 if (!LHS->hasOneUse()) return SDOperand();
2231 // We want to pull some binops through shifts, so that we have (and (shift))
2232 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2233 // thing happens with address calculations, so it's important to canonicalize
2235 bool HighBitSet = false; // Can we transform this if the high bit is set?
2237 switch (LHS->getOpcode()) {
2238 default: return SDOperand();
2241 HighBitSet = false; // We can only transform sra if the high bit is clear.
2244 HighBitSet = true; // We can only transform sra if the high bit is set.
2247 if (N->getOpcode() != ISD::SHL)
2248 return SDOperand(); // only shl(add) not sr[al](add).
2249 HighBitSet = false; // We can only transform sra if the high bit is clear.
2253 // We require the RHS of the binop to be a constant as well.
2254 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2255 if (!BinOpCst) return SDOperand();
2258 // FIXME: disable this for unless the input to the binop is a shift by a
2259 // constant. If it is not a shift, it pessimizes some common cases like:
2261 //void foo(int *X, int i) { X[i & 1235] = 1; }
2262 //int bar(int *X, int i) { return X[i & 255]; }
2263 SDNode *BinOpLHSVal = LHS->getOperand(0).Val;
2264 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2265 BinOpLHSVal->getOpcode() != ISD::SRA &&
2266 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2267 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2270 MVT::ValueType VT = N->getValueType(0);
2272 // If this is a signed shift right, and the high bit is modified
2273 // by the logical operation, do not perform the transformation.
2274 // The highBitSet boolean indicates the value of the high bit of
2275 // the constant which would cause it to be modified for this
2277 if (N->getOpcode() == ISD::SRA) {
2278 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2279 if (BinOpRHSSignSet != HighBitSet)
2283 // Fold the constants, shifting the binop RHS by the shift amount.
2284 SDOperand NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
2285 LHS->getOperand(1), N->getOperand(1));
2287 // Create the new shift.
2288 SDOperand NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
2291 // Create the new binop.
2292 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
2296 SDOperand DAGCombiner::visitSHL(SDNode *N) {
2297 SDOperand N0 = N->getOperand(0);
2298 SDOperand N1 = N->getOperand(1);
2299 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2300 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2301 MVT::ValueType VT = N0.getValueType();
2302 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2304 // fold (shl c1, c2) -> c1<<c2
2306 return DAG.getNode(ISD::SHL, VT, N0, N1);
2307 // fold (shl 0, x) -> 0
2308 if (N0C && N0C->isNullValue())
2310 // fold (shl x, c >= size(x)) -> undef
2311 if (N1C && N1C->getValue() >= OpSizeInBits)
2312 return DAG.getNode(ISD::UNDEF, VT);
2313 // fold (shl x, 0) -> x
2314 if (N1C && N1C->isNullValue())
2316 // if (shl x, c) is known to be zero, return 0
2317 if (DAG.MaskedValueIsZero(SDOperand(N, 0),
2318 APInt::getAllOnesValue(MVT::getSizeInBits(VT))))
2319 return DAG.getConstant(0, VT);
2320 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2321 return SDOperand(N, 0);
2322 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2323 if (N1C && N0.getOpcode() == ISD::SHL &&
2324 N0.getOperand(1).getOpcode() == ISD::Constant) {
2325 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2326 uint64_t c2 = N1C->getValue();
2327 if (c1 + c2 > OpSizeInBits)
2328 return DAG.getConstant(0, VT);
2329 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2330 DAG.getConstant(c1 + c2, N1.getValueType()));
2332 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2333 // (srl (and x, -1 << c1), c1-c2)
2334 if (N1C && N0.getOpcode() == ISD::SRL &&
2335 N0.getOperand(1).getOpcode() == ISD::Constant) {
2336 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2337 uint64_t c2 = N1C->getValue();
2338 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2339 DAG.getConstant(~0ULL << c1, VT));
2341 return DAG.getNode(ISD::SHL, VT, Mask,
2342 DAG.getConstant(c2-c1, N1.getValueType()));
2344 return DAG.getNode(ISD::SRL, VT, Mask,
2345 DAG.getConstant(c1-c2, N1.getValueType()));
2347 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2348 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2349 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2350 DAG.getConstant(~0ULL << N1C->getValue(), VT));
2352 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2355 SDOperand DAGCombiner::visitSRA(SDNode *N) {
2356 SDOperand N0 = N->getOperand(0);
2357 SDOperand N1 = N->getOperand(1);
2358 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2359 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2360 MVT::ValueType VT = N0.getValueType();
2362 // fold (sra c1, c2) -> c1>>c2
2364 return DAG.getNode(ISD::SRA, VT, N0, N1);
2365 // fold (sra 0, x) -> 0
2366 if (N0C && N0C->isNullValue())
2368 // fold (sra -1, x) -> -1
2369 if (N0C && N0C->isAllOnesValue())
2371 // fold (sra x, c >= size(x)) -> undef
2372 if (N1C && N1C->getValue() >= MVT::getSizeInBits(VT))
2373 return DAG.getNode(ISD::UNDEF, VT);
2374 // fold (sra x, 0) -> x
2375 if (N1C && N1C->isNullValue())
2377 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2379 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2380 unsigned LowBits = MVT::getSizeInBits(VT) - (unsigned)N1C->getValue();
2383 default: EVT = MVT::Other; break;
2384 case 1: EVT = MVT::i1; break;
2385 case 8: EVT = MVT::i8; break;
2386 case 16: EVT = MVT::i16; break;
2387 case 32: EVT = MVT::i32; break;
2389 if (EVT > MVT::Other && TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))
2390 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2391 DAG.getValueType(EVT));
2394 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2395 if (N1C && N0.getOpcode() == ISD::SRA) {
2396 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2397 unsigned Sum = N1C->getValue() + C1->getValue();
2398 if (Sum >= MVT::getSizeInBits(VT)) Sum = MVT::getSizeInBits(VT)-1;
2399 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2400 DAG.getConstant(Sum, N1C->getValueType(0)));
2404 // fold sra (shl X, m), result_size - n
2405 // -> (sign_extend (trunc (shl X, result_size - n - m))) for
2406 // result_size - n != m.
2407 // If truncate is free for the target sext(shl) is likely to result in better
2409 if (N0.getOpcode() == ISD::SHL) {
2410 // Get the two constanst of the shifts, CN0 = m, CN = n.
2411 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2413 // Determine what the truncate's result bitsize and type would be.
2414 unsigned VTValSize = MVT::getSizeInBits(VT);
2415 MVT::ValueType TruncVT = MVT::getIntegerType(VTValSize - N1C->getValue());
2416 // Determine the residual right-shift amount.
2417 unsigned ShiftAmt = N1C->getValue() - N01C->getValue();
2419 // If the shift is not a no-op (in which case this should be just a sign
2420 // extend already), the truncated to type is legal, sign_extend is legal
2421 // on that type, and the the truncate to that type is both legal and free,
2422 // perform the transform.
2424 TLI.isTypeLegal(TruncVT) &&
2425 TLI.isOperationLegal(ISD::SIGN_EXTEND, TruncVT) &&
2426 TLI.isOperationLegal(ISD::TRUNCATE, VT) &&
2427 TLI.isTruncateFree(VT, TruncVT)) {
2429 SDOperand Amt = DAG.getConstant(ShiftAmt, TLI.getShiftAmountTy());
2430 SDOperand Shift = DAG.getNode(ISD::SRL, VT, N0.getOperand(0), Amt);
2431 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, TruncVT, Shift);
2432 return DAG.getNode(ISD::SIGN_EXTEND, N->getValueType(0), Trunc);
2437 // Simplify, based on bits shifted out of the LHS.
2438 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2439 return SDOperand(N, 0);
2442 // If the sign bit is known to be zero, switch this to a SRL.
2443 if (DAG.SignBitIsZero(N0))
2444 return DAG.getNode(ISD::SRL, VT, N0, N1);
2446 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2449 SDOperand DAGCombiner::visitSRL(SDNode *N) {
2450 SDOperand N0 = N->getOperand(0);
2451 SDOperand N1 = N->getOperand(1);
2452 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2453 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2454 MVT::ValueType VT = N0.getValueType();
2455 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2457 // fold (srl c1, c2) -> c1 >>u c2
2459 return DAG.getNode(ISD::SRL, VT, N0, N1);
2460 // fold (srl 0, x) -> 0
2461 if (N0C && N0C->isNullValue())
2463 // fold (srl x, c >= size(x)) -> undef
2464 if (N1C && N1C->getValue() >= OpSizeInBits)
2465 return DAG.getNode(ISD::UNDEF, VT);
2466 // fold (srl x, 0) -> x
2467 if (N1C && N1C->isNullValue())
2469 // if (srl x, c) is known to be zero, return 0
2470 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
2471 APInt::getAllOnesValue(OpSizeInBits)))
2472 return DAG.getConstant(0, VT);
2474 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2475 if (N1C && N0.getOpcode() == ISD::SRL &&
2476 N0.getOperand(1).getOpcode() == ISD::Constant) {
2477 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2478 uint64_t c2 = N1C->getValue();
2479 if (c1 + c2 > OpSizeInBits)
2480 return DAG.getConstant(0, VT);
2481 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2482 DAG.getConstant(c1 + c2, N1.getValueType()));
2485 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2486 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2487 // Shifting in all undef bits?
2488 MVT::ValueType SmallVT = N0.getOperand(0).getValueType();
2489 if (N1C->getValue() >= MVT::getSizeInBits(SmallVT))
2490 return DAG.getNode(ISD::UNDEF, VT);
2492 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2493 AddToWorkList(SmallShift.Val);
2494 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2497 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2498 // bit, which is unmodified by sra.
2499 if (N1C && N1C->getValue()+1 == MVT::getSizeInBits(VT)) {
2500 if (N0.getOpcode() == ISD::SRA)
2501 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2504 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2505 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2506 N1C->getAPIntValue() == Log2_32(MVT::getSizeInBits(VT))) {
2507 APInt KnownZero, KnownOne;
2508 APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
2509 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2511 // If any of the input bits are KnownOne, then the input couldn't be all
2512 // zeros, thus the result of the srl will always be zero.
2513 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
2515 // If all of the bits input the to ctlz node are known to be zero, then
2516 // the result of the ctlz is "32" and the result of the shift is one.
2517 APInt UnknownBits = ~KnownZero & Mask;
2518 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2520 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2521 if ((UnknownBits & (UnknownBits-1)) == 0) {
2522 // Okay, we know that only that the single bit specified by UnknownBits
2523 // could be set on input to the CTLZ node. If this bit is set, the SRL
2524 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2525 // to an SRL,XOR pair, which is likely to simplify more.
2526 unsigned ShAmt = UnknownBits.countTrailingZeros();
2527 SDOperand Op = N0.getOperand(0);
2529 Op = DAG.getNode(ISD::SRL, VT, Op,
2530 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2531 AddToWorkList(Op.Val);
2533 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2537 // fold operands of srl based on knowledge that the low bits are not
2539 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2540 return SDOperand(N, 0);
2542 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2545 SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2546 SDOperand N0 = N->getOperand(0);
2547 MVT::ValueType VT = N->getValueType(0);
2549 // fold (ctlz c1) -> c2
2550 if (isa<ConstantSDNode>(N0))
2551 return DAG.getNode(ISD::CTLZ, VT, N0);
2555 SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2556 SDOperand N0 = N->getOperand(0);
2557 MVT::ValueType VT = N->getValueType(0);
2559 // fold (cttz c1) -> c2
2560 if (isa<ConstantSDNode>(N0))
2561 return DAG.getNode(ISD::CTTZ, VT, N0);
2565 SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2566 SDOperand N0 = N->getOperand(0);
2567 MVT::ValueType VT = N->getValueType(0);
2569 // fold (ctpop c1) -> c2
2570 if (isa<ConstantSDNode>(N0))
2571 return DAG.getNode(ISD::CTPOP, VT, N0);
2575 SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2576 SDOperand N0 = N->getOperand(0);
2577 SDOperand N1 = N->getOperand(1);
2578 SDOperand N2 = N->getOperand(2);
2579 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2580 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2581 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2582 MVT::ValueType VT = N->getValueType(0);
2583 MVT::ValueType VT0 = N0.getValueType();
2585 // fold select C, X, X -> X
2588 // fold select true, X, Y -> X
2589 if (N0C && !N0C->isNullValue())
2591 // fold select false, X, Y -> Y
2592 if (N0C && N0C->isNullValue())
2594 // fold select C, 1, X -> C | X
2595 if (MVT::i1 == VT && N1C && N1C->getAPIntValue() == 1)
2596 return DAG.getNode(ISD::OR, VT, N0, N2);
2597 // fold select C, 0, 1 -> ~C
2598 if (MVT::isInteger(VT) && MVT::isInteger(VT0) &&
2599 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
2600 SDOperand XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2603 AddToWorkList(XORNode.Val);
2604 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(VT0))
2605 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2606 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2608 // fold select C, 0, X -> ~C & X
2609 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2610 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2611 AddToWorkList(XORNode.Val);
2612 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2614 // fold select C, X, 1 -> ~C | X
2615 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
2616 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2617 AddToWorkList(XORNode.Val);
2618 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2620 // fold select C, X, 0 -> C & X
2621 // FIXME: this should check for C type == X type, not i1?
2622 if (MVT::i1 == VT && N2C && N2C->isNullValue())
2623 return DAG.getNode(ISD::AND, VT, N0, N1);
2624 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2625 if (MVT::i1 == VT && N0 == N1)
2626 return DAG.getNode(ISD::OR, VT, N0, N2);
2627 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2628 if (MVT::i1 == VT && N0 == N2)
2629 return DAG.getNode(ISD::AND, VT, N0, N1);
2631 // If we can fold this based on the true/false value, do so.
2632 if (SimplifySelectOps(N, N1, N2))
2633 return SDOperand(N, 0); // Don't revisit N.
2635 // fold selects based on a setcc into other things, such as min/max/abs
2636 if (N0.getOpcode() == ISD::SETCC) {
2638 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2639 // having to say they don't support SELECT_CC on every type the DAG knows
2640 // about, since there is no way to mark an opcode illegal at all value types
2641 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2642 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2643 N1, N2, N0.getOperand(2));
2645 return SimplifySelect(N0, N1, N2);
2650 SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2651 SDOperand N0 = N->getOperand(0);
2652 SDOperand N1 = N->getOperand(1);
2653 SDOperand N2 = N->getOperand(2);
2654 SDOperand N3 = N->getOperand(3);
2655 SDOperand N4 = N->getOperand(4);
2656 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2658 // fold select_cc lhs, rhs, x, x, cc -> x
2662 // Determine if the condition we're dealing with is constant
2663 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
2664 if (SCC.Val) AddToWorkList(SCC.Val);
2666 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
2667 if (!SCCC->isNullValue())
2668 return N2; // cond always true -> true val
2670 return N3; // cond always false -> false val
2673 // Fold to a simpler select_cc
2674 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2675 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2676 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2679 // If we can fold this based on the true/false value, do so.
2680 if (SimplifySelectOps(N, N2, N3))
2681 return SDOperand(N, 0); // Don't revisit N.
2683 // fold select_cc into other things, such as min/max/abs
2684 return SimplifySelectCC(N0, N1, N2, N3, CC);
2687 SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2688 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2689 cast<CondCodeSDNode>(N->getOperand(2))->get());
2692 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2693 // "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
2694 // transformation. Returns true if extension are possible and the above
2695 // mentioned transformation is profitable.
2696 static bool ExtendUsesToFormExtLoad(SDNode *N, SDOperand N0,
2698 SmallVector<SDNode*, 4> &ExtendNodes,
2699 TargetLowering &TLI) {
2700 bool HasCopyToRegUses = false;
2701 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2702 for (SDNode::use_iterator UI = N0.Val->use_begin(), UE = N0.Val->use_end();
2707 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2708 if (User->getOpcode() == ISD::SETCC) {
2709 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2710 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2711 // Sign bits will be lost after a zext.
2714 for (unsigned i = 0; i != 2; ++i) {
2715 SDOperand UseOp = User->getOperand(i);
2718 if (!isa<ConstantSDNode>(UseOp))
2723 ExtendNodes.push_back(User);
2725 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2726 SDOperand UseOp = User->getOperand(i);
2728 // If truncate from extended type to original load type is free
2729 // on this target, then it's ok to extend a CopyToReg.
2730 if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
2731 HasCopyToRegUses = true;
2739 if (HasCopyToRegUses) {
2740 bool BothLiveOut = false;
2741 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2744 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2745 SDOperand UseOp = User->getOperand(i);
2746 if (UseOp.Val == N && UseOp.ResNo == 0) {
2753 // Both unextended and extended values are live out. There had better be
2754 // good a reason for the transformation.
2755 return ExtendNodes.size();
2760 SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2761 SDOperand N0 = N->getOperand(0);
2762 MVT::ValueType VT = N->getValueType(0);
2764 // fold (sext c1) -> c1
2765 if (isa<ConstantSDNode>(N0))
2766 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2768 // fold (sext (sext x)) -> (sext x)
2769 // fold (sext (aext x)) -> (sext x)
2770 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2771 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2773 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2774 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2775 if (N0.getOpcode() == ISD::TRUNCATE) {
2776 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2777 if (NarrowLoad.Val) {
2778 if (NarrowLoad.Val != N0.Val)
2779 CombineTo(N0.Val, NarrowLoad);
2780 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2784 // See if the value being truncated is already sign extended. If so, just
2785 // eliminate the trunc/sext pair.
2786 if (N0.getOpcode() == ISD::TRUNCATE) {
2787 SDOperand Op = N0.getOperand(0);
2788 unsigned OpBits = MVT::getSizeInBits(Op.getValueType());
2789 unsigned MidBits = MVT::getSizeInBits(N0.getValueType());
2790 unsigned DestBits = MVT::getSizeInBits(VT);
2791 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2793 if (OpBits == DestBits) {
2794 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2795 // bits, it is already ready.
2796 if (NumSignBits > DestBits-MidBits)
2798 } else if (OpBits < DestBits) {
2799 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2800 // bits, just sext from i32.
2801 if (NumSignBits > OpBits-MidBits)
2802 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2804 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2805 // bits, just truncate to i32.
2806 if (NumSignBits > OpBits-MidBits)
2807 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2810 // fold (sext (truncate x)) -> (sextinreg x).
2811 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2812 N0.getValueType())) {
2813 if (Op.getValueType() < VT)
2814 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2815 else if (Op.getValueType() > VT)
2816 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2817 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2818 DAG.getValueType(N0.getValueType()));
2822 // fold (sext (load x)) -> (sext (truncate (sextload x)))
2823 if (ISD::isNON_EXTLoad(N0.Val) &&
2824 (!AfterLegalize||TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))){
2825 bool DoXform = true;
2826 SmallVector<SDNode*, 4> SetCCs;
2827 if (!N0.hasOneUse())
2828 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
2830 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2831 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2832 LN0->getBasePtr(), LN0->getSrcValue(),
2833 LN0->getSrcValueOffset(),
2836 LN0->getAlignment());
2837 CombineTo(N, ExtLoad);
2838 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2839 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2840 // Extend SetCC uses if necessary.
2841 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2842 SDNode *SetCC = SetCCs[i];
2843 SmallVector<SDOperand, 4> Ops;
2844 for (unsigned j = 0; j != 2; ++j) {
2845 SDOperand SOp = SetCC->getOperand(j);
2847 Ops.push_back(ExtLoad);
2849 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
2851 Ops.push_back(SetCC->getOperand(2));
2852 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2853 &Ops[0], Ops.size()));
2855 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2859 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2860 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2861 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2862 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2863 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2864 MVT::ValueType EVT = LN0->getMemoryVT();
2865 if (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
2866 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2867 LN0->getBasePtr(), LN0->getSrcValue(),
2868 LN0->getSrcValueOffset(), EVT,
2870 LN0->getAlignment());
2871 CombineTo(N, ExtLoad);
2872 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2873 ExtLoad.getValue(1));
2874 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2878 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2879 if (N0.getOpcode() == ISD::SETCC) {
2881 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2882 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2883 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2884 if (SCC.Val) return SCC;
2890 SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2891 SDOperand N0 = N->getOperand(0);
2892 MVT::ValueType VT = N->getValueType(0);
2894 // fold (zext c1) -> c1
2895 if (isa<ConstantSDNode>(N0))
2896 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2897 // fold (zext (zext x)) -> (zext x)
2898 // fold (zext (aext x)) -> (zext x)
2899 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2900 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2902 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2903 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2904 if (N0.getOpcode() == ISD::TRUNCATE) {
2905 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2906 if (NarrowLoad.Val) {
2907 if (NarrowLoad.Val != N0.Val)
2908 CombineTo(N0.Val, NarrowLoad);
2909 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2913 // fold (zext (truncate x)) -> (and x, mask)
2914 if (N0.getOpcode() == ISD::TRUNCATE &&
2915 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2916 SDOperand Op = N0.getOperand(0);
2917 if (Op.getValueType() < VT) {
2918 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2919 } else if (Op.getValueType() > VT) {
2920 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2922 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2925 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2926 if (N0.getOpcode() == ISD::AND &&
2927 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2928 N0.getOperand(1).getOpcode() == ISD::Constant) {
2929 SDOperand X = N0.getOperand(0).getOperand(0);
2930 if (X.getValueType() < VT) {
2931 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2932 } else if (X.getValueType() > VT) {
2933 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2935 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2936 Mask.zext(MVT::getSizeInBits(VT));
2937 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2940 // fold (zext (load x)) -> (zext (truncate (zextload x)))
2941 if (ISD::isNON_EXTLoad(N0.Val) &&
2942 (!AfterLegalize||TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
2943 bool DoXform = true;
2944 SmallVector<SDNode*, 4> SetCCs;
2945 if (!N0.hasOneUse())
2946 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
2948 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2949 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2950 LN0->getBasePtr(), LN0->getSrcValue(),
2951 LN0->getSrcValueOffset(),
2954 LN0->getAlignment());
2955 CombineTo(N, ExtLoad);
2956 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2957 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2958 // Extend SetCC uses if necessary.
2959 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2960 SDNode *SetCC = SetCCs[i];
2961 SmallVector<SDOperand, 4> Ops;
2962 for (unsigned j = 0; j != 2; ++j) {
2963 SDOperand SOp = SetCC->getOperand(j);
2965 Ops.push_back(ExtLoad);
2967 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
2969 Ops.push_back(SetCC->getOperand(2));
2970 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2971 &Ops[0], Ops.size()));
2973 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2977 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2978 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2979 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2980 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2981 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2982 MVT::ValueType EVT = LN0->getMemoryVT();
2983 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2984 LN0->getBasePtr(), LN0->getSrcValue(),
2985 LN0->getSrcValueOffset(), EVT,
2987 LN0->getAlignment());
2988 CombineTo(N, ExtLoad);
2989 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2990 ExtLoad.getValue(1));
2991 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2994 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
2995 if (N0.getOpcode() == ISD::SETCC) {
2997 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2998 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2999 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3000 if (SCC.Val) return SCC;
3006 SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
3007 SDOperand N0 = N->getOperand(0);
3008 MVT::ValueType VT = N->getValueType(0);
3010 // fold (aext c1) -> c1
3011 if (isa<ConstantSDNode>(N0))
3012 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
3013 // fold (aext (aext x)) -> (aext x)
3014 // fold (aext (zext x)) -> (zext x)
3015 // fold (aext (sext x)) -> (sext x)
3016 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3017 N0.getOpcode() == ISD::ZERO_EXTEND ||
3018 N0.getOpcode() == ISD::SIGN_EXTEND)
3019 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3021 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3022 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3023 if (N0.getOpcode() == ISD::TRUNCATE) {
3024 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
3025 if (NarrowLoad.Val) {
3026 if (NarrowLoad.Val != N0.Val)
3027 CombineTo(N0.Val, NarrowLoad);
3028 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
3032 // fold (aext (truncate x))
3033 if (N0.getOpcode() == ISD::TRUNCATE) {
3034 SDOperand TruncOp = N0.getOperand(0);
3035 if (TruncOp.getValueType() == VT)
3036 return TruncOp; // x iff x size == zext size.
3037 if (TruncOp.getValueType() > VT)
3038 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
3039 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
3042 // fold (aext (and (trunc x), cst)) -> (and x, cst).
3043 if (N0.getOpcode() == ISD::AND &&
3044 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3045 N0.getOperand(1).getOpcode() == ISD::Constant) {
3046 SDOperand X = N0.getOperand(0).getOperand(0);
3047 if (X.getValueType() < VT) {
3048 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
3049 } else if (X.getValueType() > VT) {
3050 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3052 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3053 Mask.zext(MVT::getSizeInBits(VT));
3054 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
3057 // fold (aext (load x)) -> (aext (truncate (extload x)))
3058 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3059 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3060 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3061 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3062 LN0->getBasePtr(), LN0->getSrcValue(),
3063 LN0->getSrcValueOffset(),
3066 LN0->getAlignment());
3067 CombineTo(N, ExtLoad);
3068 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3069 ExtLoad.getValue(1));
3070 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3073 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3074 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3075 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3076 if (N0.getOpcode() == ISD::LOAD &&
3077 !ISD::isNON_EXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3079 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3080 MVT::ValueType EVT = LN0->getMemoryVT();
3081 SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
3082 LN0->getChain(), LN0->getBasePtr(),
3084 LN0->getSrcValueOffset(), EVT,
3086 LN0->getAlignment());
3087 CombineTo(N, ExtLoad);
3088 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3089 ExtLoad.getValue(1));
3090 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3093 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3094 if (N0.getOpcode() == ISD::SETCC) {
3096 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3097 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3098 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3106 /// GetDemandedBits - See if the specified operand can be simplified with the
3107 /// knowledge that only the bits specified by Mask are used. If so, return the
3108 /// simpler operand, otherwise return a null SDOperand.
3109 SDOperand DAGCombiner::GetDemandedBits(SDOperand V, const APInt &Mask) {
3110 switch (V.getOpcode()) {
3114 // If the LHS or RHS don't contribute bits to the or, drop them.
3115 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3116 return V.getOperand(1);
3117 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3118 return V.getOperand(0);
3121 // Only look at single-use SRLs.
3122 if (!V.Val->hasOneUse())
3124 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3125 // See if we can recursively simplify the LHS.
3126 unsigned Amt = RHSC->getValue();
3127 APInt NewMask = Mask << Amt;
3128 SDOperand SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3129 if (SimplifyLHS.Val) {
3130 return DAG.getNode(ISD::SRL, V.getValueType(),
3131 SimplifyLHS, V.getOperand(1));
3138 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3139 /// bits and then truncated to a narrower type and where N is a multiple
3140 /// of number of bits of the narrower type, transform it to a narrower load
3141 /// from address + N / num of bits of new type. If the result is to be
3142 /// extended, also fold the extension to form a extending load.
3143 SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
3144 unsigned Opc = N->getOpcode();
3145 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3146 SDOperand N0 = N->getOperand(0);
3147 MVT::ValueType VT = N->getValueType(0);
3148 MVT::ValueType EVT = N->getValueType(0);
3150 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3152 if (Opc == ISD::SIGN_EXTEND_INREG) {
3153 ExtType = ISD::SEXTLOAD;
3154 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3155 if (AfterLegalize && !TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))
3159 unsigned EVTBits = MVT::getSizeInBits(EVT);
3161 bool CombineSRL = false;
3162 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3163 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3164 ShAmt = N01->getValue();
3165 // Is the shift amount a multiple of size of VT?
3166 if ((ShAmt & (EVTBits-1)) == 0) {
3167 N0 = N0.getOperand(0);
3168 if (MVT::getSizeInBits(N0.getValueType()) <= EVTBits)
3175 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3176 // Do not allow folding to i1 here. i1 is implicitly stored in memory in
3177 // zero extended form: by shrinking the load, we lose track of the fact
3178 // that it is already zero extended.
3179 // FIXME: This should be reevaluated.
3181 assert(MVT::getSizeInBits(N0.getValueType()) > EVTBits &&
3182 "Cannot truncate to larger type!");
3183 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3184 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
3185 // For big endian targets, we need to adjust the offset to the pointer to
3186 // load the correct bytes.
3187 if (TLI.isBigEndian()) {
3188 unsigned LVTStoreBits = MVT::getStoreSizeInBits(N0.getValueType());
3189 unsigned EVTStoreBits = MVT::getStoreSizeInBits(EVT);
3190 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3192 uint64_t PtrOff = ShAmt / 8;
3193 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3194 SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
3195 DAG.getConstant(PtrOff, PtrType));
3196 AddToWorkList(NewPtr.Val);
3197 SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
3198 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
3199 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3200 LN0->isVolatile(), NewAlign)
3201 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
3202 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
3203 LN0->isVolatile(), NewAlign);
3206 WorkListRemover DeadNodes(*this);
3207 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3209 CombineTo(N->getOperand(0).Val, Load);
3211 CombineTo(N0.Val, Load, Load.getValue(1));
3213 if (Opc == ISD::SIGN_EXTEND_INREG)
3214 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
3216 return DAG.getNode(Opc, VT, Load);
3218 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3225 SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3226 SDOperand N0 = N->getOperand(0);
3227 SDOperand N1 = N->getOperand(1);
3228 MVT::ValueType VT = N->getValueType(0);
3229 MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
3230 unsigned VTBits = MVT::getSizeInBits(VT);
3231 unsigned EVTBits = MVT::getSizeInBits(EVT);
3233 // fold (sext_in_reg c1) -> c1
3234 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3235 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
3237 // If the input is already sign extended, just drop the extension.
3238 if (DAG.ComputeNumSignBits(N0) >= MVT::getSizeInBits(VT)-EVTBits+1)
3241 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3242 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3243 EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
3244 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
3247 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3248 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3249 return DAG.getZeroExtendInReg(N0, EVT);
3251 // fold operands of sext_in_reg based on knowledge that the top bits are not
3253 if (SimplifyDemandedBits(SDOperand(N, 0)))
3254 return SDOperand(N, 0);
3256 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3257 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3258 SDOperand NarrowLoad = ReduceLoadWidth(N);
3262 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
3263 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
3264 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3265 if (N0.getOpcode() == ISD::SRL) {
3266 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3267 if (ShAmt->getValue()+EVTBits <= MVT::getSizeInBits(VT)) {
3268 // We can turn this into an SRA iff the input to the SRL is already sign
3270 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3271 if (MVT::getSizeInBits(VT)-(ShAmt->getValue()+EVTBits) < InSignBits)
3272 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
3276 // fold (sext_inreg (extload x)) -> (sextload x)
3277 if (ISD::isEXTLoad(N0.Val) &&
3278 ISD::isUNINDEXEDLoad(N0.Val) &&
3279 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3280 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3281 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3282 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3283 LN0->getBasePtr(), LN0->getSrcValue(),
3284 LN0->getSrcValueOffset(), EVT,
3286 LN0->getAlignment());
3287 CombineTo(N, ExtLoad);
3288 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3289 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3291 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3292 if (ISD::isZEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3294 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3295 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3296 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3297 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3298 LN0->getBasePtr(), LN0->getSrcValue(),
3299 LN0->getSrcValueOffset(), EVT,
3301 LN0->getAlignment());
3302 CombineTo(N, ExtLoad);
3303 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3304 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3309 SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
3310 SDOperand N0 = N->getOperand(0);
3311 MVT::ValueType VT = N->getValueType(0);
3314 if (N0.getValueType() == N->getValueType(0))
3316 // fold (truncate c1) -> c1
3317 if (isa<ConstantSDNode>(N0))
3318 return DAG.getNode(ISD::TRUNCATE, VT, N0);
3319 // fold (truncate (truncate x)) -> (truncate x)
3320 if (N0.getOpcode() == ISD::TRUNCATE)
3321 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3322 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3323 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3324 N0.getOpcode() == ISD::ANY_EXTEND) {
3325 if (N0.getOperand(0).getValueType() < VT)
3326 // if the source is smaller than the dest, we still need an extend
3327 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3328 else if (N0.getOperand(0).getValueType() > VT)
3329 // if the source is larger than the dest, than we just need the truncate
3330 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3332 // if the source and dest are the same type, we can drop both the extend
3334 return N0.getOperand(0);
3337 // See if we can simplify the input to this truncate through knowledge that
3338 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3341 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3342 MVT::getSizeInBits(VT)));
3344 return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3346 // fold (truncate (load x)) -> (smaller load x)
3347 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3348 return ReduceLoadWidth(N);
3351 SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3352 SDOperand N0 = N->getOperand(0);
3353 MVT::ValueType VT = N->getValueType(0);
3355 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3356 // Only do this before legalize, since afterward the target may be depending
3357 // on the bitconvert.
3358 // First check to see if this is all constant.
3359 if (!AfterLegalize &&
3360 N0.getOpcode() == ISD::BUILD_VECTOR && N0.Val->hasOneUse() &&
3361 MVT::isVector(VT)) {
3362 bool isSimple = true;
3363 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3364 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3365 N0.getOperand(i).getOpcode() != ISD::Constant &&
3366 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3371 MVT::ValueType DestEltVT = MVT::getVectorElementType(N->getValueType(0));
3372 assert(!MVT::isVector(DestEltVT) &&
3373 "Element type of vector ValueType must not be vector!");
3375 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.Val, DestEltVT);
3379 // If the input is a constant, let getNode() fold it.
3380 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3381 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3382 if (Res.Val != N) return Res;
3385 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
3386 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3388 // fold (conv (load x)) -> (load (conv*)x)
3389 // If the resultant load doesn't need a higher alignment than the original!
3390 if (ISD::isNormalLoad(N0.Val) && N0.hasOneUse() &&
3391 TLI.isOperationLegal(ISD::LOAD, VT)) {
3392 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3393 unsigned Align = TLI.getTargetMachine().getTargetData()->
3394 getABITypeAlignment(MVT::getTypeForValueType(VT));
3395 unsigned OrigAlign = LN0->getAlignment();
3396 if (Align <= OrigAlign) {
3397 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3398 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3399 LN0->isVolatile(), Align);
3401 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3407 // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit)
3408 // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit)
3409 // This often reduces constant pool loads.
3410 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3411 N0.Val->hasOneUse() && MVT::isInteger(VT) && !MVT::isVector(VT)) {
3412 SDOperand NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3413 AddToWorkList(NewConv.Val);
3415 APInt SignBit = APInt::getSignBit(MVT::getSizeInBits(VT));
3416 if (N0.getOpcode() == ISD::FNEG)
3417 return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT));
3418 assert(N0.getOpcode() == ISD::FABS);
3419 return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT));
3422 // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign'
3423 // Note that we don't handle copysign(x,cst) because this can always be folded
3424 // to an fneg or fabs.
3425 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse() &&
3426 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3427 MVT::isInteger(VT) && !MVT::isVector(VT)) {
3428 unsigned OrigXWidth = MVT::getSizeInBits(N0.getOperand(1).getValueType());
3429 SDOperand X = DAG.getNode(ISD::BIT_CONVERT, MVT::getIntegerType(OrigXWidth),
3431 AddToWorkList(X.Val);
3433 // If X has a different width than the result/lhs, sext it or truncate it.
3434 unsigned VTWidth = MVT::getSizeInBits(VT);
3435 if (OrigXWidth < VTWidth) {
3436 X = DAG.getNode(ISD::SIGN_EXTEND, VT, X);
3437 AddToWorkList(X.Val);
3438 } else if (OrigXWidth > VTWidth) {
3439 // To get the sign bit in the right place, we have to shift it right
3440 // before truncating.
3441 X = DAG.getNode(ISD::SRL, X.getValueType(), X,
3442 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3443 AddToWorkList(X.Val);
3444 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3445 AddToWorkList(X.Val);
3448 APInt SignBit = APInt::getSignBit(MVT::getSizeInBits(VT));
3449 X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT));
3450 AddToWorkList(X.Val);
3452 SDOperand Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3453 Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT));
3454 AddToWorkList(Cst.Val);
3456 return DAG.getNode(ISD::OR, VT, X, Cst);
3462 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3463 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3464 /// destination element value type.
3465 SDOperand DAGCombiner::
3466 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
3467 MVT::ValueType SrcEltVT = BV->getOperand(0).getValueType();
3469 // If this is already the right type, we're done.
3470 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
3472 unsigned SrcBitSize = MVT::getSizeInBits(SrcEltVT);
3473 unsigned DstBitSize = MVT::getSizeInBits(DstEltVT);
3475 // If this is a conversion of N elements of one type to N elements of another
3476 // type, convert each element. This handles FP<->INT cases.
3477 if (SrcBitSize == DstBitSize) {
3478 SmallVector<SDOperand, 8> Ops;
3479 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3480 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3481 AddToWorkList(Ops.back().Val);
3484 MVT::getVectorType(DstEltVT,
3485 MVT::getVectorNumElements(BV->getValueType(0)));
3486 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3489 // Otherwise, we're growing or shrinking the elements. To avoid having to
3490 // handle annoying details of growing/shrinking FP values, we convert them to
3492 if (MVT::isFloatingPoint(SrcEltVT)) {
3493 // Convert the input float vector to a int vector where the elements are the
3495 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3496 MVT::ValueType IntVT = SrcEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
3497 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).Val;
3501 // Now we know the input is an integer vector. If the output is a FP type,
3502 // convert to integer first, then to FP of the right size.
3503 if (MVT::isFloatingPoint(DstEltVT)) {
3504 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3505 MVT::ValueType TmpVT = DstEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
3506 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).Val;
3508 // Next, convert to FP elements of the same size.
3509 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3512 // Okay, we know the src/dst types are both integers of differing types.
3513 // Handling growing first.
3514 assert(MVT::isInteger(SrcEltVT) && MVT::isInteger(DstEltVT));
3515 if (SrcBitSize < DstBitSize) {
3516 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3518 SmallVector<SDOperand, 8> Ops;
3519 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3520 i += NumInputsPerOutput) {
3521 bool isLE = TLI.isLittleEndian();
3522 APInt NewBits = APInt(DstBitSize, 0);
3523 bool EltIsUndef = true;
3524 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3525 // Shift the previously computed bits over.
3526 NewBits <<= SrcBitSize;
3527 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3528 if (Op.getOpcode() == ISD::UNDEF) continue;
3532 APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).zext(DstBitSize);
3536 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3538 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3541 MVT::ValueType VT = MVT::getVectorType(DstEltVT, Ops.size());
3542 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3545 // Finally, this must be the case where we are shrinking elements: each input
3546 // turns into multiple outputs.
3547 bool isS2V = ISD::isScalarToVector(BV);
3548 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3549 MVT::ValueType VT = MVT::getVectorType(DstEltVT,
3550 NumOutputsPerInput * BV->getNumOperands());
3551 SmallVector<SDOperand, 8> Ops;
3552 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3553 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3554 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3555 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3558 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getAPIntValue();
3559 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3560 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
3561 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3562 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
3563 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3564 return DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Ops[0]);
3565 OpVal = OpVal.lshr(DstBitSize);
3568 // For big endian targets, swap the order of the pieces of each element.
3569 if (TLI.isBigEndian())
3570 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3572 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3577 SDOperand DAGCombiner::visitFADD(SDNode *N) {
3578 SDOperand N0 = N->getOperand(0);
3579 SDOperand N1 = N->getOperand(1);
3580 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3581 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3582 MVT::ValueType VT = N->getValueType(0);
3585 if (MVT::isVector(VT)) {
3586 SDOperand FoldedVOp = SimplifyVBinOp(N);
3587 if (FoldedVOp.Val) return FoldedVOp;
3590 // fold (fadd c1, c2) -> c1+c2
3591 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3592 return DAG.getNode(ISD::FADD, VT, N0, N1);
3593 // canonicalize constant to RHS
3594 if (N0CFP && !N1CFP)
3595 return DAG.getNode(ISD::FADD, VT, N1, N0);
3596 // fold (A + (-B)) -> A-B
3597 if (isNegatibleForFree(N1, AfterLegalize) == 2)
3598 return DAG.getNode(ISD::FSUB, VT, N0,
3599 GetNegatedExpression(N1, DAG, AfterLegalize));
3600 // fold ((-A) + B) -> B-A
3601 if (isNegatibleForFree(N0, AfterLegalize) == 2)
3602 return DAG.getNode(ISD::FSUB, VT, N1,
3603 GetNegatedExpression(N0, DAG, AfterLegalize));
3605 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3606 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3607 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3608 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3609 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3614 SDOperand DAGCombiner::visitFSUB(SDNode *N) {
3615 SDOperand N0 = N->getOperand(0);
3616 SDOperand N1 = N->getOperand(1);
3617 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3618 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3619 MVT::ValueType VT = N->getValueType(0);
3622 if (MVT::isVector(VT)) {
3623 SDOperand FoldedVOp = SimplifyVBinOp(N);
3624 if (FoldedVOp.Val) return FoldedVOp;
3627 // fold (fsub c1, c2) -> c1-c2
3628 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3629 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3631 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
3632 if (isNegatibleForFree(N1, AfterLegalize))
3633 return GetNegatedExpression(N1, DAG, AfterLegalize);
3634 return DAG.getNode(ISD::FNEG, VT, N1);
3636 // fold (A-(-B)) -> A+B
3637 if (isNegatibleForFree(N1, AfterLegalize))
3638 return DAG.getNode(ISD::FADD, VT, N0,
3639 GetNegatedExpression(N1, DAG, AfterLegalize));
3644 SDOperand DAGCombiner::visitFMUL(SDNode *N) {
3645 SDOperand N0 = N->getOperand(0);
3646 SDOperand N1 = N->getOperand(1);
3647 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3648 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3649 MVT::ValueType VT = N->getValueType(0);
3652 if (MVT::isVector(VT)) {
3653 SDOperand FoldedVOp = SimplifyVBinOp(N);
3654 if (FoldedVOp.Val) return FoldedVOp;
3657 // fold (fmul c1, c2) -> c1*c2
3658 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3659 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3660 // canonicalize constant to RHS
3661 if (N0CFP && !N1CFP)
3662 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3663 // fold (fmul X, 2.0) -> (fadd X, X)
3664 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3665 return DAG.getNode(ISD::FADD, VT, N0, N0);
3666 // fold (fmul X, -1.0) -> (fneg X)
3667 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3668 return DAG.getNode(ISD::FNEG, VT, N0);
3671 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3672 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3673 // Both can be negated for free, check to see if at least one is cheaper
3675 if (LHSNeg == 2 || RHSNeg == 2)
3676 return DAG.getNode(ISD::FMUL, VT,
3677 GetNegatedExpression(N0, DAG, AfterLegalize),
3678 GetNegatedExpression(N1, DAG, AfterLegalize));
3682 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3683 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3684 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3685 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3686 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3691 SDOperand DAGCombiner::visitFDIV(SDNode *N) {
3692 SDOperand N0 = N->getOperand(0);
3693 SDOperand N1 = N->getOperand(1);
3694 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3695 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3696 MVT::ValueType VT = N->getValueType(0);
3699 if (MVT::isVector(VT)) {
3700 SDOperand FoldedVOp = SimplifyVBinOp(N);
3701 if (FoldedVOp.Val) return FoldedVOp;
3704 // fold (fdiv c1, c2) -> c1/c2
3705 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3706 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3710 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3711 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3712 // Both can be negated for free, check to see if at least one is cheaper
3714 if (LHSNeg == 2 || RHSNeg == 2)
3715 return DAG.getNode(ISD::FDIV, VT,
3716 GetNegatedExpression(N0, DAG, AfterLegalize),
3717 GetNegatedExpression(N1, DAG, AfterLegalize));
3724 SDOperand DAGCombiner::visitFREM(SDNode *N) {
3725 SDOperand N0 = N->getOperand(0);
3726 SDOperand N1 = N->getOperand(1);
3727 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3728 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3729 MVT::ValueType VT = N->getValueType(0);
3731 // fold (frem c1, c2) -> fmod(c1,c2)
3732 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3733 return DAG.getNode(ISD::FREM, VT, N0, N1);
3738 SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3739 SDOperand N0 = N->getOperand(0);
3740 SDOperand N1 = N->getOperand(1);
3741 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3742 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3743 MVT::ValueType VT = N->getValueType(0);
3745 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
3746 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3749 const APFloat& V = N1CFP->getValueAPF();
3750 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3751 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
3752 if (!V.isNegative())
3753 return DAG.getNode(ISD::FABS, VT, N0);
3755 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3758 // copysign(fabs(x), y) -> copysign(x, y)
3759 // copysign(fneg(x), y) -> copysign(x, y)
3760 // copysign(copysign(x,z), y) -> copysign(x, y)
3761 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3762 N0.getOpcode() == ISD::FCOPYSIGN)
3763 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3765 // copysign(x, abs(y)) -> abs(x)
3766 if (N1.getOpcode() == ISD::FABS)
3767 return DAG.getNode(ISD::FABS, VT, N0);
3769 // copysign(x, copysign(y,z)) -> copysign(x, z)
3770 if (N1.getOpcode() == ISD::FCOPYSIGN)
3771 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3773 // copysign(x, fp_extend(y)) -> copysign(x, y)
3774 // copysign(x, fp_round(y)) -> copysign(x, y)
3775 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3776 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3783 SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3784 SDOperand N0 = N->getOperand(0);
3785 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3786 MVT::ValueType VT = N->getValueType(0);
3788 // fold (sint_to_fp c1) -> c1fp
3789 if (N0C && N0.getValueType() != MVT::ppcf128)
3790 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3794 SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3795 SDOperand N0 = N->getOperand(0);
3796 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3797 MVT::ValueType VT = N->getValueType(0);
3799 // fold (uint_to_fp c1) -> c1fp
3800 if (N0C && N0.getValueType() != MVT::ppcf128)
3801 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3805 SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3806 SDOperand N0 = N->getOperand(0);
3807 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3808 MVT::ValueType VT = N->getValueType(0);
3810 // fold (fp_to_sint c1fp) -> c1
3812 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3816 SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3817 SDOperand N0 = N->getOperand(0);
3818 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3819 MVT::ValueType VT = N->getValueType(0);
3821 // fold (fp_to_uint c1fp) -> c1
3822 if (N0CFP && VT != MVT::ppcf128)
3823 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3827 SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
3828 SDOperand N0 = N->getOperand(0);
3829 SDOperand N1 = N->getOperand(1);
3830 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3831 MVT::ValueType VT = N->getValueType(0);
3833 // fold (fp_round c1fp) -> c1fp
3834 if (N0CFP && N0.getValueType() != MVT::ppcf128)
3835 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
3837 // fold (fp_round (fp_extend x)) -> x
3838 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3839 return N0.getOperand(0);
3841 // fold (fp_round (fp_round x)) -> (fp_round x)
3842 if (N0.getOpcode() == ISD::FP_ROUND) {
3843 // This is a value preserving truncation if both round's are.
3844 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
3845 N0.Val->getConstantOperandVal(1) == 1;
3846 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
3847 DAG.getIntPtrConstant(IsTrunc));
3850 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3851 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
3852 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
3853 AddToWorkList(Tmp.Val);
3854 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
3860 SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
3861 SDOperand N0 = N->getOperand(0);
3862 MVT::ValueType VT = N->getValueType(0);
3863 MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3864 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3866 // fold (fp_round_inreg c1fp) -> c1fp
3868 SDOperand Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT);
3869 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
3874 SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
3875 SDOperand N0 = N->getOperand(0);
3876 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3877 MVT::ValueType VT = N->getValueType(0);
3879 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
3880 if (N->hasOneUse() && (*N->use_begin())->getOpcode() == ISD::FP_ROUND)
3883 // fold (fp_extend c1fp) -> c1fp
3884 if (N0CFP && VT != MVT::ppcf128)
3885 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
3887 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
3889 if (N0.getOpcode() == ISD::FP_ROUND && N0.Val->getConstantOperandVal(1) == 1){
3890 SDOperand In = N0.getOperand(0);
3891 if (In.getValueType() == VT) return In;
3892 if (VT < In.getValueType())
3893 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
3894 return DAG.getNode(ISD::FP_EXTEND, VT, In);
3897 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
3898 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3899 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3900 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3901 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3902 LN0->getBasePtr(), LN0->getSrcValue(),
3903 LN0->getSrcValueOffset(),
3906 LN0->getAlignment());
3907 CombineTo(N, ExtLoad);
3908 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad,
3909 DAG.getIntPtrConstant(1)),
3910 ExtLoad.getValue(1));
3911 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3918 SDOperand DAGCombiner::visitFNEG(SDNode *N) {
3919 SDOperand N0 = N->getOperand(0);
3921 if (isNegatibleForFree(N0, AfterLegalize))
3922 return GetNegatedExpression(N0, DAG, AfterLegalize);
3924 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
3925 // constant pool values.
3926 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
3927 MVT::isInteger(N0.getOperand(0).getValueType()) &&
3928 !MVT::isVector(N0.getOperand(0).getValueType())) {
3929 SDOperand Int = N0.getOperand(0);
3930 MVT::ValueType IntVT = Int.getValueType();
3931 if (MVT::isInteger(IntVT) && !MVT::isVector(IntVT)) {
3932 Int = DAG.getNode(ISD::XOR, IntVT, Int,
3933 DAG.getConstant(MVT::getIntVTSignBit(IntVT), IntVT));
3934 AddToWorkList(Int.Val);
3935 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
3942 SDOperand DAGCombiner::visitFABS(SDNode *N) {
3943 SDOperand N0 = N->getOperand(0);
3944 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3945 MVT::ValueType VT = N->getValueType(0);
3947 // fold (fabs c1) -> fabs(c1)
3948 if (N0CFP && VT != MVT::ppcf128)
3949 return DAG.getNode(ISD::FABS, VT, N0);
3950 // fold (fabs (fabs x)) -> (fabs x)
3951 if (N0.getOpcode() == ISD::FABS)
3952 return N->getOperand(0);
3953 // fold (fabs (fneg x)) -> (fabs x)
3954 // fold (fabs (fcopysign x, y)) -> (fabs x)
3955 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
3956 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
3958 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
3959 // constant pool values.
3960 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
3961 MVT::isInteger(N0.getOperand(0).getValueType()) &&
3962 !MVT::isVector(N0.getOperand(0).getValueType())) {
3963 SDOperand Int = N0.getOperand(0);
3964 MVT::ValueType IntVT = Int.getValueType();
3965 if (MVT::isInteger(IntVT) && !MVT::isVector(IntVT)) {
3966 Int = DAG.getNode(ISD::AND, IntVT, Int,
3967 DAG.getConstant(~MVT::getIntVTSignBit(IntVT), IntVT));
3968 AddToWorkList(Int.Val);
3969 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
3976 SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
3977 SDOperand Chain = N->getOperand(0);
3978 SDOperand N1 = N->getOperand(1);
3979 SDOperand N2 = N->getOperand(2);
3980 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3982 // never taken branch, fold to chain
3983 if (N1C && N1C->isNullValue())
3985 // unconditional branch
3986 if (N1C && N1C->getAPIntValue() == 1)
3987 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
3988 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
3990 if (N1.getOpcode() == ISD::SETCC &&
3991 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
3992 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
3993 N1.getOperand(0), N1.getOperand(1), N2);
3998 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4000 SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
4001 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4002 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4004 // Use SimplifySetCC to simplify SETCC's.
4005 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
4006 if (Simp.Val) AddToWorkList(Simp.Val);
4008 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
4010 // fold br_cc true, dest -> br dest (unconditional branch)
4011 if (SCCC && !SCCC->isNullValue())
4012 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
4014 // fold br_cc false, dest -> unconditional fall through
4015 if (SCCC && SCCC->isNullValue())
4016 return N->getOperand(0);
4018 // fold to a simpler setcc
4019 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
4020 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
4021 Simp.getOperand(2), Simp.getOperand(0),
4022 Simp.getOperand(1), N->getOperand(4));
4027 /// CombineToPreIndexedLoadStore - Try turning a load / store and a
4028 /// pre-indexed load / store when the base pointer is a add or subtract
4029 /// and it has other uses besides the load / store. After the
4030 /// transformation, the new indexed load / store has effectively folded
4031 /// the add / subtract in and all of its other uses are redirected to the
4032 /// new load / store.
4033 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4040 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4041 if (LD->isIndexed())
4043 VT = LD->getMemoryVT();
4044 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4045 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4047 Ptr = LD->getBasePtr();
4048 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4049 if (ST->isIndexed())
4051 VT = ST->getMemoryVT();
4052 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4053 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4055 Ptr = ST->getBasePtr();
4060 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4061 // out. There is no reason to make this a preinc/predec.
4062 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4063 Ptr.Val->hasOneUse())
4066 // Ask the target to do addressing mode selection.
4069 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4070 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4072 // Don't create a indexed load / store with zero offset.
4073 if (isa<ConstantSDNode>(Offset) &&
4074 cast<ConstantSDNode>(Offset)->isNullValue())
4077 // Try turning it into a pre-indexed load / store except when:
4078 // 1) The new base ptr is a frame index.
4079 // 2) If N is a store and the new base ptr is either the same as or is a
4080 // predecessor of the value being stored.
4081 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4082 // that would create a cycle.
4083 // 4) All uses are load / store ops that use it as old base ptr.
4085 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4086 // (plus the implicit offset) to a register to preinc anyway.
4087 if (isa<FrameIndexSDNode>(BasePtr))
4092 SDOperand Val = cast<StoreSDNode>(N)->getValue();
4093 if (Val == BasePtr || BasePtr.Val->isPredecessorOf(Val.Val))
4097 // Now check for #3 and #4.
4098 bool RealUse = false;
4099 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4100 E = Ptr.Val->use_end(); I != E; ++I) {
4104 if (Use->isPredecessorOf(N))
4107 if (!((Use->getOpcode() == ISD::LOAD &&
4108 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
4109 (Use->getOpcode() == ISD::STORE &&
4110 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
4118 Result = DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
4120 Result = DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4123 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
4124 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4126 WorkListRemover DeadNodes(*this);
4128 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4130 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4133 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4137 // Finally, since the node is now dead, remove it from the graph.
4140 // Replace the uses of Ptr with uses of the updated base value.
4141 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
4143 removeFromWorkList(Ptr.Val);
4144 DAG.DeleteNode(Ptr.Val);
4149 /// CombineToPostIndexedLoadStore - Try combine a load / store with a
4150 /// add / sub of the base pointer node into a post-indexed load / store.
4151 /// The transformation folded the add / subtract into the new indexed
4152 /// load / store effectively and all of its uses are redirected to the
4153 /// new load / store.
4154 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4161 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4162 if (LD->isIndexed())
4164 VT = LD->getMemoryVT();
4165 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4166 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4168 Ptr = LD->getBasePtr();
4169 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4170 if (ST->isIndexed())
4172 VT = ST->getMemoryVT();
4173 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4174 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4176 Ptr = ST->getBasePtr();
4181 if (Ptr.Val->hasOneUse())
4184 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4185 E = Ptr.Val->use_end(); I != E; ++I) {
4188 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4193 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4194 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4196 std::swap(BasePtr, Offset);
4199 // Don't create a indexed load / store with zero offset.
4200 if (isa<ConstantSDNode>(Offset) &&
4201 cast<ConstantSDNode>(Offset)->isNullValue())
4204 // Try turning it into a post-indexed load / store except when
4205 // 1) All uses are load / store ops that use it as base ptr.
4206 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4207 // nor a successor of N. Otherwise, if Op is folded that would
4211 bool TryNext = false;
4212 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
4213 EE = BasePtr.Val->use_end(); II != EE; ++II) {
4218 // If all the uses are load / store addresses, then don't do the
4220 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4221 bool RealUse = false;
4222 for (SDNode::use_iterator III = Use->use_begin(),
4223 EEE = Use->use_end(); III != EEE; ++III) {
4224 SDNode *UseUse = *III;
4225 if (!((UseUse->getOpcode() == ISD::LOAD &&
4226 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
4227 (UseUse->getOpcode() == ISD::STORE &&
4228 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use)))
4242 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
4243 SDOperand Result = isLoad
4244 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
4245 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4248 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
4249 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4251 WorkListRemover DeadNodes(*this);
4253 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4255 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4258 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4262 // Finally, since the node is now dead, remove it from the graph.
4265 // Replace the uses of Use with uses of the updated base value.
4266 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
4267 Result.getValue(isLoad ? 1 : 0),
4269 removeFromWorkList(Op);
4278 /// InferAlignment - If we can infer some alignment information from this
4279 /// pointer, return it.
4280 static unsigned InferAlignment(SDOperand Ptr, SelectionDAG &DAG) {
4281 // If this is a direct reference to a stack slot, use information about the
4282 // stack slot's alignment.
4283 int FrameIdx = 1 << 31;
4284 int64_t FrameOffset = 0;
4285 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
4286 FrameIdx = FI->getIndex();
4287 } else if (Ptr.getOpcode() == ISD::ADD &&
4288 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4289 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4290 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4291 FrameOffset = Ptr.getConstantOperandVal(1);
4294 if (FrameIdx != (1 << 31)) {
4295 // FIXME: Handle FI+CST.
4296 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
4297 if (MFI.isFixedObjectIndex(FrameIdx)) {
4298 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx);
4300 // The alignment of the frame index can be determined from its offset from
4301 // the incoming frame position. If the frame object is at offset 32 and
4302 // the stack is guaranteed to be 16-byte aligned, then we know that the
4303 // object is 16-byte aligned.
4304 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
4305 unsigned Align = MinAlign(ObjectOffset, StackAlign);
4307 // Finally, the frame object itself may have a known alignment. Factor
4308 // the alignment + offset into a new alignment. For example, if we know
4309 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
4310 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
4311 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
4312 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
4314 return std::max(Align, FIInfoAlign);
4321 SDOperand DAGCombiner::visitLOAD(SDNode *N) {
4322 LoadSDNode *LD = cast<LoadSDNode>(N);
4323 SDOperand Chain = LD->getChain();
4324 SDOperand Ptr = LD->getBasePtr();
4326 // Try to infer better alignment information than the load already has.
4327 if (LD->isUnindexed()) {
4328 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4329 if (Align > LD->getAlignment())
4330 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
4331 Chain, Ptr, LD->getSrcValue(),
4332 LD->getSrcValueOffset(), LD->getMemoryVT(),
4333 LD->isVolatile(), Align);
4338 // If load is not volatile and there are no uses of the loaded value (and
4339 // the updated indexed value in case of indexed loads), change uses of the
4340 // chain value into uses of the chain input (i.e. delete the dead load).
4341 if (!LD->isVolatile()) {
4342 if (N->getValueType(1) == MVT::Other) {
4344 if (N->hasNUsesOfValue(0, 0)) {
4345 // It's not safe to use the two value CombineTo variant here. e.g.
4346 // v1, chain2 = load chain1, loc
4347 // v2, chain3 = load chain2, loc
4349 // Now we replace use of chain2 with chain1. This makes the second load
4350 // isomorphic to the one we are deleting, and thus makes this load live.
4351 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4352 DOUT << "\nWith chain: "; DEBUG(Chain.Val->dump(&DAG));
4354 WorkListRemover DeadNodes(*this);
4355 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Chain, &DeadNodes);
4356 if (N->use_empty()) {
4357 removeFromWorkList(N);
4360 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4364 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4365 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
4366 SDOperand Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
4367 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4368 DOUT << "\nWith: "; DEBUG(Undef.Val->dump(&DAG));
4369 DOUT << " and 2 other values\n";
4370 WorkListRemover DeadNodes(*this);
4371 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Undef, &DeadNodes);
4372 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
4373 DAG.getNode(ISD::UNDEF, N->getValueType(1)),
4375 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 2), Chain, &DeadNodes);
4376 removeFromWorkList(N);
4378 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4383 // If this load is directly stored, replace the load value with the stored
4385 // TODO: Handle store large -> read small portion.
4386 // TODO: Handle TRUNCSTORE/LOADEXT
4387 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4388 if (ISD::isNON_TRUNCStore(Chain.Val)) {
4389 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4390 if (PrevST->getBasePtr() == Ptr &&
4391 PrevST->getValue().getValueType() == N->getValueType(0))
4392 return CombineTo(N, Chain.getOperand(1), Chain);
4397 // Walk up chain skipping non-aliasing memory nodes.
4398 SDOperand BetterChain = FindBetterChain(N, Chain);
4400 // If there is a better chain.
4401 if (Chain != BetterChain) {
4404 // Replace the chain to void dependency.
4405 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4406 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
4407 LD->getSrcValue(), LD->getSrcValueOffset(),
4408 LD->isVolatile(), LD->getAlignment());
4410 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
4411 LD->getValueType(0),
4412 BetterChain, Ptr, LD->getSrcValue(),
4413 LD->getSrcValueOffset(),
4416 LD->getAlignment());
4419 // Create token factor to keep old chain connected.
4420 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
4421 Chain, ReplLoad.getValue(1));
4423 // Replace uses with load result and token factor. Don't add users
4425 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4429 // Try transforming N to an indexed load.
4430 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4431 return SDOperand(N, 0);
4437 SDOperand DAGCombiner::visitSTORE(SDNode *N) {
4438 StoreSDNode *ST = cast<StoreSDNode>(N);
4439 SDOperand Chain = ST->getChain();
4440 SDOperand Value = ST->getValue();
4441 SDOperand Ptr = ST->getBasePtr();
4443 // Try to infer better alignment information than the store already has.
4444 if (ST->isUnindexed()) {
4445 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4446 if (Align > ST->getAlignment())
4447 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
4448 ST->getSrcValueOffset(), ST->getMemoryVT(),
4449 ST->isVolatile(), Align);
4453 // If this is a store of a bit convert, store the input value if the
4454 // resultant store does not need a higher alignment than the original.
4455 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
4456 ST->isUnindexed()) {
4457 unsigned Align = ST->getAlignment();
4458 MVT::ValueType SVT = Value.getOperand(0).getValueType();
4459 unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
4460 getABITypeAlignment(MVT::getTypeForValueType(SVT));
4461 if (Align <= OrigAlign && TLI.isOperationLegal(ISD::STORE, SVT))
4462 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4463 ST->getSrcValueOffset(), ST->isVolatile(), Align);
4466 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
4467 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
4468 if (Value.getOpcode() != ISD::TargetConstantFP) {
4470 switch (CFP->getValueType(0)) {
4471 default: assert(0 && "Unknown FP type");
4472 case MVT::f80: // We don't do this for these yet.
4477 if (!AfterLegalize || TLI.isTypeLegal(MVT::i32)) {
4478 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
4479 convertToAPInt().getZExtValue(), MVT::i32);
4480 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4481 ST->getSrcValueOffset(), ST->isVolatile(),
4482 ST->getAlignment());
4486 if (!AfterLegalize || TLI.isTypeLegal(MVT::i64)) {
4487 Tmp = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
4488 getZExtValue(), MVT::i64);
4489 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4490 ST->getSrcValueOffset(), ST->isVolatile(),
4491 ST->getAlignment());
4492 } else if (TLI.isTypeLegal(MVT::i32)) {
4493 // Many FP stores are not made apparent until after legalize, e.g. for
4494 // argument passing. Since this is so common, custom legalize the
4495 // 64-bit integer store into two 32-bit stores.
4496 uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue();
4497 SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
4498 SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
4499 if (TLI.isBigEndian()) std::swap(Lo, Hi);
4501 int SVOffset = ST->getSrcValueOffset();
4502 unsigned Alignment = ST->getAlignment();
4503 bool isVolatile = ST->isVolatile();
4505 SDOperand St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4506 ST->getSrcValueOffset(),
4507 isVolatile, ST->getAlignment());
4508 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4509 DAG.getConstant(4, Ptr.getValueType()));
4511 Alignment = MinAlign(Alignment, 4U);
4512 SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4513 SVOffset, isVolatile, Alignment);
4514 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4522 // Walk up chain skipping non-aliasing memory nodes.
4523 SDOperand BetterChain = FindBetterChain(N, Chain);
4525 // If there is a better chain.
4526 if (Chain != BetterChain) {
4527 // Replace the chain to avoid dependency.
4528 SDOperand ReplStore;
4529 if (ST->isTruncatingStore()) {
4530 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
4531 ST->getSrcValue(),ST->getSrcValueOffset(),
4533 ST->isVolatile(), ST->getAlignment());
4535 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
4536 ST->getSrcValue(), ST->getSrcValueOffset(),
4537 ST->isVolatile(), ST->getAlignment());
4540 // Create token to keep both nodes around.
4542 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4544 // Don't add users to work list.
4545 return CombineTo(N, Token, false);
4549 // Try transforming N to an indexed store.
4550 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4551 return SDOperand(N, 0);
4553 // FIXME: is there such a thing as a truncating indexed store?
4554 if (ST->isTruncatingStore() && ST->isUnindexed() &&
4555 MVT::isInteger(Value.getValueType())) {
4556 // See if we can simplify the input to this truncstore with knowledge that
4557 // only the low bits are being used. For example:
4558 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
4560 GetDemandedBits(Value,
4561 APInt::getLowBitsSet(Value.getValueSizeInBits(),
4562 MVT::getSizeInBits(ST->getMemoryVT())));
4563 AddToWorkList(Value.Val);
4565 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
4566 ST->getSrcValueOffset(), ST->getMemoryVT(),
4567 ST->isVolatile(), ST->getAlignment());
4569 // Otherwise, see if we can simplify the operation with
4570 // SimplifyDemandedBits, which only works if the value has a single use.
4571 if (SimplifyDemandedBits(Value,
4572 APInt::getLowBitsSet(
4573 Value.getValueSizeInBits(),
4574 MVT::getSizeInBits(ST->getMemoryVT()))))
4575 return SDOperand(N, 0);
4578 // If this is a load followed by a store to the same location, then the store
4580 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
4581 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
4582 ST->isUnindexed() && !ST->isVolatile() &&
4583 // There can't be any side effects between the load and store, such as
4585 Chain.reachesChainWithoutSideEffects(SDOperand(Ld, 1))) {
4586 // The store is dead, remove it.
4591 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
4592 // truncating store. We can do this even if this is already a truncstore.
4593 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
4594 && TLI.isTypeLegal(Value.getOperand(0).getValueType()) &&
4595 Value.Val->hasOneUse() && ST->isUnindexed() &&
4596 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
4597 ST->getMemoryVT())) {
4598 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4599 ST->getSrcValueOffset(), ST->getMemoryVT(),
4600 ST->isVolatile(), ST->getAlignment());
4606 SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4607 SDOperand InVec = N->getOperand(0);
4608 SDOperand InVal = N->getOperand(1);
4609 SDOperand EltNo = N->getOperand(2);
4611 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4612 // vector with the inserted element.
4613 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4614 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4615 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
4616 if (Elt < Ops.size())
4618 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4619 &Ops[0], Ops.size());
4625 SDOperand DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
4626 SDOperand InVec = N->getOperand(0);
4627 SDOperand EltNo = N->getOperand(1);
4629 // (vextract (v4f32 s2v (f32 load $addr)), 0) -> (f32 load $addr)
4630 // (vextract (v4i32 bc (v4f32 s2v (f32 load $addr))), 0) -> (i32 load $addr)
4631 if (isa<ConstantSDNode>(EltNo)) {
4632 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4633 bool NewLoad = false;
4635 MVT::ValueType VT = InVec.getValueType();
4636 MVT::ValueType EVT = MVT::getVectorElementType(VT);
4637 MVT::ValueType LVT = EVT;
4638 unsigned NumElts = MVT::getVectorNumElements(VT);
4639 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
4640 MVT::ValueType BCVT = InVec.getOperand(0).getValueType();
4641 if (!MVT::isVector(BCVT) ||
4642 NumElts != MVT::getVectorNumElements(BCVT))
4644 InVec = InVec.getOperand(0);
4645 EVT = MVT::getVectorElementType(BCVT);
4648 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4649 InVec.getOperand(0).getValueType() == EVT &&
4650 ISD::isNormalLoad(InVec.getOperand(0).Val) &&
4651 InVec.getOperand(0).hasOneUse()) {
4652 LoadSDNode *LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4653 unsigned Align = LN0->getAlignment();
4655 // Check the resultant load doesn't need a higher alignment than the
4657 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
4658 getABITypeAlignment(MVT::getTypeForValueType(LVT));
4659 if (!TLI.isOperationLegal(ISD::LOAD, LVT) || NewAlign > Align)
4664 return DAG.getLoad(LVT, LN0->getChain(), LN0->getBasePtr(),
4665 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4666 LN0->isVolatile(), Align);
4674 SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4675 unsigned NumInScalars = N->getNumOperands();
4676 MVT::ValueType VT = N->getValueType(0);
4677 unsigned NumElts = MVT::getVectorNumElements(VT);
4678 MVT::ValueType EltType = MVT::getVectorElementType(VT);
4680 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4681 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4682 // at most two distinct vectors, turn this into a shuffle node.
4683 SDOperand VecIn1, VecIn2;
4684 for (unsigned i = 0; i != NumInScalars; ++i) {
4685 // Ignore undef inputs.
4686 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4688 // If this input is something other than a EXTRACT_VECTOR_ELT with a
4689 // constant index, bail out.
4690 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4691 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4692 VecIn1 = VecIn2 = SDOperand(0, 0);
4696 // If the input vector type disagrees with the result of the build_vector,
4697 // we can't make a shuffle.
4698 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
4699 if (ExtractedFromVec.getValueType() != VT) {
4700 VecIn1 = VecIn2 = SDOperand(0, 0);
4704 // Otherwise, remember this. We allow up to two distinct input vectors.
4705 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
4708 if (VecIn1.Val == 0) {
4709 VecIn1 = ExtractedFromVec;
4710 } else if (VecIn2.Val == 0) {
4711 VecIn2 = ExtractedFromVec;
4714 VecIn1 = VecIn2 = SDOperand(0, 0);
4719 // If everything is good, we can make a shuffle operation.
4721 SmallVector<SDOperand, 8> BuildVecIndices;
4722 for (unsigned i = 0; i != NumInScalars; ++i) {
4723 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
4724 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
4728 SDOperand Extract = N->getOperand(i);
4730 // If extracting from the first vector, just use the index directly.
4731 if (Extract.getOperand(0) == VecIn1) {
4732 BuildVecIndices.push_back(Extract.getOperand(1));
4736 // Otherwise, use InIdx + VecSize
4737 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
4738 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
4741 // Add count and size info.
4742 MVT::ValueType BuildVecVT = MVT::getVectorType(TLI.getPointerTy(), NumElts);
4744 // Return the new VECTOR_SHUFFLE node.
4750 // Use an undef build_vector as input for the second operand.
4751 std::vector<SDOperand> UnOps(NumInScalars,
4752 DAG.getNode(ISD::UNDEF,
4754 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
4755 &UnOps[0], UnOps.size());
4756 AddToWorkList(Ops[1].Val);
4758 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
4759 &BuildVecIndices[0], BuildVecIndices.size());
4760 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
4766 SDOperand DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
4767 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
4768 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
4769 // inputs come from at most two distinct vectors, turn this into a shuffle
4772 // If we only have one input vector, we don't need to do any concatenation.
4773 if (N->getNumOperands() == 1) {
4774 return N->getOperand(0);
4780 SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
4781 SDOperand ShufMask = N->getOperand(2);
4782 unsigned NumElts = ShufMask.getNumOperands();
4784 // If the shuffle mask is an identity operation on the LHS, return the LHS.
4785 bool isIdentity = true;
4786 for (unsigned i = 0; i != NumElts; ++i) {
4787 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4788 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
4793 if (isIdentity) return N->getOperand(0);
4795 // If the shuffle mask is an identity operation on the RHS, return the RHS.
4797 for (unsigned i = 0; i != NumElts; ++i) {
4798 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4799 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
4804 if (isIdentity) return N->getOperand(1);
4806 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
4808 bool isUnary = true;
4809 bool isSplat = true;
4811 unsigned BaseIdx = 0;
4812 for (unsigned i = 0; i != NumElts; ++i)
4813 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
4814 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
4815 int V = (Idx < NumElts) ? 0 : 1;
4829 SDOperand N0 = N->getOperand(0);
4830 SDOperand N1 = N->getOperand(1);
4831 // Normalize unary shuffle so the RHS is undef.
4832 if (isUnary && VecNum == 1)
4835 // If it is a splat, check if the argument vector is a build_vector with
4836 // all scalar elements the same.
4840 // If this is a bit convert that changes the element type of the vector but
4841 // not the number of vector elements, look through it. Be careful not to
4842 // look though conversions that change things like v4f32 to v2f64.
4843 if (V->getOpcode() == ISD::BIT_CONVERT) {
4844 SDOperand ConvInput = V->getOperand(0);
4845 if (MVT::getVectorNumElements(ConvInput.getValueType()) == NumElts)
4849 if (V->getOpcode() == ISD::BUILD_VECTOR) {
4850 unsigned NumElems = V->getNumOperands();
4851 if (NumElems > BaseIdx) {
4853 bool AllSame = true;
4854 for (unsigned i = 0; i != NumElems; ++i) {
4855 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
4856 Base = V->getOperand(i);
4860 // Splat of <u, u, u, u>, return <u, u, u, u>
4863 for (unsigned i = 0; i != NumElems; ++i) {
4864 if (V->getOperand(i) != Base) {
4869 // Splat of <x, x, x, x>, return <x, x, x, x>
4876 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
4878 if (isUnary || N0 == N1) {
4879 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
4881 SmallVector<SDOperand, 8> MappedOps;
4882 for (unsigned i = 0; i != NumElts; ++i) {
4883 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
4884 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
4885 MappedOps.push_back(ShufMask.getOperand(i));
4888 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
4889 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
4892 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
4893 &MappedOps[0], MappedOps.size());
4894 AddToWorkList(ShufMask.Val);
4895 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
4897 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
4904 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
4905 /// an AND to a vector_shuffle with the destination vector and a zero vector.
4906 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
4907 /// vector_shuffle V, Zero, <0, 4, 2, 4>
4908 SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
4909 SDOperand LHS = N->getOperand(0);
4910 SDOperand RHS = N->getOperand(1);
4911 if (N->getOpcode() == ISD::AND) {
4912 if (RHS.getOpcode() == ISD::BIT_CONVERT)
4913 RHS = RHS.getOperand(0);
4914 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
4915 std::vector<SDOperand> IdxOps;
4916 unsigned NumOps = RHS.getNumOperands();
4917 unsigned NumElts = NumOps;
4918 MVT::ValueType EVT = MVT::getVectorElementType(RHS.getValueType());
4919 for (unsigned i = 0; i != NumElts; ++i) {
4920 SDOperand Elt = RHS.getOperand(i);
4921 if (!isa<ConstantSDNode>(Elt))
4923 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
4924 IdxOps.push_back(DAG.getConstant(i, EVT));
4925 else if (cast<ConstantSDNode>(Elt)->isNullValue())
4926 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
4931 // Let's see if the target supports this vector_shuffle.
4932 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
4935 // Return the new VECTOR_SHUFFLE node.
4936 MVT::ValueType VT = MVT::getVectorType(EVT, NumElts);
4937 std::vector<SDOperand> Ops;
4938 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
4940 AddToWorkList(LHS.Val);
4941 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
4942 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4943 &ZeroOps[0], ZeroOps.size()));
4944 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4945 &IdxOps[0], IdxOps.size()));
4946 SDOperand Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
4947 &Ops[0], Ops.size());
4948 if (VT != LHS.getValueType()) {
4949 Result = DAG.getNode(ISD::BIT_CONVERT, LHS.getValueType(), Result);
4957 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
4958 SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
4959 // After legalize, the target may be depending on adds and other
4960 // binary ops to provide legal ways to construct constants or other
4961 // things. Simplifying them may result in a loss of legality.
4962 if (AfterLegalize) return SDOperand();
4964 MVT::ValueType VT = N->getValueType(0);
4965 assert(MVT::isVector(VT) && "SimplifyVBinOp only works on vectors!");
4967 MVT::ValueType EltType = MVT::getVectorElementType(VT);
4968 SDOperand LHS = N->getOperand(0);
4969 SDOperand RHS = N->getOperand(1);
4970 SDOperand Shuffle = XformToShuffleWithZero(N);
4971 if (Shuffle.Val) return Shuffle;
4973 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
4975 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
4976 RHS.getOpcode() == ISD::BUILD_VECTOR) {
4977 SmallVector<SDOperand, 8> Ops;
4978 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
4979 SDOperand LHSOp = LHS.getOperand(i);
4980 SDOperand RHSOp = RHS.getOperand(i);
4981 // If these two elements can't be folded, bail out.
4982 if ((LHSOp.getOpcode() != ISD::UNDEF &&
4983 LHSOp.getOpcode() != ISD::Constant &&
4984 LHSOp.getOpcode() != ISD::ConstantFP) ||
4985 (RHSOp.getOpcode() != ISD::UNDEF &&
4986 RHSOp.getOpcode() != ISD::Constant &&
4987 RHSOp.getOpcode() != ISD::ConstantFP))
4989 // Can't fold divide by zero.
4990 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
4991 N->getOpcode() == ISD::FDIV) {
4992 if ((RHSOp.getOpcode() == ISD::Constant &&
4993 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
4994 (RHSOp.getOpcode() == ISD::ConstantFP &&
4995 cast<ConstantFPSDNode>(RHSOp.Val)->getValueAPF().isZero()))
4998 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
4999 AddToWorkList(Ops.back().Val);
5000 assert((Ops.back().getOpcode() == ISD::UNDEF ||
5001 Ops.back().getOpcode() == ISD::Constant ||
5002 Ops.back().getOpcode() == ISD::ConstantFP) &&
5003 "Scalar binop didn't fold!");
5006 if (Ops.size() == LHS.getNumOperands()) {
5007 MVT::ValueType VT = LHS.getValueType();
5008 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
5015 SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
5016 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
5018 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
5019 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5020 // If we got a simplified select_cc node back from SimplifySelectCC, then
5021 // break it down into a new SETCC node, and a new SELECT node, and then return
5022 // the SELECT node, since we were called with a SELECT node.
5024 // Check to see if we got a select_cc back (to turn into setcc/select).
5025 // Otherwise, just return whatever node we got back, like fabs.
5026 if (SCC.getOpcode() == ISD::SELECT_CC) {
5027 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
5028 SCC.getOperand(0), SCC.getOperand(1),
5030 AddToWorkList(SETCC.Val);
5031 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
5032 SCC.getOperand(3), SETCC);
5039 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5040 /// are the two values being selected between, see if we can simplify the
5041 /// select. Callers of this should assume that TheSelect is deleted if this
5042 /// returns true. As such, they should return the appropriate thing (e.g. the
5043 /// node) back to the top-level of the DAG combiner loop to avoid it being
5046 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
5049 // If this is a select from two identical things, try to pull the operation
5050 // through the select.
5051 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5052 // If this is a load and the token chain is identical, replace the select
5053 // of two loads with a load through a select of the address to load from.
5054 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5055 // constants have been dropped into the constant pool.
5056 if (LHS.getOpcode() == ISD::LOAD &&
5057 // Token chains must be identical.
5058 LHS.getOperand(0) == RHS.getOperand(0)) {
5059 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5060 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5062 // If this is an EXTLOAD, the VT's must match.
5063 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
5064 // FIXME: this conflates two src values, discarding one. This is not
5065 // the right thing to do, but nothing uses srcvalues now. When they do,
5066 // turn SrcValue into a list of locations.
5068 if (TheSelect->getOpcode() == ISD::SELECT) {
5069 // Check that the condition doesn't reach either load. If so, folding
5070 // this will induce a cycle into the DAG.
5071 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5072 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val)) {
5073 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
5074 TheSelect->getOperand(0), LLD->getBasePtr(),
5078 // Check that the condition doesn't reach either load. If so, folding
5079 // this will induce a cycle into the DAG.
5080 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5081 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5082 !LLD->isPredecessorOf(TheSelect->getOperand(1).Val) &&
5083 !RLD->isPredecessorOf(TheSelect->getOperand(1).Val)) {
5084 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
5085 TheSelect->getOperand(0),
5086 TheSelect->getOperand(1),
5087 LLD->getBasePtr(), RLD->getBasePtr(),
5088 TheSelect->getOperand(4));
5094 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
5095 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
5096 Addr,LLD->getSrcValue(),
5097 LLD->getSrcValueOffset(),
5099 LLD->getAlignment());
5101 Load = DAG.getExtLoad(LLD->getExtensionType(),
5102 TheSelect->getValueType(0),
5103 LLD->getChain(), Addr, LLD->getSrcValue(),
5104 LLD->getSrcValueOffset(),
5107 LLD->getAlignment());
5109 // Users of the select now use the result of the load.
5110 CombineTo(TheSelect, Load);
5112 // Users of the old loads now use the new load's chain. We know the
5113 // old-load value is dead now.
5114 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
5115 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
5125 SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
5126 SDOperand N2, SDOperand N3,
5127 ISD::CondCode CC, bool NotExtCompare) {
5129 MVT::ValueType VT = N2.getValueType();
5130 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
5131 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
5132 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
5134 // Determine if the condition we're dealing with is constant
5135 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
5136 if (SCC.Val) AddToWorkList(SCC.Val);
5137 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
5139 // fold select_cc true, x, y -> x
5140 if (SCCC && !SCCC->isNullValue())
5142 // fold select_cc false, x, y -> y
5143 if (SCCC && SCCC->isNullValue())
5146 // Check to see if we can simplify the select into an fabs node
5147 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5148 // Allow either -0.0 or 0.0
5149 if (CFP->getValueAPF().isZero()) {
5150 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5151 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5152 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5153 N2 == N3.getOperand(0))
5154 return DAG.getNode(ISD::FABS, VT, N0);
5156 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5157 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5158 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5159 N2.getOperand(0) == N3)
5160 return DAG.getNode(ISD::FABS, VT, N3);
5164 // Check to see if we can perform the "gzip trick", transforming
5165 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
5166 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5167 MVT::isInteger(N0.getValueType()) &&
5168 MVT::isInteger(N2.getValueType()) &&
5169 (N1C->isNullValue() || // (a < 0) ? b : 0
5170 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
5171 MVT::ValueType XType = N0.getValueType();
5172 MVT::ValueType AType = N2.getValueType();
5173 if (XType >= AType) {
5174 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5175 // single-bit constant.
5176 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
5177 unsigned ShCtV = N2C->getAPIntValue().logBase2();
5178 ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
5179 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
5180 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
5181 AddToWorkList(Shift.Val);
5182 if (XType > AType) {
5183 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5184 AddToWorkList(Shift.Val);
5186 return DAG.getNode(ISD::AND, AType, Shift, N2);
5188 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5189 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5190 TLI.getShiftAmountTy()));
5191 AddToWorkList(Shift.Val);
5192 if (XType > AType) {
5193 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5194 AddToWorkList(Shift.Val);
5196 return DAG.getNode(ISD::AND, AType, Shift, N2);
5200 // fold select C, 16, 0 -> shl C, 4
5201 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
5202 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
5204 // If the caller doesn't want us to simplify this into a zext of a compare,
5206 if (NotExtCompare && N2C->getAPIntValue() == 1)
5209 // Get a SetCC of the condition
5210 // FIXME: Should probably make sure that setcc is legal if we ever have a
5211 // target where it isn't.
5212 SDOperand Temp, SCC;
5213 // cast from setcc result type to select result type
5214 if (AfterLegalize) {
5215 SCC = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5216 if (N2.getValueType() < SCC.getValueType())
5217 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
5219 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5221 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
5222 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5224 AddToWorkList(SCC.Val);
5225 AddToWorkList(Temp.Val);
5227 if (N2C->getAPIntValue() == 1)
5229 // shl setcc result by log2 n2c
5230 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
5231 DAG.getConstant(N2C->getAPIntValue().logBase2(),
5232 TLI.getShiftAmountTy()));
5235 // Check to see if this is the equivalent of setcc
5236 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5237 // otherwise, go ahead with the folds.
5238 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
5239 MVT::ValueType XType = N0.getValueType();
5240 if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(N0))) {
5241 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5242 if (Res.getValueType() != VT)
5243 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
5247 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
5248 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5249 TLI.isOperationLegal(ISD::CTLZ, XType)) {
5250 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
5251 return DAG.getNode(ISD::SRL, XType, Ctlz,
5252 DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
5253 TLI.getShiftAmountTy()));
5255 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
5256 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5257 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
5259 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
5260 DAG.getConstant(~0ULL, XType));
5261 return DAG.getNode(ISD::SRL, XType,
5262 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
5263 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5264 TLI.getShiftAmountTy()));
5266 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
5267 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5268 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
5269 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5270 TLI.getShiftAmountTy()));
5271 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
5275 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5276 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5277 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5278 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5279 N2.getOperand(0) == N1 && MVT::isInteger(N0.getValueType())) {
5280 MVT::ValueType XType = N0.getValueType();
5281 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5282 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5283 TLI.getShiftAmountTy()));
5284 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5285 AddToWorkList(Shift.Val);
5286 AddToWorkList(Add.Val);
5287 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5289 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5290 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5291 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5292 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5293 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5294 MVT::ValueType XType = N0.getValueType();
5295 if (SubC->isNullValue() && MVT::isInteger(XType)) {
5296 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5297 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5298 TLI.getShiftAmountTy()));
5299 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5300 AddToWorkList(Shift.Val);
5301 AddToWorkList(Add.Val);
5302 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5310 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
5311 SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
5312 SDOperand N1, ISD::CondCode Cond,
5313 bool foldBooleans) {
5314 TargetLowering::DAGCombinerInfo
5315 DagCombineInfo(DAG, !AfterLegalize, false, this);
5316 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
5319 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
5320 /// return a DAG expression to select that will generate the same value by
5321 /// multiplying by a magic number. See:
5322 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5323 SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
5324 std::vector<SDNode*> Built;
5325 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
5327 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5333 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
5334 /// return a DAG expression to select that will generate the same value by
5335 /// multiplying by a magic number. See:
5336 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5337 SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
5338 std::vector<SDNode*> Built;
5339 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
5341 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5347 /// FindBaseOffset - Return true if base is known not to alias with anything
5348 /// but itself. Provides base object and offset as results.
5349 static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
5350 // Assume it is a primitive operation.
5351 Base = Ptr; Offset = 0;
5353 // If it's an adding a simple constant then integrate the offset.
5354 if (Base.getOpcode() == ISD::ADD) {
5355 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
5356 Base = Base.getOperand(0);
5357 Offset += C->getValue();
5361 // If it's any of the following then it can't alias with anything but itself.
5362 return isa<FrameIndexSDNode>(Base) ||
5363 isa<ConstantPoolSDNode>(Base) ||
5364 isa<GlobalAddressSDNode>(Base);
5367 /// isAlias - Return true if there is any possibility that the two addresses
5369 bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
5370 const Value *SrcValue1, int SrcValueOffset1,
5371 SDOperand Ptr2, int64_t Size2,
5372 const Value *SrcValue2, int SrcValueOffset2)
5374 // If they are the same then they must be aliases.
5375 if (Ptr1 == Ptr2) return true;
5377 // Gather base node and offset information.
5378 SDOperand Base1, Base2;
5379 int64_t Offset1, Offset2;
5380 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
5381 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
5383 // If they have a same base address then...
5384 if (Base1 == Base2) {
5385 // Check to see if the addresses overlap.
5386 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
5389 // If we know both bases then they can't alias.
5390 if (KnownBase1 && KnownBase2) return false;
5392 if (CombinerGlobalAA) {
5393 // Use alias analysis information.
5394 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
5395 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
5396 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
5397 AliasAnalysis::AliasResult AAResult =
5398 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
5399 if (AAResult == AliasAnalysis::NoAlias)
5403 // Otherwise we have to assume they alias.
5407 /// FindAliasInfo - Extracts the relevant alias information from the memory
5408 /// node. Returns true if the operand was a load.
5409 bool DAGCombiner::FindAliasInfo(SDNode *N,
5410 SDOperand &Ptr, int64_t &Size,
5411 const Value *&SrcValue, int &SrcValueOffset) {
5412 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5413 Ptr = LD->getBasePtr();
5414 Size = MVT::getSizeInBits(LD->getMemoryVT()) >> 3;
5415 SrcValue = LD->getSrcValue();
5416 SrcValueOffset = LD->getSrcValueOffset();
5418 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5419 Ptr = ST->getBasePtr();
5420 Size = MVT::getSizeInBits(ST->getMemoryVT()) >> 3;
5421 SrcValue = ST->getSrcValue();
5422 SrcValueOffset = ST->getSrcValueOffset();
5424 assert(0 && "FindAliasInfo expected a memory operand");
5430 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
5431 /// looking for aliasing nodes and adding them to the Aliases vector.
5432 void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
5433 SmallVector<SDOperand, 8> &Aliases) {
5434 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
5435 std::set<SDNode *> Visited; // Visited node set.
5437 // Get alias information for node.
5440 const Value *SrcValue;
5442 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
5445 Chains.push_back(OriginalChain);
5447 // Look at each chain and determine if it is an alias. If so, add it to the
5448 // aliases list. If not, then continue up the chain looking for the next
5450 while (!Chains.empty()) {
5451 SDOperand Chain = Chains.back();
5454 // Don't bother if we've been before.
5455 if (Visited.find(Chain.Val) != Visited.end()) continue;
5456 Visited.insert(Chain.Val);
5458 switch (Chain.getOpcode()) {
5459 case ISD::EntryToken:
5460 // Entry token is ideal chain operand, but handled in FindBetterChain.
5465 // Get alias information for Chain.
5468 const Value *OpSrcValue;
5469 int OpSrcValueOffset;
5470 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
5471 OpSrcValue, OpSrcValueOffset);
5473 // If chain is alias then stop here.
5474 if (!(IsLoad && IsOpLoad) &&
5475 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
5476 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
5477 Aliases.push_back(Chain);
5479 // Look further up the chain.
5480 Chains.push_back(Chain.getOperand(0));
5481 // Clean up old chain.
5482 AddToWorkList(Chain.Val);
5487 case ISD::TokenFactor:
5488 // We have to check each of the operands of the token factor, so we queue
5489 // then up. Adding the operands to the queue (stack) in reverse order
5490 // maintains the original order and increases the likelihood that getNode
5491 // will find a matching token factor (CSE.)
5492 for (unsigned n = Chain.getNumOperands(); n;)
5493 Chains.push_back(Chain.getOperand(--n));
5494 // Eliminate the token factor if we can.
5495 AddToWorkList(Chain.Val);
5499 // For all other instructions we will just have to take what we can get.
5500 Aliases.push_back(Chain);
5506 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
5507 /// for a better chain (aliasing node.)
5508 SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
5509 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
5511 // Accumulate all the aliases to this node.
5512 GatherAllAliases(N, OldChain, Aliases);
5514 if (Aliases.size() == 0) {
5515 // If no operands then chain to entry token.
5516 return DAG.getEntryNode();
5517 } else if (Aliases.size() == 1) {
5518 // If a single operand then chain to it. We don't need to revisit it.
5522 // Construct a custom tailored token factor.
5523 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5524 &Aliases[0], Aliases.size());
5526 // Make sure the old chain gets cleaned up.
5527 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
5532 // SelectionDAG::Combine - This is the entry point for the file.
5534 void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
5535 if (!RunningAfterLegalize && ViewDAGCombine1)
5537 if (RunningAfterLegalize && ViewDAGCombine2)
5539 /// run - This is the main entry point to this class.
5541 DAGCombiner(*this, AA).Run(RunningAfterLegalize);