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"
35 STATISTIC(NodesCombined , "Number of dag nodes combined");
36 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
37 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
41 CombinerAA("combiner-alias-analysis", cl::Hidden,
42 cl::desc("Turn on alias analysis during testing"));
45 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
46 cl::desc("Include global information in alias analysis"));
48 //------------------------------ DAGCombiner ---------------------------------//
50 class VISIBILITY_HIDDEN DAGCombiner {
56 // Worklist of all of the nodes that need to be simplified.
57 std::vector<SDNode*> WorkList;
59 // AA - Used for DAG load/store alias analysis.
62 /// AddUsersToWorkList - When an instruction is simplified, add all users of
63 /// the instruction to the work lists because they might get more simplified
66 void AddUsersToWorkList(SDNode *N) {
67 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
72 /// visit - call the node-specific routine that knows how to fold each
73 /// particular type of node.
74 SDValue visit(SDNode *N);
77 /// AddToWorkList - Add to the work list making sure it's instance is at the
78 /// the back (next to be processed.)
79 void AddToWorkList(SDNode *N) {
80 removeFromWorkList(N);
81 WorkList.push_back(N);
84 /// removeFromWorkList - remove all instances of N from the worklist.
86 void removeFromWorkList(SDNode *N) {
87 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
91 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
94 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
95 return CombineTo(N, &Res, 1, AddTo);
98 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
100 SDValue To[] = { Res0, Res1 };
101 return CombineTo(N, To, 2, AddTo);
106 /// SimplifyDemandedBits - Check the specified integer node value to see if
107 /// it can be simplified or if things it uses can be simplified by bit
108 /// propagation. If so, return true.
109 bool SimplifyDemandedBits(SDValue Op) {
110 APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
111 return SimplifyDemandedBits(Op, Demanded);
114 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
116 bool CombineToPreIndexedLoadStore(SDNode *N);
117 bool CombineToPostIndexedLoadStore(SDNode *N);
120 /// combine - call the node-specific routine that knows how to fold each
121 /// particular type of node. If that doesn't do anything, try the
122 /// target-specific DAG combines.
123 SDValue combine(SDNode *N);
125 // Visitation implementation - Implement dag node combining for different
126 // node types. The semantics are as follows:
128 // SDValue.getNode() == 0 - No change was made
129 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
130 // otherwise - N should be replaced by the returned Operand.
132 SDValue visitTokenFactor(SDNode *N);
133 SDValue visitMERGE_VALUES(SDNode *N);
134 SDValue visitADD(SDNode *N);
135 SDValue visitSUB(SDNode *N);
136 SDValue visitADDC(SDNode *N);
137 SDValue visitADDE(SDNode *N);
138 SDValue visitMUL(SDNode *N);
139 SDValue visitSDIV(SDNode *N);
140 SDValue visitUDIV(SDNode *N);
141 SDValue visitSREM(SDNode *N);
142 SDValue visitUREM(SDNode *N);
143 SDValue visitMULHU(SDNode *N);
144 SDValue visitMULHS(SDNode *N);
145 SDValue visitSMUL_LOHI(SDNode *N);
146 SDValue visitUMUL_LOHI(SDNode *N);
147 SDValue visitSDIVREM(SDNode *N);
148 SDValue visitUDIVREM(SDNode *N);
149 SDValue visitAND(SDNode *N);
150 SDValue visitOR(SDNode *N);
151 SDValue visitXOR(SDNode *N);
152 SDValue SimplifyVBinOp(SDNode *N);
153 SDValue visitSHL(SDNode *N);
154 SDValue visitSRA(SDNode *N);
155 SDValue visitSRL(SDNode *N);
156 SDValue visitCTLZ(SDNode *N);
157 SDValue visitCTTZ(SDNode *N);
158 SDValue visitCTPOP(SDNode *N);
159 SDValue visitSELECT(SDNode *N);
160 SDValue visitSELECT_CC(SDNode *N);
161 SDValue visitSETCC(SDNode *N);
162 SDValue visitSIGN_EXTEND(SDNode *N);
163 SDValue visitZERO_EXTEND(SDNode *N);
164 SDValue visitANY_EXTEND(SDNode *N);
165 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
166 SDValue visitTRUNCATE(SDNode *N);
167 SDValue visitBIT_CONVERT(SDNode *N);
168 SDValue visitBUILD_PAIR(SDNode *N);
169 SDValue visitFADD(SDNode *N);
170 SDValue visitFSUB(SDNode *N);
171 SDValue visitFMUL(SDNode *N);
172 SDValue visitFDIV(SDNode *N);
173 SDValue visitFREM(SDNode *N);
174 SDValue visitFCOPYSIGN(SDNode *N);
175 SDValue visitSINT_TO_FP(SDNode *N);
176 SDValue visitUINT_TO_FP(SDNode *N);
177 SDValue visitFP_TO_SINT(SDNode *N);
178 SDValue visitFP_TO_UINT(SDNode *N);
179 SDValue visitFP_ROUND(SDNode *N);
180 SDValue visitFP_ROUND_INREG(SDNode *N);
181 SDValue visitFP_EXTEND(SDNode *N);
182 SDValue visitFNEG(SDNode *N);
183 SDValue visitFABS(SDNode *N);
184 SDValue visitBRCOND(SDNode *N);
185 SDValue visitBR_CC(SDNode *N);
186 SDValue visitLOAD(SDNode *N);
187 SDValue visitSTORE(SDNode *N);
188 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
189 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
190 SDValue visitBUILD_VECTOR(SDNode *N);
191 SDValue visitCONCAT_VECTORS(SDNode *N);
192 SDValue visitVECTOR_SHUFFLE(SDNode *N);
194 SDValue XformToShuffleWithZero(SDNode *N);
195 SDValue ReassociateOps(unsigned Opc, SDValue LHS, SDValue RHS);
197 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
199 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
200 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
201 SDValue SimplifySelect(SDValue N0, SDValue N1, SDValue N2);
202 SDValue SimplifySelectCC(SDValue N0, SDValue N1, SDValue N2,
203 SDValue N3, ISD::CondCode CC,
204 bool NotExtCompare = false);
205 SDValue SimplifySetCC(MVT VT, SDValue N0, SDValue N1,
206 ISD::CondCode Cond, bool foldBooleans = true);
207 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
209 SDValue CombineConsecutiveLoads(SDNode *N, MVT VT);
210 SDValue ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT);
211 SDValue BuildSDIV(SDNode *N);
212 SDValue BuildUDIV(SDNode *N);
213 SDNode *MatchRotate(SDValue LHS, SDValue RHS);
214 SDValue ReduceLoadWidth(SDNode *N);
216 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
218 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
219 /// looking for aliasing nodes and adding them to the Aliases vector.
220 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
221 SmallVector<SDValue, 8> &Aliases);
223 /// isAlias - Return true if there is any possibility that the two addresses
225 bool isAlias(SDValue Ptr1, int64_t Size1,
226 const Value *SrcValue1, int SrcValueOffset1,
227 SDValue Ptr2, int64_t Size2,
228 const Value *SrcValue2, int SrcValueOffset2);
230 /// FindAliasInfo - Extracts the relevant alias information from the memory
231 /// node. Returns true if the operand was a load.
232 bool FindAliasInfo(SDNode *N,
233 SDValue &Ptr, int64_t &Size,
234 const Value *&SrcValue, int &SrcValueOffset);
236 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
237 /// looking for a better chain (aliasing node.)
238 SDValue FindBetterChain(SDNode *N, SDValue Chain);
241 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, bool fast)
243 TLI(D.getTargetLoweringInfo()),
244 AfterLegalize(false),
248 /// Run - runs the dag combiner on all nodes in the work list
249 void Run(bool RunningAfterLegalize);
255 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
256 /// nodes from the worklist.
257 class VISIBILITY_HIDDEN WorkListRemover :
258 public SelectionDAG::DAGUpdateListener {
261 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
263 virtual void NodeDeleted(SDNode *N, SDNode *E) {
264 DC.removeFromWorkList(N);
267 virtual void NodeUpdated(SDNode *N) {
273 //===----------------------------------------------------------------------===//
274 // TargetLowering::DAGCombinerInfo implementation
275 //===----------------------------------------------------------------------===//
277 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
278 ((DAGCombiner*)DC)->AddToWorkList(N);
281 SDValue TargetLowering::DAGCombinerInfo::
282 CombineTo(SDNode *N, const std::vector<SDValue> &To) {
283 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
286 SDValue TargetLowering::DAGCombinerInfo::
287 CombineTo(SDNode *N, SDValue Res) {
288 return ((DAGCombiner*)DC)->CombineTo(N, Res);
292 SDValue TargetLowering::DAGCombinerInfo::
293 CombineTo(SDNode *N, SDValue Res0, SDValue Res1) {
294 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
298 //===----------------------------------------------------------------------===//
300 //===----------------------------------------------------------------------===//
302 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
303 /// specified expression for the same cost as the expression itself, or 2 if we
304 /// can compute the negated form more cheaply than the expression itself.
305 static char isNegatibleForFree(SDValue Op, bool AfterLegalize,
306 unsigned Depth = 0) {
307 // No compile time optimizations on this type.
308 if (Op.getValueType() == MVT::ppcf128)
311 // fneg is removable even if it has multiple uses.
312 if (Op.getOpcode() == ISD::FNEG) return 2;
314 // Don't allow anything with multiple uses.
315 if (!Op.hasOneUse()) return 0;
317 // Don't recurse exponentially.
318 if (Depth > 6) return 0;
320 switch (Op.getOpcode()) {
321 default: return false;
322 case ISD::ConstantFP:
323 // Don't invert constant FP values after legalize. The negated constant
324 // isn't necessarily legal.
325 return AfterLegalize ? 0 : 1;
327 // FIXME: determine better conditions for this xform.
328 if (!UnsafeFPMath) return 0;
331 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
334 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
336 // We can't turn -(A-B) into B-A when we honor signed zeros.
337 if (!UnsafeFPMath) return 0;
344 if (HonorSignDependentRoundingFPMath()) return 0;
346 // -(X*Y) -> (-X * Y) or (X*-Y)
347 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
350 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
355 return isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1);
359 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
360 /// returns the newly negated expression.
361 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
362 bool AfterLegalize, unsigned Depth = 0) {
363 // fneg is removable even if it has multiple uses.
364 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
366 // Don't allow anything with multiple uses.
367 assert(Op.hasOneUse() && "Unknown reuse!");
369 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
370 switch (Op.getOpcode()) {
371 default: assert(0 && "Unknown code");
372 case ISD::ConstantFP: {
373 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
375 return DAG.getConstantFP(V, Op.getValueType());
378 // FIXME: determine better conditions for this xform.
379 assert(UnsafeFPMath);
382 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
383 return DAG.getNode(ISD::FSUB, Op.getValueType(),
384 GetNegatedExpression(Op.getOperand(0), DAG,
385 AfterLegalize, Depth+1),
388 return DAG.getNode(ISD::FSUB, Op.getValueType(),
389 GetNegatedExpression(Op.getOperand(1), DAG,
390 AfterLegalize, Depth+1),
393 // We can't turn -(A-B) into B-A when we honor signed zeros.
394 assert(UnsafeFPMath);
397 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
398 if (N0CFP->getValueAPF().isZero())
399 return Op.getOperand(1);
402 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1),
407 assert(!HonorSignDependentRoundingFPMath());
410 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
411 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
412 GetNegatedExpression(Op.getOperand(0), DAG,
413 AfterLegalize, Depth+1),
417 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
419 GetNegatedExpression(Op.getOperand(1), DAG,
420 AfterLegalize, Depth+1));
424 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
425 GetNegatedExpression(Op.getOperand(0), DAG,
426 AfterLegalize, Depth+1));
428 return DAG.getNode(ISD::FP_ROUND, Op.getValueType(),
429 GetNegatedExpression(Op.getOperand(0), DAG,
430 AfterLegalize, Depth+1),
436 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
437 // that selects between the values 1 and 0, making it equivalent to a setcc.
438 // Also, set the incoming LHS, RHS, and CC references to the appropriate
439 // nodes based on the type of node we are checking. This simplifies life a
440 // bit for the callers.
441 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
443 if (N.getOpcode() == ISD::SETCC) {
444 LHS = N.getOperand(0);
445 RHS = N.getOperand(1);
446 CC = N.getOperand(2);
449 if (N.getOpcode() == ISD::SELECT_CC &&
450 N.getOperand(2).getOpcode() == ISD::Constant &&
451 N.getOperand(3).getOpcode() == ISD::Constant &&
452 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
453 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
454 LHS = N.getOperand(0);
455 RHS = N.getOperand(1);
456 CC = N.getOperand(4);
462 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
463 // one use. If this is true, it allows the users to invert the operation for
464 // free when it is profitable to do so.
465 static bool isOneUseSetCC(SDValue N) {
467 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
472 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDValue N0, SDValue N1){
473 MVT VT = N0.getValueType();
474 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
475 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
476 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
477 if (isa<ConstantSDNode>(N1)) {
478 SDValue OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
479 AddToWorkList(OpNode.getNode());
480 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
481 } else if (N0.hasOneUse()) {
482 SDValue OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
483 AddToWorkList(OpNode.getNode());
484 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
487 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
488 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
489 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
490 if (isa<ConstantSDNode>(N0)) {
491 SDValue OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
492 AddToWorkList(OpNode.getNode());
493 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
494 } else if (N1.hasOneUse()) {
495 SDValue OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
496 AddToWorkList(OpNode.getNode());
497 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
503 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
505 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
507 DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
508 DOUT << "\nWith: "; DEBUG(To[0].getNode()->dump(&DAG));
509 DOUT << " and " << NumTo-1 << " other values\n";
510 WorkListRemover DeadNodes(*this);
511 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
514 // Push the new nodes and any users onto the worklist
515 for (unsigned i = 0, e = NumTo; i != e; ++i) {
516 AddToWorkList(To[i].getNode());
517 AddUsersToWorkList(To[i].getNode());
521 // Nodes can be reintroduced into the worklist. Make sure we do not
522 // process a node that has been replaced.
523 removeFromWorkList(N);
525 // Finally, since the node is now dead, remove it from the graph.
527 return SDValue(N, 0);
530 /// SimplifyDemandedBits - Check the specified integer node value to see if
531 /// it can be simplified or if things it uses can be simplified by bit
532 /// propagation. If so, return true.
533 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
534 TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize);
535 APInt KnownZero, KnownOne;
536 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
540 AddToWorkList(Op.getNode());
542 // Replace the old value with the new one.
544 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.getNode()->dump(&DAG));
545 DOUT << "\nWith: "; DEBUG(TLO.New.getNode()->dump(&DAG));
548 // Replace all uses. If any nodes become isomorphic to other nodes and
549 // are deleted, make sure to remove them from our worklist.
550 WorkListRemover DeadNodes(*this);
551 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
553 // Push the new node and any (possibly new) users onto the worklist.
554 AddToWorkList(TLO.New.getNode());
555 AddUsersToWorkList(TLO.New.getNode());
557 // Finally, if the node is now dead, remove it from the graph. The node
558 // may not be dead if the replacement process recursively simplified to
559 // something else needing this node.
560 if (TLO.Old.getNode()->use_empty()) {
561 removeFromWorkList(TLO.Old.getNode());
563 // If the operands of this node are only used by the node, they will now
564 // be dead. Make sure to visit them first to delete dead nodes early.
565 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
566 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
567 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
569 DAG.DeleteNode(TLO.Old.getNode());
574 //===----------------------------------------------------------------------===//
575 // Main DAG Combiner implementation
576 //===----------------------------------------------------------------------===//
578 void DAGCombiner::Run(bool RunningAfterLegalize) {
579 // set the instance variable, so that the various visit routines may use it.
580 AfterLegalize = RunningAfterLegalize;
582 // Add all the dag nodes to the worklist.
583 WorkList.reserve(DAG.allnodes_size());
584 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
585 E = DAG.allnodes_end(); I != E; ++I)
586 WorkList.push_back(I);
588 // Create a dummy node (which is not added to allnodes), that adds a reference
589 // to the root node, preventing it from being deleted, and tracking any
590 // changes of the root.
591 HandleSDNode Dummy(DAG.getRoot());
593 // The root of the dag may dangle to deleted nodes until the dag combiner is
594 // done. Set it to null to avoid confusion.
595 DAG.setRoot(SDValue());
597 // while the worklist isn't empty, inspect the node on the end of it and
598 // try and combine it.
599 while (!WorkList.empty()) {
600 SDNode *N = WorkList.back();
603 // If N has no uses, it is dead. Make sure to revisit all N's operands once
604 // N is deleted from the DAG, since they too may now be dead or may have a
605 // reduced number of uses, allowing other xforms.
606 if (N->use_empty() && N != &Dummy) {
607 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
608 AddToWorkList(N->getOperand(i).getNode());
614 SDValue RV = combine(N);
616 if (RV.getNode() == 0)
621 // If we get back the same node we passed in, rather than a new node or
622 // zero, we know that the node must have defined multiple values and
623 // CombineTo was used. Since CombineTo takes care of the worklist
624 // mechanics for us, we have no work to do in this case.
625 if (RV.getNode() == N)
628 assert(N->getOpcode() != ISD::DELETED_NODE &&
629 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
630 "Node was deleted but visit returned new node!");
632 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
633 DOUT << "\nWith: "; DEBUG(RV.getNode()->dump(&DAG));
635 WorkListRemover DeadNodes(*this);
636 if (N->getNumValues() == RV.getNode()->getNumValues())
637 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
639 assert(N->getValueType(0) == RV.getValueType() &&
640 N->getNumValues() == 1 && "Type mismatch");
642 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
645 // Push the new node and any users onto the worklist
646 AddToWorkList(RV.getNode());
647 AddUsersToWorkList(RV.getNode());
649 // Add any uses of the old node to the worklist in case this node is the
650 // last one that uses them. They may become dead after this node is
652 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
653 AddToWorkList(N->getOperand(i).getNode());
655 // Nodes can be reintroduced into the worklist. Make sure we do not
656 // process a node that has been replaced.
657 removeFromWorkList(N);
659 // Finally, since the node is now dead, remove it from the graph.
663 // If the root changed (e.g. it was a dead load, update the root).
664 DAG.setRoot(Dummy.getValue());
667 SDValue DAGCombiner::visit(SDNode *N) {
668 switch(N->getOpcode()) {
670 case ISD::TokenFactor: return visitTokenFactor(N);
671 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
672 case ISD::ADD: return visitADD(N);
673 case ISD::SUB: return visitSUB(N);
674 case ISD::ADDC: return visitADDC(N);
675 case ISD::ADDE: return visitADDE(N);
676 case ISD::MUL: return visitMUL(N);
677 case ISD::SDIV: return visitSDIV(N);
678 case ISD::UDIV: return visitUDIV(N);
679 case ISD::SREM: return visitSREM(N);
680 case ISD::UREM: return visitUREM(N);
681 case ISD::MULHU: return visitMULHU(N);
682 case ISD::MULHS: return visitMULHS(N);
683 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
684 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
685 case ISD::SDIVREM: return visitSDIVREM(N);
686 case ISD::UDIVREM: return visitUDIVREM(N);
687 case ISD::AND: return visitAND(N);
688 case ISD::OR: return visitOR(N);
689 case ISD::XOR: return visitXOR(N);
690 case ISD::SHL: return visitSHL(N);
691 case ISD::SRA: return visitSRA(N);
692 case ISD::SRL: return visitSRL(N);
693 case ISD::CTLZ: return visitCTLZ(N);
694 case ISD::CTTZ: return visitCTTZ(N);
695 case ISD::CTPOP: return visitCTPOP(N);
696 case ISD::SELECT: return visitSELECT(N);
697 case ISD::SELECT_CC: return visitSELECT_CC(N);
698 case ISD::SETCC: return visitSETCC(N);
699 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
700 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
701 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
702 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
703 case ISD::TRUNCATE: return visitTRUNCATE(N);
704 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
705 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
706 case ISD::FADD: return visitFADD(N);
707 case ISD::FSUB: return visitFSUB(N);
708 case ISD::FMUL: return visitFMUL(N);
709 case ISD::FDIV: return visitFDIV(N);
710 case ISD::FREM: return visitFREM(N);
711 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
712 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
713 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
714 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
715 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
716 case ISD::FP_ROUND: return visitFP_ROUND(N);
717 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
718 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
719 case ISD::FNEG: return visitFNEG(N);
720 case ISD::FABS: return visitFABS(N);
721 case ISD::BRCOND: return visitBRCOND(N);
722 case ISD::BR_CC: return visitBR_CC(N);
723 case ISD::LOAD: return visitLOAD(N);
724 case ISD::STORE: return visitSTORE(N);
725 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
726 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
727 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
728 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
729 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
734 SDValue DAGCombiner::combine(SDNode *N) {
736 SDValue RV = visit(N);
738 // If nothing happened, try a target-specific DAG combine.
739 if (RV.getNode() == 0) {
740 assert(N->getOpcode() != ISD::DELETED_NODE &&
741 "Node was deleted but visit returned NULL!");
743 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
744 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
746 // Expose the DAG combiner to the target combiner impls.
747 TargetLowering::DAGCombinerInfo
748 DagCombineInfo(DAG, !AfterLegalize, false, this);
750 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
754 // If N is a commutative binary node, try commuting it to enable more
756 if (RV.getNode() == 0 &&
757 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
758 N->getNumValues() == 1) {
759 SDValue N0 = N->getOperand(0);
760 SDValue N1 = N->getOperand(1);
761 // Constant operands are canonicalized to RHS.
762 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
763 SDValue Ops[] = { N1, N0 };
764 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
767 return SDValue(CSENode, 0);
774 /// getInputChainForNode - Given a node, return its input chain if it has one,
775 /// otherwise return a null sd operand.
776 static SDValue getInputChainForNode(SDNode *N) {
777 if (unsigned NumOps = N->getNumOperands()) {
778 if (N->getOperand(0).getValueType() == MVT::Other)
779 return N->getOperand(0);
780 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
781 return N->getOperand(NumOps-1);
782 for (unsigned i = 1; i < NumOps-1; ++i)
783 if (N->getOperand(i).getValueType() == MVT::Other)
784 return N->getOperand(i);
786 return SDValue(0, 0);
789 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
790 // If N has two operands, where one has an input chain equal to the other,
791 // the 'other' chain is redundant.
792 if (N->getNumOperands() == 2) {
793 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
794 return N->getOperand(0);
795 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
796 return N->getOperand(1);
799 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
800 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
801 SmallPtrSet<SDNode*, 16> SeenOps;
802 bool Changed = false; // If we should replace this token factor.
804 // Start out with this token factor.
807 // Iterate through token factors. The TFs grows when new token factors are
809 for (unsigned i = 0; i < TFs.size(); ++i) {
812 // Check each of the operands.
813 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
814 SDValue Op = TF->getOperand(i);
816 switch (Op.getOpcode()) {
817 case ISD::EntryToken:
818 // Entry tokens don't need to be added to the list. They are
823 case ISD::TokenFactor:
824 if ((CombinerAA || Op.hasOneUse()) &&
825 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
826 // Queue up for processing.
827 TFs.push_back(Op.getNode());
828 // Clean up in case the token factor is removed.
829 AddToWorkList(Op.getNode());
836 // Only add if it isn't already in the list.
837 if (SeenOps.insert(Op.getNode()))
848 // If we've change things around then replace token factor.
851 // The entry token is the only possible outcome.
852 Result = DAG.getEntryNode();
854 // New and improved token factor.
855 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
858 // Don't add users to work list.
859 return CombineTo(N, Result, false);
865 /// MERGE_VALUES can always be eliminated.
866 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
867 WorkListRemover DeadNodes(*this);
868 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
869 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
871 removeFromWorkList(N);
873 return SDValue(N, 0); // Return N so it doesn't get rechecked!
878 SDValue combineShlAddConstant(SDValue N0, SDValue N1, SelectionDAG &DAG) {
879 MVT VT = N0.getValueType();
880 SDValue N00 = N0.getOperand(0);
881 SDValue N01 = N0.getOperand(1);
882 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
883 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
884 isa<ConstantSDNode>(N00.getOperand(1))) {
885 N0 = DAG.getNode(ISD::ADD, VT,
886 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
887 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
888 return DAG.getNode(ISD::ADD, VT, N0, N1);
894 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
896 MVT VT = N->getValueType(0);
897 unsigned Opc = N->getOpcode();
898 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
899 SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
900 SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
901 ISD::CondCode CC = ISD::SETCC_INVALID;
903 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
905 SDValue CCOp = Slct.getOperand(0);
906 if (CCOp.getOpcode() == ISD::SETCC)
907 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
910 bool DoXform = false;
912 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
914 if (LHS.getOpcode() == ISD::Constant &&
915 cast<ConstantSDNode>(LHS)->isNullValue())
917 else if (CC != ISD::SETCC_INVALID &&
918 RHS.getOpcode() == ISD::Constant &&
919 cast<ConstantSDNode>(RHS)->isNullValue()) {
921 SDValue Op0 = Slct.getOperand(0);
922 bool isInt = (isSlctCC ? Op0.getValueType() :
923 Op0.getOperand(0).getValueType()).isInteger();
924 CC = ISD::getSetCCInverse(CC, isInt);
930 SDValue Result = DAG.getNode(Opc, VT, OtherOp, RHS);
932 return DAG.getSelectCC(OtherOp, Result,
933 Slct.getOperand(0), Slct.getOperand(1), CC);
934 SDValue CCOp = Slct.getOperand(0);
936 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
937 CCOp.getOperand(1), CC);
938 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
943 SDValue DAGCombiner::visitADD(SDNode *N) {
944 SDValue N0 = N->getOperand(0);
945 SDValue N1 = N->getOperand(1);
946 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
947 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
948 MVT VT = N0.getValueType();
952 SDValue FoldedVOp = SimplifyVBinOp(N);
953 if (FoldedVOp.getNode()) return FoldedVOp;
956 // fold (add x, undef) -> undef
957 if (N0.getOpcode() == ISD::UNDEF)
959 if (N1.getOpcode() == ISD::UNDEF)
961 // fold (add c1, c2) -> c1+c2
963 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
964 // canonicalize constant to RHS
966 return DAG.getNode(ISD::ADD, VT, N1, N0);
967 // fold (add x, 0) -> x
968 if (N1C && N1C->isNullValue())
970 // fold ((c1-A)+c2) -> (c1+c2)-A
971 if (N1C && N0.getOpcode() == ISD::SUB)
972 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
973 return DAG.getNode(ISD::SUB, VT,
974 DAG.getConstant(N1C->getAPIntValue()+
975 N0C->getAPIntValue(), VT),
978 SDValue RADD = ReassociateOps(ISD::ADD, N0, N1);
979 if (RADD.getNode() != 0)
981 // fold ((0-A) + B) -> B-A
982 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
983 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
984 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
985 // fold (A + (0-B)) -> A-B
986 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
987 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
988 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
989 // fold (A+(B-A)) -> B
990 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
991 return N1.getOperand(0);
993 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
994 return SDValue(N, 0);
996 // fold (a+b) -> (a|b) iff a and b share no bits.
997 if (VT.isInteger() && !VT.isVector()) {
998 APInt LHSZero, LHSOne;
999 APInt RHSZero, RHSOne;
1000 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1001 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1002 if (LHSZero.getBoolValue()) {
1003 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1005 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1006 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1007 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1008 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1009 return DAG.getNode(ISD::OR, VT, N0, N1);
1013 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1014 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1015 SDValue Result = combineShlAddConstant(N0, N1, DAG);
1016 if (Result.getNode()) return Result;
1018 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1019 SDValue Result = combineShlAddConstant(N1, N0, DAG);
1020 if (Result.getNode()) return Result;
1023 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1024 if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
1025 SDValue Result = combineSelectAndUse(N, N0, N1, DAG);
1026 if (Result.getNode()) return Result;
1028 if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
1029 SDValue Result = combineSelectAndUse(N, N1, N0, DAG);
1030 if (Result.getNode()) return Result;
1036 SDValue DAGCombiner::visitADDC(SDNode *N) {
1037 SDValue N0 = N->getOperand(0);
1038 SDValue N1 = N->getOperand(1);
1039 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1040 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1041 MVT VT = N0.getValueType();
1043 // If the flag result is dead, turn this into an ADD.
1044 if (N->hasNUsesOfValue(0, 1))
1045 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
1046 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1048 // canonicalize constant to RHS.
1050 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0);
1052 // fold (addc x, 0) -> x + no carry out
1053 if (N1C && N1C->isNullValue())
1054 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1056 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1057 APInt LHSZero, LHSOne;
1058 APInt RHSZero, RHSOne;
1059 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1060 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1061 if (LHSZero.getBoolValue()) {
1062 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1064 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1065 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1066 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1067 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1068 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
1069 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1075 SDValue DAGCombiner::visitADDE(SDNode *N) {
1076 SDValue N0 = N->getOperand(0);
1077 SDValue N1 = N->getOperand(1);
1078 SDValue CarryIn = N->getOperand(2);
1079 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1080 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1081 //MVT VT = N0.getValueType();
1083 // canonicalize constant to RHS
1085 return DAG.getNode(ISD::ADDE, N->getVTList(), N1, N0, CarryIn);
1087 // fold (adde x, y, false) -> (addc x, y)
1088 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1089 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0);
1096 SDValue DAGCombiner::visitSUB(SDNode *N) {
1097 SDValue N0 = N->getOperand(0);
1098 SDValue N1 = N->getOperand(1);
1099 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1100 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1101 MVT VT = N0.getValueType();
1104 if (VT.isVector()) {
1105 SDValue FoldedVOp = SimplifyVBinOp(N);
1106 if (FoldedVOp.getNode()) return FoldedVOp;
1109 // fold (sub x, x) -> 0
1111 return DAG.getConstant(0, N->getValueType(0));
1112 // fold (sub c1, c2) -> c1-c2
1114 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1115 // fold (sub x, c) -> (add x, -c)
1117 return DAG.getNode(ISD::ADD, VT, N0,
1118 DAG.getConstant(-N1C->getAPIntValue(), VT));
1119 // fold (A+B)-A -> B
1120 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1121 return N0.getOperand(1);
1122 // fold (A+B)-B -> A
1123 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1124 return N0.getOperand(0);
1125 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1126 if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
1127 SDValue Result = combineSelectAndUse(N, N1, N0, DAG);
1128 if (Result.getNode()) return Result;
1130 // If either operand of a sub is undef, the result is undef
1131 if (N0.getOpcode() == ISD::UNDEF)
1133 if (N1.getOpcode() == ISD::UNDEF)
1139 SDValue DAGCombiner::visitMUL(SDNode *N) {
1140 SDValue N0 = N->getOperand(0);
1141 SDValue N1 = N->getOperand(1);
1142 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1143 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1144 MVT VT = N0.getValueType();
1147 if (VT.isVector()) {
1148 SDValue FoldedVOp = SimplifyVBinOp(N);
1149 if (FoldedVOp.getNode()) return FoldedVOp;
1152 // fold (mul x, undef) -> 0
1153 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1154 return DAG.getConstant(0, VT);
1155 // fold (mul c1, c2) -> c1*c2
1157 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1158 // canonicalize constant to RHS
1160 return DAG.getNode(ISD::MUL, VT, N1, N0);
1161 // fold (mul x, 0) -> 0
1162 if (N1C && N1C->isNullValue())
1164 // fold (mul x, -1) -> 0-x
1165 if (N1C && N1C->isAllOnesValue())
1166 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1167 // fold (mul x, (1 << c)) -> x << c
1168 if (N1C && N1C->getAPIntValue().isPowerOf2())
1169 return DAG.getNode(ISD::SHL, VT, N0,
1170 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1171 TLI.getShiftAmountTy()));
1172 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1173 if (N1C && isPowerOf2_64(-N1C->getSExtValue())) {
1174 // FIXME: If the input is something that is easily negated (e.g. a
1175 // single-use add), we should put the negate there.
1176 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1177 DAG.getNode(ISD::SHL, VT, N0,
1178 DAG.getConstant(Log2_64(-N1C->getSExtValue()),
1179 TLI.getShiftAmountTy())));
1182 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1183 if (N1C && N0.getOpcode() == ISD::SHL &&
1184 isa<ConstantSDNode>(N0.getOperand(1))) {
1185 SDValue C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1186 AddToWorkList(C3.getNode());
1187 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1190 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1193 SDValue Sh(0,0), Y(0,0);
1194 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1195 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1196 N0.getNode()->hasOneUse()) {
1198 } else if (N1.getOpcode() == ISD::SHL &&
1199 isa<ConstantSDNode>(N1.getOperand(1)) &&
1200 N1.getNode()->hasOneUse()) {
1204 SDValue Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1205 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1208 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1209 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1210 isa<ConstantSDNode>(N0.getOperand(1))) {
1211 return DAG.getNode(ISD::ADD, VT,
1212 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1213 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1217 SDValue RMUL = ReassociateOps(ISD::MUL, N0, N1);
1218 if (RMUL.getNode() != 0)
1224 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1225 SDValue N0 = N->getOperand(0);
1226 SDValue N1 = N->getOperand(1);
1227 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1228 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1229 MVT VT = N->getValueType(0);
1232 if (VT.isVector()) {
1233 SDValue FoldedVOp = SimplifyVBinOp(N);
1234 if (FoldedVOp.getNode()) return FoldedVOp;
1237 // fold (sdiv c1, c2) -> c1/c2
1238 if (N0C && N1C && !N1C->isNullValue())
1239 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1240 // fold (sdiv X, 1) -> X
1241 if (N1C && N1C->getSExtValue() == 1LL)
1243 // fold (sdiv X, -1) -> 0-X
1244 if (N1C && N1C->isAllOnesValue())
1245 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1246 // If we know the sign bits of both operands are zero, strength reduce to a
1247 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1248 if (!VT.isVector()) {
1249 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1250 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1252 // fold (sdiv X, pow2) -> simple ops after legalize
1253 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1254 (isPowerOf2_64(N1C->getSExtValue()) ||
1255 isPowerOf2_64(-N1C->getSExtValue()))) {
1256 // If dividing by powers of two is cheap, then don't perform the following
1258 if (TLI.isPow2DivCheap())
1260 int64_t pow2 = N1C->getSExtValue();
1261 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1262 unsigned lg2 = Log2_64(abs2);
1263 // Splat the sign bit into the register
1264 SDValue SGN = DAG.getNode(ISD::SRA, VT, N0,
1265 DAG.getConstant(VT.getSizeInBits()-1,
1266 TLI.getShiftAmountTy()));
1267 AddToWorkList(SGN.getNode());
1268 // Add (N0 < 0) ? abs2 - 1 : 0;
1269 SDValue SRL = DAG.getNode(ISD::SRL, VT, SGN,
1270 DAG.getConstant(VT.getSizeInBits()-lg2,
1271 TLI.getShiftAmountTy()));
1272 SDValue ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1273 AddToWorkList(SRL.getNode());
1274 AddToWorkList(ADD.getNode()); // Divide by pow2
1275 SDValue SRA = DAG.getNode(ISD::SRA, VT, ADD,
1276 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1277 // If we're dividing by a positive value, we're done. Otherwise, we must
1278 // negate the result.
1281 AddToWorkList(SRA.getNode());
1282 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1284 // if integer divide is expensive and we satisfy the requirements, emit an
1285 // alternate sequence.
1286 if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1287 !TLI.isIntDivCheap()) {
1288 SDValue Op = BuildSDIV(N);
1289 if (Op.getNode()) return Op;
1293 if (N0.getOpcode() == ISD::UNDEF)
1294 return DAG.getConstant(0, VT);
1295 // X / undef -> undef
1296 if (N1.getOpcode() == ISD::UNDEF)
1302 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1303 SDValue N0 = N->getOperand(0);
1304 SDValue N1 = N->getOperand(1);
1305 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1306 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1307 MVT VT = N->getValueType(0);
1310 if (VT.isVector()) {
1311 SDValue FoldedVOp = SimplifyVBinOp(N);
1312 if (FoldedVOp.getNode()) return FoldedVOp;
1315 // fold (udiv c1, c2) -> c1/c2
1316 if (N0C && N1C && !N1C->isNullValue())
1317 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1318 // fold (udiv x, (1 << c)) -> x >>u c
1319 if (N1C && N1C->getAPIntValue().isPowerOf2())
1320 return DAG.getNode(ISD::SRL, VT, N0,
1321 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1322 TLI.getShiftAmountTy()));
1323 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1324 if (N1.getOpcode() == ISD::SHL) {
1325 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1326 if (SHC->getAPIntValue().isPowerOf2()) {
1327 MVT ADDVT = N1.getOperand(1).getValueType();
1328 SDValue Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1329 DAG.getConstant(SHC->getAPIntValue()
1332 AddToWorkList(Add.getNode());
1333 return DAG.getNode(ISD::SRL, VT, N0, Add);
1337 // fold (udiv x, c) -> alternate
1338 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1339 SDValue Op = BuildUDIV(N);
1340 if (Op.getNode()) return Op;
1344 if (N0.getOpcode() == ISD::UNDEF)
1345 return DAG.getConstant(0, VT);
1346 // X / undef -> undef
1347 if (N1.getOpcode() == ISD::UNDEF)
1353 SDValue DAGCombiner::visitSREM(SDNode *N) {
1354 SDValue N0 = N->getOperand(0);
1355 SDValue N1 = N->getOperand(1);
1356 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1357 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1358 MVT VT = N->getValueType(0);
1360 // fold (srem c1, c2) -> c1%c2
1361 if (N0C && N1C && !N1C->isNullValue())
1362 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1363 // If we know the sign bits of both operands are zero, strength reduce to a
1364 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1365 if (!VT.isVector()) {
1366 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1367 return DAG.getNode(ISD::UREM, VT, N0, N1);
1370 // If X/C can be simplified by the division-by-constant logic, lower
1371 // X%C to the equivalent of X-X/C*C.
1372 if (N1C && !N1C->isNullValue()) {
1373 SDValue Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1374 AddToWorkList(Div.getNode());
1375 SDValue OptimizedDiv = combine(Div.getNode());
1376 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1377 SDValue Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1378 SDValue Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1379 AddToWorkList(Mul.getNode());
1385 if (N0.getOpcode() == ISD::UNDEF)
1386 return DAG.getConstant(0, VT);
1387 // X % undef -> undef
1388 if (N1.getOpcode() == ISD::UNDEF)
1394 SDValue DAGCombiner::visitUREM(SDNode *N) {
1395 SDValue N0 = N->getOperand(0);
1396 SDValue N1 = N->getOperand(1);
1397 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1398 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1399 MVT VT = N->getValueType(0);
1401 // fold (urem c1, c2) -> c1%c2
1402 if (N0C && N1C && !N1C->isNullValue())
1403 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1404 // fold (urem x, pow2) -> (and x, pow2-1)
1405 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1406 return DAG.getNode(ISD::AND, VT, N0,
1407 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1408 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1409 if (N1.getOpcode() == ISD::SHL) {
1410 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1411 if (SHC->getAPIntValue().isPowerOf2()) {
1413 DAG.getNode(ISD::ADD, VT, N1,
1414 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1416 AddToWorkList(Add.getNode());
1417 return DAG.getNode(ISD::AND, VT, N0, Add);
1422 // If X/C can be simplified by the division-by-constant logic, lower
1423 // X%C to the equivalent of X-X/C*C.
1424 if (N1C && !N1C->isNullValue()) {
1425 SDValue Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1426 AddToWorkList(Div.getNode());
1427 SDValue OptimizedDiv = combine(Div.getNode());
1428 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1429 SDValue Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1430 SDValue Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1431 AddToWorkList(Mul.getNode());
1437 if (N0.getOpcode() == ISD::UNDEF)
1438 return DAG.getConstant(0, VT);
1439 // X % undef -> undef
1440 if (N1.getOpcode() == ISD::UNDEF)
1446 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1447 SDValue N0 = N->getOperand(0);
1448 SDValue N1 = N->getOperand(1);
1449 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1450 MVT VT = N->getValueType(0);
1452 // fold (mulhs x, 0) -> 0
1453 if (N1C && N1C->isNullValue())
1455 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1456 if (N1C && N1C->getAPIntValue() == 1)
1457 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1458 DAG.getConstant(N0.getValueType().getSizeInBits()-1,
1459 TLI.getShiftAmountTy()));
1460 // fold (mulhs x, undef) -> 0
1461 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1462 return DAG.getConstant(0, VT);
1467 SDValue DAGCombiner::visitMULHU(SDNode *N) {
1468 SDValue N0 = N->getOperand(0);
1469 SDValue N1 = N->getOperand(1);
1470 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1471 MVT VT = N->getValueType(0);
1473 // fold (mulhu x, 0) -> 0
1474 if (N1C && N1C->isNullValue())
1476 // fold (mulhu x, 1) -> 0
1477 if (N1C && N1C->getAPIntValue() == 1)
1478 return DAG.getConstant(0, N0.getValueType());
1479 // fold (mulhu x, undef) -> 0
1480 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1481 return DAG.getConstant(0, VT);
1486 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1487 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1488 /// that are being performed. Return true if a simplification was made.
1490 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1492 // If the high half is not needed, just compute the low half.
1493 bool HiExists = N->hasAnyUseOfValue(1);
1496 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1497 SDValue Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(),
1498 N->getNumOperands());
1499 return CombineTo(N, Res, Res);
1502 // If the low half is not needed, just compute the high half.
1503 bool LoExists = N->hasAnyUseOfValue(0);
1506 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1507 SDValue Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(),
1508 N->getNumOperands());
1509 return CombineTo(N, Res, Res);
1512 // If both halves are used, return as it is.
1513 if (LoExists && HiExists)
1516 // If the two computed results can be simplified separately, separate them.
1518 SDValue Lo = DAG.getNode(LoOp, N->getValueType(0),
1519 N->op_begin(), N->getNumOperands());
1520 AddToWorkList(Lo.getNode());
1521 SDValue LoOpt = combine(Lo.getNode());
1522 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
1524 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1525 return CombineTo(N, LoOpt, LoOpt);
1529 SDValue Hi = DAG.getNode(HiOp, N->getValueType(1),
1530 N->op_begin(), N->getNumOperands());
1531 AddToWorkList(Hi.getNode());
1532 SDValue HiOpt = combine(Hi.getNode());
1533 if (HiOpt.getNode() && HiOpt != Hi &&
1535 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1536 return CombineTo(N, HiOpt, HiOpt);
1541 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1542 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1543 if (Res.getNode()) return Res;
1548 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1549 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1550 if (Res.getNode()) return Res;
1555 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
1556 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1557 if (Res.getNode()) return Res;
1562 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
1563 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1564 if (Res.getNode()) return Res;
1569 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1570 /// two operands of the same opcode, try to simplify it.
1571 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1572 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
1573 MVT VT = N0.getValueType();
1574 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1576 // For each of OP in AND/OR/XOR:
1577 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1578 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1579 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1580 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1581 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1582 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1583 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1584 SDValue ORNode = DAG.getNode(N->getOpcode(),
1585 N0.getOperand(0).getValueType(),
1586 N0.getOperand(0), N1.getOperand(0));
1587 AddToWorkList(ORNode.getNode());
1588 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1591 // For each of OP in SHL/SRL/SRA/AND...
1592 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1593 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1594 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1595 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1596 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1597 N0.getOperand(1) == N1.getOperand(1)) {
1598 SDValue ORNode = DAG.getNode(N->getOpcode(),
1599 N0.getOperand(0).getValueType(),
1600 N0.getOperand(0), N1.getOperand(0));
1601 AddToWorkList(ORNode.getNode());
1602 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1608 SDValue DAGCombiner::visitAND(SDNode *N) {
1609 SDValue N0 = N->getOperand(0);
1610 SDValue N1 = N->getOperand(1);
1611 SDValue LL, LR, RL, RR, CC0, CC1;
1612 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1613 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1614 MVT VT = N1.getValueType();
1615 unsigned BitWidth = VT.getSizeInBits();
1618 if (VT.isVector()) {
1619 SDValue FoldedVOp = SimplifyVBinOp(N);
1620 if (FoldedVOp.getNode()) return FoldedVOp;
1623 // fold (and x, undef) -> 0
1624 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1625 return DAG.getConstant(0, VT);
1626 // fold (and c1, c2) -> c1&c2
1628 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
1629 // canonicalize constant to RHS
1631 return DAG.getNode(ISD::AND, VT, N1, N0);
1632 // fold (and x, -1) -> x
1633 if (N1C && N1C->isAllOnesValue())
1635 // if (and x, c) is known to be zero, return 0
1636 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
1637 APInt::getAllOnesValue(BitWidth)))
1638 return DAG.getConstant(0, VT);
1640 SDValue RAND = ReassociateOps(ISD::AND, N0, N1);
1641 if (RAND.getNode() != 0)
1643 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1644 if (N1C && N0.getOpcode() == ISD::OR)
1645 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1646 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
1648 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1649 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1650 SDValue N0Op0 = N0.getOperand(0);
1651 APInt Mask = ~N1C->getAPIntValue();
1652 Mask.trunc(N0Op0.getValueSizeInBits());
1653 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
1654 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1657 // Replace uses of the AND with uses of the Zero extend node.
1660 // We actually want to replace all uses of the any_extend with the
1661 // zero_extend, to avoid duplicating things. This will later cause this
1662 // AND to be folded.
1663 CombineTo(N0.getNode(), Zext);
1664 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1667 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1668 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1669 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1670 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1672 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1673 LL.getValueType().isInteger()) {
1674 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1675 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
1676 SDValue ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1677 AddToWorkList(ORNode.getNode());
1678 return DAG.getSetCC(VT, ORNode, LR, Op1);
1680 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1681 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1682 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1683 AddToWorkList(ANDNode.getNode());
1684 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1686 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1687 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1688 SDValue ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1689 AddToWorkList(ORNode.getNode());
1690 return DAG.getSetCC(VT, ORNode, LR, Op1);
1693 // canonicalize equivalent to ll == rl
1694 if (LL == RR && LR == RL) {
1695 Op1 = ISD::getSetCCSwappedOperands(Op1);
1698 if (LL == RL && LR == RR) {
1699 bool isInteger = LL.getValueType().isInteger();
1700 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1701 if (Result != ISD::SETCC_INVALID)
1702 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1706 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1707 if (N0.getOpcode() == N1.getOpcode()) {
1708 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1709 if (Tmp.getNode()) return Tmp;
1712 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1713 // fold (and (sra)) -> (and (srl)) when possible.
1714 if (!VT.isVector() &&
1715 SimplifyDemandedBits(SDValue(N, 0)))
1716 return SDValue(N, 0);
1717 // fold (zext_inreg (extload x)) -> (zextload x)
1718 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
1719 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1720 MVT EVT = LN0->getMemoryVT();
1721 // If we zero all the possible extended bits, then we can turn this into
1722 // a zextload if we are running before legalize or the operation is legal.
1723 unsigned BitWidth = N1.getValueSizeInBits();
1724 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1725 BitWidth - EVT.getSizeInBits())) &&
1726 ((!AfterLegalize && !LN0->isVolatile()) ||
1727 TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT))) {
1728 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1729 LN0->getBasePtr(), LN0->getSrcValue(),
1730 LN0->getSrcValueOffset(), EVT,
1732 LN0->getAlignment());
1734 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
1735 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1738 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1739 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
1741 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1742 MVT EVT = LN0->getMemoryVT();
1743 // If we zero all the possible extended bits, then we can turn this into
1744 // a zextload if we are running before legalize or the operation is legal.
1745 unsigned BitWidth = N1.getValueSizeInBits();
1746 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1747 BitWidth - EVT.getSizeInBits())) &&
1748 ((!AfterLegalize && !LN0->isVolatile()) ||
1749 TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT))) {
1750 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1751 LN0->getBasePtr(), LN0->getSrcValue(),
1752 LN0->getSrcValueOffset(), EVT,
1754 LN0->getAlignment());
1756 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
1757 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1761 // fold (and (load x), 255) -> (zextload x, i8)
1762 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1763 if (N1C && N0.getOpcode() == ISD::LOAD) {
1764 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1765 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1766 LN0->isUnindexed() && N0.hasOneUse() &&
1767 // Do not change the width of a volatile load.
1768 !LN0->isVolatile()) {
1769 MVT EVT = MVT::Other;
1770 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
1771 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue()))
1772 EVT = MVT::getIntegerVT(ActiveBits);
1774 MVT LoadedVT = LN0->getMemoryVT();
1775 // Do not generate loads of non-round integer types since these can
1776 // be expensive (and would be wrong if the type is not byte sized).
1777 if (EVT != MVT::Other && LoadedVT.bitsGT(EVT) && EVT.isRound() &&
1778 (!AfterLegalize || TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT))) {
1779 MVT PtrType = N0.getOperand(1).getValueType();
1780 // For big endian targets, we need to add an offset to the pointer to
1781 // load the correct bytes. For little endian systems, we merely need to
1782 // read fewer bytes from the same pointer.
1783 unsigned LVTStoreBytes = LoadedVT.getStoreSizeInBits()/8;
1784 unsigned EVTStoreBytes = EVT.getStoreSizeInBits()/8;
1785 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
1786 unsigned Alignment = LN0->getAlignment();
1787 SDValue NewPtr = LN0->getBasePtr();
1788 if (TLI.isBigEndian()) {
1789 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1790 DAG.getConstant(PtrOff, PtrType));
1791 Alignment = MinAlign(Alignment, PtrOff);
1793 AddToWorkList(NewPtr.getNode());
1795 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1796 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
1797 LN0->isVolatile(), Alignment);
1799 CombineTo(N0.getNode(), Load, Load.getValue(1));
1800 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1808 SDValue DAGCombiner::visitOR(SDNode *N) {
1809 SDValue N0 = N->getOperand(0);
1810 SDValue N1 = N->getOperand(1);
1811 SDValue LL, LR, RL, RR, CC0, CC1;
1812 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1813 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1814 MVT VT = N1.getValueType();
1817 if (VT.isVector()) {
1818 SDValue FoldedVOp = SimplifyVBinOp(N);
1819 if (FoldedVOp.getNode()) return FoldedVOp;
1822 // fold (or x, undef) -> -1
1823 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1824 return DAG.getConstant(~0ULL, VT);
1825 // fold (or c1, c2) -> c1|c2
1827 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
1828 // canonicalize constant to RHS
1830 return DAG.getNode(ISD::OR, VT, N1, N0);
1831 // fold (or x, 0) -> x
1832 if (N1C && N1C->isNullValue())
1834 // fold (or x, -1) -> -1
1835 if (N1C && N1C->isAllOnesValue())
1837 // fold (or x, c) -> c iff (x & ~c) == 0
1838 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
1841 SDValue ROR = ReassociateOps(ISD::OR, N0, N1);
1842 if (ROR.getNode() != 0)
1844 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1845 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
1846 isa<ConstantSDNode>(N0.getOperand(1))) {
1847 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1848 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1850 DAG.getConstant(N1C->getAPIntValue() |
1851 C1->getAPIntValue(), VT));
1853 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1854 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1855 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1856 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1858 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1859 LL.getValueType().isInteger()) {
1860 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1861 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1862 if (cast<ConstantSDNode>(LR)->isNullValue() &&
1863 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1864 SDValue ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1865 AddToWorkList(ORNode.getNode());
1866 return DAG.getSetCC(VT, ORNode, LR, Op1);
1868 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1869 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1870 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1871 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1872 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1873 AddToWorkList(ANDNode.getNode());
1874 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1877 // canonicalize equivalent to ll == rl
1878 if (LL == RR && LR == RL) {
1879 Op1 = ISD::getSetCCSwappedOperands(Op1);
1882 if (LL == RL && LR == RR) {
1883 bool isInteger = LL.getValueType().isInteger();
1884 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1885 if (Result != ISD::SETCC_INVALID)
1886 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1890 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1891 if (N0.getOpcode() == N1.getOpcode()) {
1892 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1893 if (Tmp.getNode()) return Tmp;
1896 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1897 if (N0.getOpcode() == ISD::AND &&
1898 N1.getOpcode() == ISD::AND &&
1899 N0.getOperand(1).getOpcode() == ISD::Constant &&
1900 N1.getOperand(1).getOpcode() == ISD::Constant &&
1901 // Don't increase # computations.
1902 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
1903 // We can only do this xform if we know that bits from X that are set in C2
1904 // but not in C1 are already zero. Likewise for Y.
1905 const APInt &LHSMask =
1906 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1907 const APInt &RHSMask =
1908 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
1910 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1911 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1912 SDValue X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1913 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1918 // See if this is some rotate idiom.
1919 if (SDNode *Rot = MatchRotate(N0, N1))
1920 return SDValue(Rot, 0);
1926 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1927 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
1928 if (Op.getOpcode() == ISD::AND) {
1929 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1930 Mask = Op.getOperand(1);
1931 Op = Op.getOperand(0);
1937 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1945 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
1946 // idioms for rotate, and if the target supports rotation instructions, generate
1948 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS) {
1949 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
1950 MVT VT = LHS.getValueType();
1951 if (!TLI.isTypeLegal(VT)) return 0;
1953 // The target must have at least one rotate flavor.
1954 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1955 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1956 if (!HasROTL && !HasROTR) return 0;
1958 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1959 SDValue LHSShift; // The shift.
1960 SDValue LHSMask; // AND value if any.
1961 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1962 return 0; // Not part of a rotate.
1964 SDValue RHSShift; // The shift.
1965 SDValue RHSMask; // AND value if any.
1966 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1967 return 0; // Not part of a rotate.
1969 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1970 return 0; // Not shifting the same value.
1972 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1973 return 0; // Shifts must disagree.
1975 // Canonicalize shl to left side in a shl/srl pair.
1976 if (RHSShift.getOpcode() == ISD::SHL) {
1977 std::swap(LHS, RHS);
1978 std::swap(LHSShift, RHSShift);
1979 std::swap(LHSMask , RHSMask );
1982 unsigned OpSizeInBits = VT.getSizeInBits();
1983 SDValue LHSShiftArg = LHSShift.getOperand(0);
1984 SDValue LHSShiftAmt = LHSShift.getOperand(1);
1985 SDValue RHSShiftAmt = RHSShift.getOperand(1);
1987 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1988 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1989 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
1990 RHSShiftAmt.getOpcode() == ISD::Constant) {
1991 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
1992 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
1993 if ((LShVal + RShVal) != OpSizeInBits)
1998 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
2000 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
2002 // If there is an AND of either shifted operand, apply it to the result.
2003 if (LHSMask.getNode() || RHSMask.getNode()) {
2004 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2006 if (LHSMask.getNode()) {
2007 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2008 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2010 if (RHSMask.getNode()) {
2011 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2012 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2015 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
2018 return Rot.getNode();
2021 // If there is a mask here, and we have a variable shift, we can't be sure
2022 // that we're masking out the right stuff.
2023 if (LHSMask.getNode() || RHSMask.getNode())
2026 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2027 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2028 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2029 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2030 if (ConstantSDNode *SUBC =
2031 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2032 if (SUBC->getAPIntValue() == OpSizeInBits) {
2034 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).getNode();
2036 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).getNode();
2041 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2042 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2043 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2044 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2045 if (ConstantSDNode *SUBC =
2046 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2047 if (SUBC->getAPIntValue() == OpSizeInBits) {
2049 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).getNode();
2051 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).getNode();
2056 // Look for sign/zext/any-extended or truncate cases:
2057 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2058 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2059 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2060 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2061 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2062 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2063 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2064 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2065 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2066 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2067 if (RExtOp0.getOpcode() == ISD::SUB &&
2068 RExtOp0.getOperand(1) == LExtOp0) {
2069 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2071 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2072 // (rotr x, (sub 32, y))
2073 if (ConstantSDNode *SUBC =
2074 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2075 if (SUBC->getAPIntValue() == OpSizeInBits) {
2076 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, VT, LHSShiftArg,
2077 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2080 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2081 RExtOp0 == LExtOp0.getOperand(1)) {
2082 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2084 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2085 // (rotl x, (sub 32, y))
2086 if (ConstantSDNode *SUBC =
2087 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2088 if (SUBC->getAPIntValue() == OpSizeInBits) {
2089 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, VT, LHSShiftArg,
2090 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2100 SDValue DAGCombiner::visitXOR(SDNode *N) {
2101 SDValue N0 = N->getOperand(0);
2102 SDValue N1 = N->getOperand(1);
2103 SDValue LHS, RHS, CC;
2104 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2105 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2106 MVT VT = N0.getValueType();
2109 if (VT.isVector()) {
2110 SDValue FoldedVOp = SimplifyVBinOp(N);
2111 if (FoldedVOp.getNode()) return FoldedVOp;
2114 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2115 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2116 return DAG.getConstant(0, VT);
2117 // fold (xor x, undef) -> undef
2118 if (N0.getOpcode() == ISD::UNDEF)
2120 if (N1.getOpcode() == ISD::UNDEF)
2122 // fold (xor c1, c2) -> c1^c2
2124 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2125 // canonicalize constant to RHS
2127 return DAG.getNode(ISD::XOR, VT, N1, N0);
2128 // fold (xor x, 0) -> x
2129 if (N1C && N1C->isNullValue())
2132 SDValue RXOR = ReassociateOps(ISD::XOR, N0, N1);
2133 if (RXOR.getNode() != 0)
2135 // fold !(x cc y) -> (x !cc y)
2136 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2137 bool isInt = LHS.getValueType().isInteger();
2138 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2140 if (N0.getOpcode() == ISD::SETCC)
2141 return DAG.getSetCC(VT, LHS, RHS, NotCC);
2142 if (N0.getOpcode() == ISD::SELECT_CC)
2143 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
2144 assert(0 && "Unhandled SetCC Equivalent!");
2147 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2148 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2149 N0.getNode()->hasOneUse() &&
2150 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2151 SDValue V = N0.getOperand(0);
2152 V = DAG.getNode(ISD::XOR, V.getValueType(), V,
2153 DAG.getConstant(1, V.getValueType()));
2154 AddToWorkList(V.getNode());
2155 return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2158 // fold !(x or y) -> (!x and !y) iff x or y are setcc
2159 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2160 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2161 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2162 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2163 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2164 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2165 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2166 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2167 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2170 // fold !(x or y) -> (!x and !y) iff x or y are constants
2171 if (N1C && N1C->isAllOnesValue() &&
2172 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2173 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2174 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2175 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2176 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2177 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2178 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2179 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2182 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2183 if (N1C && N0.getOpcode() == ISD::XOR) {
2184 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2185 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2187 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
2188 DAG.getConstant(N1C->getAPIntValue()^
2189 N00C->getAPIntValue(), VT));
2191 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
2192 DAG.getConstant(N1C->getAPIntValue()^
2193 N01C->getAPIntValue(), VT));
2195 // fold (xor x, x) -> 0
2197 if (!VT.isVector()) {
2198 return DAG.getConstant(0, VT);
2199 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
2200 // Produce a vector of zeros.
2201 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
2202 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
2203 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2207 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2208 if (N0.getOpcode() == N1.getOpcode()) {
2209 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2210 if (Tmp.getNode()) return Tmp;
2213 // Simplify the expression using non-local knowledge.
2214 if (!VT.isVector() &&
2215 SimplifyDemandedBits(SDValue(N, 0)))
2216 return SDValue(N, 0);
2221 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2222 /// the shift amount is a constant.
2223 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2224 SDNode *LHS = N->getOperand(0).getNode();
2225 if (!LHS->hasOneUse()) return SDValue();
2227 // We want to pull some binops through shifts, so that we have (and (shift))
2228 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2229 // thing happens with address calculations, so it's important to canonicalize
2231 bool HighBitSet = false; // Can we transform this if the high bit is set?
2233 switch (LHS->getOpcode()) {
2234 default: return SDValue();
2237 HighBitSet = false; // We can only transform sra if the high bit is clear.
2240 HighBitSet = true; // We can only transform sra if the high bit is set.
2243 if (N->getOpcode() != ISD::SHL)
2244 return SDValue(); // only shl(add) not sr[al](add).
2245 HighBitSet = false; // We can only transform sra if the high bit is clear.
2249 // We require the RHS of the binop to be a constant as well.
2250 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2251 if (!BinOpCst) return SDValue();
2254 // FIXME: disable this for unless the input to the binop is a shift by a
2255 // constant. If it is not a shift, it pessimizes some common cases like:
2257 //void foo(int *X, int i) { X[i & 1235] = 1; }
2258 //int bar(int *X, int i) { return X[i & 255]; }
2259 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2260 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2261 BinOpLHSVal->getOpcode() != ISD::SRA &&
2262 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2263 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2266 MVT VT = N->getValueType(0);
2268 // If this is a signed shift right, and the high bit is modified
2269 // by the logical operation, do not perform the transformation.
2270 // The highBitSet boolean indicates the value of the high bit of
2271 // the constant which would cause it to be modified for this
2273 if (N->getOpcode() == ISD::SRA) {
2274 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2275 if (BinOpRHSSignSet != HighBitSet)
2279 // Fold the constants, shifting the binop RHS by the shift amount.
2280 SDValue NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
2281 LHS->getOperand(1), N->getOperand(1));
2283 // Create the new shift.
2284 SDValue NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
2287 // Create the new binop.
2288 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
2292 SDValue DAGCombiner::visitSHL(SDNode *N) {
2293 SDValue N0 = N->getOperand(0);
2294 SDValue N1 = N->getOperand(1);
2295 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2296 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2297 MVT VT = N0.getValueType();
2298 unsigned OpSizeInBits = VT.getSizeInBits();
2300 // fold (shl c1, c2) -> c1<<c2
2302 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
2303 // fold (shl 0, x) -> 0
2304 if (N0C && N0C->isNullValue())
2306 // fold (shl x, c >= size(x)) -> undef
2307 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2308 return DAG.getNode(ISD::UNDEF, VT);
2309 // fold (shl x, 0) -> x
2310 if (N1C && N1C->isNullValue())
2312 // if (shl x, c) is known to be zero, return 0
2313 if (DAG.MaskedValueIsZero(SDValue(N, 0),
2314 APInt::getAllOnesValue(VT.getSizeInBits())))
2315 return DAG.getConstant(0, VT);
2316 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), c))
2317 // iff (trunc c) == c
2318 if (N1.getOpcode() == ISD::TRUNCATE &&
2319 N1.getOperand(0).getOpcode() == ISD::AND &&
2320 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2321 SDValue N101 = N1.getOperand(0).getOperand(1);
2322 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2323 MVT TruncVT = N1.getValueType();
2324 SDValue N100 = N1.getOperand(0).getOperand(0);
2325 return DAG.getNode(ISD::SHL, VT, N0,
2326 DAG.getNode(ISD::AND, TruncVT,
2327 DAG.getNode(ISD::TRUNCATE, TruncVT, N100),
2328 DAG.getConstant(N101C->getZExtValue(),
2333 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2334 return SDValue(N, 0);
2335 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2336 if (N1C && N0.getOpcode() == ISD::SHL &&
2337 N0.getOperand(1).getOpcode() == ISD::Constant) {
2338 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2339 uint64_t c2 = N1C->getZExtValue();
2340 if (c1 + c2 > OpSizeInBits)
2341 return DAG.getConstant(0, VT);
2342 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2343 DAG.getConstant(c1 + c2, N1.getValueType()));
2345 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2346 // (srl (and x, -1 << c1), c1-c2)
2347 if (N1C && N0.getOpcode() == ISD::SRL &&
2348 N0.getOperand(1).getOpcode() == ISD::Constant) {
2349 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2350 uint64_t c2 = N1C->getZExtValue();
2351 SDValue Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2352 DAG.getConstant(~0ULL << c1, VT));
2354 return DAG.getNode(ISD::SHL, VT, Mask,
2355 DAG.getConstant(c2-c1, N1.getValueType()));
2357 return DAG.getNode(ISD::SRL, VT, Mask,
2358 DAG.getConstant(c1-c2, N1.getValueType()));
2360 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2361 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2362 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2363 DAG.getConstant(~0ULL << N1C->getZExtValue(), VT));
2365 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2368 SDValue DAGCombiner::visitSRA(SDNode *N) {
2369 SDValue N0 = N->getOperand(0);
2370 SDValue N1 = N->getOperand(1);
2371 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2372 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2373 MVT VT = N0.getValueType();
2375 // fold (sra c1, c2) -> c1>>c2
2377 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
2378 // fold (sra 0, x) -> 0
2379 if (N0C && N0C->isNullValue())
2381 // fold (sra -1, x) -> -1
2382 if (N0C && N0C->isAllOnesValue())
2384 // fold (sra x, c >= size(x)) -> undef
2385 if (N1C && N1C->getZExtValue() >= VT.getSizeInBits())
2386 return DAG.getNode(ISD::UNDEF, VT);
2387 // fold (sra x, 0) -> x
2388 if (N1C && N1C->isNullValue())
2390 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2392 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2393 unsigned LowBits = VT.getSizeInBits() - (unsigned)N1C->getZExtValue();
2394 MVT EVT = MVT::getIntegerVT(LowBits);
2395 if (EVT.isSimple() && // TODO: remove when apint codegen support lands.
2396 (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT)))
2397 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2398 DAG.getValueType(EVT));
2401 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2402 if (N1C && N0.getOpcode() == ISD::SRA) {
2403 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2404 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
2405 if (Sum >= VT.getSizeInBits()) Sum = VT.getSizeInBits()-1;
2406 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2407 DAG.getConstant(Sum, N1C->getValueType(0)));
2411 // fold sra (shl X, m), result_size - n
2412 // -> (sign_extend (trunc (shl X, result_size - n - m))) for
2413 // result_size - n != m.
2414 // If truncate is free for the target sext(shl) is likely to result in better
2416 if (N0.getOpcode() == ISD::SHL) {
2417 // Get the two constanst of the shifts, CN0 = m, CN = n.
2418 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2420 // Determine what the truncate's result bitsize and type would be.
2421 unsigned VTValSize = VT.getSizeInBits();
2423 MVT::getIntegerVT(VTValSize - N1C->getZExtValue());
2424 // Determine the residual right-shift amount.
2425 unsigned ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
2427 // If the shift is not a no-op (in which case this should be just a sign
2428 // extend already), the truncated to type is legal, sign_extend is legal
2429 // on that type, and the the truncate to that type is both legal and free,
2430 // perform the transform.
2432 TLI.isOperationLegal(ISD::SIGN_EXTEND, TruncVT) &&
2433 TLI.isOperationLegal(ISD::TRUNCATE, VT) &&
2434 TLI.isTruncateFree(VT, TruncVT)) {
2436 SDValue Amt = DAG.getConstant(ShiftAmt, TLI.getShiftAmountTy());
2437 SDValue Shift = DAG.getNode(ISD::SRL, VT, N0.getOperand(0), Amt);
2438 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, TruncVT, Shift);
2439 return DAG.getNode(ISD::SIGN_EXTEND, N->getValueType(0), Trunc);
2444 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), c))
2445 // iff (trunc c) == c
2446 if (N1.getOpcode() == ISD::TRUNCATE &&
2447 N1.getOperand(0).getOpcode() == ISD::AND &&
2448 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2449 SDValue N101 = N1.getOperand(0).getOperand(1);
2450 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2451 MVT TruncVT = N1.getValueType();
2452 SDValue N100 = N1.getOperand(0).getOperand(0);
2453 return DAG.getNode(ISD::SRA, VT, N0,
2454 DAG.getNode(ISD::AND, TruncVT,
2455 DAG.getNode(ISD::TRUNCATE, TruncVT, N100),
2456 DAG.getConstant(N101C->getZExtValue(),
2461 // Simplify, based on bits shifted out of the LHS.
2462 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2463 return SDValue(N, 0);
2466 // If the sign bit is known to be zero, switch this to a SRL.
2467 if (DAG.SignBitIsZero(N0))
2468 return DAG.getNode(ISD::SRL, VT, N0, N1);
2470 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2473 SDValue DAGCombiner::visitSRL(SDNode *N) {
2474 SDValue N0 = N->getOperand(0);
2475 SDValue N1 = N->getOperand(1);
2476 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2477 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2478 MVT VT = N0.getValueType();
2479 unsigned OpSizeInBits = VT.getSizeInBits();
2481 // fold (srl c1, c2) -> c1 >>u c2
2483 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
2484 // fold (srl 0, x) -> 0
2485 if (N0C && N0C->isNullValue())
2487 // fold (srl x, c >= size(x)) -> undef
2488 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2489 return DAG.getNode(ISD::UNDEF, VT);
2490 // fold (srl x, 0) -> x
2491 if (N1C && N1C->isNullValue())
2493 // if (srl x, c) is known to be zero, return 0
2494 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2495 APInt::getAllOnesValue(OpSizeInBits)))
2496 return DAG.getConstant(0, VT);
2498 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2499 if (N1C && N0.getOpcode() == ISD::SRL &&
2500 N0.getOperand(1).getOpcode() == ISD::Constant) {
2501 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2502 uint64_t c2 = N1C->getZExtValue();
2503 if (c1 + c2 > OpSizeInBits)
2504 return DAG.getConstant(0, VT);
2505 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2506 DAG.getConstant(c1 + c2, N1.getValueType()));
2509 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2510 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2511 // Shifting in all undef bits?
2512 MVT SmallVT = N0.getOperand(0).getValueType();
2513 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
2514 return DAG.getNode(ISD::UNDEF, VT);
2516 SDValue SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2517 AddToWorkList(SmallShift.getNode());
2518 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2521 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2522 // bit, which is unmodified by sra.
2523 if (N1C && N1C->getZExtValue()+1 == VT.getSizeInBits()) {
2524 if (N0.getOpcode() == ISD::SRA)
2525 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2528 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2529 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2530 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
2531 APInt KnownZero, KnownOne;
2532 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
2533 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2535 // If any of the input bits are KnownOne, then the input couldn't be all
2536 // zeros, thus the result of the srl will always be zero.
2537 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
2539 // If all of the bits input the to ctlz node are known to be zero, then
2540 // the result of the ctlz is "32" and the result of the shift is one.
2541 APInt UnknownBits = ~KnownZero & Mask;
2542 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2544 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2545 if ((UnknownBits & (UnknownBits-1)) == 0) {
2546 // Okay, we know that only that the single bit specified by UnknownBits
2547 // could be set on input to the CTLZ node. If this bit is set, the SRL
2548 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2549 // to an SRL,XOR pair, which is likely to simplify more.
2550 unsigned ShAmt = UnknownBits.countTrailingZeros();
2551 SDValue Op = N0.getOperand(0);
2553 Op = DAG.getNode(ISD::SRL, VT, Op,
2554 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2555 AddToWorkList(Op.getNode());
2557 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2561 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), c))
2562 // iff (trunc c) == c
2563 if (N1.getOpcode() == ISD::TRUNCATE &&
2564 N1.getOperand(0).getOpcode() == ISD::AND &&
2565 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2566 SDValue N101 = N1.getOperand(0).getOperand(1);
2567 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2568 MVT TruncVT = N1.getValueType();
2569 SDValue N100 = N1.getOperand(0).getOperand(0);
2570 return DAG.getNode(ISD::SRL, VT, N0,
2571 DAG.getNode(ISD::AND, TruncVT,
2572 DAG.getNode(ISD::TRUNCATE, TruncVT, N100),
2573 DAG.getConstant(N101C->getZExtValue(),
2578 // fold operands of srl based on knowledge that the low bits are not
2580 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2581 return SDValue(N, 0);
2583 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2586 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
2587 SDValue N0 = N->getOperand(0);
2588 MVT VT = N->getValueType(0);
2590 // fold (ctlz c1) -> c2
2591 if (isa<ConstantSDNode>(N0))
2592 return DAG.getNode(ISD::CTLZ, VT, N0);
2596 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
2597 SDValue N0 = N->getOperand(0);
2598 MVT VT = N->getValueType(0);
2600 // fold (cttz c1) -> c2
2601 if (isa<ConstantSDNode>(N0))
2602 return DAG.getNode(ISD::CTTZ, VT, N0);
2606 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
2607 SDValue N0 = N->getOperand(0);
2608 MVT VT = N->getValueType(0);
2610 // fold (ctpop c1) -> c2
2611 if (isa<ConstantSDNode>(N0))
2612 return DAG.getNode(ISD::CTPOP, VT, N0);
2616 SDValue DAGCombiner::visitSELECT(SDNode *N) {
2617 SDValue N0 = N->getOperand(0);
2618 SDValue N1 = N->getOperand(1);
2619 SDValue N2 = N->getOperand(2);
2620 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2621 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2622 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2623 MVT VT = N->getValueType(0);
2624 MVT VT0 = N0.getValueType();
2626 // fold select C, X, X -> X
2629 // fold select true, X, Y -> X
2630 if (N0C && !N0C->isNullValue())
2632 // fold select false, X, Y -> Y
2633 if (N0C && N0C->isNullValue())
2635 // fold select C, 1, X -> C | X
2636 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
2637 return DAG.getNode(ISD::OR, VT, N0, N2);
2638 // fold select C, 0, 1 -> ~C
2639 if (VT.isInteger() && VT0.isInteger() &&
2640 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
2641 SDValue XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2644 AddToWorkList(XORNode.getNode());
2646 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2647 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2649 // fold select C, 0, X -> ~C & X
2650 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2651 SDValue XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2652 AddToWorkList(XORNode.getNode());
2653 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2655 // fold select C, X, 1 -> ~C | X
2656 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
2657 SDValue XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2658 AddToWorkList(XORNode.getNode());
2659 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2661 // fold select C, X, 0 -> C & X
2662 // FIXME: this should check for C type == X type, not i1?
2663 if (VT == MVT::i1 && N2C && N2C->isNullValue())
2664 return DAG.getNode(ISD::AND, VT, N0, N1);
2665 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2666 if (VT == MVT::i1 && N0 == N1)
2667 return DAG.getNode(ISD::OR, VT, N0, N2);
2668 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2669 if (VT == MVT::i1 && N0 == N2)
2670 return DAG.getNode(ISD::AND, VT, N0, N1);
2672 // If we can fold this based on the true/false value, do so.
2673 if (SimplifySelectOps(N, N1, N2))
2674 return SDValue(N, 0); // Don't revisit N.
2676 // fold selects based on a setcc into other things, such as min/max/abs
2677 if (N0.getOpcode() == ISD::SETCC) {
2679 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2680 // having to say they don't support SELECT_CC on every type the DAG knows
2681 // about, since there is no way to mark an opcode illegal at all value types
2682 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2683 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2684 N1, N2, N0.getOperand(2));
2686 return SimplifySelect(N0, N1, N2);
2691 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
2692 SDValue N0 = N->getOperand(0);
2693 SDValue N1 = N->getOperand(1);
2694 SDValue N2 = N->getOperand(2);
2695 SDValue N3 = N->getOperand(3);
2696 SDValue N4 = N->getOperand(4);
2697 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2699 // fold select_cc lhs, rhs, x, x, cc -> x
2703 // Determine if the condition we're dealing with is constant
2704 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
2705 if (SCC.getNode()) AddToWorkList(SCC.getNode());
2707 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
2708 if (!SCCC->isNullValue())
2709 return N2; // cond always true -> true val
2711 return N3; // cond always false -> false val
2714 // Fold to a simpler select_cc
2715 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
2716 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2717 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2720 // If we can fold this based on the true/false value, do so.
2721 if (SimplifySelectOps(N, N2, N3))
2722 return SDValue(N, 0); // Don't revisit N.
2724 // fold select_cc into other things, such as min/max/abs
2725 return SimplifySelectCC(N0, N1, N2, N3, CC);
2728 SDValue DAGCombiner::visitSETCC(SDNode *N) {
2729 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2730 cast<CondCodeSDNode>(N->getOperand(2))->get());
2733 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2734 // "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
2735 // transformation. Returns true if extension are possible and the above
2736 // mentioned transformation is profitable.
2737 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
2739 SmallVector<SDNode*, 4> &ExtendNodes,
2740 TargetLowering &TLI) {
2741 bool HasCopyToRegUses = false;
2742 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2743 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
2744 UE = N0.getNode()->use_end();
2749 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2750 if (User->getOpcode() == ISD::SETCC) {
2751 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2752 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2753 // Sign bits will be lost after a zext.
2756 for (unsigned i = 0; i != 2; ++i) {
2757 SDValue UseOp = User->getOperand(i);
2760 if (!isa<ConstantSDNode>(UseOp))
2765 ExtendNodes.push_back(User);
2767 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2768 SDValue UseOp = User->getOperand(i);
2770 // If truncate from extended type to original load type is free
2771 // on this target, then it's ok to extend a CopyToReg.
2772 if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
2773 HasCopyToRegUses = true;
2781 if (HasCopyToRegUses) {
2782 bool BothLiveOut = false;
2783 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2786 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2787 SDValue UseOp = User->getOperand(i);
2788 if (UseOp.getNode() == N && UseOp.getResNo() == 0) {
2795 // Both unextended and extended values are live out. There had better be
2796 // good a reason for the transformation.
2797 return ExtendNodes.size();
2802 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2803 SDValue N0 = N->getOperand(0);
2804 MVT VT = N->getValueType(0);
2806 // fold (sext c1) -> c1
2807 if (isa<ConstantSDNode>(N0))
2808 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2810 // fold (sext (sext x)) -> (sext x)
2811 // fold (sext (aext x)) -> (sext x)
2812 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2813 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2815 if (N0.getOpcode() == ISD::TRUNCATE) {
2816 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2817 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2818 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
2819 if (NarrowLoad.getNode()) {
2820 if (NarrowLoad.getNode() != N0.getNode())
2821 CombineTo(N0.getNode(), NarrowLoad);
2822 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2825 // See if the value being truncated is already sign extended. If so, just
2826 // eliminate the trunc/sext pair.
2827 SDValue Op = N0.getOperand(0);
2828 unsigned OpBits = Op.getValueType().getSizeInBits();
2829 unsigned MidBits = N0.getValueType().getSizeInBits();
2830 unsigned DestBits = VT.getSizeInBits();
2831 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2833 if (OpBits == DestBits) {
2834 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2835 // bits, it is already ready.
2836 if (NumSignBits > DestBits-MidBits)
2838 } else if (OpBits < DestBits) {
2839 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2840 // bits, just sext from i32.
2841 if (NumSignBits > OpBits-MidBits)
2842 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2844 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2845 // bits, just truncate to i32.
2846 if (NumSignBits > OpBits-MidBits)
2847 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2850 // fold (sext (truncate x)) -> (sextinreg x).
2851 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2852 N0.getValueType())) {
2853 if (Op.getValueType().bitsLT(VT))
2854 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2855 else if (Op.getValueType().bitsGT(VT))
2856 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2857 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2858 DAG.getValueType(N0.getValueType()));
2862 // fold (sext (load x)) -> (sext (truncate (sextload x)))
2863 if (ISD::isNON_EXTLoad(N0.getNode()) &&
2864 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
2865 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
2866 bool DoXform = true;
2867 SmallVector<SDNode*, 4> SetCCs;
2868 if (!N0.hasOneUse())
2869 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
2871 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2872 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2873 LN0->getBasePtr(), LN0->getSrcValue(),
2874 LN0->getSrcValueOffset(),
2877 LN0->getAlignment());
2878 CombineTo(N, ExtLoad);
2879 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2880 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
2881 // Extend SetCC uses if necessary.
2882 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2883 SDNode *SetCC = SetCCs[i];
2884 SmallVector<SDValue, 4> Ops;
2885 for (unsigned j = 0; j != 2; ++j) {
2886 SDValue SOp = SetCC->getOperand(j);
2888 Ops.push_back(ExtLoad);
2890 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
2892 Ops.push_back(SetCC->getOperand(2));
2893 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2894 &Ops[0], Ops.size()));
2896 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2900 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2901 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2902 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
2903 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
2904 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2905 MVT EVT = LN0->getMemoryVT();
2906 if ((!AfterLegalize && !LN0->isVolatile()) ||
2907 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT)) {
2908 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2909 LN0->getBasePtr(), LN0->getSrcValue(),
2910 LN0->getSrcValueOffset(), EVT,
2912 LN0->getAlignment());
2913 CombineTo(N, ExtLoad);
2914 CombineTo(N0.getNode(),
2915 DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2916 ExtLoad.getValue(1));
2917 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2921 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2922 if (N0.getOpcode() == ISD::SETCC) {
2924 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2925 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2926 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2927 if (SCC.getNode()) return SCC;
2930 // fold (sext x) -> (zext x) if the sign bit is known zero.
2931 if ((!AfterLegalize || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
2932 DAG.SignBitIsZero(N0))
2933 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2938 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2939 SDValue N0 = N->getOperand(0);
2940 MVT VT = N->getValueType(0);
2942 // fold (zext c1) -> c1
2943 if (isa<ConstantSDNode>(N0))
2944 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2945 // fold (zext (zext x)) -> (zext x)
2946 // fold (zext (aext x)) -> (zext x)
2947 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2948 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2950 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2951 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2952 if (N0.getOpcode() == ISD::TRUNCATE) {
2953 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
2954 if (NarrowLoad.getNode()) {
2955 if (NarrowLoad.getNode() != N0.getNode())
2956 CombineTo(N0.getNode(), NarrowLoad);
2957 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2961 // fold (zext (truncate x)) -> (and x, mask)
2962 if (N0.getOpcode() == ISD::TRUNCATE &&
2963 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2964 SDValue Op = N0.getOperand(0);
2965 if (Op.getValueType().bitsLT(VT)) {
2966 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2967 } else if (Op.getValueType().bitsGT(VT)) {
2968 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2970 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2973 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2974 if (N0.getOpcode() == ISD::AND &&
2975 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2976 N0.getOperand(1).getOpcode() == ISD::Constant) {
2977 SDValue X = N0.getOperand(0).getOperand(0);
2978 if (X.getValueType().bitsLT(VT)) {
2979 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2980 } else if (X.getValueType().bitsGT(VT)) {
2981 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2983 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2984 Mask.zext(VT.getSizeInBits());
2985 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2988 // fold (zext (load x)) -> (zext (truncate (zextload x)))
2989 if (ISD::isNON_EXTLoad(N0.getNode()) &&
2990 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
2991 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
2992 bool DoXform = true;
2993 SmallVector<SDNode*, 4> SetCCs;
2994 if (!N0.hasOneUse())
2995 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
2997 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2998 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2999 LN0->getBasePtr(), LN0->getSrcValue(),
3000 LN0->getSrcValueOffset(),
3003 LN0->getAlignment());
3004 CombineTo(N, ExtLoad);
3005 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
3006 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3007 // Extend SetCC uses if necessary.
3008 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3009 SDNode *SetCC = SetCCs[i];
3010 SmallVector<SDValue, 4> Ops;
3011 for (unsigned j = 0; j != 2; ++j) {
3012 SDValue SOp = SetCC->getOperand(j);
3014 Ops.push_back(ExtLoad);
3016 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
3018 Ops.push_back(SetCC->getOperand(2));
3019 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
3020 &Ops[0], Ops.size()));
3022 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3026 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
3027 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
3028 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3029 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3030 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3031 MVT EVT = LN0->getMemoryVT();
3032 if ((!AfterLegalize && !LN0->isVolatile()) ||
3033 TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT)) {
3034 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
3035 LN0->getBasePtr(), LN0->getSrcValue(),
3036 LN0->getSrcValueOffset(), EVT,
3038 LN0->getAlignment());
3039 CombineTo(N, ExtLoad);
3040 CombineTo(N0.getNode(),
3041 DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3042 ExtLoad.getValue(1));
3043 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3047 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3048 if (N0.getOpcode() == ISD::SETCC) {
3050 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3051 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3052 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3053 if (SCC.getNode()) return SCC;
3059 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
3060 SDValue N0 = N->getOperand(0);
3061 MVT VT = N->getValueType(0);
3063 // fold (aext c1) -> c1
3064 if (isa<ConstantSDNode>(N0))
3065 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
3066 // fold (aext (aext x)) -> (aext x)
3067 // fold (aext (zext x)) -> (zext x)
3068 // fold (aext (sext x)) -> (sext x)
3069 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3070 N0.getOpcode() == ISD::ZERO_EXTEND ||
3071 N0.getOpcode() == ISD::SIGN_EXTEND)
3072 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3074 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3075 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3076 if (N0.getOpcode() == ISD::TRUNCATE) {
3077 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3078 if (NarrowLoad.getNode()) {
3079 if (NarrowLoad.getNode() != N0.getNode())
3080 CombineTo(N0.getNode(), NarrowLoad);
3081 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
3085 // fold (aext (truncate x))
3086 if (N0.getOpcode() == ISD::TRUNCATE) {
3087 SDValue TruncOp = N0.getOperand(0);
3088 if (TruncOp.getValueType() == VT)
3089 return TruncOp; // x iff x size == zext size.
3090 if (TruncOp.getValueType().bitsGT(VT))
3091 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
3092 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
3095 // fold (aext (and (trunc x), cst)) -> (and x, cst).
3096 if (N0.getOpcode() == ISD::AND &&
3097 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3098 N0.getOperand(1).getOpcode() == ISD::Constant) {
3099 SDValue X = N0.getOperand(0).getOperand(0);
3100 if (X.getValueType().bitsLT(VT)) {
3101 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
3102 } else if (X.getValueType().bitsGT(VT)) {
3103 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3105 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3106 Mask.zext(VT.getSizeInBits());
3107 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
3110 // fold (aext (load x)) -> (aext (truncate (extload x)))
3111 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
3112 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3113 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
3114 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3115 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3116 LN0->getBasePtr(), LN0->getSrcValue(),
3117 LN0->getSrcValueOffset(),
3120 LN0->getAlignment());
3121 CombineTo(N, ExtLoad);
3122 // Redirect any chain users to the new load.
3123 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1),
3124 SDValue(ExtLoad.getNode(), 1));
3125 // If any node needs the original loaded value, recompute it.
3126 if (!LN0->use_empty())
3127 CombineTo(LN0, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3128 ExtLoad.getValue(1));
3129 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3132 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3133 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3134 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3135 if (N0.getOpcode() == ISD::LOAD &&
3136 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3138 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3139 MVT EVT = LN0->getMemoryVT();
3140 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
3141 LN0->getChain(), LN0->getBasePtr(),
3143 LN0->getSrcValueOffset(), EVT,
3145 LN0->getAlignment());
3146 CombineTo(N, ExtLoad);
3147 CombineTo(N0.getNode(),
3148 DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3149 ExtLoad.getValue(1));
3150 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3153 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3154 if (N0.getOpcode() == ISD::SETCC) {
3156 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3157 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3158 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3166 /// GetDemandedBits - See if the specified operand can be simplified with the
3167 /// knowledge that only the bits specified by Mask are used. If so, return the
3168 /// simpler operand, otherwise return a null SDValue.
3169 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
3170 switch (V.getOpcode()) {
3174 // If the LHS or RHS don't contribute bits to the or, drop them.
3175 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3176 return V.getOperand(1);
3177 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3178 return V.getOperand(0);
3181 // Only look at single-use SRLs.
3182 if (!V.getNode()->hasOneUse())
3184 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3185 // See if we can recursively simplify the LHS.
3186 unsigned Amt = RHSC->getZExtValue();
3187 APInt NewMask = Mask << Amt;
3188 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3189 if (SimplifyLHS.getNode()) {
3190 return DAG.getNode(ISD::SRL, V.getValueType(),
3191 SimplifyLHS, V.getOperand(1));
3198 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3199 /// bits and then truncated to a narrower type and where N is a multiple
3200 /// of number of bits of the narrower type, transform it to a narrower load
3201 /// from address + N / num of bits of new type. If the result is to be
3202 /// extended, also fold the extension to form a extending load.
3203 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
3204 unsigned Opc = N->getOpcode();
3205 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3206 SDValue N0 = N->getOperand(0);
3207 MVT VT = N->getValueType(0);
3208 MVT EVT = N->getValueType(0);
3210 // This transformation isn't valid for vector loads.
3214 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3216 if (Opc == ISD::SIGN_EXTEND_INREG) {
3217 ExtType = ISD::SEXTLOAD;
3218 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3219 if (AfterLegalize && !TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))
3223 unsigned EVTBits = EVT.getSizeInBits();
3225 bool CombineSRL = false;
3226 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3227 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3228 ShAmt = N01->getZExtValue();
3229 // Is the shift amount a multiple of size of VT?
3230 if ((ShAmt & (EVTBits-1)) == 0) {
3231 N0 = N0.getOperand(0);
3232 if (N0.getValueType().getSizeInBits() <= EVTBits)
3239 // Do not generate loads of non-round integer types since these can
3240 // be expensive (and would be wrong if the type is not byte sized).
3241 if (isa<LoadSDNode>(N0) && N0.hasOneUse() && VT.isRound() &&
3242 cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() > EVTBits &&
3243 // Do not change the width of a volatile load.
3244 !cast<LoadSDNode>(N0)->isVolatile()) {
3245 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3246 MVT PtrType = N0.getOperand(1).getValueType();
3247 // For big endian targets, we need to adjust the offset to the pointer to
3248 // load the correct bytes.
3249 if (TLI.isBigEndian()) {
3250 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
3251 unsigned EVTStoreBits = EVT.getStoreSizeInBits();
3252 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3254 uint64_t PtrOff = ShAmt / 8;
3255 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3256 SDValue NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
3257 DAG.getConstant(PtrOff, PtrType));
3258 AddToWorkList(NewPtr.getNode());
3259 SDValue Load = (ExtType == ISD::NON_EXTLOAD)
3260 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
3261 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3262 LN0->isVolatile(), NewAlign)
3263 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
3264 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3265 EVT, LN0->isVolatile(), NewAlign);
3268 WorkListRemover DeadNodes(*this);
3269 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3271 CombineTo(N->getOperand(0).getNode(), Load);
3273 CombineTo(N0.getNode(), Load, Load.getValue(1));
3275 if (Opc == ISD::SIGN_EXTEND_INREG)
3276 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
3278 return DAG.getNode(Opc, VT, Load);
3280 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3287 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3288 SDValue N0 = N->getOperand(0);
3289 SDValue N1 = N->getOperand(1);
3290 MVT VT = N->getValueType(0);
3291 MVT EVT = cast<VTSDNode>(N1)->getVT();
3292 unsigned VTBits = VT.getSizeInBits();
3293 unsigned EVTBits = EVT.getSizeInBits();
3295 // fold (sext_in_reg c1) -> c1
3296 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3297 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
3299 // If the input is already sign extended, just drop the extension.
3300 if (DAG.ComputeNumSignBits(N0) >= VT.getSizeInBits()-EVTBits+1)
3303 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3304 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3305 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
3306 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
3309 // fold (sext_in_reg (sext x)) -> (sext x)
3310 // fold (sext_in_reg (aext x)) -> (sext x)
3311 // if x is small enough.
3312 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
3313 SDValue N00 = N0.getOperand(0);
3314 if (N00.getValueType().getSizeInBits() < EVTBits)
3315 return DAG.getNode(ISD::SIGN_EXTEND, VT, N00, N1);
3318 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3319 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3320 return DAG.getZeroExtendInReg(N0, EVT);
3322 // fold operands of sext_in_reg based on knowledge that the top bits are not
3324 if (SimplifyDemandedBits(SDValue(N, 0)))
3325 return SDValue(N, 0);
3327 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3328 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3329 SDValue NarrowLoad = ReduceLoadWidth(N);
3330 if (NarrowLoad.getNode())
3333 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
3334 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
3335 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3336 if (N0.getOpcode() == ISD::SRL) {
3337 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3338 if (ShAmt->getZExtValue()+EVTBits <= VT.getSizeInBits()) {
3339 // We can turn this into an SRA iff the input to the SRL is already sign
3341 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3342 if (VT.getSizeInBits()-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
3343 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
3347 // fold (sext_inreg (extload x)) -> (sextload x)
3348 if (ISD::isEXTLoad(N0.getNode()) &&
3349 ISD::isUNINDEXEDLoad(N0.getNode()) &&
3350 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3351 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3352 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3353 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3354 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3355 LN0->getBasePtr(), LN0->getSrcValue(),
3356 LN0->getSrcValueOffset(), EVT,
3358 LN0->getAlignment());
3359 CombineTo(N, ExtLoad);
3360 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3361 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3363 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3364 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3366 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3367 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3368 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3369 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3370 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3371 LN0->getBasePtr(), LN0->getSrcValue(),
3372 LN0->getSrcValueOffset(), EVT,
3374 LN0->getAlignment());
3375 CombineTo(N, ExtLoad);
3376 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3377 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3382 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
3383 SDValue N0 = N->getOperand(0);
3384 MVT VT = N->getValueType(0);
3387 if (N0.getValueType() == N->getValueType(0))
3389 // fold (truncate c1) -> c1
3390 if (isa<ConstantSDNode>(N0))
3391 return DAG.getNode(ISD::TRUNCATE, VT, N0);
3392 // fold (truncate (truncate x)) -> (truncate x)
3393 if (N0.getOpcode() == ISD::TRUNCATE)
3394 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3395 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3396 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3397 N0.getOpcode() == ISD::ANY_EXTEND) {
3398 if (N0.getOperand(0).getValueType().bitsLT(VT))
3399 // if the source is smaller than the dest, we still need an extend
3400 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3401 else if (N0.getOperand(0).getValueType().bitsGT(VT))
3402 // if the source is larger than the dest, than we just need the truncate
3403 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3405 // if the source and dest are the same type, we can drop both the extend
3407 return N0.getOperand(0);
3410 // See if we can simplify the input to this truncate through knowledge that
3411 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3414 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3415 VT.getSizeInBits()));
3416 if (Shorter.getNode())
3417 return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3419 // fold (truncate (load x)) -> (smaller load x)
3420 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3421 return ReduceLoadWidth(N);
3424 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
3425 SDValue Elt = N->getOperand(i);
3426 if (Elt.getOpcode() != ISD::MERGE_VALUES)
3427 return Elt.getNode();
3428 return Elt.getOperand(Elt.getResNo()).getNode();
3431 /// CombineConsecutiveLoads - build_pair (load, load) -> load
3432 /// if load locations are consecutive.
3433 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, MVT VT) {
3434 assert(N->getOpcode() == ISD::BUILD_PAIR);
3436 SDNode *LD1 = getBuildPairElt(N, 0);
3437 if (!ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
3439 MVT LD1VT = LD1->getValueType(0);
3440 SDNode *LD2 = getBuildPairElt(N, 1);
3441 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3442 if (ISD::isNON_EXTLoad(LD2) &&
3444 // If both are volatile this would reduce the number of volatile loads.
3445 // If one is volatile it might be ok, but play conservative and bail out.
3446 !cast<LoadSDNode>(LD1)->isVolatile() &&
3447 !cast<LoadSDNode>(LD2)->isVolatile() &&
3448 TLI.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1, MFI)) {
3449 LoadSDNode *LD = cast<LoadSDNode>(LD1);
3450 unsigned Align = LD->getAlignment();
3451 unsigned NewAlign = TLI.getTargetData()->
3452 getABITypeAlignment(VT.getTypeForMVT());
3453 if (NewAlign <= Align &&
3454 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT)))
3455 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(),
3456 LD->getSrcValue(), LD->getSrcValueOffset(),
3462 SDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3463 SDValue N0 = N->getOperand(0);
3464 MVT VT = N->getValueType(0);
3466 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3467 // Only do this before legalize, since afterward the target may be depending
3468 // on the bitconvert.
3469 // First check to see if this is all constant.
3470 if (!AfterLegalize &&
3471 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
3473 bool isSimple = true;
3474 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3475 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3476 N0.getOperand(i).getOpcode() != ISD::Constant &&
3477 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3482 MVT DestEltVT = N->getValueType(0).getVectorElementType();
3483 assert(!DestEltVT.isVector() &&
3484 "Element type of vector ValueType must not be vector!");
3486 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT);
3490 // If the input is a constant, let getNode fold it.
3491 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3492 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3493 if (Res.getNode() != N) return Res;
3496 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
3497 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3499 // fold (conv (load x)) -> (load (conv*)x)
3500 // If the resultant load doesn't need a higher alignment than the original!
3501 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
3502 // Do not change the width of a volatile load.
3503 !cast<LoadSDNode>(N0)->isVolatile() &&
3504 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT))) {
3505 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3506 unsigned Align = TLI.getTargetData()->
3507 getABITypeAlignment(VT.getTypeForMVT());
3508 unsigned OrigAlign = LN0->getAlignment();
3509 if (Align <= OrigAlign) {
3510 SDValue Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3511 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3512 LN0->isVolatile(), OrigAlign);
3514 CombineTo(N0.getNode(),
3515 DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3521 // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit)
3522 // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit)
3523 // This often reduces constant pool loads.
3524 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3525 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
3526 SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3527 AddToWorkList(NewConv.getNode());
3529 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3530 if (N0.getOpcode() == ISD::FNEG)
3531 return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT));
3532 assert(N0.getOpcode() == ISD::FABS);
3533 return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT));
3536 // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign'
3537 // Note that we don't handle copysign(x,cst) because this can always be folded
3538 // to an fneg or fabs.
3539 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
3540 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3541 VT.isInteger() && !VT.isVector()) {
3542 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
3543 SDValue X = DAG.getNode(ISD::BIT_CONVERT,
3544 MVT::getIntegerVT(OrigXWidth),
3546 AddToWorkList(X.getNode());
3548 // If X has a different width than the result/lhs, sext it or truncate it.
3549 unsigned VTWidth = VT.getSizeInBits();
3550 if (OrigXWidth < VTWidth) {
3551 X = DAG.getNode(ISD::SIGN_EXTEND, VT, X);
3552 AddToWorkList(X.getNode());
3553 } else if (OrigXWidth > VTWidth) {
3554 // To get the sign bit in the right place, we have to shift it right
3555 // before truncating.
3556 X = DAG.getNode(ISD::SRL, X.getValueType(), X,
3557 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3558 AddToWorkList(X.getNode());
3559 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3560 AddToWorkList(X.getNode());
3563 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3564 X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT));
3565 AddToWorkList(X.getNode());
3567 SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3568 Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT));
3569 AddToWorkList(Cst.getNode());
3571 return DAG.getNode(ISD::OR, VT, X, Cst);
3574 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
3575 if (N0.getOpcode() == ISD::BUILD_PAIR) {
3576 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
3577 if (CombineLD.getNode())
3584 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
3585 MVT VT = N->getValueType(0);
3586 return CombineConsecutiveLoads(N, VT);
3589 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3590 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3591 /// destination element value type.
3592 SDValue DAGCombiner::
3593 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT DstEltVT) {
3594 MVT SrcEltVT = BV->getOperand(0).getValueType();
3596 // If this is already the right type, we're done.
3597 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
3599 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
3600 unsigned DstBitSize = DstEltVT.getSizeInBits();
3602 // If this is a conversion of N elements of one type to N elements of another
3603 // type, convert each element. This handles FP<->INT cases.
3604 if (SrcBitSize == DstBitSize) {
3605 SmallVector<SDValue, 8> Ops;
3606 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3607 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3608 AddToWorkList(Ops.back().getNode());
3610 MVT VT = MVT::getVectorVT(DstEltVT,
3611 BV->getValueType(0).getVectorNumElements());
3612 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3615 // Otherwise, we're growing or shrinking the elements. To avoid having to
3616 // handle annoying details of growing/shrinking FP values, we convert them to
3618 if (SrcEltVT.isFloatingPoint()) {
3619 // Convert the input float vector to a int vector where the elements are the
3621 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3622 MVT IntVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits());
3623 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode();
3627 // Now we know the input is an integer vector. If the output is a FP type,
3628 // convert to integer first, then to FP of the right size.
3629 if (DstEltVT.isFloatingPoint()) {
3630 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3631 MVT TmpVT = MVT::getIntegerVT(DstEltVT.getSizeInBits());
3632 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode();
3634 // Next, convert to FP elements of the same size.
3635 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3638 // Okay, we know the src/dst types are both integers of differing types.
3639 // Handling growing first.
3640 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
3641 if (SrcBitSize < DstBitSize) {
3642 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3644 SmallVector<SDValue, 8> Ops;
3645 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3646 i += NumInputsPerOutput) {
3647 bool isLE = TLI.isLittleEndian();
3648 APInt NewBits = APInt(DstBitSize, 0);
3649 bool EltIsUndef = true;
3650 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3651 // Shift the previously computed bits over.
3652 NewBits <<= SrcBitSize;
3653 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3654 if (Op.getOpcode() == ISD::UNDEF) continue;
3658 APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).zext(DstBitSize);
3662 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3664 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3667 MVT VT = MVT::getVectorVT(DstEltVT, Ops.size());
3668 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3671 // Finally, this must be the case where we are shrinking elements: each input
3672 // turns into multiple outputs.
3673 bool isS2V = ISD::isScalarToVector(BV);
3674 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3675 MVT VT = MVT::getVectorVT(DstEltVT, NumOutputsPerInput*BV->getNumOperands());
3676 SmallVector<SDValue, 8> Ops;
3677 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3678 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3679 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3680 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3683 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getAPIntValue();
3684 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3685 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
3686 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3687 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
3688 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3689 return DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Ops[0]);
3690 OpVal = OpVal.lshr(DstBitSize);
3693 // For big endian targets, swap the order of the pieces of each element.
3694 if (TLI.isBigEndian())
3695 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3697 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3702 SDValue DAGCombiner::visitFADD(SDNode *N) {
3703 SDValue N0 = N->getOperand(0);
3704 SDValue N1 = N->getOperand(1);
3705 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3706 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3707 MVT VT = N->getValueType(0);
3710 if (VT.isVector()) {
3711 SDValue FoldedVOp = SimplifyVBinOp(N);
3712 if (FoldedVOp.getNode()) return FoldedVOp;
3715 // fold (fadd c1, c2) -> c1+c2
3716 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3717 return DAG.getNode(ISD::FADD, VT, N0, N1);
3718 // canonicalize constant to RHS
3719 if (N0CFP && !N1CFP)
3720 return DAG.getNode(ISD::FADD, VT, N1, N0);
3721 // fold (A + (-B)) -> A-B
3722 if (isNegatibleForFree(N1, AfterLegalize) == 2)
3723 return DAG.getNode(ISD::FSUB, VT, N0,
3724 GetNegatedExpression(N1, DAG, AfterLegalize));
3725 // fold ((-A) + B) -> B-A
3726 if (isNegatibleForFree(N0, AfterLegalize) == 2)
3727 return DAG.getNode(ISD::FSUB, VT, N1,
3728 GetNegatedExpression(N0, DAG, AfterLegalize));
3730 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3731 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3732 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3733 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3734 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3739 SDValue DAGCombiner::visitFSUB(SDNode *N) {
3740 SDValue N0 = N->getOperand(0);
3741 SDValue N1 = N->getOperand(1);
3742 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3743 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3744 MVT VT = N->getValueType(0);
3747 if (VT.isVector()) {
3748 SDValue FoldedVOp = SimplifyVBinOp(N);
3749 if (FoldedVOp.getNode()) return FoldedVOp;
3752 // fold (fsub c1, c2) -> c1-c2
3753 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3754 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3756 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
3757 if (isNegatibleForFree(N1, AfterLegalize))
3758 return GetNegatedExpression(N1, DAG, AfterLegalize);
3759 return DAG.getNode(ISD::FNEG, VT, N1);
3761 // fold (A-(-B)) -> A+B
3762 if (isNegatibleForFree(N1, AfterLegalize))
3763 return DAG.getNode(ISD::FADD, VT, N0,
3764 GetNegatedExpression(N1, DAG, AfterLegalize));
3769 SDValue DAGCombiner::visitFMUL(SDNode *N) {
3770 SDValue N0 = N->getOperand(0);
3771 SDValue N1 = N->getOperand(1);
3772 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3773 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3774 MVT VT = N->getValueType(0);
3777 if (VT.isVector()) {
3778 SDValue FoldedVOp = SimplifyVBinOp(N);
3779 if (FoldedVOp.getNode()) return FoldedVOp;
3782 // fold (fmul c1, c2) -> c1*c2
3783 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3784 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3785 // canonicalize constant to RHS
3786 if (N0CFP && !N1CFP)
3787 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3788 // fold (fmul X, 2.0) -> (fadd X, X)
3789 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3790 return DAG.getNode(ISD::FADD, VT, N0, N0);
3791 // fold (fmul X, -1.0) -> (fneg X)
3792 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3793 return DAG.getNode(ISD::FNEG, VT, N0);
3796 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3797 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3798 // Both can be negated for free, check to see if at least one is cheaper
3800 if (LHSNeg == 2 || RHSNeg == 2)
3801 return DAG.getNode(ISD::FMUL, VT,
3802 GetNegatedExpression(N0, DAG, AfterLegalize),
3803 GetNegatedExpression(N1, DAG, AfterLegalize));
3807 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3808 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3809 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3810 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3811 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3816 SDValue DAGCombiner::visitFDIV(SDNode *N) {
3817 SDValue N0 = N->getOperand(0);
3818 SDValue N1 = N->getOperand(1);
3819 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3820 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3821 MVT VT = N->getValueType(0);
3824 if (VT.isVector()) {
3825 SDValue FoldedVOp = SimplifyVBinOp(N);
3826 if (FoldedVOp.getNode()) return FoldedVOp;
3829 // fold (fdiv c1, c2) -> c1/c2
3830 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3831 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3835 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3836 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3837 // Both can be negated for free, check to see if at least one is cheaper
3839 if (LHSNeg == 2 || RHSNeg == 2)
3840 return DAG.getNode(ISD::FDIV, VT,
3841 GetNegatedExpression(N0, DAG, AfterLegalize),
3842 GetNegatedExpression(N1, DAG, AfterLegalize));
3849 SDValue DAGCombiner::visitFREM(SDNode *N) {
3850 SDValue N0 = N->getOperand(0);
3851 SDValue N1 = N->getOperand(1);
3852 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3853 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3854 MVT VT = N->getValueType(0);
3856 // fold (frem c1, c2) -> fmod(c1,c2)
3857 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3858 return DAG.getNode(ISD::FREM, VT, N0, N1);
3863 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3864 SDValue N0 = N->getOperand(0);
3865 SDValue N1 = N->getOperand(1);
3866 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3867 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3868 MVT VT = N->getValueType(0);
3870 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
3871 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3874 const APFloat& V = N1CFP->getValueAPF();
3875 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3876 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
3877 if (!V.isNegative())
3878 return DAG.getNode(ISD::FABS, VT, N0);
3880 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3883 // copysign(fabs(x), y) -> copysign(x, y)
3884 // copysign(fneg(x), y) -> copysign(x, y)
3885 // copysign(copysign(x,z), y) -> copysign(x, y)
3886 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3887 N0.getOpcode() == ISD::FCOPYSIGN)
3888 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3890 // copysign(x, abs(y)) -> abs(x)
3891 if (N1.getOpcode() == ISD::FABS)
3892 return DAG.getNode(ISD::FABS, VT, N0);
3894 // copysign(x, copysign(y,z)) -> copysign(x, z)
3895 if (N1.getOpcode() == ISD::FCOPYSIGN)
3896 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3898 // copysign(x, fp_extend(y)) -> copysign(x, y)
3899 // copysign(x, fp_round(y)) -> copysign(x, y)
3900 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3901 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3908 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3909 SDValue N0 = N->getOperand(0);
3910 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3911 MVT VT = N->getValueType(0);
3912 MVT OpVT = N0.getValueType();
3914 // fold (sint_to_fp c1) -> c1fp
3915 if (N0C && OpVT != MVT::ppcf128)
3916 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3918 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
3919 // but UINT_TO_FP is legal on this target, try to convert.
3920 if (!TLI.isOperationLegal(ISD::SINT_TO_FP, OpVT) &&
3921 TLI.isOperationLegal(ISD::UINT_TO_FP, OpVT)) {
3922 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
3923 if (DAG.SignBitIsZero(N0))
3924 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3931 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3932 SDValue N0 = N->getOperand(0);
3933 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3934 MVT VT = N->getValueType(0);
3935 MVT OpVT = N0.getValueType();
3937 // fold (uint_to_fp c1) -> c1fp
3938 if (N0C && OpVT != MVT::ppcf128)
3939 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3941 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
3942 // but SINT_TO_FP is legal on this target, try to convert.
3943 if (!TLI.isOperationLegal(ISD::UINT_TO_FP, OpVT) &&
3944 TLI.isOperationLegal(ISD::SINT_TO_FP, OpVT)) {
3945 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
3946 if (DAG.SignBitIsZero(N0))
3947 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3953 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3954 SDValue N0 = N->getOperand(0);
3955 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3956 MVT VT = N->getValueType(0);
3958 // fold (fp_to_sint c1fp) -> c1
3960 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3964 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3965 SDValue N0 = N->getOperand(0);
3966 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3967 MVT VT = N->getValueType(0);
3969 // fold (fp_to_uint c1fp) -> c1
3970 if (N0CFP && VT != MVT::ppcf128)
3971 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3975 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
3976 SDValue N0 = N->getOperand(0);
3977 SDValue N1 = N->getOperand(1);
3978 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3979 MVT VT = N->getValueType(0);
3981 // fold (fp_round c1fp) -> c1fp
3982 if (N0CFP && N0.getValueType() != MVT::ppcf128)
3983 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
3985 // fold (fp_round (fp_extend x)) -> x
3986 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3987 return N0.getOperand(0);
3989 // fold (fp_round (fp_round x)) -> (fp_round x)
3990 if (N0.getOpcode() == ISD::FP_ROUND) {
3991 // This is a value preserving truncation if both round's are.
3992 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
3993 N0.getNode()->getConstantOperandVal(1) == 1;
3994 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
3995 DAG.getIntPtrConstant(IsTrunc));
3998 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3999 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
4000 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
4001 AddToWorkList(Tmp.getNode());
4002 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
4008 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
4009 SDValue N0 = N->getOperand(0);
4010 MVT VT = N->getValueType(0);
4011 MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4012 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4014 // fold (fp_round_inreg c1fp) -> c1fp
4016 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
4017 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
4022 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
4023 SDValue N0 = N->getOperand(0);
4024 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4025 MVT VT = N->getValueType(0);
4027 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
4028 if (N->hasOneUse() &&
4029 N->use_begin().getUse().getSDValue().getOpcode() == ISD::FP_ROUND)
4032 // fold (fp_extend c1fp) -> c1fp
4033 if (N0CFP && VT != MVT::ppcf128)
4034 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
4036 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
4038 if (N0.getOpcode() == ISD::FP_ROUND
4039 && N0.getNode()->getConstantOperandVal(1) == 1) {
4040 SDValue In = N0.getOperand(0);
4041 if (In.getValueType() == VT) return In;
4042 if (VT.bitsLT(In.getValueType()))
4043 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
4044 return DAG.getNode(ISD::FP_EXTEND, VT, In);
4047 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
4048 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
4049 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
4050 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4051 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4052 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
4053 LN0->getBasePtr(), LN0->getSrcValue(),
4054 LN0->getSrcValueOffset(),
4057 LN0->getAlignment());
4058 CombineTo(N, ExtLoad);
4059 CombineTo(N0.getNode(), DAG.getNode(ISD::FP_ROUND, N0.getValueType(),
4060 ExtLoad, DAG.getIntPtrConstant(1)),
4061 ExtLoad.getValue(1));
4062 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4068 SDValue DAGCombiner::visitFNEG(SDNode *N) {
4069 SDValue N0 = N->getOperand(0);
4071 if (isNegatibleForFree(N0, AfterLegalize))
4072 return GetNegatedExpression(N0, DAG, AfterLegalize);
4074 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
4075 // constant pool values.
4076 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
4077 N0.getOperand(0).getValueType().isInteger() &&
4078 !N0.getOperand(0).getValueType().isVector()) {
4079 SDValue Int = N0.getOperand(0);
4080 MVT IntVT = Int.getValueType();
4081 if (IntVT.isInteger() && !IntVT.isVector()) {
4082 Int = DAG.getNode(ISD::XOR, IntVT, Int,
4083 DAG.getConstant(IntVT.getIntegerVTSignBit(), IntVT));
4084 AddToWorkList(Int.getNode());
4085 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4092 SDValue DAGCombiner::visitFABS(SDNode *N) {
4093 SDValue N0 = N->getOperand(0);
4094 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4095 MVT VT = N->getValueType(0);
4097 // fold (fabs c1) -> fabs(c1)
4098 if (N0CFP && VT != MVT::ppcf128)
4099 return DAG.getNode(ISD::FABS, VT, N0);
4100 // fold (fabs (fabs x)) -> (fabs x)
4101 if (N0.getOpcode() == ISD::FABS)
4102 return N->getOperand(0);
4103 // fold (fabs (fneg x)) -> (fabs x)
4104 // fold (fabs (fcopysign x, y)) -> (fabs x)
4105 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4106 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
4108 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4109 // constant pool values.
4110 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
4111 N0.getOperand(0).getValueType().isInteger() &&
4112 !N0.getOperand(0).getValueType().isVector()) {
4113 SDValue Int = N0.getOperand(0);
4114 MVT IntVT = Int.getValueType();
4115 if (IntVT.isInteger() && !IntVT.isVector()) {
4116 Int = DAG.getNode(ISD::AND, IntVT, Int,
4117 DAG.getConstant(~IntVT.getIntegerVTSignBit(), IntVT));
4118 AddToWorkList(Int.getNode());
4119 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4126 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
4127 SDValue Chain = N->getOperand(0);
4128 SDValue N1 = N->getOperand(1);
4129 SDValue N2 = N->getOperand(2);
4130 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4132 // never taken branch, fold to chain
4133 if (N1C && N1C->isNullValue())
4135 // unconditional branch
4136 if (N1C && N1C->getAPIntValue() == 1)
4137 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
4138 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4140 if (N1.getOpcode() == ISD::SETCC &&
4141 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
4142 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
4143 N1.getOperand(0), N1.getOperand(1), N2);
4148 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4150 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
4151 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4152 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4154 // Use SimplifySetCC to simplify SETCC's.
4155 SDValue Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
4156 if (Simp.getNode()) AddToWorkList(Simp.getNode());
4158 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.getNode());
4160 // fold br_cc true, dest -> br dest (unconditional branch)
4161 if (SCCC && !SCCC->isNullValue())
4162 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
4164 // fold br_cc false, dest -> unconditional fall through
4165 if (SCCC && SCCC->isNullValue())
4166 return N->getOperand(0);
4168 // fold to a simpler setcc
4169 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
4170 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
4171 Simp.getOperand(2), Simp.getOperand(0),
4172 Simp.getOperand(1), N->getOperand(4));
4177 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
4178 /// pre-indexed load / store when the base pointer is an add or subtract
4179 /// and it has other uses besides the load / store. After the
4180 /// transformation, the new indexed load / store has effectively folded
4181 /// the add / subtract in and all of its other uses are redirected to the
4182 /// new load / store.
4183 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4190 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4191 if (LD->isIndexed())
4193 VT = LD->getMemoryVT();
4194 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4195 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4197 Ptr = LD->getBasePtr();
4198 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4199 if (ST->isIndexed())
4201 VT = ST->getMemoryVT();
4202 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4203 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4205 Ptr = ST->getBasePtr();
4210 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4211 // out. There is no reason to make this a preinc/predec.
4212 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4213 Ptr.getNode()->hasOneUse())
4216 // Ask the target to do addressing mode selection.
4219 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4220 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4222 // Don't create a indexed load / store with zero offset.
4223 if (isa<ConstantSDNode>(Offset) &&
4224 cast<ConstantSDNode>(Offset)->isNullValue())
4227 // Try turning it into a pre-indexed load / store except when:
4228 // 1) The new base ptr is a frame index.
4229 // 2) If N is a store and the new base ptr is either the same as or is a
4230 // predecessor of the value being stored.
4231 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4232 // that would create a cycle.
4233 // 4) All uses are load / store ops that use it as old base ptr.
4235 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4236 // (plus the implicit offset) to a register to preinc anyway.
4237 if (isa<FrameIndexSDNode>(BasePtr))
4242 SDValue Val = cast<StoreSDNode>(N)->getValue();
4243 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
4247 // Now check for #3 and #4.
4248 bool RealUse = false;
4249 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
4250 E = Ptr.getNode()->use_end(); I != E; ++I) {
4254 if (Use->isPredecessorOf(N))
4257 if (!((Use->getOpcode() == ISD::LOAD &&
4258 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
4259 (Use->getOpcode() == ISD::STORE &&
4260 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
4268 Result = DAG.getIndexedLoad(SDValue(N,0), BasePtr, Offset, AM);
4270 Result = DAG.getIndexedStore(SDValue(N,0), BasePtr, Offset, AM);
4273 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
4274 DOUT << "\nWith: "; DEBUG(Result.getNode()->dump(&DAG));
4276 WorkListRemover DeadNodes(*this);
4278 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
4280 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
4283 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
4287 // Finally, since the node is now dead, remove it from the graph.
4290 // Replace the uses of Ptr with uses of the updated base value.
4291 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
4293 removeFromWorkList(Ptr.getNode());
4294 DAG.DeleteNode(Ptr.getNode());
4299 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
4300 /// add / sub of the base pointer node into a post-indexed load / store.
4301 /// The transformation folded the add / subtract into the new indexed
4302 /// load / store effectively and all of its uses are redirected to the
4303 /// new load / store.
4304 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4311 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4312 if (LD->isIndexed())
4314 VT = LD->getMemoryVT();
4315 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4316 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4318 Ptr = LD->getBasePtr();
4319 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4320 if (ST->isIndexed())
4322 VT = ST->getMemoryVT();
4323 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4324 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4326 Ptr = ST->getBasePtr();
4331 if (Ptr.getNode()->hasOneUse())
4334 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
4335 E = Ptr.getNode()->use_end(); I != E; ++I) {
4338 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4343 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4344 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4346 std::swap(BasePtr, Offset);
4349 // Don't create a indexed load / store with zero offset.
4350 if (isa<ConstantSDNode>(Offset) &&
4351 cast<ConstantSDNode>(Offset)->isNullValue())
4354 // Try turning it into a post-indexed load / store except when
4355 // 1) All uses are load / store ops that use it as base ptr.
4356 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4357 // nor a successor of N. Otherwise, if Op is folded that would
4361 bool TryNext = false;
4362 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
4363 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
4365 if (Use == Ptr.getNode())
4368 // If all the uses are load / store addresses, then don't do the
4370 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4371 bool RealUse = false;
4372 for (SDNode::use_iterator III = Use->use_begin(),
4373 EEE = Use->use_end(); III != EEE; ++III) {
4374 SDNode *UseUse = *III;
4375 if (!((UseUse->getOpcode() == ISD::LOAD &&
4376 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
4377 (UseUse->getOpcode() == ISD::STORE &&
4378 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
4392 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
4393 SDValue Result = isLoad
4394 ? DAG.getIndexedLoad(SDValue(N,0), BasePtr, Offset, AM)
4395 : DAG.getIndexedStore(SDValue(N,0), BasePtr, Offset, AM);
4398 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
4399 DOUT << "\nWith: "; DEBUG(Result.getNode()->dump(&DAG));
4401 WorkListRemover DeadNodes(*this);
4403 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
4405 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
4408 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
4412 // Finally, since the node is now dead, remove it from the graph.
4415 // Replace the uses of Use with uses of the updated base value.
4416 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
4417 Result.getValue(isLoad ? 1 : 0),
4419 removeFromWorkList(Op);
4428 /// InferAlignment - If we can infer some alignment information from this
4429 /// pointer, return it.
4430 static unsigned InferAlignment(SDValue Ptr, SelectionDAG &DAG) {
4431 // If this is a direct reference to a stack slot, use information about the
4432 // stack slot's alignment.
4433 int FrameIdx = 1 << 31;
4434 int64_t FrameOffset = 0;
4435 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
4436 FrameIdx = FI->getIndex();
4437 } else if (Ptr.getOpcode() == ISD::ADD &&
4438 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4439 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4440 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4441 FrameOffset = Ptr.getConstantOperandVal(1);
4444 if (FrameIdx != (1 << 31)) {
4445 // FIXME: Handle FI+CST.
4446 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
4447 if (MFI.isFixedObjectIndex(FrameIdx)) {
4448 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx) + FrameOffset;
4450 // The alignment of the frame index can be determined from its offset from
4451 // the incoming frame position. If the frame object is at offset 32 and
4452 // the stack is guaranteed to be 16-byte aligned, then we know that the
4453 // object is 16-byte aligned.
4454 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
4455 unsigned Align = MinAlign(ObjectOffset, StackAlign);
4457 // Finally, the frame object itself may have a known alignment. Factor
4458 // the alignment + offset into a new alignment. For example, if we know
4459 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
4460 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
4461 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
4462 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
4464 return std::max(Align, FIInfoAlign);
4471 SDValue DAGCombiner::visitLOAD(SDNode *N) {
4472 LoadSDNode *LD = cast<LoadSDNode>(N);
4473 SDValue Chain = LD->getChain();
4474 SDValue Ptr = LD->getBasePtr();
4476 // Try to infer better alignment information than the load already has.
4477 if (!Fast && LD->isUnindexed()) {
4478 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4479 if (Align > LD->getAlignment())
4480 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
4481 Chain, Ptr, LD->getSrcValue(),
4482 LD->getSrcValueOffset(), LD->getMemoryVT(),
4483 LD->isVolatile(), Align);
4488 // If load is not volatile and there are no uses of the loaded value (and
4489 // the updated indexed value in case of indexed loads), change uses of the
4490 // chain value into uses of the chain input (i.e. delete the dead load).
4491 if (!LD->isVolatile()) {
4492 if (N->getValueType(1) == MVT::Other) {
4494 if (N->hasNUsesOfValue(0, 0)) {
4495 // It's not safe to use the two value CombineTo variant here. e.g.
4496 // v1, chain2 = load chain1, loc
4497 // v2, chain3 = load chain2, loc
4499 // Now we replace use of chain2 with chain1. This makes the second load
4500 // isomorphic to the one we are deleting, and thus makes this load live.
4501 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4502 DOUT << "\nWith chain: "; DEBUG(Chain.getNode()->dump(&DAG));
4504 WorkListRemover DeadNodes(*this);
4505 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
4506 if (N->use_empty()) {
4507 removeFromWorkList(N);
4510 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4514 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4515 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
4516 SDValue Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
4517 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4518 DOUT << "\nWith: "; DEBUG(Undef.getNode()->dump(&DAG));
4519 DOUT << " and 2 other values\n";
4520 WorkListRemover DeadNodes(*this);
4521 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
4522 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
4523 DAG.getNode(ISD::UNDEF, N->getValueType(1)),
4525 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
4526 removeFromWorkList(N);
4528 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4533 // If this load is directly stored, replace the load value with the stored
4535 // TODO: Handle store large -> read small portion.
4536 // TODO: Handle TRUNCSTORE/LOADEXT
4537 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
4538 !LD->isVolatile()) {
4539 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
4540 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4541 if (PrevST->getBasePtr() == Ptr &&
4542 PrevST->getValue().getValueType() == N->getValueType(0))
4543 return CombineTo(N, Chain.getOperand(1), Chain);
4548 // Walk up chain skipping non-aliasing memory nodes.
4549 SDValue BetterChain = FindBetterChain(N, Chain);
4551 // If there is a better chain.
4552 if (Chain != BetterChain) {
4555 // Replace the chain to void dependency.
4556 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4557 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
4558 LD->getSrcValue(), LD->getSrcValueOffset(),
4559 LD->isVolatile(), LD->getAlignment());
4561 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
4562 LD->getValueType(0),
4563 BetterChain, Ptr, LD->getSrcValue(),
4564 LD->getSrcValueOffset(),
4567 LD->getAlignment());
4570 // Create token factor to keep old chain connected.
4571 SDValue Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
4572 Chain, ReplLoad.getValue(1));
4574 // Replace uses with load result and token factor. Don't add users
4576 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4580 // Try transforming N to an indexed load.
4581 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4582 return SDValue(N, 0);
4588 SDValue DAGCombiner::visitSTORE(SDNode *N) {
4589 StoreSDNode *ST = cast<StoreSDNode>(N);
4590 SDValue Chain = ST->getChain();
4591 SDValue Value = ST->getValue();
4592 SDValue Ptr = ST->getBasePtr();
4594 // Try to infer better alignment information than the store already has.
4595 if (!Fast && ST->isUnindexed()) {
4596 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4597 if (Align > ST->getAlignment())
4598 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
4599 ST->getSrcValueOffset(), ST->getMemoryVT(),
4600 ST->isVolatile(), Align);
4604 // If this is a store of a bit convert, store the input value if the
4605 // resultant store does not need a higher alignment than the original.
4606 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
4607 ST->isUnindexed()) {
4608 unsigned Align = ST->getAlignment();
4609 MVT SVT = Value.getOperand(0).getValueType();
4610 unsigned OrigAlign = TLI.getTargetData()->
4611 getABITypeAlignment(SVT.getTypeForMVT());
4612 if (Align <= OrigAlign &&
4613 ((!AfterLegalize && !ST->isVolatile()) ||
4614 TLI.isOperationLegal(ISD::STORE, SVT)))
4615 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4616 ST->getSrcValueOffset(), ST->isVolatile(), OrigAlign);
4619 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
4620 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
4621 // NOTE: If the original store is volatile, this transform must not increase
4622 // the number of stores. For example, on x86-32 an f64 can be stored in one
4623 // processor operation but an i64 (which is not legal) requires two. So the
4624 // transform should not be done in this case.
4625 if (Value.getOpcode() != ISD::TargetConstantFP) {
4627 switch (CFP->getValueType(0).getSimpleVT()) {
4628 default: assert(0 && "Unknown FP type");
4629 case MVT::f80: // We don't do this for these yet.
4634 if ((!AfterLegalize && !ST->isVolatile()) ||
4635 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4636 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
4637 bitcastToAPInt().getZExtValue(), MVT::i32);
4638 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4639 ST->getSrcValueOffset(), ST->isVolatile(),
4640 ST->getAlignment());
4644 if ((!AfterLegalize && !ST->isVolatile()) ||
4645 TLI.isOperationLegal(ISD::STORE, MVT::i64)) {
4646 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
4647 getZExtValue(), MVT::i64);
4648 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4649 ST->getSrcValueOffset(), ST->isVolatile(),
4650 ST->getAlignment());
4651 } else if (!ST->isVolatile() &&
4652 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4653 // Many FP stores are not made apparent until after legalize, e.g. for
4654 // argument passing. Since this is so common, custom legalize the
4655 // 64-bit integer store into two 32-bit stores.
4656 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
4657 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
4658 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
4659 if (TLI.isBigEndian()) std::swap(Lo, Hi);
4661 int SVOffset = ST->getSrcValueOffset();
4662 unsigned Alignment = ST->getAlignment();
4663 bool isVolatile = ST->isVolatile();
4665 SDValue St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4666 ST->getSrcValueOffset(),
4667 isVolatile, ST->getAlignment());
4668 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4669 DAG.getConstant(4, Ptr.getValueType()));
4671 Alignment = MinAlign(Alignment, 4U);
4672 SDValue St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4673 SVOffset, isVolatile, Alignment);
4674 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4682 // Walk up chain skipping non-aliasing memory nodes.
4683 SDValue BetterChain = FindBetterChain(N, Chain);
4685 // If there is a better chain.
4686 if (Chain != BetterChain) {
4687 // Replace the chain to avoid dependency.
4689 if (ST->isTruncatingStore()) {
4690 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
4691 ST->getSrcValue(),ST->getSrcValueOffset(),
4693 ST->isVolatile(), ST->getAlignment());
4695 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
4696 ST->getSrcValue(), ST->getSrcValueOffset(),
4697 ST->isVolatile(), ST->getAlignment());
4700 // Create token to keep both nodes around.
4702 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4704 // Don't add users to work list.
4705 return CombineTo(N, Token, false);
4709 // Try transforming N to an indexed store.
4710 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4711 return SDValue(N, 0);
4713 // FIXME: is there such a thing as a truncating indexed store?
4714 if (ST->isTruncatingStore() && ST->isUnindexed() &&
4715 Value.getValueType().isInteger()) {
4716 // See if we can simplify the input to this truncstore with knowledge that
4717 // only the low bits are being used. For example:
4718 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
4720 GetDemandedBits(Value,
4721 APInt::getLowBitsSet(Value.getValueSizeInBits(),
4722 ST->getMemoryVT().getSizeInBits()));
4723 AddToWorkList(Value.getNode());
4724 if (Shorter.getNode())
4725 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
4726 ST->getSrcValueOffset(), ST->getMemoryVT(),
4727 ST->isVolatile(), ST->getAlignment());
4729 // Otherwise, see if we can simplify the operation with
4730 // SimplifyDemandedBits, which only works if the value has a single use.
4731 if (SimplifyDemandedBits(Value,
4732 APInt::getLowBitsSet(
4733 Value.getValueSizeInBits(),
4734 ST->getMemoryVT().getSizeInBits())))
4735 return SDValue(N, 0);
4738 // If this is a load followed by a store to the same location, then the store
4740 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
4741 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
4742 ST->isUnindexed() && !ST->isVolatile() &&
4743 // There can't be any side effects between the load and store, such as
4745 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
4746 // The store is dead, remove it.
4751 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
4752 // truncating store. We can do this even if this is already a truncstore.
4753 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
4754 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
4755 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
4756 ST->getMemoryVT())) {
4757 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4758 ST->getSrcValueOffset(), ST->getMemoryVT(),
4759 ST->isVolatile(), ST->getAlignment());
4765 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4766 SDValue InVec = N->getOperand(0);
4767 SDValue InVal = N->getOperand(1);
4768 SDValue EltNo = N->getOperand(2);
4770 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4771 // vector with the inserted element.
4772 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4773 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
4774 SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
4775 InVec.getNode()->op_end());
4776 if (Elt < Ops.size())
4778 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4779 &Ops[0], Ops.size());
4785 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
4786 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
4787 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
4788 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
4790 // Perform only after legalization to ensure build_vector / vector_shuffle
4791 // optimizations have already been done.
4792 if (!AfterLegalize) return SDValue();
4794 SDValue InVec = N->getOperand(0);
4795 SDValue EltNo = N->getOperand(1);
4797 if (isa<ConstantSDNode>(EltNo)) {
4798 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
4799 bool NewLoad = false;
4800 MVT VT = InVec.getValueType();
4801 MVT EVT = VT.getVectorElementType();
4803 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
4804 MVT BCVT = InVec.getOperand(0).getValueType();
4805 if (!BCVT.isVector() || EVT.bitsGT(BCVT.getVectorElementType()))
4807 InVec = InVec.getOperand(0);
4808 EVT = BCVT.getVectorElementType();
4812 LoadSDNode *LN0 = NULL;
4813 if (ISD::isNormalLoad(InVec.getNode()))
4814 LN0 = cast<LoadSDNode>(InVec);
4815 else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4816 InVec.getOperand(0).getValueType() == EVT &&
4817 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
4818 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4819 } else if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
4820 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
4822 // (load $addr+1*size)
4823 unsigned Idx = cast<ConstantSDNode>(InVec.getOperand(2).
4824 getOperand(Elt))->getZExtValue();
4825 unsigned NumElems = InVec.getOperand(2).getNumOperands();
4826 InVec = (Idx < NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
4827 if (InVec.getOpcode() == ISD::BIT_CONVERT)
4828 InVec = InVec.getOperand(0);
4829 if (ISD::isNormalLoad(InVec.getNode())) {
4830 LN0 = cast<LoadSDNode>(InVec);
4831 Elt = (Idx < NumElems) ? Idx : Idx - NumElems;
4834 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
4837 unsigned Align = LN0->getAlignment();
4839 // Check the resultant load doesn't need a higher alignment than the
4841 unsigned NewAlign = TLI.getTargetData()->
4842 getABITypeAlignment(LVT.getTypeForMVT());
4843 if (NewAlign > Align || !TLI.isOperationLegal(ISD::LOAD, LVT))
4848 SDValue NewPtr = LN0->getBasePtr();
4850 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
4851 MVT PtrType = NewPtr.getValueType();
4852 if (TLI.isBigEndian())
4853 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
4854 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
4855 DAG.getConstant(PtrOff, PtrType));
4857 return DAG.getLoad(LVT, LN0->getChain(), NewPtr,
4858 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4859 LN0->isVolatile(), Align);
4865 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4866 unsigned NumInScalars = N->getNumOperands();
4867 MVT VT = N->getValueType(0);
4868 unsigned NumElts = VT.getVectorNumElements();
4869 MVT EltType = VT.getVectorElementType();
4871 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4872 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4873 // at most two distinct vectors, turn this into a shuffle node.
4874 SDValue VecIn1, VecIn2;
4875 for (unsigned i = 0; i != NumInScalars; ++i) {
4876 // Ignore undef inputs.
4877 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4879 // If this input is something other than a EXTRACT_VECTOR_ELT with a
4880 // constant index, bail out.
4881 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4882 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4883 VecIn1 = VecIn2 = SDValue(0, 0);
4887 // If the input vector type disagrees with the result of the build_vector,
4888 // we can't make a shuffle.
4889 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
4890 if (ExtractedFromVec.getValueType() != VT) {
4891 VecIn1 = VecIn2 = SDValue(0, 0);
4895 // Otherwise, remember this. We allow up to two distinct input vectors.
4896 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
4899 if (VecIn1.getNode() == 0) {
4900 VecIn1 = ExtractedFromVec;
4901 } else if (VecIn2.getNode() == 0) {
4902 VecIn2 = ExtractedFromVec;
4905 VecIn1 = VecIn2 = SDValue(0, 0);
4910 // If everything is good, we can make a shuffle operation.
4911 if (VecIn1.getNode()) {
4912 SmallVector<SDValue, 8> BuildVecIndices;
4913 for (unsigned i = 0; i != NumInScalars; ++i) {
4914 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
4915 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
4919 SDValue Extract = N->getOperand(i);
4921 // If extracting from the first vector, just use the index directly.
4922 if (Extract.getOperand(0) == VecIn1) {
4923 BuildVecIndices.push_back(Extract.getOperand(1));
4927 // Otherwise, use InIdx + VecSize
4929 cast<ConstantSDNode>(Extract.getOperand(1))->getZExtValue();
4930 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
4933 // Add count and size info.
4934 MVT BuildVecVT = MVT::getVectorVT(TLI.getPointerTy(), NumElts);
4936 // Return the new VECTOR_SHUFFLE node.
4939 if (VecIn2.getNode()) {
4942 // Use an undef build_vector as input for the second operand.
4943 std::vector<SDValue> UnOps(NumInScalars,
4944 DAG.getNode(ISD::UNDEF,
4946 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
4947 &UnOps[0], UnOps.size());
4948 AddToWorkList(Ops[1].getNode());
4950 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
4951 &BuildVecIndices[0], BuildVecIndices.size());
4952 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
4958 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
4959 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
4960 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
4961 // inputs come from at most two distinct vectors, turn this into a shuffle
4964 // If we only have one input vector, we don't need to do any concatenation.
4965 if (N->getNumOperands() == 1) {
4966 return N->getOperand(0);
4972 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
4973 SDValue ShufMask = N->getOperand(2);
4974 unsigned NumElts = ShufMask.getNumOperands();
4976 // If the shuffle mask is an identity operation on the LHS, return the LHS.
4977 bool isIdentity = true;
4978 for (unsigned i = 0; i != NumElts; ++i) {
4979 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4980 cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue() != i) {
4985 if (isIdentity) return N->getOperand(0);
4987 // If the shuffle mask is an identity operation on the RHS, return the RHS.
4989 for (unsigned i = 0; i != NumElts; ++i) {
4990 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4991 cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue() !=
4997 if (isIdentity) return N->getOperand(1);
4999 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
5001 bool isUnary = true;
5002 bool isSplat = true;
5004 unsigned BaseIdx = 0;
5005 for (unsigned i = 0; i != NumElts; ++i)
5006 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
5007 unsigned Idx=cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue();
5008 int V = (Idx < NumElts) ? 0 : 1;
5022 SDValue N0 = N->getOperand(0);
5023 SDValue N1 = N->getOperand(1);
5024 // Normalize unary shuffle so the RHS is undef.
5025 if (isUnary && VecNum == 1)
5028 // If it is a splat, check if the argument vector is a build_vector with
5029 // all scalar elements the same.
5031 SDNode *V = N0.getNode();
5033 // If this is a bit convert that changes the element type of the vector but
5034 // not the number of vector elements, look through it. Be careful not to
5035 // look though conversions that change things like v4f32 to v2f64.
5036 if (V->getOpcode() == ISD::BIT_CONVERT) {
5037 SDValue ConvInput = V->getOperand(0);
5038 if (ConvInput.getValueType().isVector() &&
5039 ConvInput.getValueType().getVectorNumElements() == NumElts)
5040 V = ConvInput.getNode();
5043 if (V->getOpcode() == ISD::BUILD_VECTOR) {
5044 unsigned NumElems = V->getNumOperands();
5045 if (NumElems > BaseIdx) {
5047 bool AllSame = true;
5048 for (unsigned i = 0; i != NumElems; ++i) {
5049 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
5050 Base = V->getOperand(i);
5054 // Splat of <u, u, u, u>, return <u, u, u, u>
5055 if (!Base.getNode())
5057 for (unsigned i = 0; i != NumElems; ++i) {
5058 if (V->getOperand(i) != Base) {
5063 // Splat of <x, x, x, x>, return <x, x, x, x>
5070 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
5072 if (isUnary || N0 == N1) {
5073 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
5075 SmallVector<SDValue, 8> MappedOps;
5076 for (unsigned i = 0; i != NumElts; ++i) {
5077 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
5078 cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue() <
5080 MappedOps.push_back(ShufMask.getOperand(i));
5083 cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue() -
5085 MappedOps.push_back(DAG.getConstant(NewIdx,
5086 ShufMask.getOperand(i).getValueType()));
5089 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
5090 &MappedOps[0], MappedOps.size());
5091 AddToWorkList(ShufMask.getNode());
5092 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
5094 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
5101 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
5102 /// an AND to a vector_shuffle with the destination vector and a zero vector.
5103 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
5104 /// vector_shuffle V, Zero, <0, 4, 2, 4>
5105 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
5106 SDValue LHS = N->getOperand(0);
5107 SDValue RHS = N->getOperand(1);
5108 if (N->getOpcode() == ISD::AND) {
5109 if (RHS.getOpcode() == ISD::BIT_CONVERT)
5110 RHS = RHS.getOperand(0);
5111 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
5112 std::vector<SDValue> IdxOps;
5113 unsigned NumOps = RHS.getNumOperands();
5114 unsigned NumElts = NumOps;
5115 MVT EVT = RHS.getValueType().getVectorElementType();
5116 for (unsigned i = 0; i != NumElts; ++i) {
5117 SDValue Elt = RHS.getOperand(i);
5118 if (!isa<ConstantSDNode>(Elt))
5120 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
5121 IdxOps.push_back(DAG.getConstant(i, EVT));
5122 else if (cast<ConstantSDNode>(Elt)->isNullValue())
5123 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
5128 // Let's see if the target supports this vector_shuffle.
5129 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
5132 // Return the new VECTOR_SHUFFLE node.
5133 MVT VT = MVT::getVectorVT(EVT, NumElts);
5134 std::vector<SDValue> Ops;
5135 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
5137 AddToWorkList(LHS.getNode());
5138 std::vector<SDValue> ZeroOps(NumElts, DAG.getConstant(0, EVT));
5139 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5140 &ZeroOps[0], ZeroOps.size()));
5141 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5142 &IdxOps[0], IdxOps.size()));
5143 SDValue Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
5144 &Ops[0], Ops.size());
5145 if (VT != N->getValueType(0))
5146 Result = DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Result);
5153 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
5154 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
5155 // After legalize, the target may be depending on adds and other
5156 // binary ops to provide legal ways to construct constants or other
5157 // things. Simplifying them may result in a loss of legality.
5158 if (AfterLegalize) return SDValue();
5160 MVT VT = N->getValueType(0);
5161 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
5163 MVT EltType = VT.getVectorElementType();
5164 SDValue LHS = N->getOperand(0);
5165 SDValue RHS = N->getOperand(1);
5166 SDValue Shuffle = XformToShuffleWithZero(N);
5167 if (Shuffle.getNode()) return Shuffle;
5169 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
5171 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
5172 RHS.getOpcode() == ISD::BUILD_VECTOR) {
5173 SmallVector<SDValue, 8> Ops;
5174 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
5175 SDValue LHSOp = LHS.getOperand(i);
5176 SDValue RHSOp = RHS.getOperand(i);
5177 // If these two elements can't be folded, bail out.
5178 if ((LHSOp.getOpcode() != ISD::UNDEF &&
5179 LHSOp.getOpcode() != ISD::Constant &&
5180 LHSOp.getOpcode() != ISD::ConstantFP) ||
5181 (RHSOp.getOpcode() != ISD::UNDEF &&
5182 RHSOp.getOpcode() != ISD::Constant &&
5183 RHSOp.getOpcode() != ISD::ConstantFP))
5185 // Can't fold divide by zero.
5186 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
5187 N->getOpcode() == ISD::FDIV) {
5188 if ((RHSOp.getOpcode() == ISD::Constant &&
5189 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
5190 (RHSOp.getOpcode() == ISD::ConstantFP &&
5191 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
5194 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
5195 AddToWorkList(Ops.back().getNode());
5196 assert((Ops.back().getOpcode() == ISD::UNDEF ||
5197 Ops.back().getOpcode() == ISD::Constant ||
5198 Ops.back().getOpcode() == ISD::ConstantFP) &&
5199 "Scalar binop didn't fold!");
5202 if (Ops.size() == LHS.getNumOperands()) {
5203 MVT VT = LHS.getValueType();
5204 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
5211 SDValue DAGCombiner::SimplifySelect(SDValue N0, SDValue N1, SDValue N2){
5212 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
5214 SDValue SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
5215 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5216 // If we got a simplified select_cc node back from SimplifySelectCC, then
5217 // break it down into a new SETCC node, and a new SELECT node, and then return
5218 // the SELECT node, since we were called with a SELECT node.
5219 if (SCC.getNode()) {
5220 // Check to see if we got a select_cc back (to turn into setcc/select).
5221 // Otherwise, just return whatever node we got back, like fabs.
5222 if (SCC.getOpcode() == ISD::SELECT_CC) {
5223 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
5224 SCC.getOperand(0), SCC.getOperand(1),
5226 AddToWorkList(SETCC.getNode());
5227 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
5228 SCC.getOperand(3), SETCC);
5235 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5236 /// are the two values being selected between, see if we can simplify the
5237 /// select. Callers of this should assume that TheSelect is deleted if this
5238 /// returns true. As such, they should return the appropriate thing (e.g. the
5239 /// node) back to the top-level of the DAG combiner loop to avoid it being
5242 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
5245 // If this is a select from two identical things, try to pull the operation
5246 // through the select.
5247 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5248 // If this is a load and the token chain is identical, replace the select
5249 // of two loads with a load through a select of the address to load from.
5250 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5251 // constants have been dropped into the constant pool.
5252 if (LHS.getOpcode() == ISD::LOAD &&
5253 // Do not let this transformation reduce the number of volatile loads.
5254 !cast<LoadSDNode>(LHS)->isVolatile() &&
5255 !cast<LoadSDNode>(RHS)->isVolatile() &&
5256 // Token chains must be identical.
5257 LHS.getOperand(0) == RHS.getOperand(0)) {
5258 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5259 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5261 // If this is an EXTLOAD, the VT's must match.
5262 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
5263 // FIXME: this conflates two src values, discarding one. This is not
5264 // the right thing to do, but nothing uses srcvalues now. When they do,
5265 // turn SrcValue into a list of locations.
5267 if (TheSelect->getOpcode() == ISD::SELECT) {
5268 // Check that the condition doesn't reach either load. If so, folding
5269 // this will induce a cycle into the DAG.
5270 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5271 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode())) {
5272 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
5273 TheSelect->getOperand(0), LLD->getBasePtr(),
5277 // Check that the condition doesn't reach either load. If so, folding
5278 // this will induce a cycle into the DAG.
5279 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5280 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5281 !LLD->isPredecessorOf(TheSelect->getOperand(1).getNode()) &&
5282 !RLD->isPredecessorOf(TheSelect->getOperand(1).getNode())) {
5283 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
5284 TheSelect->getOperand(0),
5285 TheSelect->getOperand(1),
5286 LLD->getBasePtr(), RLD->getBasePtr(),
5287 TheSelect->getOperand(4));
5291 if (Addr.getNode()) {
5293 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
5294 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
5295 Addr,LLD->getSrcValue(),
5296 LLD->getSrcValueOffset(),
5298 LLD->getAlignment());
5300 Load = DAG.getExtLoad(LLD->getExtensionType(),
5301 TheSelect->getValueType(0),
5302 LLD->getChain(), Addr, LLD->getSrcValue(),
5303 LLD->getSrcValueOffset(),
5306 LLD->getAlignment());
5308 // Users of the select now use the result of the load.
5309 CombineTo(TheSelect, Load);
5311 // Users of the old loads now use the new load's chain. We know the
5312 // old-load value is dead now.
5313 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
5314 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
5324 SDValue DAGCombiner::SimplifySelectCC(SDValue N0, SDValue N1,
5325 SDValue N2, SDValue N3,
5326 ISD::CondCode CC, bool NotExtCompare) {
5328 MVT VT = N2.getValueType();
5329 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
5330 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
5331 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
5333 // Determine if the condition we're dealing with is constant
5334 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
5335 if (SCC.getNode()) AddToWorkList(SCC.getNode());
5336 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
5338 // fold select_cc true, x, y -> x
5339 if (SCCC && !SCCC->isNullValue())
5341 // fold select_cc false, x, y -> y
5342 if (SCCC && SCCC->isNullValue())
5345 // Check to see if we can simplify the select into an fabs node
5346 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5347 // Allow either -0.0 or 0.0
5348 if (CFP->getValueAPF().isZero()) {
5349 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5350 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5351 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5352 N2 == N3.getOperand(0))
5353 return DAG.getNode(ISD::FABS, VT, N0);
5355 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5356 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5357 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5358 N2.getOperand(0) == N3)
5359 return DAG.getNode(ISD::FABS, VT, N3);
5363 // Check to see if we can perform the "gzip trick", transforming
5364 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
5365 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5366 N0.getValueType().isInteger() &&
5367 N2.getValueType().isInteger() &&
5368 (N1C->isNullValue() || // (a < 0) ? b : 0
5369 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
5370 MVT XType = N0.getValueType();
5371 MVT AType = N2.getValueType();
5372 if (XType.bitsGE(AType)) {
5373 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5374 // single-bit constant.
5375 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
5376 unsigned ShCtV = N2C->getAPIntValue().logBase2();
5377 ShCtV = XType.getSizeInBits()-ShCtV-1;
5378 SDValue ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
5379 SDValue Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
5380 AddToWorkList(Shift.getNode());
5381 if (XType.bitsGT(AType)) {
5382 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5383 AddToWorkList(Shift.getNode());
5385 return DAG.getNode(ISD::AND, AType, Shift, N2);
5387 SDValue Shift = DAG.getNode(ISD::SRA, XType, N0,
5388 DAG.getConstant(XType.getSizeInBits()-1,
5389 TLI.getShiftAmountTy()));
5390 AddToWorkList(Shift.getNode());
5391 if (XType.bitsGT(AType)) {
5392 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5393 AddToWorkList(Shift.getNode());
5395 return DAG.getNode(ISD::AND, AType, Shift, N2);
5399 // fold select C, 16, 0 -> shl C, 4
5400 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
5401 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
5403 // If the caller doesn't want us to simplify this into a zext of a compare,
5405 if (NotExtCompare && N2C->getAPIntValue() == 1)
5408 // Get a SetCC of the condition
5409 // FIXME: Should probably make sure that setcc is legal if we ever have a
5410 // target where it isn't.
5412 // cast from setcc result type to select result type
5413 if (AfterLegalize) {
5414 SCC = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5415 if (N2.getValueType().bitsLT(SCC.getValueType()))
5416 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
5418 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5420 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
5421 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5423 AddToWorkList(SCC.getNode());
5424 AddToWorkList(Temp.getNode());
5426 if (N2C->getAPIntValue() == 1)
5428 // shl setcc result by log2 n2c
5429 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
5430 DAG.getConstant(N2C->getAPIntValue().logBase2(),
5431 TLI.getShiftAmountTy()));
5434 // Check to see if this is the equivalent of setcc
5435 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5436 // otherwise, go ahead with the folds.
5437 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
5438 MVT XType = N0.getValueType();
5439 if (!AfterLegalize ||
5440 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(N0))) {
5441 SDValue Res = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5442 if (Res.getValueType() != VT)
5443 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
5447 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
5448 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5450 TLI.isOperationLegal(ISD::CTLZ, XType))) {
5451 SDValue Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
5452 return DAG.getNode(ISD::SRL, XType, Ctlz,
5453 DAG.getConstant(Log2_32(XType.getSizeInBits()),
5454 TLI.getShiftAmountTy()));
5456 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
5457 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5458 SDValue NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
5460 SDValue NotN0 = DAG.getNode(ISD::XOR, XType, N0,
5461 DAG.getConstant(~0ULL, XType));
5462 return DAG.getNode(ISD::SRL, XType,
5463 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
5464 DAG.getConstant(XType.getSizeInBits()-1,
5465 TLI.getShiftAmountTy()));
5467 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
5468 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5469 SDValue Sign = DAG.getNode(ISD::SRL, XType, N0,
5470 DAG.getConstant(XType.getSizeInBits()-1,
5471 TLI.getShiftAmountTy()));
5472 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
5476 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5477 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5478 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5479 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5480 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
5481 MVT XType = N0.getValueType();
5482 SDValue Shift = DAG.getNode(ISD::SRA, XType, N0,
5483 DAG.getConstant(XType.getSizeInBits()-1,
5484 TLI.getShiftAmountTy()));
5485 SDValue Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5486 AddToWorkList(Shift.getNode());
5487 AddToWorkList(Add.getNode());
5488 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5490 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5491 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5492 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5493 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5494 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5495 MVT XType = N0.getValueType();
5496 if (SubC->isNullValue() && XType.isInteger()) {
5497 SDValue Shift = DAG.getNode(ISD::SRA, XType, N0,
5498 DAG.getConstant(XType.getSizeInBits()-1,
5499 TLI.getShiftAmountTy()));
5500 SDValue Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5501 AddToWorkList(Shift.getNode());
5502 AddToWorkList(Add.getNode());
5503 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5511 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
5512 SDValue DAGCombiner::SimplifySetCC(MVT VT, SDValue N0,
5513 SDValue N1, ISD::CondCode Cond,
5514 bool foldBooleans) {
5515 TargetLowering::DAGCombinerInfo
5516 DagCombineInfo(DAG, !AfterLegalize, false, this);
5517 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
5520 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
5521 /// return a DAG expression to select that will generate the same value by
5522 /// multiplying by a magic number. See:
5523 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5524 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
5525 std::vector<SDNode*> Built;
5526 SDValue S = TLI.BuildSDIV(N, DAG, &Built);
5528 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5534 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
5535 /// return a DAG expression to select that will generate the same value by
5536 /// multiplying by a magic number. See:
5537 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5538 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
5539 std::vector<SDNode*> Built;
5540 SDValue S = TLI.BuildUDIV(N, DAG, &Built);
5542 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5548 /// FindBaseOffset - Return true if base is known not to alias with anything
5549 /// but itself. Provides base object and offset as results.
5550 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset) {
5551 // Assume it is a primitive operation.
5552 Base = Ptr; Offset = 0;
5554 // If it's an adding a simple constant then integrate the offset.
5555 if (Base.getOpcode() == ISD::ADD) {
5556 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
5557 Base = Base.getOperand(0);
5558 Offset += C->getZExtValue();
5562 // If it's any of the following then it can't alias with anything but itself.
5563 return isa<FrameIndexSDNode>(Base) ||
5564 isa<ConstantPoolSDNode>(Base) ||
5565 isa<GlobalAddressSDNode>(Base);
5568 /// isAlias - Return true if there is any possibility that the two addresses
5570 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
5571 const Value *SrcValue1, int SrcValueOffset1,
5572 SDValue Ptr2, int64_t Size2,
5573 const Value *SrcValue2, int SrcValueOffset2)
5575 // If they are the same then they must be aliases.
5576 if (Ptr1 == Ptr2) return true;
5578 // Gather base node and offset information.
5579 SDValue Base1, Base2;
5580 int64_t Offset1, Offset2;
5581 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
5582 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
5584 // If they have a same base address then...
5585 if (Base1 == Base2) {
5586 // Check to see if the addresses overlap.
5587 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
5590 // If we know both bases then they can't alias.
5591 if (KnownBase1 && KnownBase2) return false;
5593 if (CombinerGlobalAA) {
5594 // Use alias analysis information.
5595 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
5596 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
5597 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
5598 AliasAnalysis::AliasResult AAResult =
5599 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
5600 if (AAResult == AliasAnalysis::NoAlias)
5604 // Otherwise we have to assume they alias.
5608 /// FindAliasInfo - Extracts the relevant alias information from the memory
5609 /// node. Returns true if the operand was a load.
5610 bool DAGCombiner::FindAliasInfo(SDNode *N,
5611 SDValue &Ptr, int64_t &Size,
5612 const Value *&SrcValue, int &SrcValueOffset) {
5613 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5614 Ptr = LD->getBasePtr();
5615 Size = LD->getMemoryVT().getSizeInBits() >> 3;
5616 SrcValue = LD->getSrcValue();
5617 SrcValueOffset = LD->getSrcValueOffset();
5619 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5620 Ptr = ST->getBasePtr();
5621 Size = ST->getMemoryVT().getSizeInBits() >> 3;
5622 SrcValue = ST->getSrcValue();
5623 SrcValueOffset = ST->getSrcValueOffset();
5625 assert(0 && "FindAliasInfo expected a memory operand");
5631 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
5632 /// looking for aliasing nodes and adding them to the Aliases vector.
5633 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
5634 SmallVector<SDValue, 8> &Aliases) {
5635 SmallVector<SDValue, 8> Chains; // List of chains to visit.
5636 std::set<SDNode *> Visited; // Visited node set.
5638 // Get alias information for node.
5641 const Value *SrcValue;
5643 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
5646 Chains.push_back(OriginalChain);
5648 // Look at each chain and determine if it is an alias. If so, add it to the
5649 // aliases list. If not, then continue up the chain looking for the next
5651 while (!Chains.empty()) {
5652 SDValue Chain = Chains.back();
5655 // Don't bother if we've been before.
5656 if (Visited.find(Chain.getNode()) != Visited.end()) continue;
5657 Visited.insert(Chain.getNode());
5659 switch (Chain.getOpcode()) {
5660 case ISD::EntryToken:
5661 // Entry token is ideal chain operand, but handled in FindBetterChain.
5666 // Get alias information for Chain.
5669 const Value *OpSrcValue;
5670 int OpSrcValueOffset;
5671 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
5672 OpSrcValue, OpSrcValueOffset);
5674 // If chain is alias then stop here.
5675 if (!(IsLoad && IsOpLoad) &&
5676 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
5677 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
5678 Aliases.push_back(Chain);
5680 // Look further up the chain.
5681 Chains.push_back(Chain.getOperand(0));
5682 // Clean up old chain.
5683 AddToWorkList(Chain.getNode());
5688 case ISD::TokenFactor:
5689 // We have to check each of the operands of the token factor, so we queue
5690 // then up. Adding the operands to the queue (stack) in reverse order
5691 // maintains the original order and increases the likelihood that getNode
5692 // will find a matching token factor (CSE.)
5693 for (unsigned n = Chain.getNumOperands(); n;)
5694 Chains.push_back(Chain.getOperand(--n));
5695 // Eliminate the token factor if we can.
5696 AddToWorkList(Chain.getNode());
5700 // For all other instructions we will just have to take what we can get.
5701 Aliases.push_back(Chain);
5707 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
5708 /// for a better chain (aliasing node.)
5709 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
5710 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
5712 // Accumulate all the aliases to this node.
5713 GatherAllAliases(N, OldChain, Aliases);
5715 if (Aliases.size() == 0) {
5716 // If no operands then chain to entry token.
5717 return DAG.getEntryNode();
5718 } else if (Aliases.size() == 1) {
5719 // If a single operand then chain to it. We don't need to revisit it.
5723 // Construct a custom tailored token factor.
5724 SDValue NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5725 &Aliases[0], Aliases.size());
5727 // Make sure the old chain gets cleaned up.
5728 if (NewChain != OldChain) AddToWorkList(OldChain.getNode());
5733 // SelectionDAG::Combine - This is the entry point for the file.
5735 void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA,
5737 /// run - This is the main entry point to this class.
5739 DAGCombiner(*this, AA, Fast).Run(RunningAfterLegalize);