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");
42 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
43 cl::desc("Pop up a window to show dags before the first "
46 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
47 cl::desc("Pop up a window to show dags before the second "
50 static const bool ViewDAGCombine1 = false;
51 static const bool ViewDAGCombine2 = false;
55 CombinerAA("combiner-alias-analysis", cl::Hidden,
56 cl::desc("Turn on alias analysis during testing"));
59 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
60 cl::desc("Include global information in alias analysis"));
62 //------------------------------ DAGCombiner ---------------------------------//
64 class VISIBILITY_HIDDEN DAGCombiner {
69 // Worklist of all of the nodes that need to be simplified.
70 std::vector<SDNode*> WorkList;
72 // AA - Used for DAG load/store alias analysis.
75 /// AddUsersToWorkList - When an instruction is simplified, add all users of
76 /// the instruction to the work lists because they might get more simplified
79 void AddUsersToWorkList(SDNode *N) {
80 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
82 AddToWorkList(UI->getUser());
85 /// visit - call the node-specific routine that knows how to fold each
86 /// particular type of node.
87 SDOperand visit(SDNode *N);
90 /// AddToWorkList - Add to the work list making sure it's instance is at the
91 /// the back (next to be processed.)
92 void AddToWorkList(SDNode *N) {
93 removeFromWorkList(N);
94 WorkList.push_back(N);
97 /// removeFromWorkList - remove all instances of N from the worklist.
99 void removeFromWorkList(SDNode *N) {
100 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
104 SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
107 SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
108 return CombineTo(N, &Res, 1, AddTo);
111 SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
113 SDOperand To[] = { Res0, Res1 };
114 return CombineTo(N, To, 2, AddTo);
119 /// SimplifyDemandedBits - Check the specified integer node value to see if
120 /// it can be simplified or if things it uses can be simplified by bit
121 /// propagation. If so, return true.
122 bool SimplifyDemandedBits(SDOperand Op) {
123 APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
124 return SimplifyDemandedBits(Op, Demanded);
127 bool SimplifyDemandedBits(SDOperand Op, const APInt &Demanded);
129 bool CombineToPreIndexedLoadStore(SDNode *N);
130 bool CombineToPostIndexedLoadStore(SDNode *N);
133 /// combine - call the node-specific routine that knows how to fold each
134 /// particular type of node. If that doesn't do anything, try the
135 /// target-specific DAG combines.
136 SDOperand combine(SDNode *N);
138 // Visitation implementation - Implement dag node combining for different
139 // node types. The semantics are as follows:
141 // SDOperand.Val == 0 - No change was made
142 // SDOperand.Val == N - N was replaced, is dead, and is already handled.
143 // otherwise - N should be replaced by the returned Operand.
145 SDOperand visitTokenFactor(SDNode *N);
146 SDOperand visitMERGE_VALUES(SDNode *N);
147 SDOperand visitADD(SDNode *N);
148 SDOperand visitSUB(SDNode *N);
149 SDOperand visitADDC(SDNode *N);
150 SDOperand visitADDE(SDNode *N);
151 SDOperand visitMUL(SDNode *N);
152 SDOperand visitSDIV(SDNode *N);
153 SDOperand visitUDIV(SDNode *N);
154 SDOperand visitSREM(SDNode *N);
155 SDOperand visitUREM(SDNode *N);
156 SDOperand visitMULHU(SDNode *N);
157 SDOperand visitMULHS(SDNode *N);
158 SDOperand visitSMUL_LOHI(SDNode *N);
159 SDOperand visitUMUL_LOHI(SDNode *N);
160 SDOperand visitSDIVREM(SDNode *N);
161 SDOperand visitUDIVREM(SDNode *N);
162 SDOperand visitAND(SDNode *N);
163 SDOperand visitOR(SDNode *N);
164 SDOperand visitXOR(SDNode *N);
165 SDOperand SimplifyVBinOp(SDNode *N);
166 SDOperand visitSHL(SDNode *N);
167 SDOperand visitSRA(SDNode *N);
168 SDOperand visitSRL(SDNode *N);
169 SDOperand visitCTLZ(SDNode *N);
170 SDOperand visitCTTZ(SDNode *N);
171 SDOperand visitCTPOP(SDNode *N);
172 SDOperand visitSELECT(SDNode *N);
173 SDOperand visitSELECT_CC(SDNode *N);
174 SDOperand visitSETCC(SDNode *N);
175 SDOperand visitSIGN_EXTEND(SDNode *N);
176 SDOperand visitZERO_EXTEND(SDNode *N);
177 SDOperand visitANY_EXTEND(SDNode *N);
178 SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
179 SDOperand visitTRUNCATE(SDNode *N);
180 SDOperand visitBIT_CONVERT(SDNode *N);
181 SDOperand visitBUILD_PAIR(SDNode *N);
182 SDOperand visitFADD(SDNode *N);
183 SDOperand visitFSUB(SDNode *N);
184 SDOperand visitFMUL(SDNode *N);
185 SDOperand visitFDIV(SDNode *N);
186 SDOperand visitFREM(SDNode *N);
187 SDOperand visitFCOPYSIGN(SDNode *N);
188 SDOperand visitSINT_TO_FP(SDNode *N);
189 SDOperand visitUINT_TO_FP(SDNode *N);
190 SDOperand visitFP_TO_SINT(SDNode *N);
191 SDOperand visitFP_TO_UINT(SDNode *N);
192 SDOperand visitFP_ROUND(SDNode *N);
193 SDOperand visitFP_ROUND_INREG(SDNode *N);
194 SDOperand visitFP_EXTEND(SDNode *N);
195 SDOperand visitFNEG(SDNode *N);
196 SDOperand visitFABS(SDNode *N);
197 SDOperand visitBRCOND(SDNode *N);
198 SDOperand visitBR_CC(SDNode *N);
199 SDOperand visitLOAD(SDNode *N);
200 SDOperand visitSTORE(SDNode *N);
201 SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
202 SDOperand visitEXTRACT_VECTOR_ELT(SDNode *N);
203 SDOperand visitBUILD_VECTOR(SDNode *N);
204 SDOperand visitCONCAT_VECTORS(SDNode *N);
205 SDOperand visitVECTOR_SHUFFLE(SDNode *N);
207 SDOperand XformToShuffleWithZero(SDNode *N);
208 SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
210 SDOperand visitShiftByConstant(SDNode *N, unsigned Amt);
212 bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
213 SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
214 SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
215 SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
216 SDOperand N3, ISD::CondCode CC,
217 bool NotExtCompare = false);
218 SDOperand SimplifySetCC(MVT VT, SDOperand N0, SDOperand N1,
219 ISD::CondCode Cond, bool foldBooleans = true);
220 SDOperand SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
222 SDOperand CombineConsecutiveLoads(SDNode *N, MVT VT);
223 SDOperand ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT);
224 SDOperand BuildSDIV(SDNode *N);
225 SDOperand BuildUDIV(SDNode *N);
226 SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
227 SDOperand ReduceLoadWidth(SDNode *N);
229 SDOperand GetDemandedBits(SDOperand V, const APInt &Mask);
231 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
232 /// looking for aliasing nodes and adding them to the Aliases vector.
233 void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
234 SmallVector<SDOperand, 8> &Aliases);
236 /// isAlias - Return true if there is any possibility that the two addresses
238 bool isAlias(SDOperand Ptr1, int64_t Size1,
239 const Value *SrcValue1, int SrcValueOffset1,
240 SDOperand Ptr2, int64_t Size2,
241 const Value *SrcValue2, int SrcValueOffset2);
243 /// FindAliasInfo - Extracts the relevant alias information from the memory
244 /// node. Returns true if the operand was a load.
245 bool FindAliasInfo(SDNode *N,
246 SDOperand &Ptr, int64_t &Size,
247 const Value *&SrcValue, int &SrcValueOffset);
249 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
250 /// looking for a better chain (aliasing node.)
251 SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
254 DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
256 TLI(D.getTargetLoweringInfo()),
257 AfterLegalize(false),
260 /// Run - runs the dag combiner on all nodes in the work list
261 void Run(bool RunningAfterLegalize);
267 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
268 /// nodes from the worklist.
269 class VISIBILITY_HIDDEN WorkListRemover :
270 public SelectionDAG::DAGUpdateListener {
273 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
275 virtual void NodeDeleted(SDNode *N, SDNode *E) {
276 DC.removeFromWorkList(N);
279 virtual void NodeUpdated(SDNode *N) {
285 //===----------------------------------------------------------------------===//
286 // TargetLowering::DAGCombinerInfo implementation
287 //===----------------------------------------------------------------------===//
289 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
290 ((DAGCombiner*)DC)->AddToWorkList(N);
293 SDOperand TargetLowering::DAGCombinerInfo::
294 CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
295 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
298 SDOperand TargetLowering::DAGCombinerInfo::
299 CombineTo(SDNode *N, SDOperand Res) {
300 return ((DAGCombiner*)DC)->CombineTo(N, Res);
304 SDOperand TargetLowering::DAGCombinerInfo::
305 CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
306 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
310 //===----------------------------------------------------------------------===//
312 //===----------------------------------------------------------------------===//
314 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
315 /// specified expression for the same cost as the expression itself, or 2 if we
316 /// can compute the negated form more cheaply than the expression itself.
317 static char isNegatibleForFree(SDOperand Op, bool AfterLegalize,
318 unsigned Depth = 0) {
319 // No compile time optimizations on this type.
320 if (Op.getValueType() == MVT::ppcf128)
323 // fneg is removable even if it has multiple uses.
324 if (Op.getOpcode() == ISD::FNEG) return 2;
326 // Don't allow anything with multiple uses.
327 if (!Op.hasOneUse()) return 0;
329 // Don't recurse exponentially.
330 if (Depth > 6) return 0;
332 switch (Op.getOpcode()) {
333 default: return false;
334 case ISD::ConstantFP:
335 // Don't invert constant FP values after legalize. The negated constant
336 // isn't necessarily legal.
337 return AfterLegalize ? 0 : 1;
339 // FIXME: determine better conditions for this xform.
340 if (!UnsafeFPMath) return 0;
343 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
346 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
348 // We can't turn -(A-B) into B-A when we honor signed zeros.
349 if (!UnsafeFPMath) return 0;
356 if (HonorSignDependentRoundingFPMath()) return 0;
358 // -(X*Y) -> (-X * Y) or (X*-Y)
359 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
362 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
367 return isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1);
371 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
372 /// returns the newly negated expression.
373 static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
374 bool AfterLegalize, unsigned Depth = 0) {
375 // fneg is removable even if it has multiple uses.
376 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
378 // Don't allow anything with multiple uses.
379 assert(Op.hasOneUse() && "Unknown reuse!");
381 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
382 switch (Op.getOpcode()) {
383 default: assert(0 && "Unknown code");
384 case ISD::ConstantFP: {
385 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
387 return DAG.getConstantFP(V, Op.getValueType());
390 // FIXME: determine better conditions for this xform.
391 assert(UnsafeFPMath);
394 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
395 return DAG.getNode(ISD::FSUB, Op.getValueType(),
396 GetNegatedExpression(Op.getOperand(0), DAG,
397 AfterLegalize, Depth+1),
400 return DAG.getNode(ISD::FSUB, Op.getValueType(),
401 GetNegatedExpression(Op.getOperand(1), DAG,
402 AfterLegalize, Depth+1),
405 // We can't turn -(A-B) into B-A when we honor signed zeros.
406 assert(UnsafeFPMath);
409 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
410 if (N0CFP->getValueAPF().isZero())
411 return Op.getOperand(1);
414 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1),
419 assert(!HonorSignDependentRoundingFPMath());
422 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
423 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
424 GetNegatedExpression(Op.getOperand(0), DAG,
425 AfterLegalize, Depth+1),
429 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
431 GetNegatedExpression(Op.getOperand(1), DAG,
432 AfterLegalize, Depth+1));
436 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
437 GetNegatedExpression(Op.getOperand(0), DAG,
438 AfterLegalize, Depth+1));
440 return DAG.getNode(ISD::FP_ROUND, Op.getValueType(),
441 GetNegatedExpression(Op.getOperand(0), DAG,
442 AfterLegalize, Depth+1),
448 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
449 // that selects between the values 1 and 0, making it equivalent to a setcc.
450 // Also, set the incoming LHS, RHS, and CC references to the appropriate
451 // nodes based on the type of node we are checking. This simplifies life a
452 // bit for the callers.
453 static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
455 if (N.getOpcode() == ISD::SETCC) {
456 LHS = N.getOperand(0);
457 RHS = N.getOperand(1);
458 CC = N.getOperand(2);
461 if (N.getOpcode() == ISD::SELECT_CC &&
462 N.getOperand(2).getOpcode() == ISD::Constant &&
463 N.getOperand(3).getOpcode() == ISD::Constant &&
464 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
465 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
466 LHS = N.getOperand(0);
467 RHS = N.getOperand(1);
468 CC = N.getOperand(4);
474 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
475 // one use. If this is true, it allows the users to invert the operation for
476 // free when it is profitable to do so.
477 static bool isOneUseSetCC(SDOperand N) {
478 SDOperand N0, N1, N2;
479 if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
484 SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
485 MVT VT = N0.getValueType();
486 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
487 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
488 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
489 if (isa<ConstantSDNode>(N1)) {
490 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
491 AddToWorkList(OpNode.Val);
492 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
493 } else if (N0.hasOneUse()) {
494 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
495 AddToWorkList(OpNode.Val);
496 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
499 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
500 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
501 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
502 if (isa<ConstantSDNode>(N0)) {
503 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
504 AddToWorkList(OpNode.Val);
505 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
506 } else if (N1.hasOneUse()) {
507 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
508 AddToWorkList(OpNode.Val);
509 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
515 SDOperand DAGCombiner::CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
517 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
519 DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
520 DOUT << "\nWith: "; DEBUG(To[0].Val->dump(&DAG));
521 DOUT << " and " << NumTo-1 << " other values\n";
522 WorkListRemover DeadNodes(*this);
523 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
526 // Push the new nodes and any users onto the worklist
527 for (unsigned i = 0, e = NumTo; i != e; ++i) {
528 AddToWorkList(To[i].Val);
529 AddUsersToWorkList(To[i].Val);
533 // Nodes can be reintroduced into the worklist. Make sure we do not
534 // process a node that has been replaced.
535 removeFromWorkList(N);
537 // Finally, since the node is now dead, remove it from the graph.
539 return SDOperand(N, 0);
542 /// SimplifyDemandedBits - Check the specified integer node value to see if
543 /// it can be simplified or if things it uses can be simplified by bit
544 /// propagation. If so, return true.
545 bool DAGCombiner::SimplifyDemandedBits(SDOperand Op, const APInt &Demanded) {
546 TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize);
547 APInt KnownZero, KnownOne;
548 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
552 AddToWorkList(Op.Val);
554 // Replace the old value with the new one.
556 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.Val->dump(&DAG));
557 DOUT << "\nWith: "; DEBUG(TLO.New.Val->dump(&DAG));
560 // Replace all uses. If any nodes become isomorphic to other nodes and
561 // are deleted, make sure to remove them from our worklist.
562 WorkListRemover DeadNodes(*this);
563 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
565 // Push the new node and any (possibly new) users onto the worklist.
566 AddToWorkList(TLO.New.Val);
567 AddUsersToWorkList(TLO.New.Val);
569 // Finally, if the node is now dead, remove it from the graph. The node
570 // may not be dead if the replacement process recursively simplified to
571 // something else needing this node.
572 if (TLO.Old.Val->use_empty()) {
573 removeFromWorkList(TLO.Old.Val);
575 // If the operands of this node are only used by the node, they will now
576 // be dead. Make sure to visit them first to delete dead nodes early.
577 for (unsigned i = 0, e = TLO.Old.Val->getNumOperands(); i != e; ++i)
578 if (TLO.Old.Val->getOperand(i).Val->hasOneUse())
579 AddToWorkList(TLO.Old.Val->getOperand(i).Val);
581 DAG.DeleteNode(TLO.Old.Val);
586 //===----------------------------------------------------------------------===//
587 // Main DAG Combiner implementation
588 //===----------------------------------------------------------------------===//
590 void DAGCombiner::Run(bool RunningAfterLegalize) {
591 // set the instance variable, so that the various visit routines may use it.
592 AfterLegalize = RunningAfterLegalize;
594 // Add all the dag nodes to the worklist.
595 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
596 E = DAG.allnodes_end(); I != E; ++I)
597 WorkList.push_back(I);
599 // Create a dummy node (which is not added to allnodes), that adds a reference
600 // to the root node, preventing it from being deleted, and tracking any
601 // changes of the root.
602 HandleSDNode Dummy(DAG.getRoot());
604 // The root of the dag may dangle to deleted nodes until the dag combiner is
605 // done. Set it to null to avoid confusion.
606 DAG.setRoot(SDOperand());
608 // while the worklist isn't empty, inspect the node on the end of it and
609 // try and combine it.
610 while (!WorkList.empty()) {
611 SDNode *N = WorkList.back();
614 // If N has no uses, it is dead. Make sure to revisit all N's operands once
615 // N is deleted from the DAG, since they too may now be dead or may have a
616 // reduced number of uses, allowing other xforms.
617 if (N->use_empty() && N != &Dummy) {
618 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
619 AddToWorkList(N->getOperand(i).Val);
625 SDOperand RV = combine(N);
632 // If we get back the same node we passed in, rather than a new node or
633 // zero, we know that the node must have defined multiple values and
634 // CombineTo was used. Since CombineTo takes care of the worklist
635 // mechanics for us, we have no work to do in this case.
639 assert(N->getOpcode() != ISD::DELETED_NODE &&
640 RV.Val->getOpcode() != ISD::DELETED_NODE &&
641 "Node was deleted but visit returned new node!");
643 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
644 DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
646 WorkListRemover DeadNodes(*this);
647 if (N->getNumValues() == RV.Val->getNumValues())
648 DAG.ReplaceAllUsesWith(N, RV.Val, &DeadNodes);
650 assert(N->getValueType(0) == RV.getValueType() &&
651 N->getNumValues() == 1 && "Type mismatch");
653 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
656 // Push the new node and any users onto the worklist
657 AddToWorkList(RV.Val);
658 AddUsersToWorkList(RV.Val);
660 // Add any uses of the old node to the worklist in case this node is the
661 // last one that uses them. They may become dead after this node is
663 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
664 AddToWorkList(N->getOperand(i).Val);
666 // Nodes can be reintroduced into the worklist. Make sure we do not
667 // process a node that has been replaced.
668 removeFromWorkList(N);
670 // Finally, since the node is now dead, remove it from the graph.
674 // If the root changed (e.g. it was a dead load, update the root).
675 DAG.setRoot(Dummy.getValue());
678 SDOperand DAGCombiner::visit(SDNode *N) {
679 switch(N->getOpcode()) {
681 case ISD::TokenFactor: return visitTokenFactor(N);
682 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
683 case ISD::ADD: return visitADD(N);
684 case ISD::SUB: return visitSUB(N);
685 case ISD::ADDC: return visitADDC(N);
686 case ISD::ADDE: return visitADDE(N);
687 case ISD::MUL: return visitMUL(N);
688 case ISD::SDIV: return visitSDIV(N);
689 case ISD::UDIV: return visitUDIV(N);
690 case ISD::SREM: return visitSREM(N);
691 case ISD::UREM: return visitUREM(N);
692 case ISD::MULHU: return visitMULHU(N);
693 case ISD::MULHS: return visitMULHS(N);
694 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
695 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
696 case ISD::SDIVREM: return visitSDIVREM(N);
697 case ISD::UDIVREM: return visitUDIVREM(N);
698 case ISD::AND: return visitAND(N);
699 case ISD::OR: return visitOR(N);
700 case ISD::XOR: return visitXOR(N);
701 case ISD::SHL: return visitSHL(N);
702 case ISD::SRA: return visitSRA(N);
703 case ISD::SRL: return visitSRL(N);
704 case ISD::CTLZ: return visitCTLZ(N);
705 case ISD::CTTZ: return visitCTTZ(N);
706 case ISD::CTPOP: return visitCTPOP(N);
707 case ISD::SELECT: return visitSELECT(N);
708 case ISD::SELECT_CC: return visitSELECT_CC(N);
709 case ISD::SETCC: return visitSETCC(N);
710 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
711 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
712 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
713 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
714 case ISD::TRUNCATE: return visitTRUNCATE(N);
715 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
716 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
717 case ISD::FADD: return visitFADD(N);
718 case ISD::FSUB: return visitFSUB(N);
719 case ISD::FMUL: return visitFMUL(N);
720 case ISD::FDIV: return visitFDIV(N);
721 case ISD::FREM: return visitFREM(N);
722 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
723 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
724 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
725 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
726 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
727 case ISD::FP_ROUND: return visitFP_ROUND(N);
728 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
729 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
730 case ISD::FNEG: return visitFNEG(N);
731 case ISD::FABS: return visitFABS(N);
732 case ISD::BRCOND: return visitBRCOND(N);
733 case ISD::BR_CC: return visitBR_CC(N);
734 case ISD::LOAD: return visitLOAD(N);
735 case ISD::STORE: return visitSTORE(N);
736 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
737 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
738 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
739 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
740 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
745 SDOperand DAGCombiner::combine(SDNode *N) {
747 SDOperand RV = visit(N);
749 // If nothing happened, try a target-specific DAG combine.
751 assert(N->getOpcode() != ISD::DELETED_NODE &&
752 "Node was deleted but visit returned NULL!");
754 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
755 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
757 // Expose the DAG combiner to the target combiner impls.
758 TargetLowering::DAGCombinerInfo
759 DagCombineInfo(DAG, !AfterLegalize, false, this);
761 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
765 // If N is a commutative binary node, try commuting it to enable more
768 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
769 N->getNumValues() == 1) {
770 SDOperand N0 = N->getOperand(0);
771 SDOperand N1 = N->getOperand(1);
772 // Constant operands are canonicalized to RHS.
773 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
774 SDOperand Ops[] = { N1, N0 };
775 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
778 return SDOperand(CSENode, 0);
785 /// getInputChainForNode - Given a node, return its input chain if it has one,
786 /// otherwise return a null sd operand.
787 static SDOperand getInputChainForNode(SDNode *N) {
788 if (unsigned NumOps = N->getNumOperands()) {
789 if (N->getOperand(0).getValueType() == MVT::Other)
790 return N->getOperand(0);
791 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
792 return N->getOperand(NumOps-1);
793 for (unsigned i = 1; i < NumOps-1; ++i)
794 if (N->getOperand(i).getValueType() == MVT::Other)
795 return N->getOperand(i);
797 return SDOperand(0, 0);
800 SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
801 // If N has two operands, where one has an input chain equal to the other,
802 // the 'other' chain is redundant.
803 if (N->getNumOperands() == 2) {
804 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
805 return N->getOperand(0);
806 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
807 return N->getOperand(1);
810 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
811 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
812 SmallPtrSet<SDNode*, 16> SeenOps;
813 bool Changed = false; // If we should replace this token factor.
815 // Start out with this token factor.
818 // Iterate through token factors. The TFs grows when new token factors are
820 for (unsigned i = 0; i < TFs.size(); ++i) {
823 // Check each of the operands.
824 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
825 SDOperand Op = TF->getOperand(i);
827 switch (Op.getOpcode()) {
828 case ISD::EntryToken:
829 // Entry tokens don't need to be added to the list. They are
834 case ISD::TokenFactor:
835 if ((CombinerAA || Op.hasOneUse()) &&
836 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
837 // Queue up for processing.
838 TFs.push_back(Op.Val);
839 // Clean up in case the token factor is removed.
840 AddToWorkList(Op.Val);
847 // Only add if it isn't already in the list.
848 if (SeenOps.insert(Op.Val))
859 // If we've change things around then replace token factor.
862 // The entry token is the only possible outcome.
863 Result = DAG.getEntryNode();
865 // New and improved token factor.
866 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
869 // Don't add users to work list.
870 return CombineTo(N, Result, false);
876 /// MERGE_VALUES can always be eliminated.
877 SDOperand DAGCombiner::visitMERGE_VALUES(SDNode *N) {
878 WorkListRemover DeadNodes(*this);
879 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
880 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, i), N->getOperand(i),
882 removeFromWorkList(N);
884 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
889 SDOperand combineShlAddConstant(SDOperand N0, SDOperand N1, SelectionDAG &DAG) {
890 MVT VT = N0.getValueType();
891 SDOperand N00 = N0.getOperand(0);
892 SDOperand N01 = N0.getOperand(1);
893 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
894 if (N01C && N00.getOpcode() == ISD::ADD && N00.Val->hasOneUse() &&
895 isa<ConstantSDNode>(N00.getOperand(1))) {
896 N0 = DAG.getNode(ISD::ADD, VT,
897 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
898 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
899 return DAG.getNode(ISD::ADD, VT, N0, N1);
905 SDOperand combineSelectAndUse(SDNode *N, SDOperand Slct, SDOperand OtherOp,
907 MVT VT = N->getValueType(0);
908 unsigned Opc = N->getOpcode();
909 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
910 SDOperand LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
911 SDOperand RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
912 ISD::CondCode CC = ISD::SETCC_INVALID;
914 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
916 SDOperand CCOp = Slct.getOperand(0);
917 if (CCOp.getOpcode() == ISD::SETCC)
918 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
921 bool DoXform = false;
923 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
925 if (LHS.getOpcode() == ISD::Constant &&
926 cast<ConstantSDNode>(LHS)->isNullValue())
928 else if (CC != ISD::SETCC_INVALID &&
929 RHS.getOpcode() == ISD::Constant &&
930 cast<ConstantSDNode>(RHS)->isNullValue()) {
932 SDOperand Op0 = Slct.getOperand(0);
933 bool isInt = (isSlctCC ? Op0.getValueType() :
934 Op0.getOperand(0).getValueType()).isInteger();
935 CC = ISD::getSetCCInverse(CC, isInt);
941 SDOperand Result = DAG.getNode(Opc, VT, OtherOp, RHS);
943 return DAG.getSelectCC(OtherOp, Result,
944 Slct.getOperand(0), Slct.getOperand(1), CC);
945 SDOperand CCOp = Slct.getOperand(0);
947 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
948 CCOp.getOperand(1), CC);
949 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
954 SDOperand DAGCombiner::visitADD(SDNode *N) {
955 SDOperand N0 = N->getOperand(0);
956 SDOperand N1 = N->getOperand(1);
957 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
958 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
959 MVT VT = N0.getValueType();
963 SDOperand FoldedVOp = SimplifyVBinOp(N);
964 if (FoldedVOp.Val) return FoldedVOp;
967 // fold (add x, undef) -> undef
968 if (N0.getOpcode() == ISD::UNDEF)
970 if (N1.getOpcode() == ISD::UNDEF)
972 // fold (add c1, c2) -> c1+c2
974 return DAG.getConstant(N0C->getAPIntValue() + N1C->getAPIntValue(), VT);
975 // canonicalize constant to RHS
977 return DAG.getNode(ISD::ADD, VT, N1, N0);
978 // fold (add x, 0) -> x
979 if (N1C && N1C->isNullValue())
981 // fold ((c1-A)+c2) -> (c1+c2)-A
982 if (N1C && N0.getOpcode() == ISD::SUB)
983 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
984 return DAG.getNode(ISD::SUB, VT,
985 DAG.getConstant(N1C->getAPIntValue()+
986 N0C->getAPIntValue(), VT),
989 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
992 // fold ((0-A) + B) -> B-A
993 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
994 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
995 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
996 // fold (A + (0-B)) -> A-B
997 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
998 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
999 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
1000 // fold (A+(B-A)) -> B
1001 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1002 return N1.getOperand(0);
1004 if (!VT.isVector() && SimplifyDemandedBits(SDOperand(N, 0)))
1005 return SDOperand(N, 0);
1007 // fold (a+b) -> (a|b) iff a and b share no bits.
1008 if (VT.isInteger() && !VT.isVector()) {
1009 APInt LHSZero, LHSOne;
1010 APInt RHSZero, RHSOne;
1011 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1012 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1013 if (LHSZero.getBoolValue()) {
1014 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1016 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1017 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1018 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1019 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1020 return DAG.getNode(ISD::OR, VT, N0, N1);
1024 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1025 if (N0.getOpcode() == ISD::SHL && N0.Val->hasOneUse()) {
1026 SDOperand Result = combineShlAddConstant(N0, N1, DAG);
1027 if (Result.Val) return Result;
1029 if (N1.getOpcode() == ISD::SHL && N1.Val->hasOneUse()) {
1030 SDOperand Result = combineShlAddConstant(N1, N0, DAG);
1031 if (Result.Val) return Result;
1034 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1035 if (N0.getOpcode() == ISD::SELECT && N0.Val->hasOneUse()) {
1036 SDOperand Result = combineSelectAndUse(N, N0, N1, DAG);
1037 if (Result.Val) return Result;
1039 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1040 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1041 if (Result.Val) return Result;
1047 SDOperand DAGCombiner::visitADDC(SDNode *N) {
1048 SDOperand N0 = N->getOperand(0);
1049 SDOperand N1 = N->getOperand(1);
1050 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1051 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1052 MVT VT = N0.getValueType();
1054 // If the flag result is dead, turn this into an ADD.
1055 if (N->hasNUsesOfValue(0, 1))
1056 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
1057 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1059 // canonicalize constant to RHS.
1061 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0);
1064 // fold (addc x, 0) -> x + no carry out
1065 if (N1C && N1C->isNullValue())
1066 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1068 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1069 APInt LHSZero, LHSOne;
1070 APInt RHSZero, RHSOne;
1071 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1072 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1073 if (LHSZero.getBoolValue()) {
1074 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1076 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1077 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1078 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1079 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1080 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
1081 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1087 SDOperand DAGCombiner::visitADDE(SDNode *N) {
1088 SDOperand N0 = N->getOperand(0);
1089 SDOperand N1 = N->getOperand(1);
1090 SDOperand CarryIn = N->getOperand(2);
1091 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1092 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1093 //MVT VT = N0.getValueType();
1095 // canonicalize constant to RHS
1097 return DAG.getNode(ISD::ADDE, N->getVTList(), N1, N0, CarryIn);
1100 // fold (adde x, y, false) -> (addc x, y)
1101 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) {
1102 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0);
1110 SDOperand DAGCombiner::visitSUB(SDNode *N) {
1111 SDOperand N0 = N->getOperand(0);
1112 SDOperand N1 = N->getOperand(1);
1113 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1114 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1115 MVT VT = N0.getValueType();
1118 if (VT.isVector()) {
1119 SDOperand FoldedVOp = SimplifyVBinOp(N);
1120 if (FoldedVOp.Val) return FoldedVOp;
1123 // fold (sub x, x) -> 0
1125 return DAG.getConstant(0, N->getValueType(0));
1126 // fold (sub c1, c2) -> c1-c2
1128 return DAG.getNode(ISD::SUB, VT, N0, N1);
1129 // fold (sub x, c) -> (add x, -c)
1131 return DAG.getNode(ISD::ADD, VT, N0,
1132 DAG.getConstant(-N1C->getAPIntValue(), VT));
1133 // fold (A+B)-A -> B
1134 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1135 return N0.getOperand(1);
1136 // fold (A+B)-B -> A
1137 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1138 return N0.getOperand(0);
1139 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1140 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1141 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1142 if (Result.Val) return Result;
1144 // If either operand of a sub is undef, the result is undef
1145 if (N0.getOpcode() == ISD::UNDEF)
1147 if (N1.getOpcode() == ISD::UNDEF)
1153 SDOperand DAGCombiner::visitMUL(SDNode *N) {
1154 SDOperand N0 = N->getOperand(0);
1155 SDOperand N1 = N->getOperand(1);
1156 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1157 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1158 MVT VT = N0.getValueType();
1161 if (VT.isVector()) {
1162 SDOperand FoldedVOp = SimplifyVBinOp(N);
1163 if (FoldedVOp.Val) return FoldedVOp;
1166 // fold (mul x, undef) -> 0
1167 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1168 return DAG.getConstant(0, VT);
1169 // fold (mul c1, c2) -> c1*c2
1171 return DAG.getNode(ISD::MUL, VT, N0, N1);
1172 // canonicalize constant to RHS
1174 return DAG.getNode(ISD::MUL, VT, N1, N0);
1175 // fold (mul x, 0) -> 0
1176 if (N1C && N1C->isNullValue())
1178 // fold (mul x, -1) -> 0-x
1179 if (N1C && N1C->isAllOnesValue())
1180 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1181 // fold (mul x, (1 << c)) -> x << c
1182 if (N1C && N1C->getAPIntValue().isPowerOf2())
1183 return DAG.getNode(ISD::SHL, VT, N0,
1184 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1185 TLI.getShiftAmountTy()));
1186 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1187 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
1188 // FIXME: If the input is something that is easily negated (e.g. a
1189 // single-use add), we should put the negate there.
1190 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1191 DAG.getNode(ISD::SHL, VT, N0,
1192 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
1193 TLI.getShiftAmountTy())));
1196 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1197 if (N1C && N0.getOpcode() == ISD::SHL &&
1198 isa<ConstantSDNode>(N0.getOperand(1))) {
1199 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1200 AddToWorkList(C3.Val);
1201 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1204 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1207 SDOperand Sh(0,0), Y(0,0);
1208 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1209 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1210 N0.Val->hasOneUse()) {
1212 } else if (N1.getOpcode() == ISD::SHL &&
1213 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1217 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1218 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1221 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1222 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1223 isa<ConstantSDNode>(N0.getOperand(1))) {
1224 return DAG.getNode(ISD::ADD, VT,
1225 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1226 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1230 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1237 SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1238 SDOperand N0 = N->getOperand(0);
1239 SDOperand N1 = N->getOperand(1);
1240 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1241 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1242 MVT VT = N->getValueType(0);
1245 if (VT.isVector()) {
1246 SDOperand FoldedVOp = SimplifyVBinOp(N);
1247 if (FoldedVOp.Val) return FoldedVOp;
1250 // fold (sdiv c1, c2) -> c1/c2
1251 if (N0C && N1C && !N1C->isNullValue())
1252 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1253 // fold (sdiv X, 1) -> X
1254 if (N1C && N1C->getSignExtended() == 1LL)
1256 // fold (sdiv X, -1) -> 0-X
1257 if (N1C && N1C->isAllOnesValue())
1258 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1259 // If we know the sign bits of both operands are zero, strength reduce to a
1260 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1261 if (!VT.isVector()) {
1262 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1263 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1265 // fold (sdiv X, pow2) -> simple ops after legalize
1266 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1267 (isPowerOf2_64(N1C->getSignExtended()) ||
1268 isPowerOf2_64(-N1C->getSignExtended()))) {
1269 // If dividing by powers of two is cheap, then don't perform the following
1271 if (TLI.isPow2DivCheap())
1273 int64_t pow2 = N1C->getSignExtended();
1274 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1275 unsigned lg2 = Log2_64(abs2);
1276 // Splat the sign bit into the register
1277 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1278 DAG.getConstant(VT.getSizeInBits()-1,
1279 TLI.getShiftAmountTy()));
1280 AddToWorkList(SGN.Val);
1281 // Add (N0 < 0) ? abs2 - 1 : 0;
1282 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1283 DAG.getConstant(VT.getSizeInBits()-lg2,
1284 TLI.getShiftAmountTy()));
1285 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1286 AddToWorkList(SRL.Val);
1287 AddToWorkList(ADD.Val); // Divide by pow2
1288 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1289 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1290 // If we're dividing by a positive value, we're done. Otherwise, we must
1291 // negate the result.
1294 AddToWorkList(SRA.Val);
1295 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1297 // if integer divide is expensive and we satisfy the requirements, emit an
1298 // alternate sequence.
1299 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1300 !TLI.isIntDivCheap()) {
1301 SDOperand Op = BuildSDIV(N);
1302 if (Op.Val) return Op;
1306 if (N0.getOpcode() == ISD::UNDEF)
1307 return DAG.getConstant(0, VT);
1308 // X / undef -> undef
1309 if (N1.getOpcode() == ISD::UNDEF)
1315 SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1316 SDOperand N0 = N->getOperand(0);
1317 SDOperand N1 = N->getOperand(1);
1318 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1319 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1320 MVT VT = N->getValueType(0);
1323 if (VT.isVector()) {
1324 SDOperand FoldedVOp = SimplifyVBinOp(N);
1325 if (FoldedVOp.Val) return FoldedVOp;
1328 // fold (udiv c1, c2) -> c1/c2
1329 if (N0C && N1C && !N1C->isNullValue())
1330 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1331 // fold (udiv x, (1 << c)) -> x >>u c
1332 if (N1C && N1C->getAPIntValue().isPowerOf2())
1333 return DAG.getNode(ISD::SRL, VT, N0,
1334 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1335 TLI.getShiftAmountTy()));
1336 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1337 if (N1.getOpcode() == ISD::SHL) {
1338 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1339 if (SHC->getAPIntValue().isPowerOf2()) {
1340 MVT ADDVT = N1.getOperand(1).getValueType();
1341 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1342 DAG.getConstant(SHC->getAPIntValue()
1345 AddToWorkList(Add.Val);
1346 return DAG.getNode(ISD::SRL, VT, N0, Add);
1350 // fold (udiv x, c) -> alternate
1351 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1352 SDOperand Op = BuildUDIV(N);
1353 if (Op.Val) return Op;
1357 if (N0.getOpcode() == ISD::UNDEF)
1358 return DAG.getConstant(0, VT);
1359 // X / undef -> undef
1360 if (N1.getOpcode() == ISD::UNDEF)
1366 SDOperand DAGCombiner::visitSREM(SDNode *N) {
1367 SDOperand N0 = N->getOperand(0);
1368 SDOperand N1 = N->getOperand(1);
1369 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1370 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1371 MVT VT = N->getValueType(0);
1373 // fold (srem c1, c2) -> c1%c2
1374 if (N0C && N1C && !N1C->isNullValue())
1375 return DAG.getNode(ISD::SREM, VT, N0, N1);
1376 // If we know the sign bits of both operands are zero, strength reduce to a
1377 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1378 if (!VT.isVector()) {
1379 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1380 return DAG.getNode(ISD::UREM, VT, N0, N1);
1383 // If X/C can be simplified by the division-by-constant logic, lower
1384 // X%C to the equivalent of X-X/C*C.
1385 if (N1C && !N1C->isNullValue()) {
1386 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1387 AddToWorkList(Div.Val);
1388 SDOperand OptimizedDiv = combine(Div.Val);
1389 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1390 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1391 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1392 AddToWorkList(Mul.Val);
1398 if (N0.getOpcode() == ISD::UNDEF)
1399 return DAG.getConstant(0, VT);
1400 // X % undef -> undef
1401 if (N1.getOpcode() == ISD::UNDEF)
1407 SDOperand DAGCombiner::visitUREM(SDNode *N) {
1408 SDOperand N0 = N->getOperand(0);
1409 SDOperand N1 = N->getOperand(1);
1410 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1411 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1412 MVT VT = N->getValueType(0);
1414 // fold (urem c1, c2) -> c1%c2
1415 if (N0C && N1C && !N1C->isNullValue())
1416 return DAG.getNode(ISD::UREM, VT, N0, N1);
1417 // fold (urem x, pow2) -> (and x, pow2-1)
1418 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1419 return DAG.getNode(ISD::AND, VT, N0,
1420 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1421 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1422 if (N1.getOpcode() == ISD::SHL) {
1423 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1424 if (SHC->getAPIntValue().isPowerOf2()) {
1426 DAG.getNode(ISD::ADD, VT, N1,
1427 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1429 AddToWorkList(Add.Val);
1430 return DAG.getNode(ISD::AND, VT, N0, Add);
1435 // If X/C can be simplified by the division-by-constant logic, lower
1436 // X%C to the equivalent of X-X/C*C.
1437 if (N1C && !N1C->isNullValue()) {
1438 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1439 SDOperand OptimizedDiv = combine(Div.Val);
1440 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1441 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1442 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1443 AddToWorkList(Mul.Val);
1449 if (N0.getOpcode() == ISD::UNDEF)
1450 return DAG.getConstant(0, VT);
1451 // X % undef -> undef
1452 if (N1.getOpcode() == ISD::UNDEF)
1458 SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1459 SDOperand N0 = N->getOperand(0);
1460 SDOperand N1 = N->getOperand(1);
1461 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1462 MVT VT = N->getValueType(0);
1464 // fold (mulhs x, 0) -> 0
1465 if (N1C && N1C->isNullValue())
1467 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1468 if (N1C && N1C->getAPIntValue() == 1)
1469 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1470 DAG.getConstant(N0.getValueType().getSizeInBits()-1,
1471 TLI.getShiftAmountTy()));
1472 // fold (mulhs x, undef) -> 0
1473 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1474 return DAG.getConstant(0, VT);
1479 SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1480 SDOperand N0 = N->getOperand(0);
1481 SDOperand N1 = N->getOperand(1);
1482 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1483 MVT VT = N->getValueType(0);
1485 // fold (mulhu x, 0) -> 0
1486 if (N1C && N1C->isNullValue())
1488 // fold (mulhu x, 1) -> 0
1489 if (N1C && N1C->getAPIntValue() == 1)
1490 return DAG.getConstant(0, N0.getValueType());
1491 // fold (mulhu x, undef) -> 0
1492 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1493 return DAG.getConstant(0, VT);
1498 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1499 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1500 /// that are being performed. Return true if a simplification was made.
1502 SDOperand DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1504 // If the high half is not needed, just compute the low half.
1505 bool HiExists = N->hasAnyUseOfValue(1);
1508 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1509 SDOperand Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(),
1510 N->getNumOperands());
1511 return CombineTo(N, Res, Res);
1514 // If the low half is not needed, just compute the high half.
1515 bool LoExists = N->hasAnyUseOfValue(0);
1518 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1519 SDOperand Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(),
1520 N->getNumOperands());
1521 return CombineTo(N, Res, Res);
1524 // If both halves are used, return as it is.
1525 if (LoExists && HiExists)
1528 // If the two computed results can be simplified separately, separate them.
1530 SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
1531 N->op_begin(), N->getNumOperands());
1532 AddToWorkList(Lo.Val);
1533 SDOperand LoOpt = combine(Lo.Val);
1534 if (LoOpt.Val && LoOpt.Val != Lo.Val &&
1536 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1537 return CombineTo(N, LoOpt, LoOpt);
1541 SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
1542 N->op_begin(), N->getNumOperands());
1543 AddToWorkList(Hi.Val);
1544 SDOperand HiOpt = combine(Hi.Val);
1545 if (HiOpt.Val && HiOpt != Hi &&
1547 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1548 return CombineTo(N, HiOpt, HiOpt);
1553 SDOperand DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1554 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1555 if (Res.Val) return Res;
1560 SDOperand DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1561 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1562 if (Res.Val) return Res;
1567 SDOperand DAGCombiner::visitSDIVREM(SDNode *N) {
1568 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1569 if (Res.Val) return Res;
1574 SDOperand DAGCombiner::visitUDIVREM(SDNode *N) {
1575 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1576 if (Res.Val) return Res;
1581 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1582 /// two operands of the same opcode, try to simplify it.
1583 SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1584 SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1585 MVT VT = N0.getValueType();
1586 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1588 // For each of OP in AND/OR/XOR:
1589 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1590 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1591 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1592 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1593 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1594 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1595 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1596 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1597 N0.getOperand(0).getValueType(),
1598 N0.getOperand(0), N1.getOperand(0));
1599 AddToWorkList(ORNode.Val);
1600 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1603 // For each of OP in SHL/SRL/SRA/AND...
1604 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1605 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1606 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1607 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1608 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1609 N0.getOperand(1) == N1.getOperand(1)) {
1610 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1611 N0.getOperand(0).getValueType(),
1612 N0.getOperand(0), N1.getOperand(0));
1613 AddToWorkList(ORNode.Val);
1614 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1620 SDOperand DAGCombiner::visitAND(SDNode *N) {
1621 SDOperand N0 = N->getOperand(0);
1622 SDOperand N1 = N->getOperand(1);
1623 SDOperand LL, LR, RL, RR, CC0, CC1;
1624 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1625 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1626 MVT VT = N1.getValueType();
1627 unsigned BitWidth = VT.getSizeInBits();
1630 if (VT.isVector()) {
1631 SDOperand FoldedVOp = SimplifyVBinOp(N);
1632 if (FoldedVOp.Val) return FoldedVOp;
1635 // fold (and x, undef) -> 0
1636 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1637 return DAG.getConstant(0, VT);
1638 // fold (and c1, c2) -> c1&c2
1640 return DAG.getNode(ISD::AND, VT, N0, N1);
1641 // canonicalize constant to RHS
1643 return DAG.getNode(ISD::AND, VT, N1, N0);
1644 // fold (and x, -1) -> x
1645 if (N1C && N1C->isAllOnesValue())
1647 // if (and x, c) is known to be zero, return 0
1648 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
1649 APInt::getAllOnesValue(BitWidth)))
1650 return DAG.getConstant(0, VT);
1652 SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1655 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1656 if (N1C && N0.getOpcode() == ISD::OR)
1657 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1658 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
1660 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1661 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1662 SDOperand N0Op0 = N0.getOperand(0);
1663 APInt Mask = ~N1C->getAPIntValue();
1664 Mask.trunc(N0Op0.getValueSizeInBits());
1665 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
1666 SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1669 // Replace uses of the AND with uses of the Zero extend node.
1672 // We actually want to replace all uses of the any_extend with the
1673 // zero_extend, to avoid duplicating things. This will later cause this
1674 // AND to be folded.
1675 CombineTo(N0.Val, Zext);
1676 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1679 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1680 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1681 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1682 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1684 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1685 LL.getValueType().isInteger()) {
1686 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1687 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
1688 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1689 AddToWorkList(ORNode.Val);
1690 return DAG.getSetCC(VT, ORNode, LR, Op1);
1692 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1693 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1694 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1695 AddToWorkList(ANDNode.Val);
1696 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1698 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1699 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1700 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1701 AddToWorkList(ORNode.Val);
1702 return DAG.getSetCC(VT, ORNode, LR, Op1);
1705 // canonicalize equivalent to ll == rl
1706 if (LL == RR && LR == RL) {
1707 Op1 = ISD::getSetCCSwappedOperands(Op1);
1710 if (LL == RL && LR == RR) {
1711 bool isInteger = LL.getValueType().isInteger();
1712 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1713 if (Result != ISD::SETCC_INVALID)
1714 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1718 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1719 if (N0.getOpcode() == N1.getOpcode()) {
1720 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1721 if (Tmp.Val) return Tmp;
1724 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1725 // fold (and (sra)) -> (and (srl)) when possible.
1726 if (!VT.isVector() &&
1727 SimplifyDemandedBits(SDOperand(N, 0)))
1728 return SDOperand(N, 0);
1729 // fold (zext_inreg (extload x)) -> (zextload x)
1730 if (ISD::isEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val)) {
1731 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1732 MVT EVT = LN0->getMemoryVT();
1733 // If we zero all the possible extended bits, then we can turn this into
1734 // a zextload if we are running before legalize or the operation is legal.
1735 unsigned BitWidth = N1.getValueSizeInBits();
1736 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1737 BitWidth - EVT.getSizeInBits())) &&
1738 ((!AfterLegalize && !LN0->isVolatile()) ||
1739 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1740 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1741 LN0->getBasePtr(), LN0->getSrcValue(),
1742 LN0->getSrcValueOffset(), EVT,
1744 LN0->getAlignment());
1746 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1747 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1750 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1751 if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
1753 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1754 MVT EVT = LN0->getMemoryVT();
1755 // If we zero all the possible extended bits, then we can turn this into
1756 // a zextload if we are running before legalize or the operation is legal.
1757 unsigned BitWidth = N1.getValueSizeInBits();
1758 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1759 BitWidth - EVT.getSizeInBits())) &&
1760 ((!AfterLegalize && !LN0->isVolatile()) ||
1761 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1762 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1763 LN0->getBasePtr(), LN0->getSrcValue(),
1764 LN0->getSrcValueOffset(), EVT,
1766 LN0->getAlignment());
1768 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1769 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1773 // fold (and (load x), 255) -> (zextload x, i8)
1774 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1775 if (N1C && N0.getOpcode() == ISD::LOAD) {
1776 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1777 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1778 LN0->isUnindexed() && N0.hasOneUse() &&
1779 // Do not change the width of a volatile load.
1780 !LN0->isVolatile()) {
1781 MVT EVT = MVT::Other;
1782 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
1783 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue()))
1784 EVT = MVT::getIntegerVT(ActiveBits);
1786 MVT LoadedVT = LN0->getMemoryVT();
1787 // Do not generate loads of non-round integer types since these can
1788 // be expensive (and would be wrong if the type is not byte sized).
1789 if (EVT != MVT::Other && LoadedVT.bitsGT(EVT) && EVT.isRound() &&
1790 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1791 MVT PtrType = N0.getOperand(1).getValueType();
1792 // For big endian targets, we need to add an offset to the pointer to
1793 // load the correct bytes. For little endian systems, we merely need to
1794 // read fewer bytes from the same pointer.
1795 unsigned LVTStoreBytes = LoadedVT.getStoreSizeInBits()/8;
1796 unsigned EVTStoreBytes = EVT.getStoreSizeInBits()/8;
1797 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
1798 unsigned Alignment = LN0->getAlignment();
1799 SDOperand NewPtr = LN0->getBasePtr();
1800 if (TLI.isBigEndian()) {
1801 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1802 DAG.getConstant(PtrOff, PtrType));
1803 Alignment = MinAlign(Alignment, PtrOff);
1805 AddToWorkList(NewPtr.Val);
1807 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1808 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
1809 LN0->isVolatile(), Alignment);
1811 CombineTo(N0.Val, Load, Load.getValue(1));
1812 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1820 SDOperand DAGCombiner::visitOR(SDNode *N) {
1821 SDOperand N0 = N->getOperand(0);
1822 SDOperand N1 = N->getOperand(1);
1823 SDOperand LL, LR, RL, RR, CC0, CC1;
1824 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1825 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1826 MVT VT = N1.getValueType();
1829 if (VT.isVector()) {
1830 SDOperand FoldedVOp = SimplifyVBinOp(N);
1831 if (FoldedVOp.Val) return FoldedVOp;
1834 // fold (or x, undef) -> -1
1835 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1836 return DAG.getConstant(~0ULL, VT);
1837 // fold (or c1, c2) -> c1|c2
1839 return DAG.getNode(ISD::OR, VT, N0, N1);
1840 // canonicalize constant to RHS
1842 return DAG.getNode(ISD::OR, VT, N1, N0);
1843 // fold (or x, 0) -> x
1844 if (N1C && N1C->isNullValue())
1846 // fold (or x, -1) -> -1
1847 if (N1C && N1C->isAllOnesValue())
1849 // fold (or x, c) -> c iff (x & ~c) == 0
1850 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
1853 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1856 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1857 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1858 isa<ConstantSDNode>(N0.getOperand(1))) {
1859 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1860 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1862 DAG.getConstant(N1C->getAPIntValue() |
1863 C1->getAPIntValue(), VT));
1865 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1866 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1867 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1868 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1870 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1871 LL.getValueType().isInteger()) {
1872 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1873 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1874 if (cast<ConstantSDNode>(LR)->isNullValue() &&
1875 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1876 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1877 AddToWorkList(ORNode.Val);
1878 return DAG.getSetCC(VT, ORNode, LR, Op1);
1880 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1881 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1882 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1883 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1884 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1885 AddToWorkList(ANDNode.Val);
1886 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1889 // canonicalize equivalent to ll == rl
1890 if (LL == RR && LR == RL) {
1891 Op1 = ISD::getSetCCSwappedOperands(Op1);
1894 if (LL == RL && LR == RR) {
1895 bool isInteger = LL.getValueType().isInteger();
1896 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1897 if (Result != ISD::SETCC_INVALID)
1898 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1902 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1903 if (N0.getOpcode() == N1.getOpcode()) {
1904 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1905 if (Tmp.Val) return Tmp;
1908 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1909 if (N0.getOpcode() == ISD::AND &&
1910 N1.getOpcode() == ISD::AND &&
1911 N0.getOperand(1).getOpcode() == ISD::Constant &&
1912 N1.getOperand(1).getOpcode() == ISD::Constant &&
1913 // Don't increase # computations.
1914 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1915 // We can only do this xform if we know that bits from X that are set in C2
1916 // but not in C1 are already zero. Likewise for Y.
1917 const APInt &LHSMask =
1918 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1919 const APInt &RHSMask =
1920 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
1922 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1923 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1924 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1925 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1930 // See if this is some rotate idiom.
1931 if (SDNode *Rot = MatchRotate(N0, N1))
1932 return SDOperand(Rot, 0);
1938 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1939 static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1940 if (Op.getOpcode() == ISD::AND) {
1941 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1942 Mask = Op.getOperand(1);
1943 Op = Op.getOperand(0);
1949 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1957 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
1958 // idioms for rotate, and if the target supports rotation instructions, generate
1960 SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1961 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
1962 MVT VT = LHS.getValueType();
1963 if (!TLI.isTypeLegal(VT)) return 0;
1965 // The target must have at least one rotate flavor.
1966 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1967 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1968 if (!HasROTL && !HasROTR) return 0;
1970 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1971 SDOperand LHSShift; // The shift.
1972 SDOperand LHSMask; // AND value if any.
1973 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1974 return 0; // Not part of a rotate.
1976 SDOperand RHSShift; // The shift.
1977 SDOperand RHSMask; // AND value if any.
1978 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1979 return 0; // Not part of a rotate.
1981 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1982 return 0; // Not shifting the same value.
1984 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1985 return 0; // Shifts must disagree.
1987 // Canonicalize shl to left side in a shl/srl pair.
1988 if (RHSShift.getOpcode() == ISD::SHL) {
1989 std::swap(LHS, RHS);
1990 std::swap(LHSShift, RHSShift);
1991 std::swap(LHSMask , RHSMask );
1994 unsigned OpSizeInBits = VT.getSizeInBits();
1995 SDOperand LHSShiftArg = LHSShift.getOperand(0);
1996 SDOperand LHSShiftAmt = LHSShift.getOperand(1);
1997 SDOperand RHSShiftAmt = RHSShift.getOperand(1);
1999 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2000 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2001 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2002 RHSShiftAmt.getOpcode() == ISD::Constant) {
2003 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue();
2004 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue();
2005 if ((LShVal + RShVal) != OpSizeInBits)
2010 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
2012 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
2014 // If there is an AND of either shifted operand, apply it to the result.
2015 if (LHSMask.Val || RHSMask.Val) {
2016 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2019 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2020 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2023 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2024 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2027 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
2033 // If there is a mask here, and we have a variable shift, we can't be sure
2034 // that we're masking out the right stuff.
2035 if (LHSMask.Val || RHSMask.Val)
2038 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2039 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2040 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2041 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2042 if (ConstantSDNode *SUBC =
2043 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2044 if (SUBC->getAPIntValue() == OpSizeInBits) {
2046 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2048 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2053 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2054 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2055 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2056 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2057 if (ConstantSDNode *SUBC =
2058 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2059 if (SUBC->getAPIntValue() == OpSizeInBits) {
2061 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2063 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2068 // Look for sign/zext/any-extended cases:
2069 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2070 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2071 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) &&
2072 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2073 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2074 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) {
2075 SDOperand LExtOp0 = LHSShiftAmt.getOperand(0);
2076 SDOperand RExtOp0 = RHSShiftAmt.getOperand(0);
2077 if (RExtOp0.getOpcode() == ISD::SUB &&
2078 RExtOp0.getOperand(1) == LExtOp0) {
2079 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2081 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2082 // (rotl x, (sub 32, y))
2083 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2084 if (SUBC->getAPIntValue() == OpSizeInBits) {
2086 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2088 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2091 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2092 RExtOp0 == LExtOp0.getOperand(1)) {
2093 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2095 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2096 // (rotr x, (sub 32, y))
2097 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2098 if (SUBC->getAPIntValue() == OpSizeInBits) {
2100 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
2102 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2112 SDOperand DAGCombiner::visitXOR(SDNode *N) {
2113 SDOperand N0 = N->getOperand(0);
2114 SDOperand N1 = N->getOperand(1);
2115 SDOperand LHS, RHS, CC;
2116 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2117 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2118 MVT VT = N0.getValueType();
2121 if (VT.isVector()) {
2122 SDOperand FoldedVOp = SimplifyVBinOp(N);
2123 if (FoldedVOp.Val) return FoldedVOp;
2126 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2127 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2128 return DAG.getConstant(0, VT);
2129 // fold (xor x, undef) -> undef
2130 if (N0.getOpcode() == ISD::UNDEF)
2132 if (N1.getOpcode() == ISD::UNDEF)
2134 // fold (xor c1, c2) -> c1^c2
2136 return DAG.getNode(ISD::XOR, VT, N0, N1);
2137 // canonicalize constant to RHS
2139 return DAG.getNode(ISD::XOR, VT, N1, N0);
2140 // fold (xor x, 0) -> x
2141 if (N1C && N1C->isNullValue())
2144 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
2147 // fold !(x cc y) -> (x !cc y)
2148 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2149 bool isInt = LHS.getValueType().isInteger();
2150 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2152 if (N0.getOpcode() == ISD::SETCC)
2153 return DAG.getSetCC(VT, LHS, RHS, NotCC);
2154 if (N0.getOpcode() == ISD::SELECT_CC)
2155 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
2156 assert(0 && "Unhandled SetCC Equivalent!");
2159 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2160 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2161 N0.Val->hasOneUse() && isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2162 SDOperand V = N0.getOperand(0);
2163 V = DAG.getNode(ISD::XOR, V.getValueType(), V,
2164 DAG.getConstant(1, V.getValueType()));
2165 AddToWorkList(V.Val);
2166 return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2169 // fold !(x or y) -> (!x and !y) iff x or y are setcc
2170 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2171 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2172 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2173 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2174 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2175 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2176 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2177 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2178 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2181 // fold !(x or y) -> (!x and !y) iff x or y are constants
2182 if (N1C && N1C->isAllOnesValue() &&
2183 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2184 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2185 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2186 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2187 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2188 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2189 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2190 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2193 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2194 if (N1C && N0.getOpcode() == ISD::XOR) {
2195 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2196 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2198 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
2199 DAG.getConstant(N1C->getAPIntValue()^
2200 N00C->getAPIntValue(), VT));
2202 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
2203 DAG.getConstant(N1C->getAPIntValue()^
2204 N01C->getAPIntValue(), VT));
2206 // fold (xor x, x) -> 0
2208 if (!VT.isVector()) {
2209 return DAG.getConstant(0, VT);
2210 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
2211 // Produce a vector of zeros.
2212 SDOperand El = DAG.getConstant(0, VT.getVectorElementType());
2213 std::vector<SDOperand> Ops(VT.getVectorNumElements(), El);
2214 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2218 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2219 if (N0.getOpcode() == N1.getOpcode()) {
2220 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2221 if (Tmp.Val) return Tmp;
2224 // Simplify the expression using non-local knowledge.
2225 if (!VT.isVector() &&
2226 SimplifyDemandedBits(SDOperand(N, 0)))
2227 return SDOperand(N, 0);
2232 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2233 /// the shift amount is a constant.
2234 SDOperand DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2235 SDNode *LHS = N->getOperand(0).Val;
2236 if (!LHS->hasOneUse()) return SDOperand();
2238 // We want to pull some binops through shifts, so that we have (and (shift))
2239 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2240 // thing happens with address calculations, so it's important to canonicalize
2242 bool HighBitSet = false; // Can we transform this if the high bit is set?
2244 switch (LHS->getOpcode()) {
2245 default: return SDOperand();
2248 HighBitSet = false; // We can only transform sra if the high bit is clear.
2251 HighBitSet = true; // We can only transform sra if the high bit is set.
2254 if (N->getOpcode() != ISD::SHL)
2255 return SDOperand(); // only shl(add) not sr[al](add).
2256 HighBitSet = false; // We can only transform sra if the high bit is clear.
2260 // We require the RHS of the binop to be a constant as well.
2261 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2262 if (!BinOpCst) return SDOperand();
2265 // FIXME: disable this for unless the input to the binop is a shift by a
2266 // constant. If it is not a shift, it pessimizes some common cases like:
2268 //void foo(int *X, int i) { X[i & 1235] = 1; }
2269 //int bar(int *X, int i) { return X[i & 255]; }
2270 SDNode *BinOpLHSVal = LHS->getOperand(0).Val;
2271 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2272 BinOpLHSVal->getOpcode() != ISD::SRA &&
2273 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2274 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2277 MVT VT = N->getValueType(0);
2279 // If this is a signed shift right, and the high bit is modified
2280 // by the logical operation, do not perform the transformation.
2281 // The highBitSet boolean indicates the value of the high bit of
2282 // the constant which would cause it to be modified for this
2284 if (N->getOpcode() == ISD::SRA) {
2285 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2286 if (BinOpRHSSignSet != HighBitSet)
2290 // Fold the constants, shifting the binop RHS by the shift amount.
2291 SDOperand NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
2292 LHS->getOperand(1), N->getOperand(1));
2294 // Create the new shift.
2295 SDOperand NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
2298 // Create the new binop.
2299 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
2303 SDOperand DAGCombiner::visitSHL(SDNode *N) {
2304 SDOperand N0 = N->getOperand(0);
2305 SDOperand N1 = N->getOperand(1);
2306 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2307 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2308 MVT VT = N0.getValueType();
2309 unsigned OpSizeInBits = VT.getSizeInBits();
2311 // fold (shl c1, c2) -> c1<<c2
2313 return DAG.getNode(ISD::SHL, VT, N0, N1);
2314 // fold (shl 0, x) -> 0
2315 if (N0C && N0C->isNullValue())
2317 // fold (shl x, c >= size(x)) -> undef
2318 if (N1C && N1C->getValue() >= OpSizeInBits)
2319 return DAG.getNode(ISD::UNDEF, VT);
2320 // fold (shl x, 0) -> x
2321 if (N1C && N1C->isNullValue())
2323 // if (shl x, c) is known to be zero, return 0
2324 if (DAG.MaskedValueIsZero(SDOperand(N, 0),
2325 APInt::getAllOnesValue(VT.getSizeInBits())))
2326 return DAG.getConstant(0, VT);
2327 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2328 return SDOperand(N, 0);
2329 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2330 if (N1C && N0.getOpcode() == ISD::SHL &&
2331 N0.getOperand(1).getOpcode() == ISD::Constant) {
2332 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2333 uint64_t c2 = N1C->getValue();
2334 if (c1 + c2 > OpSizeInBits)
2335 return DAG.getConstant(0, VT);
2336 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2337 DAG.getConstant(c1 + c2, N1.getValueType()));
2339 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2340 // (srl (and x, -1 << c1), c1-c2)
2341 if (N1C && N0.getOpcode() == ISD::SRL &&
2342 N0.getOperand(1).getOpcode() == ISD::Constant) {
2343 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2344 uint64_t c2 = N1C->getValue();
2345 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2346 DAG.getConstant(~0ULL << c1, VT));
2348 return DAG.getNode(ISD::SHL, VT, Mask,
2349 DAG.getConstant(c2-c1, N1.getValueType()));
2351 return DAG.getNode(ISD::SRL, VT, Mask,
2352 DAG.getConstant(c1-c2, N1.getValueType()));
2354 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2355 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2356 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2357 DAG.getConstant(~0ULL << N1C->getValue(), VT));
2359 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2362 SDOperand DAGCombiner::visitSRA(SDNode *N) {
2363 SDOperand N0 = N->getOperand(0);
2364 SDOperand N1 = N->getOperand(1);
2365 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2366 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2367 MVT VT = N0.getValueType();
2369 // fold (sra c1, c2) -> c1>>c2
2371 return DAG.getNode(ISD::SRA, VT, N0, N1);
2372 // fold (sra 0, x) -> 0
2373 if (N0C && N0C->isNullValue())
2375 // fold (sra -1, x) -> -1
2376 if (N0C && N0C->isAllOnesValue())
2378 // fold (sra x, c >= size(x)) -> undef
2379 if (N1C && N1C->getValue() >= VT.getSizeInBits())
2380 return DAG.getNode(ISD::UNDEF, VT);
2381 // fold (sra x, 0) -> x
2382 if (N1C && N1C->isNullValue())
2384 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2386 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2387 unsigned LowBits = VT.getSizeInBits() - (unsigned)N1C->getValue();
2388 MVT EVT = MVT::getIntegerVT(LowBits);
2389 if (EVT.isSimple() && // TODO: remove when apint codegen support lands.
2390 (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT)))
2391 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2392 DAG.getValueType(EVT));
2395 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2396 if (N1C && N0.getOpcode() == ISD::SRA) {
2397 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2398 unsigned Sum = N1C->getValue() + C1->getValue();
2399 if (Sum >= VT.getSizeInBits()) Sum = VT.getSizeInBits()-1;
2400 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2401 DAG.getConstant(Sum, N1C->getValueType(0)));
2405 // fold sra (shl X, m), result_size - n
2406 // -> (sign_extend (trunc (shl X, result_size - n - m))) for
2407 // result_size - n != m.
2408 // If truncate is free for the target sext(shl) is likely to result in better
2410 if (N0.getOpcode() == ISD::SHL) {
2411 // Get the two constanst of the shifts, CN0 = m, CN = n.
2412 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2414 // Determine what the truncate's result bitsize and type would be.
2415 unsigned VTValSize = VT.getSizeInBits();
2417 MVT::getIntegerVT(VTValSize - N1C->getValue());
2418 // Determine the residual right-shift amount.
2419 unsigned ShiftAmt = N1C->getValue() - N01C->getValue();
2421 // If the shift is not a no-op (in which case this should be just a sign
2422 // extend already), the truncated to type is legal, sign_extend is legal
2423 // on that type, and the the truncate to that type is both legal and free,
2424 // perform the transform.
2426 TLI.isOperationLegal(ISD::SIGN_EXTEND, TruncVT) &&
2427 TLI.isOperationLegal(ISD::TRUNCATE, VT) &&
2428 TLI.isTruncateFree(VT, TruncVT)) {
2430 SDOperand Amt = DAG.getConstant(ShiftAmt, TLI.getShiftAmountTy());
2431 SDOperand Shift = DAG.getNode(ISD::SRL, VT, N0.getOperand(0), Amt);
2432 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, TruncVT, Shift);
2433 return DAG.getNode(ISD::SIGN_EXTEND, N->getValueType(0), Trunc);
2438 // Simplify, based on bits shifted out of the LHS.
2439 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2440 return SDOperand(N, 0);
2443 // If the sign bit is known to be zero, switch this to a SRL.
2444 if (DAG.SignBitIsZero(N0))
2445 return DAG.getNode(ISD::SRL, VT, N0, N1);
2447 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2450 SDOperand DAGCombiner::visitSRL(SDNode *N) {
2451 SDOperand N0 = N->getOperand(0);
2452 SDOperand N1 = N->getOperand(1);
2453 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2454 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2455 MVT VT = N0.getValueType();
2456 unsigned OpSizeInBits = VT.getSizeInBits();
2458 // fold (srl c1, c2) -> c1 >>u c2
2460 return DAG.getNode(ISD::SRL, VT, N0, N1);
2461 // fold (srl 0, x) -> 0
2462 if (N0C && N0C->isNullValue())
2464 // fold (srl x, c >= size(x)) -> undef
2465 if (N1C && N1C->getValue() >= OpSizeInBits)
2466 return DAG.getNode(ISD::UNDEF, VT);
2467 // fold (srl x, 0) -> x
2468 if (N1C && N1C->isNullValue())
2470 // if (srl x, c) is known to be zero, return 0
2471 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
2472 APInt::getAllOnesValue(OpSizeInBits)))
2473 return DAG.getConstant(0, VT);
2475 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2476 if (N1C && N0.getOpcode() == ISD::SRL &&
2477 N0.getOperand(1).getOpcode() == ISD::Constant) {
2478 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2479 uint64_t c2 = N1C->getValue();
2480 if (c1 + c2 > OpSizeInBits)
2481 return DAG.getConstant(0, VT);
2482 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2483 DAG.getConstant(c1 + c2, N1.getValueType()));
2486 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2487 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2488 // Shifting in all undef bits?
2489 MVT SmallVT = N0.getOperand(0).getValueType();
2490 if (N1C->getValue() >= SmallVT.getSizeInBits())
2491 return DAG.getNode(ISD::UNDEF, VT);
2493 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2494 AddToWorkList(SmallShift.Val);
2495 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2498 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2499 // bit, which is unmodified by sra.
2500 if (N1C && N1C->getValue()+1 == VT.getSizeInBits()) {
2501 if (N0.getOpcode() == ISD::SRA)
2502 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2505 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2506 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2507 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
2508 APInt KnownZero, KnownOne;
2509 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
2510 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2512 // If any of the input bits are KnownOne, then the input couldn't be all
2513 // zeros, thus the result of the srl will always be zero.
2514 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
2516 // If all of the bits input the to ctlz node are known to be zero, then
2517 // the result of the ctlz is "32" and the result of the shift is one.
2518 APInt UnknownBits = ~KnownZero & Mask;
2519 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2521 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2522 if ((UnknownBits & (UnknownBits-1)) == 0) {
2523 // Okay, we know that only that the single bit specified by UnknownBits
2524 // could be set on input to the CTLZ node. If this bit is set, the SRL
2525 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2526 // to an SRL,XOR pair, which is likely to simplify more.
2527 unsigned ShAmt = UnknownBits.countTrailingZeros();
2528 SDOperand Op = N0.getOperand(0);
2530 Op = DAG.getNode(ISD::SRL, VT, Op,
2531 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2532 AddToWorkList(Op.Val);
2534 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2538 // fold operands of srl based on knowledge that the low bits are not
2540 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2541 return SDOperand(N, 0);
2543 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2546 SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2547 SDOperand N0 = N->getOperand(0);
2548 MVT VT = N->getValueType(0);
2550 // fold (ctlz c1) -> c2
2551 if (isa<ConstantSDNode>(N0))
2552 return DAG.getNode(ISD::CTLZ, VT, N0);
2556 SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2557 SDOperand N0 = N->getOperand(0);
2558 MVT VT = N->getValueType(0);
2560 // fold (cttz c1) -> c2
2561 if (isa<ConstantSDNode>(N0))
2562 return DAG.getNode(ISD::CTTZ, VT, N0);
2566 SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2567 SDOperand N0 = N->getOperand(0);
2568 MVT VT = N->getValueType(0);
2570 // fold (ctpop c1) -> c2
2571 if (isa<ConstantSDNode>(N0))
2572 return DAG.getNode(ISD::CTPOP, VT, N0);
2576 SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2577 SDOperand N0 = N->getOperand(0);
2578 SDOperand N1 = N->getOperand(1);
2579 SDOperand N2 = N->getOperand(2);
2580 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2581 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2582 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2583 MVT VT = N->getValueType(0);
2584 MVT VT0 = N0.getValueType();
2586 // fold select C, X, X -> X
2589 // fold select true, X, Y -> X
2590 if (N0C && !N0C->isNullValue())
2592 // fold select false, X, Y -> Y
2593 if (N0C && N0C->isNullValue())
2595 // fold select C, 1, X -> C | X
2596 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
2597 return DAG.getNode(ISD::OR, VT, N0, N2);
2598 // fold select C, 0, 1 -> ~C
2599 if (VT.isInteger() && VT0.isInteger() &&
2600 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
2601 SDOperand XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2604 AddToWorkList(XORNode.Val);
2606 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2607 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2609 // fold select C, 0, X -> ~C & X
2610 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2611 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2612 AddToWorkList(XORNode.Val);
2613 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2615 // fold select C, X, 1 -> ~C | X
2616 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
2617 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2618 AddToWorkList(XORNode.Val);
2619 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2621 // fold select C, X, 0 -> C & X
2622 // FIXME: this should check for C type == X type, not i1?
2623 if (VT == MVT::i1 && N2C && N2C->isNullValue())
2624 return DAG.getNode(ISD::AND, VT, N0, N1);
2625 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2626 if (VT == MVT::i1 && N0 == N1)
2627 return DAG.getNode(ISD::OR, VT, N0, N2);
2628 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2629 if (VT == MVT::i1 && N0 == N2)
2630 return DAG.getNode(ISD::AND, VT, N0, N1);
2632 // If we can fold this based on the true/false value, do so.
2633 if (SimplifySelectOps(N, N1, N2))
2634 return SDOperand(N, 0); // Don't revisit N.
2636 // fold selects based on a setcc into other things, such as min/max/abs
2637 if (N0.getOpcode() == ISD::SETCC) {
2639 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2640 // having to say they don't support SELECT_CC on every type the DAG knows
2641 // about, since there is no way to mark an opcode illegal at all value types
2642 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2643 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2644 N1, N2, N0.getOperand(2));
2646 return SimplifySelect(N0, N1, N2);
2651 SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2652 SDOperand N0 = N->getOperand(0);
2653 SDOperand N1 = N->getOperand(1);
2654 SDOperand N2 = N->getOperand(2);
2655 SDOperand N3 = N->getOperand(3);
2656 SDOperand N4 = N->getOperand(4);
2657 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2659 // fold select_cc lhs, rhs, x, x, cc -> x
2663 // Determine if the condition we're dealing with is constant
2664 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
2665 if (SCC.Val) AddToWorkList(SCC.Val);
2667 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
2668 if (!SCCC->isNullValue())
2669 return N2; // cond always true -> true val
2671 return N3; // cond always false -> false val
2674 // Fold to a simpler select_cc
2675 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2676 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2677 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2680 // If we can fold this based on the true/false value, do so.
2681 if (SimplifySelectOps(N, N2, N3))
2682 return SDOperand(N, 0); // Don't revisit N.
2684 // fold select_cc into other things, such as min/max/abs
2685 return SimplifySelectCC(N0, N1, N2, N3, CC);
2688 SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2689 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2690 cast<CondCodeSDNode>(N->getOperand(2))->get());
2693 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2694 // "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
2695 // transformation. Returns true if extension are possible and the above
2696 // mentioned transformation is profitable.
2697 static bool ExtendUsesToFormExtLoad(SDNode *N, SDOperand N0,
2699 SmallVector<SDNode*, 4> &ExtendNodes,
2700 TargetLowering &TLI) {
2701 bool HasCopyToRegUses = false;
2702 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2703 for (SDNode::use_iterator UI = N0.Val->use_begin(), UE = N0.Val->use_end();
2705 SDNode *User = UI->getUser();
2708 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2709 if (User->getOpcode() == ISD::SETCC) {
2710 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2711 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2712 // Sign bits will be lost after a zext.
2715 for (unsigned i = 0; i != 2; ++i) {
2716 SDOperand UseOp = User->getOperand(i);
2719 if (!isa<ConstantSDNode>(UseOp))
2724 ExtendNodes.push_back(User);
2726 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2727 SDOperand UseOp = User->getOperand(i);
2729 // If truncate from extended type to original load type is free
2730 // on this target, then it's ok to extend a CopyToReg.
2731 if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
2732 HasCopyToRegUses = true;
2740 if (HasCopyToRegUses) {
2741 bool BothLiveOut = false;
2742 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2744 SDNode *User = UI->getUser();
2745 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2746 SDOperand UseOp = User->getOperand(i);
2747 if (UseOp.Val == N && UseOp.ResNo == 0) {
2754 // Both unextended and extended values are live out. There had better be
2755 // good a reason for the transformation.
2756 return ExtendNodes.size();
2761 SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2762 SDOperand N0 = N->getOperand(0);
2763 MVT VT = N->getValueType(0);
2765 // fold (sext c1) -> c1
2766 if (isa<ConstantSDNode>(N0))
2767 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2769 // fold (sext (sext x)) -> (sext x)
2770 // fold (sext (aext x)) -> (sext x)
2771 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2772 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2774 if (N0.getOpcode() == ISD::TRUNCATE) {
2775 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2776 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2777 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2778 if (NarrowLoad.Val) {
2779 if (NarrowLoad.Val != N0.Val)
2780 CombineTo(N0.Val, NarrowLoad);
2781 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2784 // See if the value being truncated is already sign extended. If so, just
2785 // eliminate the trunc/sext pair.
2786 SDOperand Op = N0.getOperand(0);
2787 unsigned OpBits = Op.getValueType().getSizeInBits();
2788 unsigned MidBits = N0.getValueType().getSizeInBits();
2789 unsigned DestBits = VT.getSizeInBits();
2790 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2792 if (OpBits == DestBits) {
2793 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2794 // bits, it is already ready.
2795 if (NumSignBits > DestBits-MidBits)
2797 } else if (OpBits < DestBits) {
2798 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2799 // bits, just sext from i32.
2800 if (NumSignBits > OpBits-MidBits)
2801 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2803 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2804 // bits, just truncate to i32.
2805 if (NumSignBits > OpBits-MidBits)
2806 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2809 // fold (sext (truncate x)) -> (sextinreg x).
2810 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2811 N0.getValueType())) {
2812 if (Op.getValueType().bitsLT(VT))
2813 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2814 else if (Op.getValueType().bitsGT(VT))
2815 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2816 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2817 DAG.getValueType(N0.getValueType()));
2821 // fold (sext (load x)) -> (sext (truncate (sextload x)))
2822 if (ISD::isNON_EXTLoad(N0.Val) &&
2823 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
2824 TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))) {
2825 bool DoXform = true;
2826 SmallVector<SDNode*, 4> SetCCs;
2827 if (!N0.hasOneUse())
2828 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
2830 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2831 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2832 LN0->getBasePtr(), LN0->getSrcValue(),
2833 LN0->getSrcValueOffset(),
2836 LN0->getAlignment());
2837 CombineTo(N, ExtLoad);
2838 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2839 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2840 // Extend SetCC uses if necessary.
2841 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2842 SDNode *SetCC = SetCCs[i];
2843 SmallVector<SDOperand, 4> Ops;
2844 for (unsigned j = 0; j != 2; ++j) {
2845 SDOperand SOp = SetCC->getOperand(j);
2847 Ops.push_back(ExtLoad);
2849 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
2851 Ops.push_back(SetCC->getOperand(2));
2852 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2853 &Ops[0], Ops.size()));
2855 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2859 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2860 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2861 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2862 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2863 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2864 MVT EVT = LN0->getMemoryVT();
2865 if ((!AfterLegalize && !LN0->isVolatile()) ||
2866 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
2867 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2868 LN0->getBasePtr(), LN0->getSrcValue(),
2869 LN0->getSrcValueOffset(), EVT,
2871 LN0->getAlignment());
2872 CombineTo(N, ExtLoad);
2873 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2874 ExtLoad.getValue(1));
2875 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2879 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2880 if (N0.getOpcode() == ISD::SETCC) {
2882 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2883 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2884 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2885 if (SCC.Val) return SCC;
2888 // fold (sext x) -> (zext x) if the sign bit is known zero.
2889 if ((!AfterLegalize || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
2890 DAG.SignBitIsZero(N0))
2891 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2896 SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2897 SDOperand N0 = N->getOperand(0);
2898 MVT VT = N->getValueType(0);
2900 // fold (zext c1) -> c1
2901 if (isa<ConstantSDNode>(N0))
2902 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2903 // fold (zext (zext x)) -> (zext x)
2904 // fold (zext (aext x)) -> (zext x)
2905 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2906 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2908 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2909 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2910 if (N0.getOpcode() == ISD::TRUNCATE) {
2911 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2912 if (NarrowLoad.Val) {
2913 if (NarrowLoad.Val != N0.Val)
2914 CombineTo(N0.Val, NarrowLoad);
2915 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2919 // fold (zext (truncate x)) -> (and x, mask)
2920 if (N0.getOpcode() == ISD::TRUNCATE &&
2921 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2922 SDOperand Op = N0.getOperand(0);
2923 if (Op.getValueType().bitsLT(VT)) {
2924 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2925 } else if (Op.getValueType().bitsGT(VT)) {
2926 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2928 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2931 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2932 if (N0.getOpcode() == ISD::AND &&
2933 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2934 N0.getOperand(1).getOpcode() == ISD::Constant) {
2935 SDOperand X = N0.getOperand(0).getOperand(0);
2936 if (X.getValueType().bitsLT(VT)) {
2937 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2938 } else if (X.getValueType().bitsGT(VT)) {
2939 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2941 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2942 Mask.zext(VT.getSizeInBits());
2943 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2946 // fold (zext (load x)) -> (zext (truncate (zextload x)))
2947 if (ISD::isNON_EXTLoad(N0.Val) &&
2948 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
2949 TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
2950 bool DoXform = true;
2951 SmallVector<SDNode*, 4> SetCCs;
2952 if (!N0.hasOneUse())
2953 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
2955 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2956 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2957 LN0->getBasePtr(), LN0->getSrcValue(),
2958 LN0->getSrcValueOffset(),
2961 LN0->getAlignment());
2962 CombineTo(N, ExtLoad);
2963 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2964 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2965 // Extend SetCC uses if necessary.
2966 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2967 SDNode *SetCC = SetCCs[i];
2968 SmallVector<SDOperand, 4> Ops;
2969 for (unsigned j = 0; j != 2; ++j) {
2970 SDOperand SOp = SetCC->getOperand(j);
2972 Ops.push_back(ExtLoad);
2974 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
2976 Ops.push_back(SetCC->getOperand(2));
2977 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2978 &Ops[0], Ops.size()));
2980 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2984 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2985 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2986 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2987 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2988 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2989 MVT EVT = LN0->getMemoryVT();
2990 if ((!AfterLegalize && !LN0->isVolatile()) ||
2991 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT)) {
2992 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2993 LN0->getBasePtr(), LN0->getSrcValue(),
2994 LN0->getSrcValueOffset(), EVT,
2996 LN0->getAlignment());
2997 CombineTo(N, ExtLoad);
2998 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2999 ExtLoad.getValue(1));
3000 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3004 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3005 if (N0.getOpcode() == ISD::SETCC) {
3007 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3008 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3009 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3010 if (SCC.Val) return SCC;
3016 SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
3017 SDOperand N0 = N->getOperand(0);
3018 MVT VT = N->getValueType(0);
3020 // fold (aext c1) -> c1
3021 if (isa<ConstantSDNode>(N0))
3022 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
3023 // fold (aext (aext x)) -> (aext x)
3024 // fold (aext (zext x)) -> (zext x)
3025 // fold (aext (sext x)) -> (sext x)
3026 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3027 N0.getOpcode() == ISD::ZERO_EXTEND ||
3028 N0.getOpcode() == ISD::SIGN_EXTEND)
3029 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3031 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3032 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3033 if (N0.getOpcode() == ISD::TRUNCATE) {
3034 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
3035 if (NarrowLoad.Val) {
3036 if (NarrowLoad.Val != N0.Val)
3037 CombineTo(N0.Val, NarrowLoad);
3038 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
3042 // fold (aext (truncate x))
3043 if (N0.getOpcode() == ISD::TRUNCATE) {
3044 SDOperand TruncOp = N0.getOperand(0);
3045 if (TruncOp.getValueType() == VT)
3046 return TruncOp; // x iff x size == zext size.
3047 if (TruncOp.getValueType().bitsGT(VT))
3048 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
3049 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
3052 // fold (aext (and (trunc x), cst)) -> (and x, cst).
3053 if (N0.getOpcode() == ISD::AND &&
3054 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3055 N0.getOperand(1).getOpcode() == ISD::Constant) {
3056 SDOperand X = N0.getOperand(0).getOperand(0);
3057 if (X.getValueType().bitsLT(VT)) {
3058 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
3059 } else if (X.getValueType().bitsGT(VT)) {
3060 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3062 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3063 Mask.zext(VT.getSizeInBits());
3064 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
3067 // fold (aext (load x)) -> (aext (truncate (extload x)))
3068 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3069 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3070 TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3071 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3072 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3073 LN0->getBasePtr(), LN0->getSrcValue(),
3074 LN0->getSrcValueOffset(),
3077 LN0->getAlignment());
3078 CombineTo(N, ExtLoad);
3079 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3080 ExtLoad.getValue(1));
3081 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3084 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3085 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3086 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3087 if (N0.getOpcode() == ISD::LOAD &&
3088 !ISD::isNON_EXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3090 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3091 MVT EVT = LN0->getMemoryVT();
3092 SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
3093 LN0->getChain(), LN0->getBasePtr(),
3095 LN0->getSrcValueOffset(), EVT,
3097 LN0->getAlignment());
3098 CombineTo(N, ExtLoad);
3099 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3100 ExtLoad.getValue(1));
3101 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3104 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3105 if (N0.getOpcode() == ISD::SETCC) {
3107 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3108 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3109 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3117 /// GetDemandedBits - See if the specified operand can be simplified with the
3118 /// knowledge that only the bits specified by Mask are used. If so, return the
3119 /// simpler operand, otherwise return a null SDOperand.
3120 SDOperand DAGCombiner::GetDemandedBits(SDOperand V, const APInt &Mask) {
3121 switch (V.getOpcode()) {
3125 // If the LHS or RHS don't contribute bits to the or, drop them.
3126 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3127 return V.getOperand(1);
3128 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3129 return V.getOperand(0);
3132 // Only look at single-use SRLs.
3133 if (!V.Val->hasOneUse())
3135 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3136 // See if we can recursively simplify the LHS.
3137 unsigned Amt = RHSC->getValue();
3138 APInt NewMask = Mask << Amt;
3139 SDOperand SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3140 if (SimplifyLHS.Val) {
3141 return DAG.getNode(ISD::SRL, V.getValueType(),
3142 SimplifyLHS, V.getOperand(1));
3149 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3150 /// bits and then truncated to a narrower type and where N is a multiple
3151 /// of number of bits of the narrower type, transform it to a narrower load
3152 /// from address + N / num of bits of new type. If the result is to be
3153 /// extended, also fold the extension to form a extending load.
3154 SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
3155 unsigned Opc = N->getOpcode();
3156 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3157 SDOperand N0 = N->getOperand(0);
3158 MVT VT = N->getValueType(0);
3159 MVT EVT = N->getValueType(0);
3161 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3163 if (Opc == ISD::SIGN_EXTEND_INREG) {
3164 ExtType = ISD::SEXTLOAD;
3165 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3166 if (AfterLegalize && !TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))
3170 unsigned EVTBits = EVT.getSizeInBits();
3172 bool CombineSRL = false;
3173 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3174 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3175 ShAmt = N01->getValue();
3176 // Is the shift amount a multiple of size of VT?
3177 if ((ShAmt & (EVTBits-1)) == 0) {
3178 N0 = N0.getOperand(0);
3179 if (N0.getValueType().getSizeInBits() <= EVTBits)
3186 // Do not generate loads of non-round integer types since these can
3187 // be expensive (and would be wrong if the type is not byte sized).
3188 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() && VT.isRound() &&
3189 // Do not change the width of a volatile load.
3190 !cast<LoadSDNode>(N0)->isVolatile()) {
3191 assert(N0.getValueType().getSizeInBits() > EVTBits &&
3192 "Cannot truncate to larger type!");
3193 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3194 MVT PtrType = N0.getOperand(1).getValueType();
3195 // For big endian targets, we need to adjust the offset to the pointer to
3196 // load the correct bytes.
3197 if (TLI.isBigEndian()) {
3198 unsigned LVTStoreBits = N0.getValueType().getStoreSizeInBits();
3199 unsigned EVTStoreBits = EVT.getStoreSizeInBits();
3200 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3202 uint64_t PtrOff = ShAmt / 8;
3203 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3204 SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
3205 DAG.getConstant(PtrOff, PtrType));
3206 AddToWorkList(NewPtr.Val);
3207 SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
3208 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
3209 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3210 LN0->isVolatile(), NewAlign)
3211 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
3212 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
3213 LN0->isVolatile(), NewAlign);
3216 WorkListRemover DeadNodes(*this);
3217 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3219 CombineTo(N->getOperand(0).Val, Load);
3221 CombineTo(N0.Val, Load, Load.getValue(1));
3223 if (Opc == ISD::SIGN_EXTEND_INREG)
3224 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
3226 return DAG.getNode(Opc, VT, Load);
3228 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3235 SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3236 SDOperand N0 = N->getOperand(0);
3237 SDOperand N1 = N->getOperand(1);
3238 MVT VT = N->getValueType(0);
3239 MVT EVT = cast<VTSDNode>(N1)->getVT();
3240 unsigned VTBits = VT.getSizeInBits();
3241 unsigned EVTBits = EVT.getSizeInBits();
3243 // fold (sext_in_reg c1) -> c1
3244 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3245 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
3247 // If the input is already sign extended, just drop the extension.
3248 if (DAG.ComputeNumSignBits(N0) >= VT.getSizeInBits()-EVTBits+1)
3251 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3252 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3253 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
3254 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
3257 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3258 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3259 return DAG.getZeroExtendInReg(N0, EVT);
3261 // fold operands of sext_in_reg based on knowledge that the top bits are not
3263 if (SimplifyDemandedBits(SDOperand(N, 0)))
3264 return SDOperand(N, 0);
3266 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3267 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3268 SDOperand NarrowLoad = ReduceLoadWidth(N);
3272 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
3273 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
3274 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3275 if (N0.getOpcode() == ISD::SRL) {
3276 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3277 if (ShAmt->getValue()+EVTBits <= VT.getSizeInBits()) {
3278 // We can turn this into an SRA iff the input to the SRL is already sign
3280 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3281 if (VT.getSizeInBits()-(ShAmt->getValue()+EVTBits) < InSignBits)
3282 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
3286 // fold (sext_inreg (extload x)) -> (sextload x)
3287 if (ISD::isEXTLoad(N0.Val) &&
3288 ISD::isUNINDEXEDLoad(N0.Val) &&
3289 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3290 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3291 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3292 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3293 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3294 LN0->getBasePtr(), LN0->getSrcValue(),
3295 LN0->getSrcValueOffset(), EVT,
3297 LN0->getAlignment());
3298 CombineTo(N, ExtLoad);
3299 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3300 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3302 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3303 if (ISD::isZEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3305 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3306 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3307 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3308 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3309 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3310 LN0->getBasePtr(), LN0->getSrcValue(),
3311 LN0->getSrcValueOffset(), EVT,
3313 LN0->getAlignment());
3314 CombineTo(N, ExtLoad);
3315 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3316 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3321 SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
3322 SDOperand N0 = N->getOperand(0);
3323 MVT VT = N->getValueType(0);
3326 if (N0.getValueType() == N->getValueType(0))
3328 // fold (truncate c1) -> c1
3329 if (isa<ConstantSDNode>(N0))
3330 return DAG.getNode(ISD::TRUNCATE, VT, N0);
3331 // fold (truncate (truncate x)) -> (truncate x)
3332 if (N0.getOpcode() == ISD::TRUNCATE)
3333 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3334 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3335 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3336 N0.getOpcode() == ISD::ANY_EXTEND) {
3337 if (N0.getOperand(0).getValueType().bitsLT(VT))
3338 // if the source is smaller than the dest, we still need an extend
3339 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3340 else if (N0.getOperand(0).getValueType().bitsGT(VT))
3341 // if the source is larger than the dest, than we just need the truncate
3342 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3344 // if the source and dest are the same type, we can drop both the extend
3346 return N0.getOperand(0);
3349 // See if we can simplify the input to this truncate through knowledge that
3350 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3353 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3354 VT.getSizeInBits()));
3356 return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3358 // fold (truncate (load x)) -> (smaller load x)
3359 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3360 return ReduceLoadWidth(N);
3363 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
3364 SDOperand Elt = N->getOperand(i);
3365 if (Elt.getOpcode() != ISD::MERGE_VALUES)
3367 return Elt.getOperand(Elt.ResNo).Val;
3370 /// CombineConsecutiveLoads - build_pair (load, load) -> load
3371 /// if load locations are consecutive.
3372 SDOperand DAGCombiner::CombineConsecutiveLoads(SDNode *N, MVT VT) {
3373 assert(N->getOpcode() == ISD::BUILD_PAIR);
3375 SDNode *LD1 = getBuildPairElt(N, 0);
3376 if (!ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
3378 MVT LD1VT = LD1->getValueType(0);
3379 SDNode *LD2 = getBuildPairElt(N, 1);
3380 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3381 if (ISD::isNON_EXTLoad(LD2) &&
3383 // If both are volatile this would reduce the number of volatile loads.
3384 // If one is volatile it might be ok, but play conservative and bail out.
3385 !cast<LoadSDNode>(LD1)->isVolatile() &&
3386 !cast<LoadSDNode>(LD2)->isVolatile() &&
3387 TLI.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1, MFI)) {
3388 LoadSDNode *LD = cast<LoadSDNode>(LD1);
3389 unsigned Align = LD->getAlignment();
3390 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
3391 getABITypeAlignment(VT.getTypeForMVT());
3392 if (NewAlign <= Align &&
3393 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT)))
3394 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(),
3395 LD->getSrcValue(), LD->getSrcValueOffset(),
3401 SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3402 SDOperand N0 = N->getOperand(0);
3403 MVT VT = N->getValueType(0);
3405 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3406 // Only do this before legalize, since afterward the target may be depending
3407 // on the bitconvert.
3408 // First check to see if this is all constant.
3409 if (!AfterLegalize &&
3410 N0.getOpcode() == ISD::BUILD_VECTOR && N0.Val->hasOneUse() &&
3412 bool isSimple = true;
3413 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3414 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3415 N0.getOperand(i).getOpcode() != ISD::Constant &&
3416 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3421 MVT DestEltVT = N->getValueType(0).getVectorElementType();
3422 assert(!DestEltVT.isVector() &&
3423 "Element type of vector ValueType must not be vector!");
3425 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.Val, DestEltVT);
3429 // If the input is a constant, let getNode() fold it.
3430 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3431 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3432 if (Res.Val != N) return Res;
3435 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
3436 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3438 // fold (conv (load x)) -> (load (conv*)x)
3439 // If the resultant load doesn't need a higher alignment than the original!
3440 if (ISD::isNormalLoad(N0.Val) && N0.hasOneUse() &&
3441 // Do not change the width of a volatile load.
3442 !cast<LoadSDNode>(N0)->isVolatile() &&
3443 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT))) {
3444 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3445 unsigned Align = TLI.getTargetMachine().getTargetData()->
3446 getABITypeAlignment(VT.getTypeForMVT());
3447 unsigned OrigAlign = LN0->getAlignment();
3448 if (Align <= OrigAlign) {
3449 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3450 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3451 LN0->isVolatile(), Align);
3453 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3459 // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit)
3460 // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit)
3461 // This often reduces constant pool loads.
3462 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3463 N0.Val->hasOneUse() && VT.isInteger() && !VT.isVector()) {
3464 SDOperand NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3465 AddToWorkList(NewConv.Val);
3467 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3468 if (N0.getOpcode() == ISD::FNEG)
3469 return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT));
3470 assert(N0.getOpcode() == ISD::FABS);
3471 return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT));
3474 // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign'
3475 // Note that we don't handle copysign(x,cst) because this can always be folded
3476 // to an fneg or fabs.
3477 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse() &&
3478 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3479 VT.isInteger() && !VT.isVector()) {
3480 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
3481 SDOperand X = DAG.getNode(ISD::BIT_CONVERT,
3482 MVT::getIntegerVT(OrigXWidth),
3484 AddToWorkList(X.Val);
3486 // If X has a different width than the result/lhs, sext it or truncate it.
3487 unsigned VTWidth = VT.getSizeInBits();
3488 if (OrigXWidth < VTWidth) {
3489 X = DAG.getNode(ISD::SIGN_EXTEND, VT, X);
3490 AddToWorkList(X.Val);
3491 } else if (OrigXWidth > VTWidth) {
3492 // To get the sign bit in the right place, we have to shift it right
3493 // before truncating.
3494 X = DAG.getNode(ISD::SRL, X.getValueType(), X,
3495 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3496 AddToWorkList(X.Val);
3497 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3498 AddToWorkList(X.Val);
3501 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3502 X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT));
3503 AddToWorkList(X.Val);
3505 SDOperand Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3506 Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT));
3507 AddToWorkList(Cst.Val);
3509 return DAG.getNode(ISD::OR, VT, X, Cst);
3512 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
3513 if (N0.getOpcode() == ISD::BUILD_PAIR) {
3514 SDOperand CombineLD = CombineConsecutiveLoads(N0.Val, VT);
3522 SDOperand DAGCombiner::visitBUILD_PAIR(SDNode *N) {
3523 MVT VT = N->getValueType(0);
3524 return CombineConsecutiveLoads(N, VT);
3527 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3528 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3529 /// destination element value type.
3530 SDOperand DAGCombiner::
3531 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT DstEltVT) {
3532 MVT SrcEltVT = BV->getOperand(0).getValueType();
3534 // If this is already the right type, we're done.
3535 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
3537 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
3538 unsigned DstBitSize = DstEltVT.getSizeInBits();
3540 // If this is a conversion of N elements of one type to N elements of another
3541 // type, convert each element. This handles FP<->INT cases.
3542 if (SrcBitSize == DstBitSize) {
3543 SmallVector<SDOperand, 8> Ops;
3544 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3545 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3546 AddToWorkList(Ops.back().Val);
3548 MVT VT = MVT::getVectorVT(DstEltVT,
3549 BV->getValueType(0).getVectorNumElements());
3550 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3553 // Otherwise, we're growing or shrinking the elements. To avoid having to
3554 // handle annoying details of growing/shrinking FP values, we convert them to
3556 if (SrcEltVT.isFloatingPoint()) {
3557 // Convert the input float vector to a int vector where the elements are the
3559 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3560 MVT IntVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits());
3561 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).Val;
3565 // Now we know the input is an integer vector. If the output is a FP type,
3566 // convert to integer first, then to FP of the right size.
3567 if (DstEltVT.isFloatingPoint()) {
3568 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3569 MVT TmpVT = MVT::getIntegerVT(DstEltVT.getSizeInBits());
3570 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).Val;
3572 // Next, convert to FP elements of the same size.
3573 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3576 // Okay, we know the src/dst types are both integers of differing types.
3577 // Handling growing first.
3578 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
3579 if (SrcBitSize < DstBitSize) {
3580 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3582 SmallVector<SDOperand, 8> Ops;
3583 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3584 i += NumInputsPerOutput) {
3585 bool isLE = TLI.isLittleEndian();
3586 APInt NewBits = APInt(DstBitSize, 0);
3587 bool EltIsUndef = true;
3588 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3589 // Shift the previously computed bits over.
3590 NewBits <<= SrcBitSize;
3591 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3592 if (Op.getOpcode() == ISD::UNDEF) continue;
3596 APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).zext(DstBitSize);
3600 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3602 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3605 MVT VT = MVT::getVectorVT(DstEltVT, Ops.size());
3606 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3609 // Finally, this must be the case where we are shrinking elements: each input
3610 // turns into multiple outputs.
3611 bool isS2V = ISD::isScalarToVector(BV);
3612 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3613 MVT VT = MVT::getVectorVT(DstEltVT, NumOutputsPerInput*BV->getNumOperands());
3614 SmallVector<SDOperand, 8> Ops;
3615 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3616 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3617 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3618 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3621 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getAPIntValue();
3622 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3623 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
3624 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3625 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
3626 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3627 return DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Ops[0]);
3628 OpVal = OpVal.lshr(DstBitSize);
3631 // For big endian targets, swap the order of the pieces of each element.
3632 if (TLI.isBigEndian())
3633 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3635 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3640 SDOperand DAGCombiner::visitFADD(SDNode *N) {
3641 SDOperand N0 = N->getOperand(0);
3642 SDOperand N1 = N->getOperand(1);
3643 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3644 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3645 MVT VT = N->getValueType(0);
3648 if (VT.isVector()) {
3649 SDOperand FoldedVOp = SimplifyVBinOp(N);
3650 if (FoldedVOp.Val) return FoldedVOp;
3653 // fold (fadd c1, c2) -> c1+c2
3654 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3655 return DAG.getNode(ISD::FADD, VT, N0, N1);
3656 // canonicalize constant to RHS
3657 if (N0CFP && !N1CFP)
3658 return DAG.getNode(ISD::FADD, VT, N1, N0);
3659 // fold (A + (-B)) -> A-B
3660 if (isNegatibleForFree(N1, AfterLegalize) == 2)
3661 return DAG.getNode(ISD::FSUB, VT, N0,
3662 GetNegatedExpression(N1, DAG, AfterLegalize));
3663 // fold ((-A) + B) -> B-A
3664 if (isNegatibleForFree(N0, AfterLegalize) == 2)
3665 return DAG.getNode(ISD::FSUB, VT, N1,
3666 GetNegatedExpression(N0, DAG, AfterLegalize));
3668 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3669 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3670 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3671 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3672 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3677 SDOperand DAGCombiner::visitFSUB(SDNode *N) {
3678 SDOperand N0 = N->getOperand(0);
3679 SDOperand N1 = N->getOperand(1);
3680 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3681 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3682 MVT VT = N->getValueType(0);
3685 if (VT.isVector()) {
3686 SDOperand FoldedVOp = SimplifyVBinOp(N);
3687 if (FoldedVOp.Val) return FoldedVOp;
3690 // fold (fsub c1, c2) -> c1-c2
3691 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3692 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3694 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
3695 if (isNegatibleForFree(N1, AfterLegalize))
3696 return GetNegatedExpression(N1, DAG, AfterLegalize);
3697 return DAG.getNode(ISD::FNEG, VT, N1);
3699 // fold (A-(-B)) -> A+B
3700 if (isNegatibleForFree(N1, AfterLegalize))
3701 return DAG.getNode(ISD::FADD, VT, N0,
3702 GetNegatedExpression(N1, DAG, AfterLegalize));
3707 SDOperand DAGCombiner::visitFMUL(SDNode *N) {
3708 SDOperand N0 = N->getOperand(0);
3709 SDOperand N1 = N->getOperand(1);
3710 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3711 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3712 MVT VT = N->getValueType(0);
3715 if (VT.isVector()) {
3716 SDOperand FoldedVOp = SimplifyVBinOp(N);
3717 if (FoldedVOp.Val) return FoldedVOp;
3720 // fold (fmul c1, c2) -> c1*c2
3721 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3722 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3723 // canonicalize constant to RHS
3724 if (N0CFP && !N1CFP)
3725 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3726 // fold (fmul X, 2.0) -> (fadd X, X)
3727 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3728 return DAG.getNode(ISD::FADD, VT, N0, N0);
3729 // fold (fmul X, -1.0) -> (fneg X)
3730 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3731 return DAG.getNode(ISD::FNEG, VT, N0);
3734 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3735 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3736 // Both can be negated for free, check to see if at least one is cheaper
3738 if (LHSNeg == 2 || RHSNeg == 2)
3739 return DAG.getNode(ISD::FMUL, VT,
3740 GetNegatedExpression(N0, DAG, AfterLegalize),
3741 GetNegatedExpression(N1, DAG, AfterLegalize));
3745 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3746 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3747 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3748 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3749 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3754 SDOperand DAGCombiner::visitFDIV(SDNode *N) {
3755 SDOperand N0 = N->getOperand(0);
3756 SDOperand N1 = N->getOperand(1);
3757 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3758 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3759 MVT VT = N->getValueType(0);
3762 if (VT.isVector()) {
3763 SDOperand FoldedVOp = SimplifyVBinOp(N);
3764 if (FoldedVOp.Val) return FoldedVOp;
3767 // fold (fdiv c1, c2) -> c1/c2
3768 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3769 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3773 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3774 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3775 // Both can be negated for free, check to see if at least one is cheaper
3777 if (LHSNeg == 2 || RHSNeg == 2)
3778 return DAG.getNode(ISD::FDIV, VT,
3779 GetNegatedExpression(N0, DAG, AfterLegalize),
3780 GetNegatedExpression(N1, DAG, AfterLegalize));
3787 SDOperand DAGCombiner::visitFREM(SDNode *N) {
3788 SDOperand N0 = N->getOperand(0);
3789 SDOperand N1 = N->getOperand(1);
3790 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3791 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3792 MVT VT = N->getValueType(0);
3794 // fold (frem c1, c2) -> fmod(c1,c2)
3795 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3796 return DAG.getNode(ISD::FREM, VT, N0, N1);
3801 SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3802 SDOperand N0 = N->getOperand(0);
3803 SDOperand N1 = N->getOperand(1);
3804 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3805 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3806 MVT VT = N->getValueType(0);
3808 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
3809 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3812 const APFloat& V = N1CFP->getValueAPF();
3813 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3814 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
3815 if (!V.isNegative())
3816 return DAG.getNode(ISD::FABS, VT, N0);
3818 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3821 // copysign(fabs(x), y) -> copysign(x, y)
3822 // copysign(fneg(x), y) -> copysign(x, y)
3823 // copysign(copysign(x,z), y) -> copysign(x, y)
3824 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3825 N0.getOpcode() == ISD::FCOPYSIGN)
3826 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3828 // copysign(x, abs(y)) -> abs(x)
3829 if (N1.getOpcode() == ISD::FABS)
3830 return DAG.getNode(ISD::FABS, VT, N0);
3832 // copysign(x, copysign(y,z)) -> copysign(x, z)
3833 if (N1.getOpcode() == ISD::FCOPYSIGN)
3834 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3836 // copysign(x, fp_extend(y)) -> copysign(x, y)
3837 // copysign(x, fp_round(y)) -> copysign(x, y)
3838 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3839 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3846 SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3847 SDOperand N0 = N->getOperand(0);
3848 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3849 MVT VT = N->getValueType(0);
3851 // fold (sint_to_fp c1) -> c1fp
3852 if (N0C && N0.getValueType() != MVT::ppcf128)
3853 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3857 SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3858 SDOperand N0 = N->getOperand(0);
3859 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3860 MVT VT = N->getValueType(0);
3862 // fold (uint_to_fp c1) -> c1fp
3863 if (N0C && N0.getValueType() != MVT::ppcf128)
3864 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3868 SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3869 SDOperand N0 = N->getOperand(0);
3870 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3871 MVT VT = N->getValueType(0);
3873 // fold (fp_to_sint c1fp) -> c1
3875 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3879 SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3880 SDOperand N0 = N->getOperand(0);
3881 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3882 MVT VT = N->getValueType(0);
3884 // fold (fp_to_uint c1fp) -> c1
3885 if (N0CFP && VT != MVT::ppcf128)
3886 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3890 SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
3891 SDOperand N0 = N->getOperand(0);
3892 SDOperand N1 = N->getOperand(1);
3893 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3894 MVT VT = N->getValueType(0);
3896 // fold (fp_round c1fp) -> c1fp
3897 if (N0CFP && N0.getValueType() != MVT::ppcf128)
3898 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
3900 // fold (fp_round (fp_extend x)) -> x
3901 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3902 return N0.getOperand(0);
3904 // fold (fp_round (fp_round x)) -> (fp_round x)
3905 if (N0.getOpcode() == ISD::FP_ROUND) {
3906 // This is a value preserving truncation if both round's are.
3907 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
3908 N0.Val->getConstantOperandVal(1) == 1;
3909 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
3910 DAG.getIntPtrConstant(IsTrunc));
3913 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3914 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
3915 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
3916 AddToWorkList(Tmp.Val);
3917 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
3923 SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
3924 SDOperand N0 = N->getOperand(0);
3925 MVT VT = N->getValueType(0);
3926 MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3927 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3929 // fold (fp_round_inreg c1fp) -> c1fp
3931 SDOperand Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT);
3932 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
3937 SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
3938 SDOperand N0 = N->getOperand(0);
3939 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3940 MVT VT = N->getValueType(0);
3942 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
3943 if (N->hasOneUse() &&
3944 N->use_begin()->getSDOperand().getOpcode() == ISD::FP_ROUND)
3947 // fold (fp_extend c1fp) -> c1fp
3948 if (N0CFP && VT != MVT::ppcf128)
3949 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
3951 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
3953 if (N0.getOpcode() == ISD::FP_ROUND && N0.Val->getConstantOperandVal(1) == 1){
3954 SDOperand In = N0.getOperand(0);
3955 if (In.getValueType() == VT) return In;
3956 if (VT.bitsLT(In.getValueType()))
3957 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
3958 return DAG.getNode(ISD::FP_EXTEND, VT, In);
3961 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
3962 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3963 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3964 TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3965 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3966 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3967 LN0->getBasePtr(), LN0->getSrcValue(),
3968 LN0->getSrcValueOffset(),
3971 LN0->getAlignment());
3972 CombineTo(N, ExtLoad);
3973 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad,
3974 DAG.getIntPtrConstant(1)),
3975 ExtLoad.getValue(1));
3976 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3982 SDOperand DAGCombiner::visitFNEG(SDNode *N) {
3983 SDOperand N0 = N->getOperand(0);
3985 if (isNegatibleForFree(N0, AfterLegalize))
3986 return GetNegatedExpression(N0, DAG, AfterLegalize);
3988 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
3989 // constant pool values.
3990 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
3991 N0.getOperand(0).getValueType().isInteger() &&
3992 !N0.getOperand(0).getValueType().isVector()) {
3993 SDOperand Int = N0.getOperand(0);
3994 MVT IntVT = Int.getValueType();
3995 if (IntVT.isInteger() && !IntVT.isVector()) {
3996 Int = DAG.getNode(ISD::XOR, IntVT, Int,
3997 DAG.getConstant(IntVT.getIntegerVTSignBit(), IntVT));
3998 AddToWorkList(Int.Val);
3999 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4006 SDOperand DAGCombiner::visitFABS(SDNode *N) {
4007 SDOperand N0 = N->getOperand(0);
4008 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4009 MVT VT = N->getValueType(0);
4011 // fold (fabs c1) -> fabs(c1)
4012 if (N0CFP && VT != MVT::ppcf128)
4013 return DAG.getNode(ISD::FABS, VT, N0);
4014 // fold (fabs (fabs x)) -> (fabs x)
4015 if (N0.getOpcode() == ISD::FABS)
4016 return N->getOperand(0);
4017 // fold (fabs (fneg x)) -> (fabs x)
4018 // fold (fabs (fcopysign x, y)) -> (fabs x)
4019 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4020 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
4022 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4023 // constant pool values.
4024 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
4025 N0.getOperand(0).getValueType().isInteger() &&
4026 !N0.getOperand(0).getValueType().isVector()) {
4027 SDOperand Int = N0.getOperand(0);
4028 MVT IntVT = Int.getValueType();
4029 if (IntVT.isInteger() && !IntVT.isVector()) {
4030 Int = DAG.getNode(ISD::AND, IntVT, Int,
4031 DAG.getConstant(~IntVT.getIntegerVTSignBit(), IntVT));
4032 AddToWorkList(Int.Val);
4033 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4040 SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
4041 SDOperand Chain = N->getOperand(0);
4042 SDOperand N1 = N->getOperand(1);
4043 SDOperand N2 = N->getOperand(2);
4044 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4046 // never taken branch, fold to chain
4047 if (N1C && N1C->isNullValue())
4049 // unconditional branch
4050 if (N1C && N1C->getAPIntValue() == 1)
4051 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
4052 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4054 if (N1.getOpcode() == ISD::SETCC &&
4055 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
4056 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
4057 N1.getOperand(0), N1.getOperand(1), N2);
4062 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4064 SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
4065 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4066 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4068 // Use SimplifySetCC to simplify SETCC's.
4069 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
4070 if (Simp.Val) AddToWorkList(Simp.Val);
4072 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
4074 // fold br_cc true, dest -> br dest (unconditional branch)
4075 if (SCCC && !SCCC->isNullValue())
4076 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
4078 // fold br_cc false, dest -> unconditional fall through
4079 if (SCCC && SCCC->isNullValue())
4080 return N->getOperand(0);
4082 // fold to a simpler setcc
4083 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
4084 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
4085 Simp.getOperand(2), Simp.getOperand(0),
4086 Simp.getOperand(1), N->getOperand(4));
4091 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
4092 /// pre-indexed load / store when the base pointer is an add or subtract
4093 /// and it has other uses besides the load / store. After the
4094 /// transformation, the new indexed load / store has effectively folded
4095 /// the add / subtract in and all of its other uses are redirected to the
4096 /// new load / store.
4097 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4104 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4105 if (LD->isIndexed())
4107 VT = LD->getMemoryVT();
4108 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4109 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4111 Ptr = LD->getBasePtr();
4112 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4113 if (ST->isIndexed())
4115 VT = ST->getMemoryVT();
4116 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4117 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4119 Ptr = ST->getBasePtr();
4124 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4125 // out. There is no reason to make this a preinc/predec.
4126 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4127 Ptr.Val->hasOneUse())
4130 // Ask the target to do addressing mode selection.
4133 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4134 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4136 // Don't create a indexed load / store with zero offset.
4137 if (isa<ConstantSDNode>(Offset) &&
4138 cast<ConstantSDNode>(Offset)->isNullValue())
4141 // Try turning it into a pre-indexed load / store except when:
4142 // 1) The new base ptr is a frame index.
4143 // 2) If N is a store and the new base ptr is either the same as or is a
4144 // predecessor of the value being stored.
4145 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4146 // that would create a cycle.
4147 // 4) All uses are load / store ops that use it as old base ptr.
4149 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4150 // (plus the implicit offset) to a register to preinc anyway.
4151 if (isa<FrameIndexSDNode>(BasePtr))
4156 SDOperand Val = cast<StoreSDNode>(N)->getValue();
4157 if (Val == BasePtr || BasePtr.Val->isPredecessorOf(Val.Val))
4161 // Now check for #3 and #4.
4162 bool RealUse = false;
4163 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4164 E = Ptr.Val->use_end(); I != E; ++I) {
4165 SDNode *Use = I->getUser();
4168 if (Use->isPredecessorOf(N))
4171 if (!((Use->getOpcode() == ISD::LOAD &&
4172 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
4173 (Use->getOpcode() == ISD::STORE &&
4174 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
4182 Result = DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
4184 Result = DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4187 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
4188 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4190 WorkListRemover DeadNodes(*this);
4192 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4194 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4197 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4201 // Finally, since the node is now dead, remove it from the graph.
4204 // Replace the uses of Ptr with uses of the updated base value.
4205 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
4207 removeFromWorkList(Ptr.Val);
4208 DAG.DeleteNode(Ptr.Val);
4213 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
4214 /// add / sub of the base pointer node into a post-indexed load / store.
4215 /// The transformation folded the add / subtract into the new indexed
4216 /// load / store effectively and all of its uses are redirected to the
4217 /// new load / store.
4218 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4225 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4226 if (LD->isIndexed())
4228 VT = LD->getMemoryVT();
4229 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4230 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4232 Ptr = LD->getBasePtr();
4233 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4234 if (ST->isIndexed())
4236 VT = ST->getMemoryVT();
4237 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4238 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4240 Ptr = ST->getBasePtr();
4245 if (Ptr.Val->hasOneUse())
4248 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4249 E = Ptr.Val->use_end(); I != E; ++I) {
4250 SDNode *Op = I->getUser();
4252 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4257 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4258 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4260 std::swap(BasePtr, Offset);
4263 // Don't create a indexed load / store with zero offset.
4264 if (isa<ConstantSDNode>(Offset) &&
4265 cast<ConstantSDNode>(Offset)->isNullValue())
4268 // Try turning it into a post-indexed load / store except when
4269 // 1) All uses are load / store ops that use it as base ptr.
4270 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4271 // nor a successor of N. Otherwise, if Op is folded that would
4275 bool TryNext = false;
4276 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
4277 EE = BasePtr.Val->use_end(); II != EE; ++II) {
4278 SDNode *Use = II->getUser();
4282 // If all the uses are load / store addresses, then don't do the
4284 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4285 bool RealUse = false;
4286 for (SDNode::use_iterator III = Use->use_begin(),
4287 EEE = Use->use_end(); III != EEE; ++III) {
4288 SDNode *UseUse = III->getUser();
4289 if (!((UseUse->getOpcode() == ISD::LOAD &&
4290 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
4291 (UseUse->getOpcode() == ISD::STORE &&
4292 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use)))
4306 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
4307 SDOperand Result = isLoad
4308 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
4309 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4312 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
4313 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4315 WorkListRemover DeadNodes(*this);
4317 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4319 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4322 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4326 // Finally, since the node is now dead, remove it from the graph.
4329 // Replace the uses of Use with uses of the updated base value.
4330 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
4331 Result.getValue(isLoad ? 1 : 0),
4333 removeFromWorkList(Op);
4342 /// InferAlignment - If we can infer some alignment information from this
4343 /// pointer, return it.
4344 static unsigned InferAlignment(SDOperand Ptr, SelectionDAG &DAG) {
4345 // If this is a direct reference to a stack slot, use information about the
4346 // stack slot's alignment.
4347 int FrameIdx = 1 << 31;
4348 int64_t FrameOffset = 0;
4349 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
4350 FrameIdx = FI->getIndex();
4351 } else if (Ptr.getOpcode() == ISD::ADD &&
4352 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4353 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4354 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4355 FrameOffset = Ptr.getConstantOperandVal(1);
4358 if (FrameIdx != (1 << 31)) {
4359 // FIXME: Handle FI+CST.
4360 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
4361 if (MFI.isFixedObjectIndex(FrameIdx)) {
4362 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx);
4364 // The alignment of the frame index can be determined from its offset from
4365 // the incoming frame position. If the frame object is at offset 32 and
4366 // the stack is guaranteed to be 16-byte aligned, then we know that the
4367 // object is 16-byte aligned.
4368 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
4369 unsigned Align = MinAlign(ObjectOffset, StackAlign);
4371 // Finally, the frame object itself may have a known alignment. Factor
4372 // the alignment + offset into a new alignment. For example, if we know
4373 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
4374 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
4375 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
4376 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
4378 return std::max(Align, FIInfoAlign);
4385 SDOperand DAGCombiner::visitLOAD(SDNode *N) {
4386 LoadSDNode *LD = cast<LoadSDNode>(N);
4387 SDOperand Chain = LD->getChain();
4388 SDOperand Ptr = LD->getBasePtr();
4390 // Try to infer better alignment information than the load already has.
4391 if (LD->isUnindexed()) {
4392 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4393 if (Align > LD->getAlignment())
4394 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
4395 Chain, Ptr, LD->getSrcValue(),
4396 LD->getSrcValueOffset(), LD->getMemoryVT(),
4397 LD->isVolatile(), Align);
4402 // If load is not volatile and there are no uses of the loaded value (and
4403 // the updated indexed value in case of indexed loads), change uses of the
4404 // chain value into uses of the chain input (i.e. delete the dead load).
4405 if (!LD->isVolatile()) {
4406 if (N->getValueType(1) == MVT::Other) {
4408 if (N->hasNUsesOfValue(0, 0)) {
4409 // It's not safe to use the two value CombineTo variant here. e.g.
4410 // v1, chain2 = load chain1, loc
4411 // v2, chain3 = load chain2, loc
4413 // Now we replace use of chain2 with chain1. This makes the second load
4414 // isomorphic to the one we are deleting, and thus makes this load live.
4415 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4416 DOUT << "\nWith chain: "; DEBUG(Chain.Val->dump(&DAG));
4418 WorkListRemover DeadNodes(*this);
4419 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Chain, &DeadNodes);
4420 if (N->use_empty()) {
4421 removeFromWorkList(N);
4424 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4428 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4429 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
4430 SDOperand Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
4431 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4432 DOUT << "\nWith: "; DEBUG(Undef.Val->dump(&DAG));
4433 DOUT << " and 2 other values\n";
4434 WorkListRemover DeadNodes(*this);
4435 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Undef, &DeadNodes);
4436 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
4437 DAG.getNode(ISD::UNDEF, N->getValueType(1)),
4439 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 2), Chain, &DeadNodes);
4440 removeFromWorkList(N);
4442 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4447 // If this load is directly stored, replace the load value with the stored
4449 // TODO: Handle store large -> read small portion.
4450 // TODO: Handle TRUNCSTORE/LOADEXT
4451 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
4452 !LD->isVolatile()) {
4453 if (ISD::isNON_TRUNCStore(Chain.Val)) {
4454 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4455 if (PrevST->getBasePtr() == Ptr &&
4456 PrevST->getValue().getValueType() == N->getValueType(0))
4457 return CombineTo(N, Chain.getOperand(1), Chain);
4462 // Walk up chain skipping non-aliasing memory nodes.
4463 SDOperand BetterChain = FindBetterChain(N, Chain);
4465 // If there is a better chain.
4466 if (Chain != BetterChain) {
4469 // Replace the chain to void dependency.
4470 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4471 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
4472 LD->getSrcValue(), LD->getSrcValueOffset(),
4473 LD->isVolatile(), LD->getAlignment());
4475 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
4476 LD->getValueType(0),
4477 BetterChain, Ptr, LD->getSrcValue(),
4478 LD->getSrcValueOffset(),
4481 LD->getAlignment());
4484 // Create token factor to keep old chain connected.
4485 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
4486 Chain, ReplLoad.getValue(1));
4488 // Replace uses with load result and token factor. Don't add users
4490 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4494 // Try transforming N to an indexed load.
4495 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4496 return SDOperand(N, 0);
4502 SDOperand DAGCombiner::visitSTORE(SDNode *N) {
4503 StoreSDNode *ST = cast<StoreSDNode>(N);
4504 SDOperand Chain = ST->getChain();
4505 SDOperand Value = ST->getValue();
4506 SDOperand Ptr = ST->getBasePtr();
4508 // Try to infer better alignment information than the store already has.
4509 if (ST->isUnindexed()) {
4510 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4511 if (Align > ST->getAlignment())
4512 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
4513 ST->getSrcValueOffset(), ST->getMemoryVT(),
4514 ST->isVolatile(), Align);
4518 // If this is a store of a bit convert, store the input value if the
4519 // resultant store does not need a higher alignment than the original.
4520 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
4521 ST->isUnindexed()) {
4522 unsigned Align = ST->getAlignment();
4523 MVT SVT = Value.getOperand(0).getValueType();
4524 unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
4525 getABITypeAlignment(SVT.getTypeForMVT());
4526 if (Align <= OrigAlign &&
4527 ((!AfterLegalize && !ST->isVolatile()) ||
4528 TLI.isOperationLegal(ISD::STORE, SVT)))
4529 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4530 ST->getSrcValueOffset(), ST->isVolatile(), Align);
4533 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
4534 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
4535 // NOTE: If the original store is volatile, this transform must not increase
4536 // the number of stores. For example, on x86-32 an f64 can be stored in one
4537 // processor operation but an i64 (which is not legal) requires two. So the
4538 // transform should not be done in this case.
4539 if (Value.getOpcode() != ISD::TargetConstantFP) {
4541 switch (CFP->getValueType(0).getSimpleVT()) {
4542 default: assert(0 && "Unknown FP type");
4543 case MVT::f80: // We don't do this for these yet.
4548 if ((!AfterLegalize && !ST->isVolatile()) ||
4549 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4550 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
4551 convertToAPInt().getZExtValue(), MVT::i32);
4552 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4553 ST->getSrcValueOffset(), ST->isVolatile(),
4554 ST->getAlignment());
4558 if ((!AfterLegalize && !ST->isVolatile()) ||
4559 TLI.isOperationLegal(ISD::STORE, MVT::i64)) {
4560 Tmp = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
4561 getZExtValue(), MVT::i64);
4562 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4563 ST->getSrcValueOffset(), ST->isVolatile(),
4564 ST->getAlignment());
4565 } else if (!ST->isVolatile() &&
4566 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4567 // Many FP stores are not made apparent until after legalize, e.g. for
4568 // argument passing. Since this is so common, custom legalize the
4569 // 64-bit integer store into two 32-bit stores.
4570 uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue();
4571 SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
4572 SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
4573 if (TLI.isBigEndian()) std::swap(Lo, Hi);
4575 int SVOffset = ST->getSrcValueOffset();
4576 unsigned Alignment = ST->getAlignment();
4577 bool isVolatile = ST->isVolatile();
4579 SDOperand St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4580 ST->getSrcValueOffset(),
4581 isVolatile, ST->getAlignment());
4582 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4583 DAG.getConstant(4, Ptr.getValueType()));
4585 Alignment = MinAlign(Alignment, 4U);
4586 SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4587 SVOffset, isVolatile, Alignment);
4588 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4596 // Walk up chain skipping non-aliasing memory nodes.
4597 SDOperand BetterChain = FindBetterChain(N, Chain);
4599 // If there is a better chain.
4600 if (Chain != BetterChain) {
4601 // Replace the chain to avoid dependency.
4602 SDOperand ReplStore;
4603 if (ST->isTruncatingStore()) {
4604 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
4605 ST->getSrcValue(),ST->getSrcValueOffset(),
4607 ST->isVolatile(), ST->getAlignment());
4609 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
4610 ST->getSrcValue(), ST->getSrcValueOffset(),
4611 ST->isVolatile(), ST->getAlignment());
4614 // Create token to keep both nodes around.
4616 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4618 // Don't add users to work list.
4619 return CombineTo(N, Token, false);
4623 // Try transforming N to an indexed store.
4624 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4625 return SDOperand(N, 0);
4627 // FIXME: is there such a thing as a truncating indexed store?
4628 if (ST->isTruncatingStore() && ST->isUnindexed() &&
4629 Value.getValueType().isInteger()) {
4630 // See if we can simplify the input to this truncstore with knowledge that
4631 // only the low bits are being used. For example:
4632 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
4634 GetDemandedBits(Value,
4635 APInt::getLowBitsSet(Value.getValueSizeInBits(),
4636 ST->getMemoryVT().getSizeInBits()));
4637 AddToWorkList(Value.Val);
4639 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
4640 ST->getSrcValueOffset(), ST->getMemoryVT(),
4641 ST->isVolatile(), ST->getAlignment());
4643 // Otherwise, see if we can simplify the operation with
4644 // SimplifyDemandedBits, which only works if the value has a single use.
4645 if (SimplifyDemandedBits(Value,
4646 APInt::getLowBitsSet(
4647 Value.getValueSizeInBits(),
4648 ST->getMemoryVT().getSizeInBits())))
4649 return SDOperand(N, 0);
4652 // If this is a load followed by a store to the same location, then the store
4654 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
4655 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
4656 ST->isUnindexed() && !ST->isVolatile() &&
4657 // There can't be any side effects between the load and store, such as
4659 Chain.reachesChainWithoutSideEffects(SDOperand(Ld, 1))) {
4660 // The store is dead, remove it.
4665 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
4666 // truncating store. We can do this even if this is already a truncstore.
4667 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
4668 && Value.Val->hasOneUse() && ST->isUnindexed() &&
4669 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
4670 ST->getMemoryVT())) {
4671 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4672 ST->getSrcValueOffset(), ST->getMemoryVT(),
4673 ST->isVolatile(), ST->getAlignment());
4679 SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4680 SDOperand InVec = N->getOperand(0);
4681 SDOperand InVal = N->getOperand(1);
4682 SDOperand EltNo = N->getOperand(2);
4684 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4685 // vector with the inserted element.
4686 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4687 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4688 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
4689 if (Elt < Ops.size())
4691 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4692 &Ops[0], Ops.size());
4698 SDOperand DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
4699 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
4700 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
4701 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
4703 // Perform only after legalization to ensure build_vector / vector_shuffle
4704 // optimizations have already been done.
4705 if (!AfterLegalize) return SDOperand();
4707 SDOperand InVec = N->getOperand(0);
4708 SDOperand EltNo = N->getOperand(1);
4710 if (isa<ConstantSDNode>(EltNo)) {
4711 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4712 bool NewLoad = false;
4713 MVT VT = InVec.getValueType();
4714 MVT EVT = VT.getVectorElementType();
4716 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
4717 MVT BCVT = InVec.getOperand(0).getValueType();
4718 if (!BCVT.isVector() || EVT.bitsGT(BCVT.getVectorElementType()))
4720 InVec = InVec.getOperand(0);
4721 EVT = BCVT.getVectorElementType();
4725 LoadSDNode *LN0 = NULL;
4726 if (ISD::isNormalLoad(InVec.Val))
4727 LN0 = cast<LoadSDNode>(InVec);
4728 else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4729 InVec.getOperand(0).getValueType() == EVT &&
4730 ISD::isNormalLoad(InVec.getOperand(0).Val)) {
4731 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4732 } else if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
4733 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
4735 // (load $addr+1*size)
4736 unsigned Idx = cast<ConstantSDNode>(InVec.getOperand(2).
4737 getOperand(Elt))->getValue();
4738 unsigned NumElems = InVec.getOperand(2).getNumOperands();
4739 InVec = (Idx < NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
4740 if (InVec.getOpcode() == ISD::BIT_CONVERT)
4741 InVec = InVec.getOperand(0);
4742 if (ISD::isNormalLoad(InVec.Val)) {
4743 LN0 = cast<LoadSDNode>(InVec);
4744 Elt = (Idx < NumElems) ? Idx : Idx - NumElems;
4747 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
4750 unsigned Align = LN0->getAlignment();
4752 // Check the resultant load doesn't need a higher alignment than the
4754 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
4755 getABITypeAlignment(LVT.getTypeForMVT());
4756 if (NewAlign > Align || !TLI.isOperationLegal(ISD::LOAD, LVT))
4761 SDOperand NewPtr = LN0->getBasePtr();
4763 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
4764 MVT PtrType = NewPtr.getValueType();
4765 if (TLI.isBigEndian())
4766 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
4767 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
4768 DAG.getConstant(PtrOff, PtrType));
4770 return DAG.getLoad(LVT, LN0->getChain(), NewPtr,
4771 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4772 LN0->isVolatile(), Align);
4778 SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4779 unsigned NumInScalars = N->getNumOperands();
4780 MVT VT = N->getValueType(0);
4781 unsigned NumElts = VT.getVectorNumElements();
4782 MVT EltType = VT.getVectorElementType();
4784 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4785 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4786 // at most two distinct vectors, turn this into a shuffle node.
4787 SDOperand VecIn1, VecIn2;
4788 for (unsigned i = 0; i != NumInScalars; ++i) {
4789 // Ignore undef inputs.
4790 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4792 // If this input is something other than a EXTRACT_VECTOR_ELT with a
4793 // constant index, bail out.
4794 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4795 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4796 VecIn1 = VecIn2 = SDOperand(0, 0);
4800 // If the input vector type disagrees with the result of the build_vector,
4801 // we can't make a shuffle.
4802 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
4803 if (ExtractedFromVec.getValueType() != VT) {
4804 VecIn1 = VecIn2 = SDOperand(0, 0);
4808 // Otherwise, remember this. We allow up to two distinct input vectors.
4809 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
4812 if (VecIn1.Val == 0) {
4813 VecIn1 = ExtractedFromVec;
4814 } else if (VecIn2.Val == 0) {
4815 VecIn2 = ExtractedFromVec;
4818 VecIn1 = VecIn2 = SDOperand(0, 0);
4823 // If everything is good, we can make a shuffle operation.
4825 SmallVector<SDOperand, 8> BuildVecIndices;
4826 for (unsigned i = 0; i != NumInScalars; ++i) {
4827 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
4828 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
4832 SDOperand Extract = N->getOperand(i);
4834 // If extracting from the first vector, just use the index directly.
4835 if (Extract.getOperand(0) == VecIn1) {
4836 BuildVecIndices.push_back(Extract.getOperand(1));
4840 // Otherwise, use InIdx + VecSize
4841 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
4842 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
4845 // Add count and size info.
4846 MVT BuildVecVT = MVT::getVectorVT(TLI.getPointerTy(), NumElts);
4848 // Return the new VECTOR_SHUFFLE node.
4854 // Use an undef build_vector as input for the second operand.
4855 std::vector<SDOperand> UnOps(NumInScalars,
4856 DAG.getNode(ISD::UNDEF,
4858 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
4859 &UnOps[0], UnOps.size());
4860 AddToWorkList(Ops[1].Val);
4862 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
4863 &BuildVecIndices[0], BuildVecIndices.size());
4864 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
4870 SDOperand DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
4871 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
4872 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
4873 // inputs come from at most two distinct vectors, turn this into a shuffle
4876 // If we only have one input vector, we don't need to do any concatenation.
4877 if (N->getNumOperands() == 1) {
4878 return N->getOperand(0);
4884 SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
4885 SDOperand ShufMask = N->getOperand(2);
4886 unsigned NumElts = ShufMask.getNumOperands();
4888 // If the shuffle mask is an identity operation on the LHS, return the LHS.
4889 bool isIdentity = true;
4890 for (unsigned i = 0; i != NumElts; ++i) {
4891 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4892 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
4897 if (isIdentity) return N->getOperand(0);
4899 // If the shuffle mask is an identity operation on the RHS, return the RHS.
4901 for (unsigned i = 0; i != NumElts; ++i) {
4902 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4903 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
4908 if (isIdentity) return N->getOperand(1);
4910 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
4912 bool isUnary = true;
4913 bool isSplat = true;
4915 unsigned BaseIdx = 0;
4916 for (unsigned i = 0; i != NumElts; ++i)
4917 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
4918 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
4919 int V = (Idx < NumElts) ? 0 : 1;
4933 SDOperand N0 = N->getOperand(0);
4934 SDOperand N1 = N->getOperand(1);
4935 // Normalize unary shuffle so the RHS is undef.
4936 if (isUnary && VecNum == 1)
4939 // If it is a splat, check if the argument vector is a build_vector with
4940 // all scalar elements the same.
4944 // If this is a bit convert that changes the element type of the vector but
4945 // not the number of vector elements, look through it. Be careful not to
4946 // look though conversions that change things like v4f32 to v2f64.
4947 if (V->getOpcode() == ISD::BIT_CONVERT) {
4948 SDOperand ConvInput = V->getOperand(0);
4949 if (ConvInput.getValueType().getVectorNumElements() == NumElts)
4953 if (V->getOpcode() == ISD::BUILD_VECTOR) {
4954 unsigned NumElems = V->getNumOperands();
4955 if (NumElems > BaseIdx) {
4957 bool AllSame = true;
4958 for (unsigned i = 0; i != NumElems; ++i) {
4959 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
4960 Base = V->getOperand(i);
4964 // Splat of <u, u, u, u>, return <u, u, u, u>
4967 for (unsigned i = 0; i != NumElems; ++i) {
4968 if (V->getOperand(i) != Base) {
4973 // Splat of <x, x, x, x>, return <x, x, x, x>
4980 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
4982 if (isUnary || N0 == N1) {
4983 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
4985 SmallVector<SDOperand, 8> MappedOps;
4986 for (unsigned i = 0; i != NumElts; ++i) {
4987 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
4988 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
4989 MappedOps.push_back(ShufMask.getOperand(i));
4992 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
4993 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
4996 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
4997 &MappedOps[0], MappedOps.size());
4998 AddToWorkList(ShufMask.Val);
4999 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
5001 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
5008 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
5009 /// an AND to a vector_shuffle with the destination vector and a zero vector.
5010 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
5011 /// vector_shuffle V, Zero, <0, 4, 2, 4>
5012 SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
5013 SDOperand LHS = N->getOperand(0);
5014 SDOperand RHS = N->getOperand(1);
5015 if (N->getOpcode() == ISD::AND) {
5016 if (RHS.getOpcode() == ISD::BIT_CONVERT)
5017 RHS = RHS.getOperand(0);
5018 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
5019 std::vector<SDOperand> IdxOps;
5020 unsigned NumOps = RHS.getNumOperands();
5021 unsigned NumElts = NumOps;
5022 MVT EVT = RHS.getValueType().getVectorElementType();
5023 for (unsigned i = 0; i != NumElts; ++i) {
5024 SDOperand Elt = RHS.getOperand(i);
5025 if (!isa<ConstantSDNode>(Elt))
5027 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
5028 IdxOps.push_back(DAG.getConstant(i, EVT));
5029 else if (cast<ConstantSDNode>(Elt)->isNullValue())
5030 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
5035 // Let's see if the target supports this vector_shuffle.
5036 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
5039 // Return the new VECTOR_SHUFFLE node.
5040 MVT VT = MVT::getVectorVT(EVT, NumElts);
5041 std::vector<SDOperand> Ops;
5042 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
5044 AddToWorkList(LHS.Val);
5045 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
5046 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5047 &ZeroOps[0], ZeroOps.size()));
5048 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5049 &IdxOps[0], IdxOps.size()));
5050 SDOperand Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
5051 &Ops[0], Ops.size());
5052 if (VT != LHS.getValueType()) {
5053 Result = DAG.getNode(ISD::BIT_CONVERT, LHS.getValueType(), Result);
5061 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
5062 SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
5063 // After legalize, the target may be depending on adds and other
5064 // binary ops to provide legal ways to construct constants or other
5065 // things. Simplifying them may result in a loss of legality.
5066 if (AfterLegalize) return SDOperand();
5068 MVT VT = N->getValueType(0);
5069 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
5071 MVT EltType = VT.getVectorElementType();
5072 SDOperand LHS = N->getOperand(0);
5073 SDOperand RHS = N->getOperand(1);
5074 SDOperand Shuffle = XformToShuffleWithZero(N);
5075 if (Shuffle.Val) return Shuffle;
5077 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
5079 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
5080 RHS.getOpcode() == ISD::BUILD_VECTOR) {
5081 SmallVector<SDOperand, 8> Ops;
5082 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
5083 SDOperand LHSOp = LHS.getOperand(i);
5084 SDOperand RHSOp = RHS.getOperand(i);
5085 // If these two elements can't be folded, bail out.
5086 if ((LHSOp.getOpcode() != ISD::UNDEF &&
5087 LHSOp.getOpcode() != ISD::Constant &&
5088 LHSOp.getOpcode() != ISD::ConstantFP) ||
5089 (RHSOp.getOpcode() != ISD::UNDEF &&
5090 RHSOp.getOpcode() != ISD::Constant &&
5091 RHSOp.getOpcode() != ISD::ConstantFP))
5093 // Can't fold divide by zero.
5094 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
5095 N->getOpcode() == ISD::FDIV) {
5096 if ((RHSOp.getOpcode() == ISD::Constant &&
5097 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
5098 (RHSOp.getOpcode() == ISD::ConstantFP &&
5099 cast<ConstantFPSDNode>(RHSOp.Val)->getValueAPF().isZero()))
5102 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
5103 AddToWorkList(Ops.back().Val);
5104 assert((Ops.back().getOpcode() == ISD::UNDEF ||
5105 Ops.back().getOpcode() == ISD::Constant ||
5106 Ops.back().getOpcode() == ISD::ConstantFP) &&
5107 "Scalar binop didn't fold!");
5110 if (Ops.size() == LHS.getNumOperands()) {
5111 MVT VT = LHS.getValueType();
5112 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
5119 SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
5120 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
5122 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
5123 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5124 // If we got a simplified select_cc node back from SimplifySelectCC, then
5125 // break it down into a new SETCC node, and a new SELECT node, and then return
5126 // the SELECT node, since we were called with a SELECT node.
5128 // Check to see if we got a select_cc back (to turn into setcc/select).
5129 // Otherwise, just return whatever node we got back, like fabs.
5130 if (SCC.getOpcode() == ISD::SELECT_CC) {
5131 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
5132 SCC.getOperand(0), SCC.getOperand(1),
5134 AddToWorkList(SETCC.Val);
5135 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
5136 SCC.getOperand(3), SETCC);
5143 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5144 /// are the two values being selected between, see if we can simplify the
5145 /// select. Callers of this should assume that TheSelect is deleted if this
5146 /// returns true. As such, they should return the appropriate thing (e.g. the
5147 /// node) back to the top-level of the DAG combiner loop to avoid it being
5150 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
5153 // If this is a select from two identical things, try to pull the operation
5154 // through the select.
5155 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5156 // If this is a load and the token chain is identical, replace the select
5157 // of two loads with a load through a select of the address to load from.
5158 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5159 // constants have been dropped into the constant pool.
5160 if (LHS.getOpcode() == ISD::LOAD &&
5161 // Do not let this transformation reduce the number of volatile loads.
5162 !cast<LoadSDNode>(LHS)->isVolatile() &&
5163 !cast<LoadSDNode>(RHS)->isVolatile() &&
5164 // Token chains must be identical.
5165 LHS.getOperand(0) == RHS.getOperand(0)) {
5166 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5167 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5169 // If this is an EXTLOAD, the VT's must match.
5170 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
5171 // FIXME: this conflates two src values, discarding one. This is not
5172 // the right thing to do, but nothing uses srcvalues now. When they do,
5173 // turn SrcValue into a list of locations.
5175 if (TheSelect->getOpcode() == ISD::SELECT) {
5176 // Check that the condition doesn't reach either load. If so, folding
5177 // this will induce a cycle into the DAG.
5178 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5179 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val)) {
5180 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
5181 TheSelect->getOperand(0), LLD->getBasePtr(),
5185 // Check that the condition doesn't reach either load. If so, folding
5186 // this will induce a cycle into the DAG.
5187 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5188 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5189 !LLD->isPredecessorOf(TheSelect->getOperand(1).Val) &&
5190 !RLD->isPredecessorOf(TheSelect->getOperand(1).Val)) {
5191 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
5192 TheSelect->getOperand(0),
5193 TheSelect->getOperand(1),
5194 LLD->getBasePtr(), RLD->getBasePtr(),
5195 TheSelect->getOperand(4));
5201 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
5202 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
5203 Addr,LLD->getSrcValue(),
5204 LLD->getSrcValueOffset(),
5206 LLD->getAlignment());
5208 Load = DAG.getExtLoad(LLD->getExtensionType(),
5209 TheSelect->getValueType(0),
5210 LLD->getChain(), Addr, LLD->getSrcValue(),
5211 LLD->getSrcValueOffset(),
5214 LLD->getAlignment());
5216 // Users of the select now use the result of the load.
5217 CombineTo(TheSelect, Load);
5219 // Users of the old loads now use the new load's chain. We know the
5220 // old-load value is dead now.
5221 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
5222 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
5232 SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
5233 SDOperand N2, SDOperand N3,
5234 ISD::CondCode CC, bool NotExtCompare) {
5236 MVT VT = N2.getValueType();
5237 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
5238 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
5239 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
5241 // Determine if the condition we're dealing with is constant
5242 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
5243 if (SCC.Val) AddToWorkList(SCC.Val);
5244 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
5246 // fold select_cc true, x, y -> x
5247 if (SCCC && !SCCC->isNullValue())
5249 // fold select_cc false, x, y -> y
5250 if (SCCC && SCCC->isNullValue())
5253 // Check to see if we can simplify the select into an fabs node
5254 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5255 // Allow either -0.0 or 0.0
5256 if (CFP->getValueAPF().isZero()) {
5257 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5258 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5259 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5260 N2 == N3.getOperand(0))
5261 return DAG.getNode(ISD::FABS, VT, N0);
5263 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5264 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5265 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5266 N2.getOperand(0) == N3)
5267 return DAG.getNode(ISD::FABS, VT, N3);
5271 // Check to see if we can perform the "gzip trick", transforming
5272 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
5273 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5274 N0.getValueType().isInteger() &&
5275 N2.getValueType().isInteger() &&
5276 (N1C->isNullValue() || // (a < 0) ? b : 0
5277 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
5278 MVT XType = N0.getValueType();
5279 MVT AType = N2.getValueType();
5280 if (XType.bitsGE(AType)) {
5281 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5282 // single-bit constant.
5283 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
5284 unsigned ShCtV = N2C->getAPIntValue().logBase2();
5285 ShCtV = XType.getSizeInBits()-ShCtV-1;
5286 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
5287 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
5288 AddToWorkList(Shift.Val);
5289 if (XType.bitsGT(AType)) {
5290 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5291 AddToWorkList(Shift.Val);
5293 return DAG.getNode(ISD::AND, AType, Shift, N2);
5295 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5296 DAG.getConstant(XType.getSizeInBits()-1,
5297 TLI.getShiftAmountTy()));
5298 AddToWorkList(Shift.Val);
5299 if (XType.bitsGT(AType)) {
5300 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5301 AddToWorkList(Shift.Val);
5303 return DAG.getNode(ISD::AND, AType, Shift, N2);
5307 // fold select C, 16, 0 -> shl C, 4
5308 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
5309 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
5311 // If the caller doesn't want us to simplify this into a zext of a compare,
5313 if (NotExtCompare && N2C->getAPIntValue() == 1)
5316 // Get a SetCC of the condition
5317 // FIXME: Should probably make sure that setcc is legal if we ever have a
5318 // target where it isn't.
5319 SDOperand Temp, SCC;
5320 // cast from setcc result type to select result type
5321 if (AfterLegalize) {
5322 SCC = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5323 if (N2.getValueType().bitsLT(SCC.getValueType()))
5324 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
5326 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5328 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
5329 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5331 AddToWorkList(SCC.Val);
5332 AddToWorkList(Temp.Val);
5334 if (N2C->getAPIntValue() == 1)
5336 // shl setcc result by log2 n2c
5337 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
5338 DAG.getConstant(N2C->getAPIntValue().logBase2(),
5339 TLI.getShiftAmountTy()));
5342 // Check to see if this is the equivalent of setcc
5343 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5344 // otherwise, go ahead with the folds.
5345 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
5346 MVT XType = N0.getValueType();
5347 if (!AfterLegalize ||
5348 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(N0))) {
5349 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5350 if (Res.getValueType() != VT)
5351 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
5355 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
5356 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5358 TLI.isOperationLegal(ISD::CTLZ, XType))) {
5359 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
5360 return DAG.getNode(ISD::SRL, XType, Ctlz,
5361 DAG.getConstant(Log2_32(XType.getSizeInBits()),
5362 TLI.getShiftAmountTy()));
5364 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
5365 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5366 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
5368 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
5369 DAG.getConstant(~0ULL, XType));
5370 return DAG.getNode(ISD::SRL, XType,
5371 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
5372 DAG.getConstant(XType.getSizeInBits()-1,
5373 TLI.getShiftAmountTy()));
5375 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
5376 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5377 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
5378 DAG.getConstant(XType.getSizeInBits()-1,
5379 TLI.getShiftAmountTy()));
5380 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
5384 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5385 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5386 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5387 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5388 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
5389 MVT XType = N0.getValueType();
5390 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5391 DAG.getConstant(XType.getSizeInBits()-1,
5392 TLI.getShiftAmountTy()));
5393 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5394 AddToWorkList(Shift.Val);
5395 AddToWorkList(Add.Val);
5396 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5398 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5399 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5400 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5401 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5402 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5403 MVT XType = N0.getValueType();
5404 if (SubC->isNullValue() && XType.isInteger()) {
5405 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5406 DAG.getConstant(XType.getSizeInBits()-1,
5407 TLI.getShiftAmountTy()));
5408 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5409 AddToWorkList(Shift.Val);
5410 AddToWorkList(Add.Val);
5411 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5419 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
5420 SDOperand DAGCombiner::SimplifySetCC(MVT VT, SDOperand N0,
5421 SDOperand N1, ISD::CondCode Cond,
5422 bool foldBooleans) {
5423 TargetLowering::DAGCombinerInfo
5424 DagCombineInfo(DAG, !AfterLegalize, false, this);
5425 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
5428 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
5429 /// return a DAG expression to select that will generate the same value by
5430 /// multiplying by a magic number. See:
5431 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5432 SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
5433 std::vector<SDNode*> Built;
5434 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
5436 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5442 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
5443 /// return a DAG expression to select that will generate the same value by
5444 /// multiplying by a magic number. See:
5445 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5446 SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
5447 std::vector<SDNode*> Built;
5448 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
5450 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5456 /// FindBaseOffset - Return true if base is known not to alias with anything
5457 /// but itself. Provides base object and offset as results.
5458 static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
5459 // Assume it is a primitive operation.
5460 Base = Ptr; Offset = 0;
5462 // If it's an adding a simple constant then integrate the offset.
5463 if (Base.getOpcode() == ISD::ADD) {
5464 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
5465 Base = Base.getOperand(0);
5466 Offset += C->getValue();
5470 // If it's any of the following then it can't alias with anything but itself.
5471 return isa<FrameIndexSDNode>(Base) ||
5472 isa<ConstantPoolSDNode>(Base) ||
5473 isa<GlobalAddressSDNode>(Base);
5476 /// isAlias - Return true if there is any possibility that the two addresses
5478 bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
5479 const Value *SrcValue1, int SrcValueOffset1,
5480 SDOperand Ptr2, int64_t Size2,
5481 const Value *SrcValue2, int SrcValueOffset2)
5483 // If they are the same then they must be aliases.
5484 if (Ptr1 == Ptr2) return true;
5486 // Gather base node and offset information.
5487 SDOperand Base1, Base2;
5488 int64_t Offset1, Offset2;
5489 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
5490 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
5492 // If they have a same base address then...
5493 if (Base1 == Base2) {
5494 // Check to see if the addresses overlap.
5495 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
5498 // If we know both bases then they can't alias.
5499 if (KnownBase1 && KnownBase2) return false;
5501 if (CombinerGlobalAA) {
5502 // Use alias analysis information.
5503 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
5504 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
5505 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
5506 AliasAnalysis::AliasResult AAResult =
5507 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
5508 if (AAResult == AliasAnalysis::NoAlias)
5512 // Otherwise we have to assume they alias.
5516 /// FindAliasInfo - Extracts the relevant alias information from the memory
5517 /// node. Returns true if the operand was a load.
5518 bool DAGCombiner::FindAliasInfo(SDNode *N,
5519 SDOperand &Ptr, int64_t &Size,
5520 const Value *&SrcValue, int &SrcValueOffset) {
5521 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5522 Ptr = LD->getBasePtr();
5523 Size = LD->getMemoryVT().getSizeInBits() >> 3;
5524 SrcValue = LD->getSrcValue();
5525 SrcValueOffset = LD->getSrcValueOffset();
5527 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5528 Ptr = ST->getBasePtr();
5529 Size = ST->getMemoryVT().getSizeInBits() >> 3;
5530 SrcValue = ST->getSrcValue();
5531 SrcValueOffset = ST->getSrcValueOffset();
5533 assert(0 && "FindAliasInfo expected a memory operand");
5539 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
5540 /// looking for aliasing nodes and adding them to the Aliases vector.
5541 void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
5542 SmallVector<SDOperand, 8> &Aliases) {
5543 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
5544 std::set<SDNode *> Visited; // Visited node set.
5546 // Get alias information for node.
5549 const Value *SrcValue;
5551 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
5554 Chains.push_back(OriginalChain);
5556 // Look at each chain and determine if it is an alias. If so, add it to the
5557 // aliases list. If not, then continue up the chain looking for the next
5559 while (!Chains.empty()) {
5560 SDOperand Chain = Chains.back();
5563 // Don't bother if we've been before.
5564 if (Visited.find(Chain.Val) != Visited.end()) continue;
5565 Visited.insert(Chain.Val);
5567 switch (Chain.getOpcode()) {
5568 case ISD::EntryToken:
5569 // Entry token is ideal chain operand, but handled in FindBetterChain.
5574 // Get alias information for Chain.
5577 const Value *OpSrcValue;
5578 int OpSrcValueOffset;
5579 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
5580 OpSrcValue, OpSrcValueOffset);
5582 // If chain is alias then stop here.
5583 if (!(IsLoad && IsOpLoad) &&
5584 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
5585 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
5586 Aliases.push_back(Chain);
5588 // Look further up the chain.
5589 Chains.push_back(Chain.getOperand(0));
5590 // Clean up old chain.
5591 AddToWorkList(Chain.Val);
5596 case ISD::TokenFactor:
5597 // We have to check each of the operands of the token factor, so we queue
5598 // then up. Adding the operands to the queue (stack) in reverse order
5599 // maintains the original order and increases the likelihood that getNode
5600 // will find a matching token factor (CSE.)
5601 for (unsigned n = Chain.getNumOperands(); n;)
5602 Chains.push_back(Chain.getOperand(--n));
5603 // Eliminate the token factor if we can.
5604 AddToWorkList(Chain.Val);
5608 // For all other instructions we will just have to take what we can get.
5609 Aliases.push_back(Chain);
5615 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
5616 /// for a better chain (aliasing node.)
5617 SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
5618 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
5620 // Accumulate all the aliases to this node.
5621 GatherAllAliases(N, OldChain, Aliases);
5623 if (Aliases.size() == 0) {
5624 // If no operands then chain to entry token.
5625 return DAG.getEntryNode();
5626 } else if (Aliases.size() == 1) {
5627 // If a single operand then chain to it. We don't need to revisit it.
5631 // Construct a custom tailored token factor.
5632 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5633 &Aliases[0], Aliases.size());
5635 // Make sure the old chain gets cleaned up.
5636 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
5641 // SelectionDAG::Combine - This is the entry point for the file.
5643 void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
5644 if (!RunningAfterLegalize && ViewDAGCombine1)
5646 if (RunningAfterLegalize && ViewDAGCombine2)
5648 /// run - This is the main entry point to this class.
5650 DAGCombiner(*this, AA).Run(RunningAfterLegalize);