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 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/PseudoSourceValue.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetFrameInfo.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
42 STATISTIC(NodesCombined , "Number of dag nodes combined");
43 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
44 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
45 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 CombinerAA("combiner-alias-analysis", cl::Hidden,
50 cl::desc("Turn on alias analysis during testing"));
53 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
54 cl::desc("Include global information in alias analysis"));
56 //------------------------------ DAGCombiner ---------------------------------//
60 const TargetLowering &TLI;
62 CodeGenOpt::Level OptLevel;
66 // Worklist of all of the nodes that need to be simplified.
67 std::vector<SDNode*> WorkList;
69 // AA - Used for DAG load/store alias analysis.
72 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
76 void AddUsersToWorkList(SDNode *N) {
77 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
82 /// visit - call the node-specific routine that knows how to fold each
83 /// particular type of node.
84 SDValue visit(SDNode *N);
87 /// AddToWorkList - Add to the work list making sure it's instance is at the
88 /// the back (next to be processed.)
89 void AddToWorkList(SDNode *N) {
90 removeFromWorkList(N);
91 WorkList.push_back(N);
94 /// removeFromWorkList - remove all instances of N from the worklist.
96 void removeFromWorkList(SDNode *N) {
97 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
101 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
104 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
105 return CombineTo(N, &Res, 1, AddTo);
108 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
110 SDValue To[] = { Res0, Res1 };
111 return CombineTo(N, To, 2, AddTo);
114 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
118 /// SimplifyDemandedBits - Check the specified integer node value to see if
119 /// it can be simplified or if things it uses can be simplified by bit
120 /// propagation. If so, return true.
121 bool SimplifyDemandedBits(SDValue Op) {
122 APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
123 return SimplifyDemandedBits(Op, Demanded);
126 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
128 bool CombineToPreIndexedLoadStore(SDNode *N);
129 bool CombineToPostIndexedLoadStore(SDNode *N);
132 /// combine - call the node-specific routine that knows how to fold each
133 /// particular type of node. If that doesn't do anything, try the
134 /// target-specific DAG combines.
135 SDValue combine(SDNode *N);
137 // Visitation implementation - Implement dag node combining for different
138 // node types. The semantics are as follows:
140 // SDValue.getNode() == 0 - No change was made
141 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
142 // otherwise - N should be replaced by the returned Operand.
144 SDValue visitTokenFactor(SDNode *N);
145 SDValue visitMERGE_VALUES(SDNode *N);
146 SDValue visitADD(SDNode *N);
147 SDValue visitSUB(SDNode *N);
148 SDValue visitADDC(SDNode *N);
149 SDValue visitADDE(SDNode *N);
150 SDValue visitMUL(SDNode *N);
151 SDValue visitSDIV(SDNode *N);
152 SDValue visitUDIV(SDNode *N);
153 SDValue visitSREM(SDNode *N);
154 SDValue visitUREM(SDNode *N);
155 SDValue visitMULHU(SDNode *N);
156 SDValue visitMULHS(SDNode *N);
157 SDValue visitSMUL_LOHI(SDNode *N);
158 SDValue visitUMUL_LOHI(SDNode *N);
159 SDValue visitSDIVREM(SDNode *N);
160 SDValue visitUDIVREM(SDNode *N);
161 SDValue visitAND(SDNode *N);
162 SDValue visitOR(SDNode *N);
163 SDValue visitXOR(SDNode *N);
164 SDValue SimplifyVBinOp(SDNode *N);
165 SDValue visitSHL(SDNode *N);
166 SDValue visitSRA(SDNode *N);
167 SDValue visitSRL(SDNode *N);
168 SDValue visitCTLZ(SDNode *N);
169 SDValue visitCTTZ(SDNode *N);
170 SDValue visitCTPOP(SDNode *N);
171 SDValue visitSELECT(SDNode *N);
172 SDValue visitSELECT_CC(SDNode *N);
173 SDValue visitSETCC(SDNode *N);
174 SDValue visitSIGN_EXTEND(SDNode *N);
175 SDValue visitZERO_EXTEND(SDNode *N);
176 SDValue visitANY_EXTEND(SDNode *N);
177 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
178 SDValue visitTRUNCATE(SDNode *N);
179 SDValue visitBIT_CONVERT(SDNode *N);
180 SDValue visitBUILD_PAIR(SDNode *N);
181 SDValue visitFADD(SDNode *N);
182 SDValue visitFSUB(SDNode *N);
183 SDValue visitFMUL(SDNode *N);
184 SDValue visitFDIV(SDNode *N);
185 SDValue visitFREM(SDNode *N);
186 SDValue visitFCOPYSIGN(SDNode *N);
187 SDValue visitSINT_TO_FP(SDNode *N);
188 SDValue visitUINT_TO_FP(SDNode *N);
189 SDValue visitFP_TO_SINT(SDNode *N);
190 SDValue visitFP_TO_UINT(SDNode *N);
191 SDValue visitFP_ROUND(SDNode *N);
192 SDValue visitFP_ROUND_INREG(SDNode *N);
193 SDValue visitFP_EXTEND(SDNode *N);
194 SDValue visitFNEG(SDNode *N);
195 SDValue visitFABS(SDNode *N);
196 SDValue visitBRCOND(SDNode *N);
197 SDValue visitBR_CC(SDNode *N);
198 SDValue visitLOAD(SDNode *N);
199 SDValue visitSTORE(SDNode *N);
200 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
201 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
202 SDValue visitBUILD_VECTOR(SDNode *N);
203 SDValue visitCONCAT_VECTORS(SDNode *N);
204 SDValue visitVECTOR_SHUFFLE(SDNode *N);
206 SDValue XformToShuffleWithZero(SDNode *N);
207 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
209 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
211 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
212 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
213 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
214 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
215 SDValue N3, ISD::CondCode CC,
216 bool NotExtCompare = false);
217 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
218 DebugLoc DL, bool foldBooleans = true);
219 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
221 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
222 SDValue ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, EVT);
223 SDValue BuildSDIV(SDNode *N);
224 SDValue BuildUDIV(SDNode *N);
225 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
226 SDValue ReduceLoadWidth(SDNode *N);
227 SDValue ReduceLoadOpStoreWidth(SDNode *N);
229 SDValue GetDemandedBits(SDValue 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, SDValue OriginalChain,
234 SmallVector<SDValue, 8> &Aliases);
236 /// isAlias - Return true if there is any possibility that the two addresses
238 bool isAlias(SDValue Ptr1, int64_t Size1,
239 const Value *SrcValue1, int SrcValueOffset1,
240 unsigned SrcValueAlign1,
241 SDValue Ptr2, int64_t Size2,
242 const Value *SrcValue2, int SrcValueOffset2,
243 unsigned SrcValueAlign2) const;
245 /// FindAliasInfo - Extracts the relevant alias information from the memory
246 /// node. Returns true if the operand was a load.
247 bool FindAliasInfo(SDNode *N,
248 SDValue &Ptr, int64_t &Size,
249 const Value *&SrcValue, int &SrcValueOffset,
250 unsigned &SrcValueAlignment) const;
252 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
253 /// looking for a better chain (aliasing node.)
254 SDValue FindBetterChain(SDNode *N, SDValue Chain);
256 /// getShiftAmountTy - Returns a type large enough to hold any valid
257 /// shift amount - before type legalization these can be huge.
258 EVT getShiftAmountTy() {
259 return LegalTypes ? TLI.getShiftAmountTy() : TLI.getPointerTy();
263 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
265 TLI(D.getTargetLoweringInfo()),
268 LegalOperations(false),
272 /// Run - runs the dag combiner on all nodes in the work list
273 void Run(CombineLevel AtLevel);
279 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
280 /// nodes from the worklist.
281 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
284 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
286 virtual void NodeDeleted(SDNode *N, SDNode *E) {
287 DC.removeFromWorkList(N);
290 virtual void NodeUpdated(SDNode *N) {
296 //===----------------------------------------------------------------------===//
297 // TargetLowering::DAGCombinerInfo implementation
298 //===----------------------------------------------------------------------===//
300 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
301 ((DAGCombiner*)DC)->AddToWorkList(N);
304 SDValue TargetLowering::DAGCombinerInfo::
305 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
306 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
309 SDValue TargetLowering::DAGCombinerInfo::
310 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
311 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
315 SDValue TargetLowering::DAGCombinerInfo::
316 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
317 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
320 void TargetLowering::DAGCombinerInfo::
321 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
322 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
325 //===----------------------------------------------------------------------===//
327 //===----------------------------------------------------------------------===//
329 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
330 /// specified expression for the same cost as the expression itself, or 2 if we
331 /// can compute the negated form more cheaply than the expression itself.
332 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
333 unsigned Depth = 0) {
334 // No compile time optimizations on this type.
335 if (Op.getValueType() == MVT::ppcf128)
338 // fneg is removable even if it has multiple uses.
339 if (Op.getOpcode() == ISD::FNEG) return 2;
341 // Don't allow anything with multiple uses.
342 if (!Op.hasOneUse()) return 0;
344 // Don't recurse exponentially.
345 if (Depth > 6) return 0;
347 switch (Op.getOpcode()) {
348 default: return false;
349 case ISD::ConstantFP:
350 // Don't invert constant FP values after legalize. The negated constant
351 // isn't necessarily legal.
352 return LegalOperations ? 0 : 1;
354 // FIXME: determine better conditions for this xform.
355 if (!UnsafeFPMath) return 0;
357 // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
358 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
360 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
361 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
363 // We can't turn -(A-B) into B-A when we honor signed zeros.
364 if (!UnsafeFPMath) return 0;
366 // fold (fneg (fsub A, B)) -> (fsub B, A)
371 if (HonorSignDependentRoundingFPMath()) return 0;
373 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
374 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
377 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
382 return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
386 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
387 /// returns the newly negated expression.
388 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
389 bool LegalOperations, unsigned Depth = 0) {
390 // fneg is removable even if it has multiple uses.
391 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
393 // Don't allow anything with multiple uses.
394 assert(Op.hasOneUse() && "Unknown reuse!");
396 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
397 switch (Op.getOpcode()) {
398 default: llvm_unreachable("Unknown code");
399 case ISD::ConstantFP: {
400 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
402 return DAG.getConstantFP(V, Op.getValueType());
405 // FIXME: determine better conditions for this xform.
406 assert(UnsafeFPMath);
408 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
409 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
410 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
411 GetNegatedExpression(Op.getOperand(0), DAG,
412 LegalOperations, Depth+1),
414 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
415 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
416 GetNegatedExpression(Op.getOperand(1), DAG,
417 LegalOperations, Depth+1),
420 // We can't turn -(A-B) into B-A when we honor signed zeros.
421 assert(UnsafeFPMath);
423 // fold (fneg (fsub 0, B)) -> B
424 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
425 if (N0CFP->getValueAPF().isZero())
426 return Op.getOperand(1);
428 // fold (fneg (fsub A, B)) -> (fsub B, A)
429 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
430 Op.getOperand(1), Op.getOperand(0));
434 assert(!HonorSignDependentRoundingFPMath());
436 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
437 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
438 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
439 GetNegatedExpression(Op.getOperand(0), DAG,
440 LegalOperations, Depth+1),
443 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
444 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
446 GetNegatedExpression(Op.getOperand(1), DAG,
447 LegalOperations, Depth+1));
451 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
452 GetNegatedExpression(Op.getOperand(0), DAG,
453 LegalOperations, Depth+1));
455 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
456 GetNegatedExpression(Op.getOperand(0), DAG,
457 LegalOperations, Depth+1),
463 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
464 // that selects between the values 1 and 0, making it equivalent to a setcc.
465 // Also, set the incoming LHS, RHS, and CC references to the appropriate
466 // nodes based on the type of node we are checking. This simplifies life a
467 // bit for the callers.
468 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
470 if (N.getOpcode() == ISD::SETCC) {
471 LHS = N.getOperand(0);
472 RHS = N.getOperand(1);
473 CC = N.getOperand(2);
476 if (N.getOpcode() == ISD::SELECT_CC &&
477 N.getOperand(2).getOpcode() == ISD::Constant &&
478 N.getOperand(3).getOpcode() == ISD::Constant &&
479 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
480 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
481 LHS = N.getOperand(0);
482 RHS = N.getOperand(1);
483 CC = N.getOperand(4);
489 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
490 // one use. If this is true, it allows the users to invert the operation for
491 // free when it is profitable to do so.
492 static bool isOneUseSetCC(SDValue N) {
494 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
499 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
500 SDValue N0, SDValue N1) {
501 EVT VT = N0.getValueType();
502 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
503 if (isa<ConstantSDNode>(N1)) {
504 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
506 DAG.FoldConstantArithmetic(Opc, VT,
507 cast<ConstantSDNode>(N0.getOperand(1)),
508 cast<ConstantSDNode>(N1));
509 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
510 } else if (N0.hasOneUse()) {
511 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
512 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
513 N0.getOperand(0), N1);
514 AddToWorkList(OpNode.getNode());
515 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
519 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
520 if (isa<ConstantSDNode>(N0)) {
521 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
523 DAG.FoldConstantArithmetic(Opc, VT,
524 cast<ConstantSDNode>(N1.getOperand(1)),
525 cast<ConstantSDNode>(N0));
526 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
527 } else if (N1.hasOneUse()) {
528 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
529 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
530 N1.getOperand(0), N0);
531 AddToWorkList(OpNode.getNode());
532 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
539 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
541 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
543 DEBUG(errs() << "\nReplacing.1 ";
545 errs() << "\nWith: ";
546 To[0].getNode()->dump(&DAG);
547 errs() << " and " << NumTo-1 << " other values\n";
548 for (unsigned i = 0, e = NumTo; i != e; ++i)
549 assert((!To[i].getNode() ||
550 N->getValueType(i) == To[i].getValueType()) &&
551 "Cannot combine value to value of different type!"));
552 WorkListRemover DeadNodes(*this);
553 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
556 // Push the new nodes and any users onto the worklist
557 for (unsigned i = 0, e = NumTo; i != e; ++i) {
558 if (To[i].getNode()) {
559 AddToWorkList(To[i].getNode());
560 AddUsersToWorkList(To[i].getNode());
565 // Finally, if the node is now dead, remove it from the graph. The node
566 // may not be dead if the replacement process recursively simplified to
567 // something else needing this node.
568 if (N->use_empty()) {
569 // Nodes can be reintroduced into the worklist. Make sure we do not
570 // process a node that has been replaced.
571 removeFromWorkList(N);
573 // Finally, since the node is now dead, remove it from the graph.
576 return SDValue(N, 0);
580 DAGCombiner::CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &
582 // Replace all uses. If any nodes become isomorphic to other nodes and
583 // are deleted, make sure to remove them from our worklist.
584 WorkListRemover DeadNodes(*this);
585 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
587 // Push the new node and any (possibly new) users onto the worklist.
588 AddToWorkList(TLO.New.getNode());
589 AddUsersToWorkList(TLO.New.getNode());
591 // Finally, if the node is now dead, remove it from the graph. The node
592 // may not be dead if the replacement process recursively simplified to
593 // something else needing this node.
594 if (TLO.Old.getNode()->use_empty()) {
595 removeFromWorkList(TLO.Old.getNode());
597 // If the operands of this node are only used by the node, they will now
598 // be dead. Make sure to visit them first to delete dead nodes early.
599 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
600 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
601 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
603 DAG.DeleteNode(TLO.Old.getNode());
607 /// SimplifyDemandedBits - Check the specified integer node value to see if
608 /// it can be simplified or if things it uses can be simplified by bit
609 /// propagation. If so, return true.
610 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
611 TargetLowering::TargetLoweringOpt TLO(DAG);
612 APInt KnownZero, KnownOne;
613 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
617 AddToWorkList(Op.getNode());
619 // Replace the old value with the new one.
621 DEBUG(errs() << "\nReplacing.2 ";
622 TLO.Old.getNode()->dump(&DAG);
623 errs() << "\nWith: ";
624 TLO.New.getNode()->dump(&DAG);
627 CommitTargetLoweringOpt(TLO);
631 //===----------------------------------------------------------------------===//
632 // Main DAG Combiner implementation
633 //===----------------------------------------------------------------------===//
635 void DAGCombiner::Run(CombineLevel AtLevel) {
636 // set the instance variables, so that the various visit routines may use it.
638 LegalOperations = Level >= NoIllegalOperations;
639 LegalTypes = Level >= NoIllegalTypes;
641 // Add all the dag nodes to the worklist.
642 WorkList.reserve(DAG.allnodes_size());
643 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
644 E = DAG.allnodes_end(); I != E; ++I)
645 WorkList.push_back(I);
647 // Create a dummy node (which is not added to allnodes), that adds a reference
648 // to the root node, preventing it from being deleted, and tracking any
649 // changes of the root.
650 HandleSDNode Dummy(DAG.getRoot());
652 // The root of the dag may dangle to deleted nodes until the dag combiner is
653 // done. Set it to null to avoid confusion.
654 DAG.setRoot(SDValue());
656 // while the worklist isn't empty, inspect the node on the end of it and
657 // try and combine it.
658 while (!WorkList.empty()) {
659 SDNode *N = WorkList.back();
662 // If N has no uses, it is dead. Make sure to revisit all N's operands once
663 // N is deleted from the DAG, since they too may now be dead or may have a
664 // reduced number of uses, allowing other xforms.
665 if (N->use_empty() && N != &Dummy) {
666 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
667 AddToWorkList(N->getOperand(i).getNode());
673 SDValue RV = combine(N);
675 if (RV.getNode() == 0)
680 // If we get back the same node we passed in, rather than a new node or
681 // zero, we know that the node must have defined multiple values and
682 // CombineTo was used. Since CombineTo takes care of the worklist
683 // mechanics for us, we have no work to do in this case.
684 if (RV.getNode() == N)
687 assert(N->getOpcode() != ISD::DELETED_NODE &&
688 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
689 "Node was deleted but visit returned new node!");
691 DEBUG(errs() << "\nReplacing.3 ";
693 errs() << "\nWith: ";
694 RV.getNode()->dump(&DAG);
696 WorkListRemover DeadNodes(*this);
697 if (N->getNumValues() == RV.getNode()->getNumValues())
698 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
700 assert(N->getValueType(0) == RV.getValueType() &&
701 N->getNumValues() == 1 && "Type mismatch");
703 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
706 // Push the new node and any users onto the worklist
707 AddToWorkList(RV.getNode());
708 AddUsersToWorkList(RV.getNode());
710 // Add any uses of the old node to the worklist in case this node is the
711 // last one that uses them. They may become dead after this node is
713 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
714 AddToWorkList(N->getOperand(i).getNode());
716 // Finally, if the node is now dead, remove it from the graph. The node
717 // may not be dead if the replacement process recursively simplified to
718 // something else needing this node.
719 if (N->use_empty()) {
720 // Nodes can be reintroduced into the worklist. Make sure we do not
721 // process a node that has been replaced.
722 removeFromWorkList(N);
724 // Finally, since the node is now dead, remove it from the graph.
729 // If the root changed (e.g. it was a dead load, update the root).
730 DAG.setRoot(Dummy.getValue());
733 SDValue DAGCombiner::visit(SDNode *N) {
734 switch(N->getOpcode()) {
736 case ISD::TokenFactor: return visitTokenFactor(N);
737 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
738 case ISD::ADD: return visitADD(N);
739 case ISD::SUB: return visitSUB(N);
740 case ISD::ADDC: return visitADDC(N);
741 case ISD::ADDE: return visitADDE(N);
742 case ISD::MUL: return visitMUL(N);
743 case ISD::SDIV: return visitSDIV(N);
744 case ISD::UDIV: return visitUDIV(N);
745 case ISD::SREM: return visitSREM(N);
746 case ISD::UREM: return visitUREM(N);
747 case ISD::MULHU: return visitMULHU(N);
748 case ISD::MULHS: return visitMULHS(N);
749 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
750 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
751 case ISD::SDIVREM: return visitSDIVREM(N);
752 case ISD::UDIVREM: return visitUDIVREM(N);
753 case ISD::AND: return visitAND(N);
754 case ISD::OR: return visitOR(N);
755 case ISD::XOR: return visitXOR(N);
756 case ISD::SHL: return visitSHL(N);
757 case ISD::SRA: return visitSRA(N);
758 case ISD::SRL: return visitSRL(N);
759 case ISD::CTLZ: return visitCTLZ(N);
760 case ISD::CTTZ: return visitCTTZ(N);
761 case ISD::CTPOP: return visitCTPOP(N);
762 case ISD::SELECT: return visitSELECT(N);
763 case ISD::SELECT_CC: return visitSELECT_CC(N);
764 case ISD::SETCC: return visitSETCC(N);
765 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
766 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
767 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
768 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
769 case ISD::TRUNCATE: return visitTRUNCATE(N);
770 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
771 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
772 case ISD::FADD: return visitFADD(N);
773 case ISD::FSUB: return visitFSUB(N);
774 case ISD::FMUL: return visitFMUL(N);
775 case ISD::FDIV: return visitFDIV(N);
776 case ISD::FREM: return visitFREM(N);
777 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
778 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
779 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
780 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
781 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
782 case ISD::FP_ROUND: return visitFP_ROUND(N);
783 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
784 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
785 case ISD::FNEG: return visitFNEG(N);
786 case ISD::FABS: return visitFABS(N);
787 case ISD::BRCOND: return visitBRCOND(N);
788 case ISD::BR_CC: return visitBR_CC(N);
789 case ISD::LOAD: return visitLOAD(N);
790 case ISD::STORE: return visitSTORE(N);
791 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
792 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
793 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
794 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
795 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
800 SDValue DAGCombiner::combine(SDNode *N) {
801 SDValue RV = visit(N);
803 // If nothing happened, try a target-specific DAG combine.
804 if (RV.getNode() == 0) {
805 assert(N->getOpcode() != ISD::DELETED_NODE &&
806 "Node was deleted but visit returned NULL!");
808 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
809 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
811 // Expose the DAG combiner to the target combiner impls.
812 TargetLowering::DAGCombinerInfo
813 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
815 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
819 // If N is a commutative binary node, try commuting it to enable more
821 if (RV.getNode() == 0 &&
822 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
823 N->getNumValues() == 1) {
824 SDValue N0 = N->getOperand(0);
825 SDValue N1 = N->getOperand(1);
827 // Constant operands are canonicalized to RHS.
828 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
829 SDValue Ops[] = { N1, N0 };
830 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
833 return SDValue(CSENode, 0);
840 /// getInputChainForNode - Given a node, return its input chain if it has one,
841 /// otherwise return a null sd operand.
842 static SDValue getInputChainForNode(SDNode *N) {
843 if (unsigned NumOps = N->getNumOperands()) {
844 if (N->getOperand(0).getValueType() == MVT::Other)
845 return N->getOperand(0);
846 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
847 return N->getOperand(NumOps-1);
848 for (unsigned i = 1; i < NumOps-1; ++i)
849 if (N->getOperand(i).getValueType() == MVT::Other)
850 return N->getOperand(i);
855 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
856 // If N has two operands, where one has an input chain equal to the other,
857 // the 'other' chain is redundant.
858 if (N->getNumOperands() == 2) {
859 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
860 return N->getOperand(0);
861 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
862 return N->getOperand(1);
865 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
866 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
867 SmallPtrSet<SDNode*, 16> SeenOps;
868 bool Changed = false; // If we should replace this token factor.
870 // Start out with this token factor.
873 // Iterate through token factors. The TFs grows when new token factors are
875 for (unsigned i = 0; i < TFs.size(); ++i) {
878 // Check each of the operands.
879 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
880 SDValue Op = TF->getOperand(i);
882 switch (Op.getOpcode()) {
883 case ISD::EntryToken:
884 // Entry tokens don't need to be added to the list. They are
889 case ISD::TokenFactor:
890 if (Op.hasOneUse() &&
891 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
892 // Queue up for processing.
893 TFs.push_back(Op.getNode());
894 // Clean up in case the token factor is removed.
895 AddToWorkList(Op.getNode());
902 // Only add if it isn't already in the list.
903 if (SeenOps.insert(Op.getNode()))
914 // If we've change things around then replace token factor.
917 // The entry token is the only possible outcome.
918 Result = DAG.getEntryNode();
920 // New and improved token factor.
921 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
922 MVT::Other, &Ops[0], Ops.size());
925 // Don't add users to work list.
926 return CombineTo(N, Result, false);
932 /// MERGE_VALUES can always be eliminated.
933 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
934 WorkListRemover DeadNodes(*this);
935 // Replacing results may cause a different MERGE_VALUES to suddenly
936 // be CSE'd with N, and carry its uses with it. Iterate until no
937 // uses remain, to ensure that the node can be safely deleted.
939 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
940 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
942 } while (!N->use_empty());
943 removeFromWorkList(N);
945 return SDValue(N, 0); // Return N so it doesn't get rechecked!
949 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
951 EVT VT = N0.getValueType();
952 SDValue N00 = N0.getOperand(0);
953 SDValue N01 = N0.getOperand(1);
954 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
956 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
957 isa<ConstantSDNode>(N00.getOperand(1))) {
958 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
959 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
960 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
961 N00.getOperand(0), N01),
962 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
963 N00.getOperand(1), N01));
964 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
970 SDValue DAGCombiner::visitADD(SDNode *N) {
971 SDValue N0 = N->getOperand(0);
972 SDValue N1 = N->getOperand(1);
973 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
974 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
975 EVT VT = N0.getValueType();
979 SDValue FoldedVOp = SimplifyVBinOp(N);
980 if (FoldedVOp.getNode()) return FoldedVOp;
983 // fold (add x, undef) -> undef
984 if (N0.getOpcode() == ISD::UNDEF)
986 if (N1.getOpcode() == ISD::UNDEF)
988 // fold (add c1, c2) -> c1+c2
990 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
991 // canonicalize constant to RHS
993 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
994 // fold (add x, 0) -> x
995 if (N1C && N1C->isNullValue())
997 // fold (add Sym, c) -> Sym+c
998 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
999 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1000 GA->getOpcode() == ISD::GlobalAddress)
1001 return DAG.getGlobalAddress(GA->getGlobal(), VT,
1003 (uint64_t)N1C->getSExtValue());
1004 // fold ((c1-A)+c2) -> (c1+c2)-A
1005 if (N1C && N0.getOpcode() == ISD::SUB)
1006 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1007 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1008 DAG.getConstant(N1C->getAPIntValue()+
1009 N0C->getAPIntValue(), VT),
1012 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1013 if (RADD.getNode() != 0)
1015 // fold ((0-A) + B) -> B-A
1016 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1017 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1018 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1019 // fold (A + (0-B)) -> A-B
1020 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1021 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1022 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1023 // fold (A+(B-A)) -> B
1024 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1025 return N1.getOperand(0);
1026 // fold ((B-A)+A) -> B
1027 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1028 return N0.getOperand(0);
1029 // fold (A+(B-(A+C))) to (B-C)
1030 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1031 N0 == N1.getOperand(1).getOperand(0))
1032 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1033 N1.getOperand(1).getOperand(1));
1034 // fold (A+(B-(C+A))) to (B-C)
1035 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1036 N0 == N1.getOperand(1).getOperand(1))
1037 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1038 N1.getOperand(1).getOperand(0));
1039 // fold (A+((B-A)+or-C)) to (B+or-C)
1040 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1041 N1.getOperand(0).getOpcode() == ISD::SUB &&
1042 N0 == N1.getOperand(0).getOperand(1))
1043 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1044 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1046 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1047 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1048 SDValue N00 = N0.getOperand(0);
1049 SDValue N01 = N0.getOperand(1);
1050 SDValue N10 = N1.getOperand(0);
1051 SDValue N11 = N1.getOperand(1);
1053 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1054 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1055 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1056 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1059 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1060 return SDValue(N, 0);
1062 // fold (a+b) -> (a|b) iff a and b share no bits.
1063 if (VT.isInteger() && !VT.isVector()) {
1064 APInt LHSZero, LHSOne;
1065 APInt RHSZero, RHSOne;
1066 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1067 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1069 if (LHSZero.getBoolValue()) {
1070 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1072 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1073 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1074 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1075 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1076 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1080 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1081 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1082 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1083 if (Result.getNode()) return Result;
1085 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1086 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1087 if (Result.getNode()) return Result;
1093 SDValue DAGCombiner::visitADDC(SDNode *N) {
1094 SDValue N0 = N->getOperand(0);
1095 SDValue N1 = N->getOperand(1);
1096 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1097 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1098 EVT VT = N0.getValueType();
1100 // If the flag result is dead, turn this into an ADD.
1101 if (N->hasNUsesOfValue(0, 1))
1102 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
1103 DAG.getNode(ISD::CARRY_FALSE,
1104 N->getDebugLoc(), MVT::Flag));
1106 // canonicalize constant to RHS.
1108 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1110 // fold (addc x, 0) -> x + no carry out
1111 if (N1C && N1C->isNullValue())
1112 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1113 N->getDebugLoc(), MVT::Flag));
1115 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1116 APInt LHSZero, LHSOne;
1117 APInt RHSZero, RHSOne;
1118 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1119 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1121 if (LHSZero.getBoolValue()) {
1122 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1124 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1125 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1126 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1127 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1128 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1129 DAG.getNode(ISD::CARRY_FALSE,
1130 N->getDebugLoc(), MVT::Flag));
1136 SDValue DAGCombiner::visitADDE(SDNode *N) {
1137 SDValue N0 = N->getOperand(0);
1138 SDValue N1 = N->getOperand(1);
1139 SDValue CarryIn = N->getOperand(2);
1140 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1141 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1143 // canonicalize constant to RHS
1145 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1148 // fold (adde x, y, false) -> (addc x, y)
1149 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1150 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1155 SDValue DAGCombiner::visitSUB(SDNode *N) {
1156 SDValue N0 = N->getOperand(0);
1157 SDValue N1 = N->getOperand(1);
1158 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1159 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1160 EVT VT = N0.getValueType();
1163 if (VT.isVector()) {
1164 SDValue FoldedVOp = SimplifyVBinOp(N);
1165 if (FoldedVOp.getNode()) return FoldedVOp;
1168 // fold (sub x, x) -> 0
1170 return DAG.getConstant(0, N->getValueType(0));
1171 // fold (sub c1, c2) -> c1-c2
1173 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1174 // fold (sub x, c) -> (add x, -c)
1176 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1177 DAG.getConstant(-N1C->getAPIntValue(), VT));
1178 // fold (A+B)-A -> B
1179 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1180 return N0.getOperand(1);
1181 // fold (A+B)-B -> A
1182 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1183 return N0.getOperand(0);
1184 // fold ((A+(B+or-C))-B) -> A+or-C
1185 if (N0.getOpcode() == ISD::ADD &&
1186 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1187 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1188 N0.getOperand(1).getOperand(0) == N1)
1189 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1190 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1191 // fold ((A+(C+B))-B) -> A+C
1192 if (N0.getOpcode() == ISD::ADD &&
1193 N0.getOperand(1).getOpcode() == ISD::ADD &&
1194 N0.getOperand(1).getOperand(1) == N1)
1195 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1196 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1197 // fold ((A-(B-C))-C) -> A-B
1198 if (N0.getOpcode() == ISD::SUB &&
1199 N0.getOperand(1).getOpcode() == ISD::SUB &&
1200 N0.getOperand(1).getOperand(1) == N1)
1201 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1202 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1204 // If either operand of a sub is undef, the result is undef
1205 if (N0.getOpcode() == ISD::UNDEF)
1207 if (N1.getOpcode() == ISD::UNDEF)
1210 // If the relocation model supports it, consider symbol offsets.
1211 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1212 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1213 // fold (sub Sym, c) -> Sym-c
1214 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1215 return DAG.getGlobalAddress(GA->getGlobal(), VT,
1217 (uint64_t)N1C->getSExtValue());
1218 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1219 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1220 if (GA->getGlobal() == GB->getGlobal())
1221 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1228 SDValue DAGCombiner::visitMUL(SDNode *N) {
1229 SDValue N0 = N->getOperand(0);
1230 SDValue N1 = N->getOperand(1);
1231 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1232 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1233 EVT VT = N0.getValueType();
1236 if (VT.isVector()) {
1237 SDValue FoldedVOp = SimplifyVBinOp(N);
1238 if (FoldedVOp.getNode()) return FoldedVOp;
1241 // fold (mul x, undef) -> 0
1242 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1243 return DAG.getConstant(0, VT);
1244 // fold (mul c1, c2) -> c1*c2
1246 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1247 // canonicalize constant to RHS
1249 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1250 // fold (mul x, 0) -> 0
1251 if (N1C && N1C->isNullValue())
1253 // fold (mul x, -1) -> 0-x
1254 if (N1C && N1C->isAllOnesValue())
1255 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1256 DAG.getConstant(0, VT), N0);
1257 // fold (mul x, (1 << c)) -> x << c
1258 if (N1C && N1C->getAPIntValue().isPowerOf2())
1259 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1260 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1261 getShiftAmountTy()));
1262 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1263 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1264 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1265 // FIXME: If the input is something that is easily negated (e.g. a
1266 // single-use add), we should put the negate there.
1267 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1268 DAG.getConstant(0, VT),
1269 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1270 DAG.getConstant(Log2Val, getShiftAmountTy())));
1272 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1273 if (N1C && N0.getOpcode() == ISD::SHL &&
1274 isa<ConstantSDNode>(N0.getOperand(1))) {
1275 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1276 N1, N0.getOperand(1));
1277 AddToWorkList(C3.getNode());
1278 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1279 N0.getOperand(0), C3);
1282 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1285 SDValue Sh(0,0), Y(0,0);
1286 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1287 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1288 N0.getNode()->hasOneUse()) {
1290 } else if (N1.getOpcode() == ISD::SHL &&
1291 isa<ConstantSDNode>(N1.getOperand(1)) &&
1292 N1.getNode()->hasOneUse()) {
1297 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1298 Sh.getOperand(0), Y);
1299 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1300 Mul, Sh.getOperand(1));
1304 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1305 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1306 isa<ConstantSDNode>(N0.getOperand(1)))
1307 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1308 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1309 N0.getOperand(0), N1),
1310 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1311 N0.getOperand(1), N1));
1314 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1315 if (RMUL.getNode() != 0)
1321 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1322 SDValue N0 = N->getOperand(0);
1323 SDValue N1 = N->getOperand(1);
1324 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1325 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1326 EVT VT = N->getValueType(0);
1329 if (VT.isVector()) {
1330 SDValue FoldedVOp = SimplifyVBinOp(N);
1331 if (FoldedVOp.getNode()) return FoldedVOp;
1334 // fold (sdiv c1, c2) -> c1/c2
1335 if (N0C && N1C && !N1C->isNullValue())
1336 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1337 // fold (sdiv X, 1) -> X
1338 if (N1C && N1C->getSExtValue() == 1LL)
1340 // fold (sdiv X, -1) -> 0-X
1341 if (N1C && N1C->isAllOnesValue())
1342 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1343 DAG.getConstant(0, VT), N0);
1344 // If we know the sign bits of both operands are zero, strength reduce to a
1345 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1346 if (!VT.isVector()) {
1347 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1348 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1351 // fold (sdiv X, pow2) -> simple ops after legalize
1352 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1353 (isPowerOf2_64(N1C->getSExtValue()) ||
1354 isPowerOf2_64(-N1C->getSExtValue()))) {
1355 // If dividing by powers of two is cheap, then don't perform the following
1357 if (TLI.isPow2DivCheap())
1360 int64_t pow2 = N1C->getSExtValue();
1361 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1362 unsigned lg2 = Log2_64(abs2);
1364 // Splat the sign bit into the register
1365 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1366 DAG.getConstant(VT.getSizeInBits()-1,
1367 getShiftAmountTy()));
1368 AddToWorkList(SGN.getNode());
1370 // Add (N0 < 0) ? abs2 - 1 : 0;
1371 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1372 DAG.getConstant(VT.getSizeInBits() - lg2,
1373 getShiftAmountTy()));
1374 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1375 AddToWorkList(SRL.getNode());
1376 AddToWorkList(ADD.getNode()); // Divide by pow2
1377 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1378 DAG.getConstant(lg2, getShiftAmountTy()));
1380 // If we're dividing by a positive value, we're done. Otherwise, we must
1381 // negate the result.
1385 AddToWorkList(SRA.getNode());
1386 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1387 DAG.getConstant(0, VT), SRA);
1390 // if integer divide is expensive and we satisfy the requirements, emit an
1391 // alternate sequence.
1392 if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1393 !TLI.isIntDivCheap()) {
1394 SDValue Op = BuildSDIV(N);
1395 if (Op.getNode()) return Op;
1399 if (N0.getOpcode() == ISD::UNDEF)
1400 return DAG.getConstant(0, VT);
1401 // X / undef -> undef
1402 if (N1.getOpcode() == ISD::UNDEF)
1408 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1409 SDValue N0 = N->getOperand(0);
1410 SDValue N1 = N->getOperand(1);
1411 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1412 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1413 EVT VT = N->getValueType(0);
1416 if (VT.isVector()) {
1417 SDValue FoldedVOp = SimplifyVBinOp(N);
1418 if (FoldedVOp.getNode()) return FoldedVOp;
1421 // fold (udiv c1, c2) -> c1/c2
1422 if (N0C && N1C && !N1C->isNullValue())
1423 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1424 // fold (udiv x, (1 << c)) -> x >>u c
1425 if (N1C && N1C->getAPIntValue().isPowerOf2())
1426 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1427 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1428 getShiftAmountTy()));
1429 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1430 if (N1.getOpcode() == ISD::SHL) {
1431 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1432 if (SHC->getAPIntValue().isPowerOf2()) {
1433 EVT ADDVT = N1.getOperand(1).getValueType();
1434 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1436 DAG.getConstant(SHC->getAPIntValue()
1439 AddToWorkList(Add.getNode());
1440 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1444 // fold (udiv x, c) -> alternate
1445 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1446 SDValue Op = BuildUDIV(N);
1447 if (Op.getNode()) return Op;
1451 if (N0.getOpcode() == ISD::UNDEF)
1452 return DAG.getConstant(0, VT);
1453 // X / undef -> undef
1454 if (N1.getOpcode() == ISD::UNDEF)
1460 SDValue DAGCombiner::visitSREM(SDNode *N) {
1461 SDValue N0 = N->getOperand(0);
1462 SDValue N1 = N->getOperand(1);
1463 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1464 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1465 EVT VT = N->getValueType(0);
1467 // fold (srem c1, c2) -> c1%c2
1468 if (N0C && N1C && !N1C->isNullValue())
1469 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1470 // If we know the sign bits of both operands are zero, strength reduce to a
1471 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1472 if (!VT.isVector()) {
1473 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1474 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1477 // If X/C can be simplified by the division-by-constant logic, lower
1478 // X%C to the equivalent of X-X/C*C.
1479 if (N1C && !N1C->isNullValue()) {
1480 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1481 AddToWorkList(Div.getNode());
1482 SDValue OptimizedDiv = combine(Div.getNode());
1483 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1484 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1486 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1487 AddToWorkList(Mul.getNode());
1493 if (N0.getOpcode() == ISD::UNDEF)
1494 return DAG.getConstant(0, VT);
1495 // X % undef -> undef
1496 if (N1.getOpcode() == ISD::UNDEF)
1502 SDValue DAGCombiner::visitUREM(SDNode *N) {
1503 SDValue N0 = N->getOperand(0);
1504 SDValue N1 = N->getOperand(1);
1505 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1506 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1507 EVT VT = N->getValueType(0);
1509 // fold (urem c1, c2) -> c1%c2
1510 if (N0C && N1C && !N1C->isNullValue())
1511 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1512 // fold (urem x, pow2) -> (and x, pow2-1)
1513 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1514 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
1515 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1516 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1517 if (N1.getOpcode() == ISD::SHL) {
1518 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1519 if (SHC->getAPIntValue().isPowerOf2()) {
1521 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
1522 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1524 AddToWorkList(Add.getNode());
1525 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
1530 // If X/C can be simplified by the division-by-constant logic, lower
1531 // X%C to the equivalent of X-X/C*C.
1532 if (N1C && !N1C->isNullValue()) {
1533 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
1534 AddToWorkList(Div.getNode());
1535 SDValue OptimizedDiv = combine(Div.getNode());
1536 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1537 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1539 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1540 AddToWorkList(Mul.getNode());
1546 if (N0.getOpcode() == ISD::UNDEF)
1547 return DAG.getConstant(0, VT);
1548 // X % undef -> undef
1549 if (N1.getOpcode() == ISD::UNDEF)
1555 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1556 SDValue N0 = N->getOperand(0);
1557 SDValue N1 = N->getOperand(1);
1558 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1559 EVT VT = N->getValueType(0);
1561 // fold (mulhs x, 0) -> 0
1562 if (N1C && N1C->isNullValue())
1564 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1565 if (N1C && N1C->getAPIntValue() == 1)
1566 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
1567 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
1568 getShiftAmountTy()));
1569 // fold (mulhs x, undef) -> 0
1570 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1571 return DAG.getConstant(0, VT);
1576 SDValue DAGCombiner::visitMULHU(SDNode *N) {
1577 SDValue N0 = N->getOperand(0);
1578 SDValue N1 = N->getOperand(1);
1579 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1580 EVT VT = N->getValueType(0);
1582 // fold (mulhu x, 0) -> 0
1583 if (N1C && N1C->isNullValue())
1585 // fold (mulhu x, 1) -> 0
1586 if (N1C && N1C->getAPIntValue() == 1)
1587 return DAG.getConstant(0, N0.getValueType());
1588 // fold (mulhu x, undef) -> 0
1589 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1590 return DAG.getConstant(0, VT);
1595 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1596 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1597 /// that are being performed. Return true if a simplification was made.
1599 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1601 // If the high half is not needed, just compute the low half.
1602 bool HiExists = N->hasAnyUseOfValue(1);
1604 (!LegalOperations ||
1605 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1606 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1607 N->op_begin(), N->getNumOperands());
1608 return CombineTo(N, Res, Res);
1611 // If the low half is not needed, just compute the high half.
1612 bool LoExists = N->hasAnyUseOfValue(0);
1614 (!LegalOperations ||
1615 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1616 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1617 N->op_begin(), N->getNumOperands());
1618 return CombineTo(N, Res, Res);
1621 // If both halves are used, return as it is.
1622 if (LoExists && HiExists)
1625 // If the two computed results can be simplified separately, separate them.
1627 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1628 N->op_begin(), N->getNumOperands());
1629 AddToWorkList(Lo.getNode());
1630 SDValue LoOpt = combine(Lo.getNode());
1631 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
1632 (!LegalOperations ||
1633 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1634 return CombineTo(N, LoOpt, LoOpt);
1638 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1639 N->op_begin(), N->getNumOperands());
1640 AddToWorkList(Hi.getNode());
1641 SDValue HiOpt = combine(Hi.getNode());
1642 if (HiOpt.getNode() && HiOpt != Hi &&
1643 (!LegalOperations ||
1644 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1645 return CombineTo(N, HiOpt, HiOpt);
1651 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1652 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1653 if (Res.getNode()) return Res;
1658 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1659 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1660 if (Res.getNode()) return Res;
1665 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
1666 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1667 if (Res.getNode()) return Res;
1672 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
1673 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1674 if (Res.getNode()) return Res;
1679 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1680 /// two operands of the same opcode, try to simplify it.
1681 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1682 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
1683 EVT VT = N0.getValueType();
1684 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1686 // For each of OP in AND/OR/XOR:
1687 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1688 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1689 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1690 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
1692 // do not sink logical op inside of a vector extend, since it may combine
1694 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1695 N0.getOpcode() == ISD::SIGN_EXTEND ||
1696 (N0.getOpcode() == ISD::TRUNCATE &&
1697 !TLI.isTruncateFree(N0.getOperand(0).getValueType(), VT))) &&
1699 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
1700 (!LegalOperations ||
1701 TLI.isOperationLegal(N->getOpcode(), N0.getOperand(0).getValueType()))) {
1702 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
1703 N0.getOperand(0).getValueType(),
1704 N0.getOperand(0), N1.getOperand(0));
1705 AddToWorkList(ORNode.getNode());
1706 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
1709 // For each of OP in SHL/SRL/SRA/AND...
1710 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1711 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1712 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1713 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1714 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1715 N0.getOperand(1) == N1.getOperand(1)) {
1716 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
1717 N0.getOperand(0).getValueType(),
1718 N0.getOperand(0), N1.getOperand(0));
1719 AddToWorkList(ORNode.getNode());
1720 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
1721 ORNode, N0.getOperand(1));
1727 SDValue DAGCombiner::visitAND(SDNode *N) {
1728 SDValue N0 = N->getOperand(0);
1729 SDValue N1 = N->getOperand(1);
1730 SDValue LL, LR, RL, RR, CC0, CC1;
1731 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1732 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1733 EVT VT = N1.getValueType();
1734 unsigned BitWidth = VT.getSizeInBits();
1737 if (VT.isVector()) {
1738 SDValue FoldedVOp = SimplifyVBinOp(N);
1739 if (FoldedVOp.getNode()) return FoldedVOp;
1742 // fold (and x, undef) -> 0
1743 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1744 return DAG.getConstant(0, VT);
1745 // fold (and c1, c2) -> c1&c2
1747 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
1748 // canonicalize constant to RHS
1750 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
1751 // fold (and x, -1) -> x
1752 if (N1C && N1C->isAllOnesValue())
1754 // if (and x, c) is known to be zero, return 0
1755 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
1756 APInt::getAllOnesValue(BitWidth)))
1757 return DAG.getConstant(0, VT);
1759 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
1760 if (RAND.getNode() != 0)
1762 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1763 if (N1C && N0.getOpcode() == ISD::OR)
1764 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1765 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
1767 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1768 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1769 SDValue N0Op0 = N0.getOperand(0);
1770 APInt Mask = ~N1C->getAPIntValue();
1771 Mask.trunc(N0Op0.getValueSizeInBits());
1772 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
1773 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
1774 N0.getValueType(), N0Op0);
1776 // Replace uses of the AND with uses of the Zero extend node.
1779 // We actually want to replace all uses of the any_extend with the
1780 // zero_extend, to avoid duplicating things. This will later cause this
1781 // AND to be folded.
1782 CombineTo(N0.getNode(), Zext);
1783 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1786 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1787 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1788 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1789 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1791 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1792 LL.getValueType().isInteger()) {
1793 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
1794 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
1795 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
1796 LR.getValueType(), LL, RL);
1797 AddToWorkList(ORNode.getNode());
1798 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
1800 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
1801 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1802 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
1803 LR.getValueType(), LL, RL);
1804 AddToWorkList(ANDNode.getNode());
1805 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
1807 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
1808 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1809 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
1810 LR.getValueType(), LL, RL);
1811 AddToWorkList(ORNode.getNode());
1812 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
1815 // canonicalize equivalent to ll == rl
1816 if (LL == RR && LR == RL) {
1817 Op1 = ISD::getSetCCSwappedOperands(Op1);
1820 if (LL == RL && LR == RR) {
1821 bool isInteger = LL.getValueType().isInteger();
1822 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1823 if (Result != ISD::SETCC_INVALID &&
1824 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
1825 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
1830 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
1831 if (N0.getOpcode() == N1.getOpcode()) {
1832 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1833 if (Tmp.getNode()) return Tmp;
1836 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1837 // fold (and (sra)) -> (and (srl)) when possible.
1838 if (!VT.isVector() &&
1839 SimplifyDemandedBits(SDValue(N, 0)))
1840 return SDValue(N, 0);
1841 // fold (zext_inreg (extload x)) -> (zextload x)
1842 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
1843 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1844 EVT MemVT = LN0->getMemoryVT();
1845 // If we zero all the possible extended bits, then we can turn this into
1846 // a zextload if we are running before legalize or the operation is legal.
1847 unsigned BitWidth = N1.getValueSizeInBits();
1848 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1849 BitWidth - MemVT.getSizeInBits())) &&
1850 ((!LegalOperations && !LN0->isVolatile()) ||
1851 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
1852 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
1853 LN0->getChain(), LN0->getBasePtr(),
1855 LN0->getSrcValueOffset(), MemVT,
1856 LN0->isVolatile(), LN0->getAlignment());
1858 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
1859 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1862 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1863 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
1865 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1866 EVT MemVT = LN0->getMemoryVT();
1867 // If we zero all the possible extended bits, then we can turn this into
1868 // a zextload if we are running before legalize or the operation is legal.
1869 unsigned BitWidth = N1.getValueSizeInBits();
1870 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1871 BitWidth - MemVT.getSizeInBits())) &&
1872 ((!LegalOperations && !LN0->isVolatile()) ||
1873 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
1874 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
1876 LN0->getBasePtr(), LN0->getSrcValue(),
1877 LN0->getSrcValueOffset(), MemVT,
1878 LN0->isVolatile(), LN0->getAlignment());
1880 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
1881 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1885 // fold (and (load x), 255) -> (zextload x, i8)
1886 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1887 if (N1C && N0.getOpcode() == ISD::LOAD) {
1888 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1889 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1890 LN0->isUnindexed() && N0.hasOneUse() &&
1891 // Do not change the width of a volatile load.
1892 !LN0->isVolatile()) {
1893 EVT ExtVT = MVT::Other;
1894 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
1895 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue()))
1896 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
1898 EVT LoadedVT = LN0->getMemoryVT();
1900 // Do not generate loads of non-round integer types since these can
1901 // be expensive (and would be wrong if the type is not byte sized).
1902 if (ExtVT != MVT::Other && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
1903 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
1904 EVT PtrType = N0.getOperand(1).getValueType();
1906 // For big endian targets, we need to add an offset to the pointer to
1907 // load the correct bytes. For little endian systems, we merely need to
1908 // read fewer bytes from the same pointer.
1909 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
1910 unsigned EVTStoreBytes = ExtVT.getStoreSize();
1911 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
1912 unsigned Alignment = LN0->getAlignment();
1913 SDValue NewPtr = LN0->getBasePtr();
1915 if (TLI.isBigEndian()) {
1916 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
1917 NewPtr, DAG.getConstant(PtrOff, PtrType));
1918 Alignment = MinAlign(Alignment, PtrOff);
1921 AddToWorkList(NewPtr.getNode());
1923 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT, LN0->getChain(),
1924 NewPtr, LN0->getSrcValue(), LN0->getSrcValueOffset(),
1925 ExtVT, LN0->isVolatile(), Alignment);
1927 CombineTo(N0.getNode(), Load, Load.getValue(1));
1928 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1936 SDValue DAGCombiner::visitOR(SDNode *N) {
1937 SDValue N0 = N->getOperand(0);
1938 SDValue N1 = N->getOperand(1);
1939 SDValue LL, LR, RL, RR, CC0, CC1;
1940 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1941 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1942 EVT VT = N1.getValueType();
1945 if (VT.isVector()) {
1946 SDValue FoldedVOp = SimplifyVBinOp(N);
1947 if (FoldedVOp.getNode()) return FoldedVOp;
1950 // fold (or x, undef) -> -1
1951 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) {
1952 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
1953 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
1955 // fold (or c1, c2) -> c1|c2
1957 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
1958 // canonicalize constant to RHS
1960 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
1961 // fold (or x, 0) -> x
1962 if (N1C && N1C->isNullValue())
1964 // fold (or x, -1) -> -1
1965 if (N1C && N1C->isAllOnesValue())
1967 // fold (or x, c) -> c iff (x & ~c) == 0
1968 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
1971 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
1972 if (ROR.getNode() != 0)
1974 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1975 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
1976 isa<ConstantSDNode>(N0.getOperand(1))) {
1977 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1978 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
1979 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
1980 N0.getOperand(0), N1),
1981 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
1983 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1984 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1985 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1986 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1988 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1989 LL.getValueType().isInteger()) {
1990 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
1991 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
1992 if (cast<ConstantSDNode>(LR)->isNullValue() &&
1993 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1994 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
1995 LR.getValueType(), LL, RL);
1996 AddToWorkList(ORNode.getNode());
1997 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
1999 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
2000 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
2001 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2002 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
2003 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
2004 LR.getValueType(), LL, RL);
2005 AddToWorkList(ANDNode.getNode());
2006 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2009 // canonicalize equivalent to ll == rl
2010 if (LL == RR && LR == RL) {
2011 Op1 = ISD::getSetCCSwappedOperands(Op1);
2014 if (LL == RL && LR == RR) {
2015 bool isInteger = LL.getValueType().isInteger();
2016 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
2017 if (Result != ISD::SETCC_INVALID &&
2018 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2019 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2024 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
2025 if (N0.getOpcode() == N1.getOpcode()) {
2026 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2027 if (Tmp.getNode()) return Tmp;
2030 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
2031 if (N0.getOpcode() == ISD::AND &&
2032 N1.getOpcode() == ISD::AND &&
2033 N0.getOperand(1).getOpcode() == ISD::Constant &&
2034 N1.getOperand(1).getOpcode() == ISD::Constant &&
2035 // Don't increase # computations.
2036 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2037 // We can only do this xform if we know that bits from X that are set in C2
2038 // but not in C1 are already zero. Likewise for Y.
2039 const APInt &LHSMask =
2040 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2041 const APInt &RHSMask =
2042 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2044 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2045 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2046 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2047 N0.getOperand(0), N1.getOperand(0));
2048 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
2049 DAG.getConstant(LHSMask | RHSMask, VT));
2053 // See if this is some rotate idiom.
2054 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
2055 return SDValue(Rot, 0);
2060 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2061 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2062 if (Op.getOpcode() == ISD::AND) {
2063 if (isa<ConstantSDNode>(Op.getOperand(1))) {
2064 Mask = Op.getOperand(1);
2065 Op = Op.getOperand(0);
2071 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2079 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
2080 // idioms for rotate, and if the target supports rotation instructions, generate
2082 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
2083 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
2084 EVT VT = LHS.getValueType();
2085 if (!TLI.isTypeLegal(VT)) return 0;
2087 // The target must have at least one rotate flavor.
2088 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
2089 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
2090 if (!HasROTL && !HasROTR) return 0;
2092 // Match "(X shl/srl V1) & V2" where V2 may not be present.
2093 SDValue LHSShift; // The shift.
2094 SDValue LHSMask; // AND value if any.
2095 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2096 return 0; // Not part of a rotate.
2098 SDValue RHSShift; // The shift.
2099 SDValue RHSMask; // AND value if any.
2100 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2101 return 0; // Not part of a rotate.
2103 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2104 return 0; // Not shifting the same value.
2106 if (LHSShift.getOpcode() == RHSShift.getOpcode())
2107 return 0; // Shifts must disagree.
2109 // Canonicalize shl to left side in a shl/srl pair.
2110 if (RHSShift.getOpcode() == ISD::SHL) {
2111 std::swap(LHS, RHS);
2112 std::swap(LHSShift, RHSShift);
2113 std::swap(LHSMask , RHSMask );
2116 unsigned OpSizeInBits = VT.getSizeInBits();
2117 SDValue LHSShiftArg = LHSShift.getOperand(0);
2118 SDValue LHSShiftAmt = LHSShift.getOperand(1);
2119 SDValue RHSShiftAmt = RHSShift.getOperand(1);
2121 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2122 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2123 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2124 RHSShiftAmt.getOpcode() == ISD::Constant) {
2125 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2126 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2127 if ((LShVal + RShVal) != OpSizeInBits)
2132 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
2134 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
2136 // If there is an AND of either shifted operand, apply it to the result.
2137 if (LHSMask.getNode() || RHSMask.getNode()) {
2138 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2140 if (LHSMask.getNode()) {
2141 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2142 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2144 if (RHSMask.getNode()) {
2145 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2146 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2149 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
2152 return Rot.getNode();
2155 // If there is a mask here, and we have a variable shift, we can't be sure
2156 // that we're masking out the right stuff.
2157 if (LHSMask.getNode() || RHSMask.getNode())
2160 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2161 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2162 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2163 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2164 if (ConstantSDNode *SUBC =
2165 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2166 if (SUBC->getAPIntValue() == OpSizeInBits) {
2168 return DAG.getNode(ISD::ROTL, DL, VT,
2169 LHSShiftArg, LHSShiftAmt).getNode();
2171 return DAG.getNode(ISD::ROTR, DL, VT,
2172 LHSShiftArg, RHSShiftAmt).getNode();
2177 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2178 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2179 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2180 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2181 if (ConstantSDNode *SUBC =
2182 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2183 if (SUBC->getAPIntValue() == OpSizeInBits) {
2185 return DAG.getNode(ISD::ROTR, DL, VT,
2186 LHSShiftArg, RHSShiftAmt).getNode();
2188 return DAG.getNode(ISD::ROTL, DL, VT,
2189 LHSShiftArg, LHSShiftAmt).getNode();
2194 // Look for sign/zext/any-extended or truncate cases:
2195 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2196 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2197 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2198 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2199 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2200 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2201 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2202 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2203 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2204 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2205 if (RExtOp0.getOpcode() == ISD::SUB &&
2206 RExtOp0.getOperand(1) == LExtOp0) {
2207 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2209 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2210 // (rotr x, (sub 32, y))
2211 if (ConstantSDNode *SUBC =
2212 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2213 if (SUBC->getAPIntValue() == OpSizeInBits) {
2214 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
2216 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2219 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2220 RExtOp0 == LExtOp0.getOperand(1)) {
2221 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2223 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2224 // (rotl x, (sub 32, y))
2225 if (ConstantSDNode *SUBC =
2226 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2227 if (SUBC->getAPIntValue() == OpSizeInBits) {
2228 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
2230 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2239 SDValue DAGCombiner::visitXOR(SDNode *N) {
2240 SDValue N0 = N->getOperand(0);
2241 SDValue N1 = N->getOperand(1);
2242 SDValue LHS, RHS, CC;
2243 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2244 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2245 EVT VT = N0.getValueType();
2248 if (VT.isVector()) {
2249 SDValue FoldedVOp = SimplifyVBinOp(N);
2250 if (FoldedVOp.getNode()) return FoldedVOp;
2253 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2254 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2255 return DAG.getConstant(0, VT);
2256 // fold (xor x, undef) -> undef
2257 if (N0.getOpcode() == ISD::UNDEF)
2259 if (N1.getOpcode() == ISD::UNDEF)
2261 // fold (xor c1, c2) -> c1^c2
2263 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2264 // canonicalize constant to RHS
2266 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
2267 // fold (xor x, 0) -> x
2268 if (N1C && N1C->isNullValue())
2271 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
2272 if (RXOR.getNode() != 0)
2275 // fold !(x cc y) -> (x !cc y)
2276 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2277 bool isInt = LHS.getValueType().isInteger();
2278 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2281 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
2282 switch (N0.getOpcode()) {
2284 llvm_unreachable("Unhandled SetCC Equivalent!");
2286 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
2287 case ISD::SELECT_CC:
2288 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
2289 N0.getOperand(3), NotCC);
2294 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2295 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2296 N0.getNode()->hasOneUse() &&
2297 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2298 SDValue V = N0.getOperand(0);
2299 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
2300 DAG.getConstant(1, V.getValueType()));
2301 AddToWorkList(V.getNode());
2302 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
2305 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
2306 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2307 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2308 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2309 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2310 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2311 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2312 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2313 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2314 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2317 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
2318 if (N1C && N1C->isAllOnesValue() &&
2319 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2320 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2321 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2322 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2323 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2324 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2325 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2326 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2329 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
2330 if (N1C && N0.getOpcode() == ISD::XOR) {
2331 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2332 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2334 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
2335 DAG.getConstant(N1C->getAPIntValue() ^
2336 N00C->getAPIntValue(), VT));
2338 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
2339 DAG.getConstant(N1C->getAPIntValue() ^
2340 N01C->getAPIntValue(), VT));
2342 // fold (xor x, x) -> 0
2344 if (!VT.isVector()) {
2345 return DAG.getConstant(0, VT);
2346 } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)){
2347 // Produce a vector of zeros.
2348 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
2349 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
2350 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
2351 &Ops[0], Ops.size());
2355 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2356 if (N0.getOpcode() == N1.getOpcode()) {
2357 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2358 if (Tmp.getNode()) return Tmp;
2361 // Simplify the expression using non-local knowledge.
2362 if (!VT.isVector() &&
2363 SimplifyDemandedBits(SDValue(N, 0)))
2364 return SDValue(N, 0);
2369 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2370 /// the shift amount is a constant.
2371 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2372 SDNode *LHS = N->getOperand(0).getNode();
2373 if (!LHS->hasOneUse()) return SDValue();
2375 // We want to pull some binops through shifts, so that we have (and (shift))
2376 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2377 // thing happens with address calculations, so it's important to canonicalize
2379 bool HighBitSet = false; // Can we transform this if the high bit is set?
2381 switch (LHS->getOpcode()) {
2382 default: return SDValue();
2385 HighBitSet = false; // We can only transform sra if the high bit is clear.
2388 HighBitSet = true; // We can only transform sra if the high bit is set.
2391 if (N->getOpcode() != ISD::SHL)
2392 return SDValue(); // only shl(add) not sr[al](add).
2393 HighBitSet = false; // We can only transform sra if the high bit is clear.
2397 // We require the RHS of the binop to be a constant as well.
2398 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2399 if (!BinOpCst) return SDValue();
2401 // FIXME: disable this unless the input to the binop is a shift by a constant.
2402 // If it is not a shift, it pessimizes some common cases like:
2404 // void foo(int *X, int i) { X[i & 1235] = 1; }
2405 // int bar(int *X, int i) { return X[i & 255]; }
2406 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2407 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2408 BinOpLHSVal->getOpcode() != ISD::SRA &&
2409 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2410 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2413 EVT VT = N->getValueType(0);
2415 // If this is a signed shift right, and the high bit is modified by the
2416 // logical operation, do not perform the transformation. The highBitSet
2417 // boolean indicates the value of the high bit of the constant which would
2418 // cause it to be modified for this operation.
2419 if (N->getOpcode() == ISD::SRA) {
2420 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2421 if (BinOpRHSSignSet != HighBitSet)
2425 // Fold the constants, shifting the binop RHS by the shift amount.
2426 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
2428 LHS->getOperand(1), N->getOperand(1));
2430 // Create the new shift.
2431 SDValue NewShift = DAG.getNode(N->getOpcode(), LHS->getOperand(0).getDebugLoc(),
2432 VT, LHS->getOperand(0), N->getOperand(1));
2434 // Create the new binop.
2435 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
2438 SDValue DAGCombiner::visitSHL(SDNode *N) {
2439 SDValue N0 = N->getOperand(0);
2440 SDValue N1 = N->getOperand(1);
2441 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2442 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2443 EVT VT = N0.getValueType();
2444 unsigned OpSizeInBits = VT.getSizeInBits();
2446 // fold (shl c1, c2) -> c1<<c2
2448 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
2449 // fold (shl 0, x) -> 0
2450 if (N0C && N0C->isNullValue())
2452 // fold (shl x, c >= size(x)) -> undef
2453 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2454 return DAG.getUNDEF(VT);
2455 // fold (shl x, 0) -> x
2456 if (N1C && N1C->isNullValue())
2458 // if (shl x, c) is known to be zero, return 0
2459 if (DAG.MaskedValueIsZero(SDValue(N, 0),
2460 APInt::getAllOnesValue(VT.getSizeInBits())))
2461 return DAG.getConstant(0, VT);
2462 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
2463 if (N1.getOpcode() == ISD::TRUNCATE &&
2464 N1.getOperand(0).getOpcode() == ISD::AND &&
2465 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2466 SDValue N101 = N1.getOperand(0).getOperand(1);
2467 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2468 EVT TruncVT = N1.getValueType();
2469 SDValue N100 = N1.getOperand(0).getOperand(0);
2470 APInt TruncC = N101C->getAPIntValue();
2471 TruncC.trunc(TruncVT.getSizeInBits());
2472 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
2473 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
2474 DAG.getNode(ISD::TRUNCATE,
2477 DAG.getConstant(TruncC, TruncVT)));
2481 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2482 return SDValue(N, 0);
2484 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
2485 if (N1C && N0.getOpcode() == ISD::SHL &&
2486 N0.getOperand(1).getOpcode() == ISD::Constant) {
2487 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2488 uint64_t c2 = N1C->getZExtValue();
2489 if (c1 + c2 > OpSizeInBits)
2490 return DAG.getConstant(0, VT);
2491 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
2492 DAG.getConstant(c1 + c2, N1.getValueType()));
2494 // fold (shl (srl x, c1), c2) -> (shl (and x, (shl -1, c1)), (sub c2, c1)) or
2495 // (srl (and x, (shl -1, c1)), (sub c1, c2))
2496 if (N1C && N0.getOpcode() == ISD::SRL &&
2497 N0.getOperand(1).getOpcode() == ISD::Constant) {
2498 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2499 if (c1 < VT.getSizeInBits()) {
2500 uint64_t c2 = N1C->getZExtValue();
2501 SDValue HiBitsMask =
2502 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2503 VT.getSizeInBits() - c1),
2505 SDValue Mask = DAG.getNode(ISD::AND, N0.getDebugLoc(), VT,
2509 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, Mask,
2510 DAG.getConstant(c2-c1, N1.getValueType()));
2512 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Mask,
2513 DAG.getConstant(c1-c2, N1.getValueType()));
2516 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
2517 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
2518 SDValue HiBitsMask =
2519 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2520 VT.getSizeInBits() -
2521 N1C->getZExtValue()),
2523 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
2527 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2530 SDValue DAGCombiner::visitSRA(SDNode *N) {
2531 SDValue N0 = N->getOperand(0);
2532 SDValue N1 = N->getOperand(1);
2533 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2534 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2535 EVT VT = N0.getValueType();
2537 // fold (sra c1, c2) -> (sra c1, c2)
2539 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
2540 // fold (sra 0, x) -> 0
2541 if (N0C && N0C->isNullValue())
2543 // fold (sra -1, x) -> -1
2544 if (N0C && N0C->isAllOnesValue())
2546 // fold (sra x, (setge c, size(x))) -> undef
2547 if (N1C && N1C->getZExtValue() >= VT.getSizeInBits())
2548 return DAG.getUNDEF(VT);
2549 // fold (sra x, 0) -> x
2550 if (N1C && N1C->isNullValue())
2552 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2554 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2555 unsigned LowBits = VT.getSizeInBits() - (unsigned)N1C->getZExtValue();
2556 EVT EVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
2557 if ((!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT)))
2558 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
2559 N0.getOperand(0), DAG.getValueType(EVT));
2562 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
2563 if (N1C && N0.getOpcode() == ISD::SRA) {
2564 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2565 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
2566 if (Sum >= VT.getSizeInBits()) Sum = VT.getSizeInBits()-1;
2567 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
2568 DAG.getConstant(Sum, N1C->getValueType(0)));
2572 // fold (sra (shl X, m), (sub result_size, n))
2573 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
2574 // result_size - n != m.
2575 // If truncate is free for the target sext(shl) is likely to result in better
2577 if (N0.getOpcode() == ISD::SHL) {
2578 // Get the two constanst of the shifts, CN0 = m, CN = n.
2579 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2581 // Determine what the truncate's result bitsize and type would be.
2582 unsigned VTValSize = VT.getSizeInBits();
2584 EVT::getIntegerVT(*DAG.getContext(), VTValSize - N1C->getZExtValue());
2585 // Determine the residual right-shift amount.
2586 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
2588 // If the shift is not a no-op (in which case this should be just a sign
2589 // extend already), the truncated to type is legal, sign_extend is legal
2590 // on that type, and the the truncate to that type is both legal and free,
2591 // perform the transform.
2592 if ((ShiftAmt > 0) &&
2593 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
2594 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
2595 TLI.isTruncateFree(VT, TruncVT)) {
2597 SDValue Amt = DAG.getConstant(ShiftAmt, getShiftAmountTy());
2598 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
2599 N0.getOperand(0), Amt);
2600 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
2602 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
2603 N->getValueType(0), Trunc);
2608 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
2609 if (N1.getOpcode() == ISD::TRUNCATE &&
2610 N1.getOperand(0).getOpcode() == ISD::AND &&
2611 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2612 SDValue N101 = N1.getOperand(0).getOperand(1);
2613 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2614 EVT TruncVT = N1.getValueType();
2615 SDValue N100 = N1.getOperand(0).getOperand(0);
2616 APInt TruncC = N101C->getAPIntValue();
2617 TruncC.trunc(TruncVT.getSizeInBits());
2618 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
2619 DAG.getNode(ISD::AND, N->getDebugLoc(),
2621 DAG.getNode(ISD::TRUNCATE,
2624 DAG.getConstant(TruncC, TruncVT)));
2628 // Simplify, based on bits shifted out of the LHS.
2629 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2630 return SDValue(N, 0);
2633 // If the sign bit is known to be zero, switch this to a SRL.
2634 if (DAG.SignBitIsZero(N0))
2635 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
2637 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2640 SDValue DAGCombiner::visitSRL(SDNode *N) {
2641 SDValue N0 = N->getOperand(0);
2642 SDValue N1 = N->getOperand(1);
2643 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2644 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2645 EVT VT = N0.getValueType();
2646 unsigned OpSizeInBits = VT.getSizeInBits();
2648 // fold (srl c1, c2) -> c1 >>u c2
2650 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
2651 // fold (srl 0, x) -> 0
2652 if (N0C && N0C->isNullValue())
2654 // fold (srl x, c >= size(x)) -> undef
2655 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2656 return DAG.getUNDEF(VT);
2657 // fold (srl x, 0) -> x
2658 if (N1C && N1C->isNullValue())
2660 // if (srl x, c) is known to be zero, return 0
2661 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2662 APInt::getAllOnesValue(OpSizeInBits)))
2663 return DAG.getConstant(0, VT);
2665 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
2666 if (N1C && N0.getOpcode() == ISD::SRL &&
2667 N0.getOperand(1).getOpcode() == ISD::Constant) {
2668 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2669 uint64_t c2 = N1C->getZExtValue();
2670 if (c1 + c2 > OpSizeInBits)
2671 return DAG.getConstant(0, VT);
2672 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
2673 DAG.getConstant(c1 + c2, N1.getValueType()));
2676 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2677 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2678 // Shifting in all undef bits?
2679 EVT SmallVT = N0.getOperand(0).getValueType();
2680 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
2681 return DAG.getUNDEF(VT);
2683 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
2684 N0.getOperand(0), N1);
2685 AddToWorkList(SmallShift.getNode());
2686 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
2689 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2690 // bit, which is unmodified by sra.
2691 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
2692 if (N0.getOpcode() == ISD::SRA)
2693 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
2696 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2697 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2698 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
2699 APInt KnownZero, KnownOne;
2700 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
2701 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2703 // If any of the input bits are KnownOne, then the input couldn't be all
2704 // zeros, thus the result of the srl will always be zero.
2705 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
2707 // If all of the bits input the to ctlz node are known to be zero, then
2708 // the result of the ctlz is "32" and the result of the shift is one.
2709 APInt UnknownBits = ~KnownZero & Mask;
2710 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2712 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2713 if ((UnknownBits & (UnknownBits - 1)) == 0) {
2714 // Okay, we know that only that the single bit specified by UnknownBits
2715 // could be set on input to the CTLZ node. If this bit is set, the SRL
2716 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2717 // to an SRL/XOR pair, which is likely to simplify more.
2718 unsigned ShAmt = UnknownBits.countTrailingZeros();
2719 SDValue Op = N0.getOperand(0);
2722 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
2723 DAG.getConstant(ShAmt, getShiftAmountTy()));
2724 AddToWorkList(Op.getNode());
2727 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
2728 Op, DAG.getConstant(1, VT));
2732 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
2733 if (N1.getOpcode() == ISD::TRUNCATE &&
2734 N1.getOperand(0).getOpcode() == ISD::AND &&
2735 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2736 SDValue N101 = N1.getOperand(0).getOperand(1);
2737 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2738 EVT TruncVT = N1.getValueType();
2739 SDValue N100 = N1.getOperand(0).getOperand(0);
2740 APInt TruncC = N101C->getAPIntValue();
2741 TruncC.trunc(TruncVT.getSizeInBits());
2742 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
2743 DAG.getNode(ISD::AND, N->getDebugLoc(),
2745 DAG.getNode(ISD::TRUNCATE,
2748 DAG.getConstant(TruncC, TruncVT)));
2752 // fold operands of srl based on knowledge that the low bits are not
2754 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2755 return SDValue(N, 0);
2757 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2760 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
2761 SDValue N0 = N->getOperand(0);
2762 EVT VT = N->getValueType(0);
2764 // fold (ctlz c1) -> c2
2765 if (isa<ConstantSDNode>(N0))
2766 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
2770 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
2771 SDValue N0 = N->getOperand(0);
2772 EVT VT = N->getValueType(0);
2774 // fold (cttz c1) -> c2
2775 if (isa<ConstantSDNode>(N0))
2776 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
2780 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
2781 SDValue N0 = N->getOperand(0);
2782 EVT VT = N->getValueType(0);
2784 // fold (ctpop c1) -> c2
2785 if (isa<ConstantSDNode>(N0))
2786 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
2790 SDValue DAGCombiner::visitSELECT(SDNode *N) {
2791 SDValue N0 = N->getOperand(0);
2792 SDValue N1 = N->getOperand(1);
2793 SDValue N2 = N->getOperand(2);
2794 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2795 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2796 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2797 EVT VT = N->getValueType(0);
2798 EVT VT0 = N0.getValueType();
2800 // fold (select C, X, X) -> X
2803 // fold (select true, X, Y) -> X
2804 if (N0C && !N0C->isNullValue())
2806 // fold (select false, X, Y) -> Y
2807 if (N0C && N0C->isNullValue())
2809 // fold (select C, 1, X) -> (or C, X)
2810 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
2811 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
2812 // fold (select C, 0, 1) -> (xor C, 1)
2813 if (VT.isInteger() &&
2816 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) &&
2817 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
2820 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
2821 N0, DAG.getConstant(1, VT0));
2822 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
2823 N0, DAG.getConstant(1, VT0));
2824 AddToWorkList(XORNode.getNode());
2826 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
2827 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
2829 // fold (select C, 0, X) -> (and (not C), X)
2830 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2831 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
2832 AddToWorkList(NOTNode.getNode());
2833 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
2835 // fold (select C, X, 1) -> (or (not C), X)
2836 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
2837 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
2838 AddToWorkList(NOTNode.getNode());
2839 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
2841 // fold (select C, X, 0) -> (and C, X)
2842 if (VT == MVT::i1 && N2C && N2C->isNullValue())
2843 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
2844 // fold (select X, X, Y) -> (or X, Y)
2845 // fold (select X, 1, Y) -> (or X, Y)
2846 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
2847 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
2848 // fold (select X, Y, X) -> (and X, Y)
2849 // fold (select X, Y, 0) -> (and X, Y)
2850 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
2851 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
2853 // If we can fold this based on the true/false value, do so.
2854 if (SimplifySelectOps(N, N1, N2))
2855 return SDValue(N, 0); // Don't revisit N.
2857 // fold selects based on a setcc into other things, such as min/max/abs
2858 if (N0.getOpcode() == ISD::SETCC) {
2860 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2861 // having to say they don't support SELECT_CC on every type the DAG knows
2862 // about, since there is no way to mark an opcode illegal at all value types
2863 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
2864 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
2865 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
2866 N0.getOperand(0), N0.getOperand(1),
2867 N1, N2, N0.getOperand(2));
2868 return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
2874 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
2875 SDValue N0 = N->getOperand(0);
2876 SDValue N1 = N->getOperand(1);
2877 SDValue N2 = N->getOperand(2);
2878 SDValue N3 = N->getOperand(3);
2879 SDValue N4 = N->getOperand(4);
2880 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2882 // fold select_cc lhs, rhs, x, x, cc -> x
2886 // Determine if the condition we're dealing with is constant
2887 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
2888 N0, N1, CC, N->getDebugLoc(), false);
2889 if (SCC.getNode()) AddToWorkList(SCC.getNode());
2891 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
2892 if (!SCCC->isNullValue())
2893 return N2; // cond always true -> true val
2895 return N3; // cond always false -> false val
2898 // Fold to a simpler select_cc
2899 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
2900 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
2901 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2904 // If we can fold this based on the true/false value, do so.
2905 if (SimplifySelectOps(N, N2, N3))
2906 return SDValue(N, 0); // Don't revisit N.
2908 // fold select_cc into other things, such as min/max/abs
2909 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
2912 SDValue DAGCombiner::visitSETCC(SDNode *N) {
2913 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2914 cast<CondCodeSDNode>(N->getOperand(2))->get(),
2918 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2919 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
2920 // transformation. Returns true if extension are possible and the above
2921 // mentioned transformation is profitable.
2922 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
2924 SmallVector<SDNode*, 4> &ExtendNodes,
2925 const TargetLowering &TLI) {
2926 bool HasCopyToRegUses = false;
2927 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2928 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
2929 UE = N0.getNode()->use_end();
2934 if (UI.getUse().getResNo() != N0.getResNo())
2936 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2937 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
2938 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2939 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2940 // Sign bits will be lost after a zext.
2943 for (unsigned i = 0; i != 2; ++i) {
2944 SDValue UseOp = User->getOperand(i);
2947 if (!isa<ConstantSDNode>(UseOp))
2952 ExtendNodes.push_back(User);
2955 // If truncates aren't free and there are users we can't
2956 // extend, it isn't worthwhile.
2959 // Remember if this value is live-out.
2960 if (User->getOpcode() == ISD::CopyToReg)
2961 HasCopyToRegUses = true;
2964 if (HasCopyToRegUses) {
2965 bool BothLiveOut = false;
2966 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2968 SDUse &Use = UI.getUse();
2969 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
2975 // Both unextended and extended values are live out. There had better be
2976 // good a reason for the transformation.
2977 return ExtendNodes.size();
2982 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2983 SDValue N0 = N->getOperand(0);
2984 EVT VT = N->getValueType(0);
2986 // fold (sext c1) -> c1
2987 if (isa<ConstantSDNode>(N0))
2988 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
2990 // fold (sext (sext x)) -> (sext x)
2991 // fold (sext (aext x)) -> (sext x)
2992 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2993 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
2996 if (N0.getOpcode() == ISD::TRUNCATE) {
2997 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2998 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2999 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3000 if (NarrowLoad.getNode()) {
3001 if (NarrowLoad.getNode() != N0.getNode())
3002 CombineTo(N0.getNode(), NarrowLoad);
3003 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3006 // See if the value being truncated is already sign extended. If so, just
3007 // eliminate the trunc/sext pair.
3008 SDValue Op = N0.getOperand(0);
3009 unsigned OpBits = Op.getValueType().getSizeInBits();
3010 unsigned MidBits = N0.getValueType().getSizeInBits();
3011 unsigned DestBits = VT.getSizeInBits();
3012 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
3014 if (OpBits == DestBits) {
3015 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
3016 // bits, it is already ready.
3017 if (NumSignBits > DestBits-MidBits)
3019 } else if (OpBits < DestBits) {
3020 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
3021 // bits, just sext from i32.
3022 if (NumSignBits > OpBits-MidBits)
3023 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
3025 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
3026 // bits, just truncate to i32.
3027 if (NumSignBits > OpBits-MidBits)
3028 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3031 // fold (sext (truncate x)) -> (sextinreg x).
3032 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
3033 N0.getValueType())) {
3034 if (Op.getValueType().bitsLT(VT))
3035 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
3036 else if (Op.getValueType().bitsGT(VT))
3037 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
3038 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
3039 DAG.getValueType(N0.getValueType()));
3043 // fold (sext (load x)) -> (sext (truncate (sextload x)))
3044 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3045 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3046 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
3047 bool DoXform = true;
3048 SmallVector<SDNode*, 4> SetCCs;
3049 if (!N0.hasOneUse())
3050 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
3052 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3053 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3055 LN0->getBasePtr(), LN0->getSrcValue(),
3056 LN0->getSrcValueOffset(),
3058 LN0->isVolatile(), LN0->getAlignment());
3059 CombineTo(N, ExtLoad);
3060 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3061 N0.getValueType(), ExtLoad);
3062 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3064 // Extend SetCC uses if necessary.
3065 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3066 SDNode *SetCC = SetCCs[i];
3067 SmallVector<SDValue, 4> Ops;
3069 for (unsigned j = 0; j != 2; ++j) {
3070 SDValue SOp = SetCC->getOperand(j);
3072 Ops.push_back(ExtLoad);
3074 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND,
3075 N->getDebugLoc(), VT, SOp));
3078 Ops.push_back(SetCC->getOperand(2));
3079 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3080 SetCC->getValueType(0),
3081 &Ops[0], Ops.size()));
3084 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3088 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
3089 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
3090 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3091 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3092 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3093 EVT MemVT = LN0->getMemoryVT();
3094 if ((!LegalOperations && !LN0->isVolatile()) ||
3095 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
3096 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3098 LN0->getBasePtr(), LN0->getSrcValue(),
3099 LN0->getSrcValueOffset(), MemVT,
3100 LN0->isVolatile(), LN0->getAlignment());
3101 CombineTo(N, ExtLoad);
3102 CombineTo(N0.getNode(),
3103 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3104 N0.getValueType(), ExtLoad),
3105 ExtLoad.getValue(1));
3106 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3110 if (N0.getOpcode() == ISD::SETCC) {
3111 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
3112 if (VT.isVector() &&
3113 // We know that the # elements of the results is the same as the
3114 // # elements of the compare (and the # elements of the compare result
3115 // for that matter). Check to see that they are the same size. If so,
3116 // we know that the element size of the sext'd result matches the
3117 // element size of the compare operands.
3118 VT.getSizeInBits() == N0.getOperand(0).getValueType().getSizeInBits() &&
3120 // Only do this before legalize for now.
3122 return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3124 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3127 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
3129 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
3131 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3132 NegOne, DAG.getConstant(0, VT),
3133 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3134 if (SCC.getNode()) return SCC;
3139 // fold (sext x) -> (zext x) if the sign bit is known zero.
3140 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
3141 DAG.SignBitIsZero(N0))
3142 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3147 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
3148 SDValue N0 = N->getOperand(0);
3149 EVT VT = N->getValueType(0);
3151 // fold (zext c1) -> c1
3152 if (isa<ConstantSDNode>(N0))
3153 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3154 // fold (zext (zext x)) -> (zext x)
3155 // fold (zext (aext x)) -> (zext x)
3156 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3157 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
3160 // fold (zext (truncate (load x))) -> (zext (smaller load x))
3161 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
3162 if (N0.getOpcode() == ISD::TRUNCATE) {
3163 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3164 if (NarrowLoad.getNode()) {
3165 if (NarrowLoad.getNode() != N0.getNode())
3166 CombineTo(N0.getNode(), NarrowLoad);
3167 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3171 // fold (zext (truncate x)) -> (and x, mask)
3172 if (N0.getOpcode() == ISD::TRUNCATE &&
3173 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
3174 SDValue Op = N0.getOperand(0);
3175 if (Op.getValueType().bitsLT(VT)) {
3176 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
3177 } else if (Op.getValueType().bitsGT(VT)) {
3178 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3180 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(), N0.getValueType());
3183 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
3184 // if either of the casts is not free.
3185 if (N0.getOpcode() == ISD::AND &&
3186 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3187 N0.getOperand(1).getOpcode() == ISD::Constant &&
3188 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3189 N0.getValueType()) ||
3190 !TLI.isZExtFree(N0.getValueType(), VT))) {
3191 SDValue X = N0.getOperand(0).getOperand(0);
3192 if (X.getValueType().bitsLT(VT)) {
3193 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
3194 } else if (X.getValueType().bitsGT(VT)) {
3195 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3197 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3198 Mask.zext(VT.getSizeInBits());
3199 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3200 X, DAG.getConstant(Mask, VT));
3203 // fold (zext (load x)) -> (zext (truncate (zextload x)))
3204 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3205 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3206 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
3207 bool DoXform = true;
3208 SmallVector<SDNode*, 4> SetCCs;
3209 if (!N0.hasOneUse())
3210 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
3212 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3213 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3215 LN0->getBasePtr(), LN0->getSrcValue(),
3216 LN0->getSrcValueOffset(),
3218 LN0->isVolatile(), LN0->getAlignment());
3219 CombineTo(N, ExtLoad);
3220 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3221 N0.getValueType(), ExtLoad);
3222 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3224 // Extend SetCC uses if necessary.
3225 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3226 SDNode *SetCC = SetCCs[i];
3227 SmallVector<SDValue, 4> Ops;
3229 for (unsigned j = 0; j != 2; ++j) {
3230 SDValue SOp = SetCC->getOperand(j);
3232 Ops.push_back(ExtLoad);
3234 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND,
3235 N->getDebugLoc(), VT, SOp));
3238 Ops.push_back(SetCC->getOperand(2));
3239 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3240 SetCC->getValueType(0),
3241 &Ops[0], Ops.size()));
3244 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3248 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
3249 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
3250 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3251 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3252 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3253 EVT MemVT = LN0->getMemoryVT();
3254 if ((!LegalOperations && !LN0->isVolatile()) ||
3255 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
3256 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3258 LN0->getBasePtr(), LN0->getSrcValue(),
3259 LN0->getSrcValueOffset(), MemVT,
3260 LN0->isVolatile(), LN0->getAlignment());
3261 CombineTo(N, ExtLoad);
3262 CombineTo(N0.getNode(),
3263 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
3265 ExtLoad.getValue(1));
3266 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3270 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3271 if (N0.getOpcode() == ISD::SETCC) {
3273 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3274 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3275 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3276 if (SCC.getNode()) return SCC;
3282 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
3283 SDValue N0 = N->getOperand(0);
3284 EVT VT = N->getValueType(0);
3286 // fold (aext c1) -> c1
3287 if (isa<ConstantSDNode>(N0))
3288 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
3289 // fold (aext (aext x)) -> (aext x)
3290 // fold (aext (zext x)) -> (zext x)
3291 // fold (aext (sext x)) -> (sext x)
3292 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3293 N0.getOpcode() == ISD::ZERO_EXTEND ||
3294 N0.getOpcode() == ISD::SIGN_EXTEND)
3295 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
3297 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3298 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3299 if (N0.getOpcode() == ISD::TRUNCATE) {
3300 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3301 if (NarrowLoad.getNode()) {
3302 if (NarrowLoad.getNode() != N0.getNode())
3303 CombineTo(N0.getNode(), NarrowLoad);
3304 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3308 // fold (aext (truncate x))
3309 if (N0.getOpcode() == ISD::TRUNCATE) {
3310 SDValue TruncOp = N0.getOperand(0);
3311 if (TruncOp.getValueType() == VT)
3312 return TruncOp; // x iff x size == zext size.
3313 if (TruncOp.getValueType().bitsGT(VT))
3314 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
3315 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
3318 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
3319 // if the trunc is not free.
3320 if (N0.getOpcode() == ISD::AND &&
3321 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3322 N0.getOperand(1).getOpcode() == ISD::Constant &&
3323 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3324 N0.getValueType())) {
3325 SDValue X = N0.getOperand(0).getOperand(0);
3326 if (X.getValueType().bitsLT(VT)) {
3327 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
3328 } else if (X.getValueType().bitsGT(VT)) {
3329 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
3331 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3332 Mask.zext(VT.getSizeInBits());
3333 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3334 X, DAG.getConstant(Mask, VT));
3337 // fold (aext (load x)) -> (aext (truncate (extload x)))
3338 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3339 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3340 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
3341 bool DoXform = true;
3342 SmallVector<SDNode*, 4> SetCCs;
3343 if (!N0.hasOneUse())
3344 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
3346 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3347 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
3349 LN0->getBasePtr(), LN0->getSrcValue(),
3350 LN0->getSrcValueOffset(),
3352 LN0->isVolatile(), LN0->getAlignment());
3353 CombineTo(N, ExtLoad);
3354 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3355 N0.getValueType(), ExtLoad);
3356 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3358 // Extend SetCC uses if necessary.
3359 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3360 SDNode *SetCC = SetCCs[i];
3361 SmallVector<SDValue, 4> Ops;
3363 for (unsigned j = 0; j != 2; ++j) {
3364 SDValue SOp = SetCC->getOperand(j);
3366 Ops.push_back(ExtLoad);
3368 Ops.push_back(DAG.getNode(ISD::ANY_EXTEND,
3369 N->getDebugLoc(), VT, SOp));
3372 Ops.push_back(SetCC->getOperand(2));
3373 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3374 SetCC->getValueType(0),
3375 &Ops[0], Ops.size()));
3378 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3382 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3383 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3384 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3385 if (N0.getOpcode() == ISD::LOAD &&
3386 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3388 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3389 EVT MemVT = LN0->getMemoryVT();
3390 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
3391 VT, LN0->getChain(), LN0->getBasePtr(),
3393 LN0->getSrcValueOffset(), MemVT,
3394 LN0->isVolatile(), LN0->getAlignment());
3395 CombineTo(N, ExtLoad);
3396 CombineTo(N0.getNode(),
3397 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3398 N0.getValueType(), ExtLoad),
3399 ExtLoad.getValue(1));
3400 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3403 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3404 if (N0.getOpcode() == ISD::SETCC) {
3406 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3407 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3408 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3416 /// GetDemandedBits - See if the specified operand can be simplified with the
3417 /// knowledge that only the bits specified by Mask are used. If so, return the
3418 /// simpler operand, otherwise return a null SDValue.
3419 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
3420 switch (V.getOpcode()) {
3424 // If the LHS or RHS don't contribute bits to the or, drop them.
3425 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3426 return V.getOperand(1);
3427 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3428 return V.getOperand(0);
3431 // Only look at single-use SRLs.
3432 if (!V.getNode()->hasOneUse())
3434 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3435 // See if we can recursively simplify the LHS.
3436 unsigned Amt = RHSC->getZExtValue();
3438 // Watch out for shift count overflow though.
3439 if (Amt >= Mask.getBitWidth()) break;
3440 APInt NewMask = Mask << Amt;
3441 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3442 if (SimplifyLHS.getNode())
3443 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
3444 SimplifyLHS, V.getOperand(1));
3450 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3451 /// bits and then truncated to a narrower type and where N is a multiple
3452 /// of number of bits of the narrower type, transform it to a narrower load
3453 /// from address + N / num of bits of new type. If the result is to be
3454 /// extended, also fold the extension to form a extending load.
3455 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
3456 unsigned Opc = N->getOpcode();
3457 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3458 SDValue N0 = N->getOperand(0);
3459 EVT VT = N->getValueType(0);
3462 // This transformation isn't valid for vector loads.
3466 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3468 if (Opc == ISD::SIGN_EXTEND_INREG) {
3469 ExtType = ISD::SEXTLOAD;
3470 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3471 if (LegalOperations && !TLI.isLoadExtLegal(ISD::SEXTLOAD, ExtVT))
3475 unsigned EVTBits = ExtVT.getSizeInBits();
3477 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse() && ExtVT.isRound()) {
3478 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3479 ShAmt = N01->getZExtValue();
3480 // Is the shift amount a multiple of size of VT?
3481 if ((ShAmt & (EVTBits-1)) == 0) {
3482 N0 = N0.getOperand(0);
3483 // Is the load width a multiple of size of VT?
3484 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
3490 // Do not generate loads of non-round integer types since these can
3491 // be expensive (and would be wrong if the type is not byte sized).
3492 if (isa<LoadSDNode>(N0) && N0.hasOneUse() && ExtVT.isRound() &&
3493 cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() > EVTBits &&
3494 // Do not change the width of a volatile load.
3495 !cast<LoadSDNode>(N0)->isVolatile()) {
3496 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3497 EVT PtrType = N0.getOperand(1).getValueType();
3499 // For big endian targets, we need to adjust the offset to the pointer to
3500 // load the correct bytes.
3501 if (TLI.isBigEndian()) {
3502 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
3503 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
3504 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3507 uint64_t PtrOff = ShAmt / 8;
3508 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3509 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
3510 PtrType, LN0->getBasePtr(),
3511 DAG.getConstant(PtrOff, PtrType));
3512 AddToWorkList(NewPtr.getNode());
3514 SDValue Load = (ExtType == ISD::NON_EXTLOAD)
3515 ? DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
3516 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3517 LN0->isVolatile(), NewAlign)
3518 : DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(), NewPtr,
3519 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3520 ExtVT, LN0->isVolatile(), NewAlign);
3522 // Replace the old load's chain with the new load's chain.
3523 WorkListRemover DeadNodes(*this);
3524 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3527 // Return the new loaded value.
3534 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3535 SDValue N0 = N->getOperand(0);
3536 SDValue N1 = N->getOperand(1);
3537 EVT VT = N->getValueType(0);
3538 EVT EVT = cast<VTSDNode>(N1)->getVT();
3539 unsigned VTBits = VT.getSizeInBits();
3540 unsigned EVTBits = EVT.getSizeInBits();
3542 // fold (sext_in_reg c1) -> c1
3543 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3544 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
3546 // If the input is already sign extended, just drop the extension.
3547 if (DAG.ComputeNumSignBits(N0) >= VT.getSizeInBits()-EVTBits+1)
3550 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3551 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3552 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
3553 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3554 N0.getOperand(0), N1);
3557 // fold (sext_in_reg (sext x)) -> (sext x)
3558 // fold (sext_in_reg (aext x)) -> (sext x)
3559 // if x is small enough.
3560 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
3561 SDValue N00 = N0.getOperand(0);
3562 if (N00.getValueType().getSizeInBits() < EVTBits)
3563 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
3566 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3567 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3568 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
3570 // fold operands of sext_in_reg based on knowledge that the top bits are not
3572 if (SimplifyDemandedBits(SDValue(N, 0)))
3573 return SDValue(N, 0);
3575 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3576 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3577 SDValue NarrowLoad = ReduceLoadWidth(N);
3578 if (NarrowLoad.getNode())
3581 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
3582 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
3583 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3584 if (N0.getOpcode() == ISD::SRL) {
3585 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3586 if (ShAmt->getZExtValue()+EVTBits <= VT.getSizeInBits()) {
3587 // We can turn this into an SRA iff the input to the SRL is already sign
3589 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3590 if (VT.getSizeInBits()-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
3591 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
3592 N0.getOperand(0), N0.getOperand(1));
3596 // fold (sext_inreg (extload x)) -> (sextload x)
3597 if (ISD::isEXTLoad(N0.getNode()) &&
3598 ISD::isUNINDEXEDLoad(N0.getNode()) &&
3599 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3600 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3601 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3602 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3603 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3605 LN0->getBasePtr(), LN0->getSrcValue(),
3606 LN0->getSrcValueOffset(), EVT,
3607 LN0->isVolatile(), LN0->getAlignment());
3608 CombineTo(N, ExtLoad);
3609 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3610 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3612 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3613 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3615 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3616 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3617 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3618 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3619 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3621 LN0->getBasePtr(), LN0->getSrcValue(),
3622 LN0->getSrcValueOffset(), EVT,
3623 LN0->isVolatile(), LN0->getAlignment());
3624 CombineTo(N, ExtLoad);
3625 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3626 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3631 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
3632 SDValue N0 = N->getOperand(0);
3633 EVT VT = N->getValueType(0);
3636 if (N0.getValueType() == N->getValueType(0))
3638 // fold (truncate c1) -> c1
3639 if (isa<ConstantSDNode>(N0))
3640 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
3641 // fold (truncate (truncate x)) -> (truncate x)
3642 if (N0.getOpcode() == ISD::TRUNCATE)
3643 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
3644 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3645 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3646 N0.getOpcode() == ISD::ANY_EXTEND) {
3647 if (N0.getOperand(0).getValueType().bitsLT(VT))
3648 // if the source is smaller than the dest, we still need an extend
3649 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
3651 else if (N0.getOperand(0).getValueType().bitsGT(VT))
3652 // if the source is larger than the dest, than we just need the truncate
3653 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
3655 // if the source and dest are the same type, we can drop both the extend
3657 return N0.getOperand(0);
3660 // See if we can simplify the input to this truncate through knowledge that
3661 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3664 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3665 VT.getSizeInBits()));
3666 if (Shorter.getNode())
3667 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
3669 // fold (truncate (load x)) -> (smaller load x)
3670 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3671 return ReduceLoadWidth(N);
3674 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
3675 SDValue Elt = N->getOperand(i);
3676 if (Elt.getOpcode() != ISD::MERGE_VALUES)
3677 return Elt.getNode();
3678 return Elt.getOperand(Elt.getResNo()).getNode();
3681 /// CombineConsecutiveLoads - build_pair (load, load) -> load
3682 /// if load locations are consecutive.
3683 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
3684 assert(N->getOpcode() == ISD::BUILD_PAIR);
3686 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
3687 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
3688 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
3690 EVT LD1VT = LD1->getValueType(0);
3692 if (ISD::isNON_EXTLoad(LD2) &&
3694 // If both are volatile this would reduce the number of volatile loads.
3695 // If one is volatile it might be ok, but play conservative and bail out.
3696 !LD1->isVolatile() &&
3697 !LD2->isVolatile() &&
3698 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
3699 unsigned Align = LD1->getAlignment();
3700 unsigned NewAlign = TLI.getTargetData()->
3701 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
3703 if (NewAlign <= Align &&
3704 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
3705 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
3706 LD1->getBasePtr(), LD1->getSrcValue(),
3707 LD1->getSrcValueOffset(), false, Align);
3713 SDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3714 SDValue N0 = N->getOperand(0);
3715 EVT VT = N->getValueType(0);
3717 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3718 // Only do this before legalize, since afterward the target may be depending
3719 // on the bitconvert.
3720 // First check to see if this is all constant.
3722 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
3724 bool isSimple = true;
3725 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3726 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3727 N0.getOperand(i).getOpcode() != ISD::Constant &&
3728 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3733 EVT DestEltVT = N->getValueType(0).getVectorElementType();
3734 assert(!DestEltVT.isVector() &&
3735 "Element type of vector ValueType must not be vector!");
3737 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT);
3740 // If the input is a constant, let getNode fold it.
3741 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3742 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, N0);
3743 if (Res.getNode() != N) {
3744 if (!LegalOperations ||
3745 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
3748 // Folding it resulted in an illegal node, and it's too late to
3749 // do that. Clean up the old node and forego the transformation.
3750 // Ideally this won't happen very often, because instcombine
3751 // and the earlier dagcombine runs (where illegal nodes are
3752 // permitted) should have folded most of them already.
3753 DAG.DeleteNode(Res.getNode());
3757 // (conv (conv x, t1), t2) -> (conv x, t2)
3758 if (N0.getOpcode() == ISD::BIT_CONVERT)
3759 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT,
3762 // fold (conv (load x)) -> (load (conv*)x)
3763 // If the resultant load doesn't need a higher alignment than the original!
3764 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
3765 // Do not change the width of a volatile load.
3766 !cast<LoadSDNode>(N0)->isVolatile() &&
3767 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
3768 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3769 unsigned Align = TLI.getTargetData()->
3770 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
3771 unsigned OrigAlign = LN0->getAlignment();
3773 if (Align <= OrigAlign) {
3774 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
3776 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3777 LN0->isVolatile(), OrigAlign);
3779 CombineTo(N0.getNode(),
3780 DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
3781 N0.getValueType(), Load),
3787 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
3788 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
3789 // This often reduces constant pool loads.
3790 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3791 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
3792 SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(), VT,
3794 AddToWorkList(NewConv.getNode());
3796 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3797 if (N0.getOpcode() == ISD::FNEG)
3798 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3799 NewConv, DAG.getConstant(SignBit, VT));
3800 assert(N0.getOpcode() == ISD::FABS);
3801 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3802 NewConv, DAG.getConstant(~SignBit, VT));
3805 // fold (bitconvert (fcopysign cst, x)) ->
3806 // (or (and (bitconvert x), sign), (and cst, (not sign)))
3807 // Note that we don't handle (copysign x, cst) because this can always be
3808 // folded to an fneg or fabs.
3809 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
3810 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3811 VT.isInteger() && !VT.isVector()) {
3812 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
3813 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
3814 if (TLI.isTypeLegal(IntXVT) || !LegalTypes) {
3815 SDValue X = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
3816 IntXVT, N0.getOperand(1));
3817 AddToWorkList(X.getNode());
3819 // If X has a different width than the result/lhs, sext it or truncate it.
3820 unsigned VTWidth = VT.getSizeInBits();
3821 if (OrigXWidth < VTWidth) {
3822 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
3823 AddToWorkList(X.getNode());
3824 } else if (OrigXWidth > VTWidth) {
3825 // To get the sign bit in the right place, we have to shift it right
3826 // before truncating.
3827 X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
3828 X.getValueType(), X,
3829 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3830 AddToWorkList(X.getNode());
3831 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3832 AddToWorkList(X.getNode());
3835 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3836 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
3837 X, DAG.getConstant(SignBit, VT));
3838 AddToWorkList(X.getNode());
3840 SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
3841 VT, N0.getOperand(0));
3842 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
3843 Cst, DAG.getConstant(~SignBit, VT));
3844 AddToWorkList(Cst.getNode());
3846 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
3850 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
3851 if (N0.getOpcode() == ISD::BUILD_PAIR) {
3852 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
3853 if (CombineLD.getNode())
3860 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
3861 EVT VT = N->getValueType(0);
3862 return CombineConsecutiveLoads(N, VT);
3865 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3866 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3867 /// destination element value type.
3868 SDValue DAGCombiner::
3869 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
3870 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
3872 // If this is already the right type, we're done.
3873 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
3875 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
3876 unsigned DstBitSize = DstEltVT.getSizeInBits();
3878 // If this is a conversion of N elements of one type to N elements of another
3879 // type, convert each element. This handles FP<->INT cases.
3880 if (SrcBitSize == DstBitSize) {
3881 SmallVector<SDValue, 8> Ops;
3882 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3883 SDValue Op = BV->getOperand(i);
3884 // If the vector element type is not legal, the BUILD_VECTOR operands
3885 // are promoted and implicitly truncated. Make that explicit here.
3886 if (Op.getValueType() != SrcEltVT)
3887 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
3888 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, BV->getDebugLoc(),
3890 AddToWorkList(Ops.back().getNode());
3892 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
3893 BV->getValueType(0).getVectorNumElements());
3894 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
3895 &Ops[0], Ops.size());
3898 // Otherwise, we're growing or shrinking the elements. To avoid having to
3899 // handle annoying details of growing/shrinking FP values, we convert them to
3901 if (SrcEltVT.isFloatingPoint()) {
3902 // Convert the input float vector to a int vector where the elements are the
3904 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3905 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
3906 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode();
3910 // Now we know the input is an integer vector. If the output is a FP type,
3911 // convert to integer first, then to FP of the right size.
3912 if (DstEltVT.isFloatingPoint()) {
3913 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3914 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
3915 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode();
3917 // Next, convert to FP elements of the same size.
3918 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3921 // Okay, we know the src/dst types are both integers of differing types.
3922 // Handling growing first.
3923 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
3924 if (SrcBitSize < DstBitSize) {
3925 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3927 SmallVector<SDValue, 8> Ops;
3928 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3929 i += NumInputsPerOutput) {
3930 bool isLE = TLI.isLittleEndian();
3931 APInt NewBits = APInt(DstBitSize, 0);
3932 bool EltIsUndef = true;
3933 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3934 // Shift the previously computed bits over.
3935 NewBits <<= SrcBitSize;
3936 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3937 if (Op.getOpcode() == ISD::UNDEF) continue;
3940 NewBits |= (APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).
3941 zextOrTrunc(SrcBitSize).zext(DstBitSize));
3945 Ops.push_back(DAG.getUNDEF(DstEltVT));
3947 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3950 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
3951 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
3952 &Ops[0], Ops.size());
3955 // Finally, this must be the case where we are shrinking elements: each input
3956 // turns into multiple outputs.
3957 bool isS2V = ISD::isScalarToVector(BV);
3958 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3959 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
3960 NumOutputsPerInput*BV->getNumOperands());
3961 SmallVector<SDValue, 8> Ops;
3963 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3964 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3965 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3966 Ops.push_back(DAG.getUNDEF(DstEltVT));
3970 APInt OpVal = APInt(cast<ConstantSDNode>(BV->getOperand(i))->
3971 getAPIntValue()).zextOrTrunc(SrcBitSize);
3973 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3974 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
3975 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3976 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
3977 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3978 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
3980 OpVal = OpVal.lshr(DstBitSize);
3983 // For big endian targets, swap the order of the pieces of each element.
3984 if (TLI.isBigEndian())
3985 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3988 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
3989 &Ops[0], Ops.size());
3992 SDValue DAGCombiner::visitFADD(SDNode *N) {
3993 SDValue N0 = N->getOperand(0);
3994 SDValue N1 = N->getOperand(1);
3995 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3996 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3997 EVT VT = N->getValueType(0);
4000 if (VT.isVector()) {
4001 SDValue FoldedVOp = SimplifyVBinOp(N);
4002 if (FoldedVOp.getNode()) return FoldedVOp;
4005 // fold (fadd c1, c2) -> (fadd c1, c2)
4006 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4007 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
4008 // canonicalize constant to RHS
4009 if (N0CFP && !N1CFP)
4010 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
4011 // fold (fadd A, 0) -> A
4012 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4014 // fold (fadd A, (fneg B)) -> (fsub A, B)
4015 if (isNegatibleForFree(N1, LegalOperations) == 2)
4016 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
4017 GetNegatedExpression(N1, DAG, LegalOperations));
4018 // fold (fadd (fneg A), B) -> (fsub B, A)
4019 if (isNegatibleForFree(N0, LegalOperations) == 2)
4020 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
4021 GetNegatedExpression(N0, DAG, LegalOperations));
4023 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
4024 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
4025 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4026 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
4027 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
4028 N0.getOperand(1), N1));
4033 SDValue DAGCombiner::visitFSUB(SDNode *N) {
4034 SDValue N0 = N->getOperand(0);
4035 SDValue N1 = N->getOperand(1);
4036 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4037 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4038 EVT VT = N->getValueType(0);
4041 if (VT.isVector()) {
4042 SDValue FoldedVOp = SimplifyVBinOp(N);
4043 if (FoldedVOp.getNode()) return FoldedVOp;
4046 // fold (fsub c1, c2) -> c1-c2
4047 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4048 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
4049 // fold (fsub A, 0) -> A
4050 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4052 // fold (fsub 0, B) -> -B
4053 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
4054 if (isNegatibleForFree(N1, LegalOperations))
4055 return GetNegatedExpression(N1, DAG, LegalOperations);
4056 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4057 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
4059 // fold (fsub A, (fneg B)) -> (fadd A, B)
4060 if (isNegatibleForFree(N1, LegalOperations))
4061 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
4062 GetNegatedExpression(N1, DAG, LegalOperations));
4067 SDValue DAGCombiner::visitFMUL(SDNode *N) {
4068 SDValue N0 = N->getOperand(0);
4069 SDValue N1 = N->getOperand(1);
4070 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4071 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4072 EVT VT = N->getValueType(0);
4075 if (VT.isVector()) {
4076 SDValue FoldedVOp = SimplifyVBinOp(N);
4077 if (FoldedVOp.getNode()) return FoldedVOp;
4080 // fold (fmul c1, c2) -> c1*c2
4081 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4082 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
4083 // canonicalize constant to RHS
4084 if (N0CFP && !N1CFP)
4085 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
4086 // fold (fmul A, 0) -> 0
4087 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4089 // fold (fmul A, 0) -> 0, vector edition.
4090 if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
4092 // fold (fmul X, 2.0) -> (fadd X, X)
4093 if (N1CFP && N1CFP->isExactlyValue(+2.0))
4094 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
4095 // fold (fmul X, -1.0) -> (fneg X)
4096 if (N1CFP && N1CFP->isExactlyValue(-1.0))
4097 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4098 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
4100 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
4101 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4102 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4103 // Both can be negated for free, check to see if at least one is cheaper
4105 if (LHSNeg == 2 || RHSNeg == 2)
4106 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4107 GetNegatedExpression(N0, DAG, LegalOperations),
4108 GetNegatedExpression(N1, DAG, LegalOperations));
4112 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
4113 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
4114 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4115 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
4116 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4117 N0.getOperand(1), N1));
4122 SDValue DAGCombiner::visitFDIV(SDNode *N) {
4123 SDValue N0 = N->getOperand(0);
4124 SDValue N1 = N->getOperand(1);
4125 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4126 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4127 EVT VT = N->getValueType(0);
4130 if (VT.isVector()) {
4131 SDValue FoldedVOp = SimplifyVBinOp(N);
4132 if (FoldedVOp.getNode()) return FoldedVOp;
4135 // fold (fdiv c1, c2) -> c1/c2
4136 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4137 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
4140 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
4141 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4142 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4143 // Both can be negated for free, check to see if at least one is cheaper
4145 if (LHSNeg == 2 || RHSNeg == 2)
4146 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
4147 GetNegatedExpression(N0, DAG, LegalOperations),
4148 GetNegatedExpression(N1, DAG, LegalOperations));
4155 SDValue DAGCombiner::visitFREM(SDNode *N) {
4156 SDValue N0 = N->getOperand(0);
4157 SDValue N1 = N->getOperand(1);
4158 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4159 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4160 EVT VT = N->getValueType(0);
4162 // fold (frem c1, c2) -> fmod(c1,c2)
4163 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4164 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
4169 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
4170 SDValue N0 = N->getOperand(0);
4171 SDValue N1 = N->getOperand(1);
4172 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4173 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4174 EVT VT = N->getValueType(0);
4176 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
4177 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
4180 const APFloat& V = N1CFP->getValueAPF();
4181 // copysign(x, c1) -> fabs(x) iff ispos(c1)
4182 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
4183 if (!V.isNegative()) {
4184 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
4185 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4187 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4188 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
4189 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
4193 // copysign(fabs(x), y) -> copysign(x, y)
4194 // copysign(fneg(x), y) -> copysign(x, y)
4195 // copysign(copysign(x,z), y) -> copysign(x, y)
4196 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
4197 N0.getOpcode() == ISD::FCOPYSIGN)
4198 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4199 N0.getOperand(0), N1);
4201 // copysign(x, abs(y)) -> abs(x)
4202 if (N1.getOpcode() == ISD::FABS)
4203 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4205 // copysign(x, copysign(y,z)) -> copysign(x, z)
4206 if (N1.getOpcode() == ISD::FCOPYSIGN)
4207 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4208 N0, N1.getOperand(1));
4210 // copysign(x, fp_extend(y)) -> copysign(x, y)
4211 // copysign(x, fp_round(y)) -> copysign(x, y)
4212 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
4213 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4214 N0, N1.getOperand(0));
4219 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
4220 SDValue N0 = N->getOperand(0);
4221 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4222 EVT VT = N->getValueType(0);
4223 EVT OpVT = N0.getValueType();
4225 // fold (sint_to_fp c1) -> c1fp
4226 if (N0C && OpVT != MVT::ppcf128)
4227 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4229 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
4230 // but UINT_TO_FP is legal on this target, try to convert.
4231 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
4232 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
4233 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
4234 if (DAG.SignBitIsZero(N0))
4235 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4241 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
4242 SDValue N0 = N->getOperand(0);
4243 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4244 EVT VT = N->getValueType(0);
4245 EVT OpVT = N0.getValueType();
4247 // fold (uint_to_fp c1) -> c1fp
4248 if (N0C && OpVT != MVT::ppcf128)
4249 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4251 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
4252 // but SINT_TO_FP is legal on this target, try to convert.
4253 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
4254 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
4255 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
4256 if (DAG.SignBitIsZero(N0))
4257 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4263 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
4264 SDValue N0 = N->getOperand(0);
4265 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4266 EVT VT = N->getValueType(0);
4268 // fold (fp_to_sint c1fp) -> c1
4270 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
4275 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
4276 SDValue N0 = N->getOperand(0);
4277 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4278 EVT VT = N->getValueType(0);
4280 // fold (fp_to_uint c1fp) -> c1
4281 if (N0CFP && VT != MVT::ppcf128)
4282 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
4287 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
4288 SDValue N0 = N->getOperand(0);
4289 SDValue N1 = N->getOperand(1);
4290 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4291 EVT VT = N->getValueType(0);
4293 // fold (fp_round c1fp) -> c1fp
4294 if (N0CFP && N0.getValueType() != MVT::ppcf128)
4295 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
4297 // fold (fp_round (fp_extend x)) -> x
4298 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
4299 return N0.getOperand(0);
4301 // fold (fp_round (fp_round x)) -> (fp_round x)
4302 if (N0.getOpcode() == ISD::FP_ROUND) {
4303 // This is a value preserving truncation if both round's are.
4304 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
4305 N0.getNode()->getConstantOperandVal(1) == 1;
4306 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
4307 DAG.getIntPtrConstant(IsTrunc));
4310 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
4311 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
4312 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
4313 N0.getOperand(0), N1);
4314 AddToWorkList(Tmp.getNode());
4315 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4316 Tmp, N0.getOperand(1));
4322 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
4323 SDValue N0 = N->getOperand(0);
4324 EVT VT = N->getValueType(0);
4325 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4326 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4328 // fold (fp_round_inreg c1fp) -> c1fp
4329 if (N0CFP && (TLI.isTypeLegal(EVT) || !LegalTypes)) {
4330 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
4331 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
4337 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
4338 SDValue N0 = N->getOperand(0);
4339 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4340 EVT VT = N->getValueType(0);
4342 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
4343 if (N->hasOneUse() &&
4344 N->use_begin()->getOpcode() == ISD::FP_ROUND)
4347 // fold (fp_extend c1fp) -> c1fp
4348 if (N0CFP && VT != MVT::ppcf128)
4349 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
4351 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
4353 if (N0.getOpcode() == ISD::FP_ROUND
4354 && N0.getNode()->getConstantOperandVal(1) == 1) {
4355 SDValue In = N0.getOperand(0);
4356 if (In.getValueType() == VT) return In;
4357 if (VT.bitsLT(In.getValueType()))
4358 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
4359 In, N0.getOperand(1));
4360 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
4363 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
4364 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
4365 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4366 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4367 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4368 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4370 LN0->getBasePtr(), LN0->getSrcValue(),
4371 LN0->getSrcValueOffset(),
4373 LN0->isVolatile(), LN0->getAlignment());
4374 CombineTo(N, ExtLoad);
4375 CombineTo(N0.getNode(),
4376 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
4377 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
4378 ExtLoad.getValue(1));
4379 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4385 SDValue DAGCombiner::visitFNEG(SDNode *N) {
4386 SDValue N0 = N->getOperand(0);
4387 EVT VT = N->getValueType(0);
4389 if (isNegatibleForFree(N0, LegalOperations))
4390 return GetNegatedExpression(N0, DAG, LegalOperations);
4392 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
4393 // constant pool values.
4394 if (N0.getOpcode() == ISD::BIT_CONVERT &&
4396 N0.getNode()->hasOneUse() &&
4397 N0.getOperand(0).getValueType().isInteger()) {
4398 SDValue Int = N0.getOperand(0);
4399 EVT IntVT = Int.getValueType();
4400 if (IntVT.isInteger() && !IntVT.isVector()) {
4401 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
4402 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4403 AddToWorkList(Int.getNode());
4404 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4412 SDValue DAGCombiner::visitFABS(SDNode *N) {
4413 SDValue N0 = N->getOperand(0);
4414 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4415 EVT VT = N->getValueType(0);
4417 // fold (fabs c1) -> fabs(c1)
4418 if (N0CFP && VT != MVT::ppcf128)
4419 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4420 // fold (fabs (fabs x)) -> (fabs x)
4421 if (N0.getOpcode() == ISD::FABS)
4422 return N->getOperand(0);
4423 // fold (fabs (fneg x)) -> (fabs x)
4424 // fold (fabs (fcopysign x, y)) -> (fabs x)
4425 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4426 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
4428 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4429 // constant pool values.
4430 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
4431 N0.getOperand(0).getValueType().isInteger() &&
4432 !N0.getOperand(0).getValueType().isVector()) {
4433 SDValue Int = N0.getOperand(0);
4434 EVT IntVT = Int.getValueType();
4435 if (IntVT.isInteger() && !IntVT.isVector()) {
4436 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
4437 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4438 AddToWorkList(Int.getNode());
4439 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4440 N->getValueType(0), Int);
4447 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
4448 SDValue Chain = N->getOperand(0);
4449 SDValue N1 = N->getOperand(1);
4450 SDValue N2 = N->getOperand(2);
4452 // If N is a constant we could fold this into a fallthrough or unconditional
4453 // branch. However that doesn't happen very often in normal code, because
4454 // Instcombine/SimplifyCFG should have handled the available opportunities.
4455 // If we did this folding here, it would be necessary to update the
4456 // MachineBasicBlock CFG, which is awkward.
4458 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4460 if (N1.getOpcode() == ISD::SETCC &&
4461 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
4462 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
4463 Chain, N1.getOperand(2),
4464 N1.getOperand(0), N1.getOperand(1), N2);
4467 if (N1.hasOneUse() && N1.getOpcode() == ISD::SRL) {
4468 // Match this pattern so that we can generate simpler code:
4471 // %b = and i32 %a, 2
4472 // %c = srl i32 %b, 1
4473 // brcond i32 %c ...
4479 // %c = setcc eq %b, 0
4482 // This applies only when the AND constant value has one bit set and the
4483 // SRL constant is equal to the log2 of the AND constant. The back-end is
4484 // smart enough to convert the result into a TEST/JMP sequence.
4485 SDValue Op0 = N1.getOperand(0);
4486 SDValue Op1 = N1.getOperand(1);
4488 if (Op0.getOpcode() == ISD::AND &&
4490 Op1.getOpcode() == ISD::Constant) {
4491 SDValue AndOp1 = Op0.getOperand(1);
4493 if (AndOp1.getOpcode() == ISD::Constant) {
4494 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
4496 if (AndConst.isPowerOf2() &&
4497 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
4499 DAG.getSetCC(N->getDebugLoc(),
4500 TLI.getSetCCResultType(Op0.getValueType()),
4501 Op0, DAG.getConstant(0, Op0.getValueType()),
4504 // Replace the uses of SRL with SETCC
4505 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
4506 removeFromWorkList(N1.getNode());
4507 DAG.DeleteNode(N1.getNode());
4508 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
4509 MVT::Other, Chain, SetCC, N2);
4518 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4520 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
4521 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4522 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4524 // If N is a constant we could fold this into a fallthrough or unconditional
4525 // branch. However that doesn't happen very often in normal code, because
4526 // Instcombine/SimplifyCFG should have handled the available opportunities.
4527 // If we did this folding here, it would be necessary to update the
4528 // MachineBasicBlock CFG, which is awkward.
4530 // Use SimplifySetCC to simplify SETCC's.
4531 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
4532 CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
4534 if (Simp.getNode()) AddToWorkList(Simp.getNode());
4536 // fold to a simpler setcc
4537 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
4538 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
4539 N->getOperand(0), Simp.getOperand(2),
4540 Simp.getOperand(0), Simp.getOperand(1),
4546 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
4547 /// pre-indexed load / store when the base pointer is an add or subtract
4548 /// and it has other uses besides the load / store. After the
4549 /// transformation, the new indexed load / store has effectively folded
4550 /// the add / subtract in and all of its other uses are redirected to the
4551 /// new load / store.
4552 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4553 if (!LegalOperations)
4559 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4560 if (LD->isIndexed())
4562 VT = LD->getMemoryVT();
4563 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4564 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4566 Ptr = LD->getBasePtr();
4567 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4568 if (ST->isIndexed())
4570 VT = ST->getMemoryVT();
4571 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4572 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4574 Ptr = ST->getBasePtr();
4580 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4581 // out. There is no reason to make this a preinc/predec.
4582 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4583 Ptr.getNode()->hasOneUse())
4586 // Ask the target to do addressing mode selection.
4589 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4590 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4592 // Don't create a indexed load / store with zero offset.
4593 if (isa<ConstantSDNode>(Offset) &&
4594 cast<ConstantSDNode>(Offset)->isNullValue())
4597 // Try turning it into a pre-indexed load / store except when:
4598 // 1) The new base ptr is a frame index.
4599 // 2) If N is a store and the new base ptr is either the same as or is a
4600 // predecessor of the value being stored.
4601 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4602 // that would create a cycle.
4603 // 4) All uses are load / store ops that use it as old base ptr.
4605 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4606 // (plus the implicit offset) to a register to preinc anyway.
4607 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
4612 SDValue Val = cast<StoreSDNode>(N)->getValue();
4613 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
4617 // Now check for #3 and #4.
4618 bool RealUse = false;
4619 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
4620 E = Ptr.getNode()->use_end(); I != E; ++I) {
4624 if (Use->isPredecessorOf(N))
4627 if (!((Use->getOpcode() == ISD::LOAD &&
4628 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
4629 (Use->getOpcode() == ISD::STORE &&
4630 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
4639 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
4640 BasePtr, Offset, AM);
4642 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
4643 BasePtr, Offset, AM);
4646 DEBUG(errs() << "\nReplacing.4 ";
4648 errs() << "\nWith: ";
4649 Result.getNode()->dump(&DAG);
4651 WorkListRemover DeadNodes(*this);
4653 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
4655 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
4658 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
4662 // Finally, since the node is now dead, remove it from the graph.
4665 // Replace the uses of Ptr with uses of the updated base value.
4666 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
4668 removeFromWorkList(Ptr.getNode());
4669 DAG.DeleteNode(Ptr.getNode());
4674 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
4675 /// add / sub of the base pointer node into a post-indexed load / store.
4676 /// The transformation folded the add / subtract into the new indexed
4677 /// load / store effectively and all of its uses are redirected to the
4678 /// new load / store.
4679 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4680 if (!LegalOperations)
4686 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4687 if (LD->isIndexed())
4689 VT = LD->getMemoryVT();
4690 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4691 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4693 Ptr = LD->getBasePtr();
4694 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4695 if (ST->isIndexed())
4697 VT = ST->getMemoryVT();
4698 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4699 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4701 Ptr = ST->getBasePtr();
4707 if (Ptr.getNode()->hasOneUse())
4710 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
4711 E = Ptr.getNode()->use_end(); I != E; ++I) {
4714 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4719 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4720 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4721 if (Ptr == Offset && Op->getOpcode() == ISD::ADD)
4722 std::swap(BasePtr, Offset);
4725 // Don't create a indexed load / store with zero offset.
4726 if (isa<ConstantSDNode>(Offset) &&
4727 cast<ConstantSDNode>(Offset)->isNullValue())
4730 // Try turning it into a post-indexed load / store except when
4731 // 1) All uses are load / store ops that use it as base ptr.
4732 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4733 // nor a successor of N. Otherwise, if Op is folded that would
4736 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
4740 bool TryNext = false;
4741 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
4742 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
4744 if (Use == Ptr.getNode())
4747 // If all the uses are load / store addresses, then don't do the
4749 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4750 bool RealUse = false;
4751 for (SDNode::use_iterator III = Use->use_begin(),
4752 EEE = Use->use_end(); III != EEE; ++III) {
4753 SDNode *UseUse = *III;
4754 if (!((UseUse->getOpcode() == ISD::LOAD &&
4755 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
4756 (UseUse->getOpcode() == ISD::STORE &&
4757 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
4772 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
4773 SDValue Result = isLoad
4774 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
4775 BasePtr, Offset, AM)
4776 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
4777 BasePtr, Offset, AM);
4780 DEBUG(errs() << "\nReplacing.5 ";
4782 errs() << "\nWith: ";
4783 Result.getNode()->dump(&DAG);
4785 WorkListRemover DeadNodes(*this);
4787 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
4789 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
4792 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
4796 // Finally, since the node is now dead, remove it from the graph.
4799 // Replace the uses of Use with uses of the updated base value.
4800 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
4801 Result.getValue(isLoad ? 1 : 0),
4803 removeFromWorkList(Op);
4813 SDValue DAGCombiner::visitLOAD(SDNode *N) {
4814 LoadSDNode *LD = cast<LoadSDNode>(N);
4815 SDValue Chain = LD->getChain();
4816 SDValue Ptr = LD->getBasePtr();
4818 // Try to infer better alignment information than the load already has.
4819 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
4820 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
4821 if (Align > LD->getAlignment())
4822 return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
4823 LD->getValueType(0),
4824 Chain, Ptr, LD->getSrcValue(),
4825 LD->getSrcValueOffset(), LD->getMemoryVT(),
4826 LD->isVolatile(), Align);
4830 // If load is not volatile and there are no uses of the loaded value (and
4831 // the updated indexed value in case of indexed loads), change uses of the
4832 // chain value into uses of the chain input (i.e. delete the dead load).
4833 if (!LD->isVolatile()) {
4834 if (N->getValueType(1) == MVT::Other) {
4836 if (N->hasNUsesOfValue(0, 0)) {
4837 // It's not safe to use the two value CombineTo variant here. e.g.
4838 // v1, chain2 = load chain1, loc
4839 // v2, chain3 = load chain2, loc
4841 // Now we replace use of chain2 with chain1. This makes the second load
4842 // isomorphic to the one we are deleting, and thus makes this load live.
4843 DEBUG(errs() << "\nReplacing.6 ";
4845 errs() << "\nWith chain: ";
4846 Chain.getNode()->dump(&DAG);
4848 WorkListRemover DeadNodes(*this);
4849 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
4851 if (N->use_empty()) {
4852 removeFromWorkList(N);
4856 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4860 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4861 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
4862 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
4863 DEBUG(errs() << "\nReplacing.6 ";
4865 errs() << "\nWith: ";
4866 Undef.getNode()->dump(&DAG);
4867 errs() << " and 2 other values\n");
4868 WorkListRemover DeadNodes(*this);
4869 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
4870 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
4871 DAG.getUNDEF(N->getValueType(1)),
4873 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
4874 removeFromWorkList(N);
4876 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4881 // If this load is directly stored, replace the load value with the stored
4883 // TODO: Handle store large -> read small portion.
4884 // TODO: Handle TRUNCSTORE/LOADEXT
4885 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
4886 !LD->isVolatile()) {
4887 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
4888 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4889 if (PrevST->getBasePtr() == Ptr &&
4890 PrevST->getValue().getValueType() == N->getValueType(0))
4891 return CombineTo(N, Chain.getOperand(1), Chain);
4896 // Walk up chain skipping non-aliasing memory nodes.
4897 SDValue BetterChain = FindBetterChain(N, Chain);
4899 // If there is a better chain.
4900 if (Chain != BetterChain) {
4903 // Replace the chain to void dependency.
4904 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4905 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
4907 LD->getSrcValue(), LD->getSrcValueOffset(),
4908 LD->isVolatile(), LD->getAlignment());
4910 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
4911 LD->getValueType(0),
4912 BetterChain, Ptr, LD->getSrcValue(),
4913 LD->getSrcValueOffset(),
4916 LD->getAlignment());
4919 // Create token factor to keep old chain connected.
4920 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
4921 MVT::Other, Chain, ReplLoad.getValue(1));
4923 // Make sure the new and old chains are cleaned up.
4924 AddToWorkList(Token.getNode());
4926 // Replace uses with load result and token factor. Don't add users
4928 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4932 // Try transforming N to an indexed load.
4933 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4934 return SDValue(N, 0);
4940 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
4941 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
4942 /// of the loaded bits, try narrowing the load and store if it would end up
4943 /// being a win for performance or code size.
4944 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
4945 StoreSDNode *ST = cast<StoreSDNode>(N);
4946 if (ST->isVolatile())
4949 SDValue Chain = ST->getChain();
4950 SDValue Value = ST->getValue();
4951 SDValue Ptr = ST->getBasePtr();
4952 EVT VT = Value.getValueType();
4954 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
4957 unsigned Opc = Value.getOpcode();
4958 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
4959 Value.getOperand(1).getOpcode() != ISD::Constant)
4962 SDValue N0 = Value.getOperand(0);
4963 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
4964 LoadSDNode *LD = cast<LoadSDNode>(N0);
4965 if (LD->getBasePtr() != Ptr)
4968 // Find the type to narrow it the load / op / store to.
4969 SDValue N1 = Value.getOperand(1);
4970 unsigned BitWidth = N1.getValueSizeInBits();
4971 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
4972 if (Opc == ISD::AND)
4973 Imm ^= APInt::getAllOnesValue(BitWidth);
4974 if (Imm == 0 || Imm.isAllOnesValue())
4976 unsigned ShAmt = Imm.countTrailingZeros();
4977 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
4978 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
4979 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
4980 while (NewBW < BitWidth &&
4981 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
4982 TLI.isNarrowingProfitable(VT, NewVT))) {
4983 NewBW = NextPowerOf2(NewBW);
4984 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
4986 if (NewBW >= BitWidth)
4989 // If the lsb changed does not start at the type bitwidth boundary,
4990 // start at the previous one.
4992 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
4993 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
4994 if ((Imm & Mask) == Imm) {
4995 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
4996 if (Opc == ISD::AND)
4997 NewImm ^= APInt::getAllOnesValue(NewBW);
4998 uint64_t PtrOff = ShAmt / 8;
4999 // For big endian targets, we need to adjust the offset to the pointer to
5000 // load the correct bytes.
5001 if (TLI.isBigEndian())
5002 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
5004 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
5006 TLI.getTargetData()->getABITypeAlignment(NewVT.getTypeForEVT(*DAG.getContext())))
5009 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
5010 Ptr.getValueType(), Ptr,
5011 DAG.getConstant(PtrOff, Ptr.getValueType()));
5012 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
5013 LD->getChain(), NewPtr,
5014 LD->getSrcValue(), LD->getSrcValueOffset(),
5015 LD->isVolatile(), NewAlign);
5016 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
5017 DAG.getConstant(NewImm, NewVT));
5018 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
5020 ST->getSrcValue(), ST->getSrcValueOffset(),
5023 AddToWorkList(NewPtr.getNode());
5024 AddToWorkList(NewLD.getNode());
5025 AddToWorkList(NewVal.getNode());
5026 WorkListRemover DeadNodes(*this);
5027 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
5037 SDValue DAGCombiner::visitSTORE(SDNode *N) {
5038 StoreSDNode *ST = cast<StoreSDNode>(N);
5039 SDValue Chain = ST->getChain();
5040 SDValue Value = ST->getValue();
5041 SDValue Ptr = ST->getBasePtr();
5043 // Try to infer better alignment information than the store already has.
5044 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
5045 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5046 if (Align > ST->getAlignment())
5047 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
5048 Ptr, ST->getSrcValue(),
5049 ST->getSrcValueOffset(), ST->getMemoryVT(),
5050 ST->isVolatile(), Align);
5054 // If this is a store of a bit convert, store the input value if the
5055 // resultant store does not need a higher alignment than the original.
5056 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
5057 ST->isUnindexed()) {
5058 unsigned OrigAlign = ST->getAlignment();
5059 EVT SVT = Value.getOperand(0).getValueType();
5060 unsigned Align = TLI.getTargetData()->
5061 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
5062 if (Align <= OrigAlign &&
5063 ((!LegalOperations && !ST->isVolatile()) ||
5064 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
5065 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5066 Ptr, ST->getSrcValue(),
5067 ST->getSrcValueOffset(), ST->isVolatile(), OrigAlign);
5070 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
5071 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
5072 // NOTE: If the original store is volatile, this transform must not increase
5073 // the number of stores. For example, on x86-32 an f64 can be stored in one
5074 // processor operation but an i64 (which is not legal) requires two. So the
5075 // transform should not be done in this case.
5076 if (Value.getOpcode() != ISD::TargetConstantFP) {
5078 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
5079 default: llvm_unreachable("Unknown FP type");
5080 case MVT::f80: // We don't do this for these yet.
5085 if (((TLI.isTypeLegal(MVT::i32) || !LegalTypes) && !LegalOperations &&
5086 !ST->isVolatile()) ||
5087 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5088 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
5089 bitcastToAPInt().getZExtValue(), MVT::i32);
5090 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5091 Ptr, ST->getSrcValue(),
5092 ST->getSrcValueOffset(), ST->isVolatile(),
5093 ST->getAlignment());
5097 if (((TLI.isTypeLegal(MVT::i64) || !LegalTypes) && !LegalOperations &&
5098 !ST->isVolatile()) ||
5099 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
5100 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
5101 getZExtValue(), MVT::i64);
5102 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5103 Ptr, ST->getSrcValue(),
5104 ST->getSrcValueOffset(), ST->isVolatile(),
5105 ST->getAlignment());
5106 } else if (!ST->isVolatile() &&
5107 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5108 // Many FP stores are not made apparent until after legalize, e.g. for
5109 // argument passing. Since this is so common, custom legalize the
5110 // 64-bit integer store into two 32-bit stores.
5111 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
5112 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
5113 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
5114 if (TLI.isBigEndian()) std::swap(Lo, Hi);
5116 int SVOffset = ST->getSrcValueOffset();
5117 unsigned Alignment = ST->getAlignment();
5118 bool isVolatile = ST->isVolatile();
5120 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
5121 Ptr, ST->getSrcValue(),
5122 ST->getSrcValueOffset(),
5123 isVolatile, ST->getAlignment());
5124 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
5125 DAG.getConstant(4, Ptr.getValueType()));
5127 Alignment = MinAlign(Alignment, 4U);
5128 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
5129 Ptr, ST->getSrcValue(),
5130 SVOffset, isVolatile, Alignment);
5131 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
5141 // Walk up chain skipping non-aliasing memory nodes.
5142 SDValue BetterChain = FindBetterChain(N, Chain);
5144 // If there is a better chain.
5145 if (Chain != BetterChain) {
5148 // Replace the chain to avoid dependency.
5149 if (ST->isTruncatingStore()) {
5150 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5151 ST->getSrcValue(),ST->getSrcValueOffset(),
5153 ST->isVolatile(), ST->getAlignment());
5155 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5156 ST->getSrcValue(), ST->getSrcValueOffset(),
5157 ST->isVolatile(), ST->getAlignment());
5160 // Create token to keep both nodes around.
5161 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5162 MVT::Other, Chain, ReplStore);
5164 // Make sure the new and old chains are cleaned up.
5165 AddToWorkList(Token.getNode());
5167 // Don't add users to work list.
5168 return CombineTo(N, Token, false);
5172 // Try transforming N to an indexed store.
5173 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5174 return SDValue(N, 0);
5176 // FIXME: is there such a thing as a truncating indexed store?
5177 if (ST->isTruncatingStore() && ST->isUnindexed() &&
5178 Value.getValueType().isInteger()) {
5179 // See if we can simplify the input to this truncstore with knowledge that
5180 // only the low bits are being used. For example:
5181 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
5183 GetDemandedBits(Value,
5184 APInt::getLowBitsSet(Value.getValueSizeInBits(),
5185 ST->getMemoryVT().getSizeInBits()));
5186 AddToWorkList(Value.getNode());
5187 if (Shorter.getNode())
5188 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
5189 Ptr, ST->getSrcValue(),
5190 ST->getSrcValueOffset(), ST->getMemoryVT(),
5191 ST->isVolatile(), ST->getAlignment());
5193 // Otherwise, see if we can simplify the operation with
5194 // SimplifyDemandedBits, which only works if the value has a single use.
5195 if (SimplifyDemandedBits(Value,
5196 APInt::getLowBitsSet(
5197 Value.getValueSizeInBits(),
5198 ST->getMemoryVT().getSizeInBits())))
5199 return SDValue(N, 0);
5202 // If this is a load followed by a store to the same location, then the store
5204 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
5205 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
5206 ST->isUnindexed() && !ST->isVolatile() &&
5207 // There can't be any side effects between the load and store, such as
5209 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
5210 // The store is dead, remove it.
5215 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
5216 // truncating store. We can do this even if this is already a truncstore.
5217 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
5218 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
5219 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
5220 ST->getMemoryVT())) {
5221 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5222 Ptr, ST->getSrcValue(),
5223 ST->getSrcValueOffset(), ST->getMemoryVT(),
5224 ST->isVolatile(), ST->getAlignment());
5227 return ReduceLoadOpStoreWidth(N);
5230 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
5231 SDValue InVec = N->getOperand(0);
5232 SDValue InVal = N->getOperand(1);
5233 SDValue EltNo = N->getOperand(2);
5235 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
5236 // vector with the inserted element.
5237 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
5238 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5239 SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
5240 InVec.getNode()->op_end());
5241 if (Elt < Ops.size())
5243 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5244 InVec.getValueType(), &Ops[0], Ops.size());
5246 // If the invec is an UNDEF and if EltNo is a constant, create a new
5247 // BUILD_VECTOR with undef elements and the inserted element.
5248 if (!LegalOperations && InVec.getOpcode() == ISD::UNDEF &&
5249 isa<ConstantSDNode>(EltNo)) {
5250 EVT VT = InVec.getValueType();
5251 EVT EltVT = VT.getVectorElementType();
5252 unsigned NElts = VT.getVectorNumElements();
5253 SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EltVT));
5255 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5256 if (Elt < Ops.size())
5258 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5259 InVec.getValueType(), &Ops[0], Ops.size());
5264 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
5265 // (vextract (scalar_to_vector val, 0) -> val
5266 SDValue InVec = N->getOperand(0);
5268 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5269 // If the operand is wider than the vector element type then it is implicitly
5270 // truncated. Make that explicit here.
5271 EVT EltVT = InVec.getValueType().getVectorElementType();
5272 SDValue InOp = InVec.getOperand(0);
5273 if (InOp.getValueType() != EltVT)
5274 return DAG.getNode(ISD::TRUNCATE, InVec.getDebugLoc(), EltVT, InOp);
5278 // Perform only after legalization to ensure build_vector / vector_shuffle
5279 // optimizations have already been done.
5280 if (!LegalOperations) return SDValue();
5282 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
5283 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
5284 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
5285 SDValue EltNo = N->getOperand(1);
5287 if (isa<ConstantSDNode>(EltNo)) {
5288 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5289 bool NewLoad = false;
5290 bool BCNumEltsChanged = false;
5291 EVT VT = InVec.getValueType();
5292 EVT ExtVT = VT.getVectorElementType();
5295 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
5296 EVT BCVT = InVec.getOperand(0).getValueType();
5297 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
5299 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
5300 BCNumEltsChanged = true;
5301 InVec = InVec.getOperand(0);
5302 ExtVT = BCVT.getVectorElementType();
5306 LoadSDNode *LN0 = NULL;
5307 const ShuffleVectorSDNode *SVN = NULL;
5308 if (ISD::isNormalLoad(InVec.getNode())) {
5309 LN0 = cast<LoadSDNode>(InVec);
5310 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5311 InVec.getOperand(0).getValueType() == ExtVT &&
5312 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
5313 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
5314 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
5315 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
5317 // (load $addr+1*size)
5319 // If the bit convert changed the number of elements, it is unsafe
5320 // to examine the mask.
5321 if (BCNumEltsChanged)
5324 // Select the input vector, guarding against out of range extract vector.
5325 unsigned NumElems = VT.getVectorNumElements();
5326 int Idx = (Elt > NumElems) ? -1 : SVN->getMaskElt(Elt);
5327 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
5329 if (InVec.getOpcode() == ISD::BIT_CONVERT)
5330 InVec = InVec.getOperand(0);
5331 if (ISD::isNormalLoad(InVec.getNode())) {
5332 LN0 = cast<LoadSDNode>(InVec);
5333 Elt = (Idx < (int)NumElems) ? Idx : Idx - NumElems;
5337 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
5340 unsigned Align = LN0->getAlignment();
5342 // Check the resultant load doesn't need a higher alignment than the
5345 TLI.getTargetData()->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
5347 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
5353 SDValue NewPtr = LN0->getBasePtr();
5355 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
5356 EVT PtrType = NewPtr.getValueType();
5357 if (TLI.isBigEndian())
5358 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
5359 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
5360 DAG.getConstant(PtrOff, PtrType));
5363 return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
5364 LN0->getSrcValue(), LN0->getSrcValueOffset(),
5365 LN0->isVolatile(), Align);
5371 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
5372 unsigned NumInScalars = N->getNumOperands();
5373 EVT VT = N->getValueType(0);
5375 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
5376 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
5377 // at most two distinct vectors, turn this into a shuffle node.
5378 SDValue VecIn1, VecIn2;
5379 for (unsigned i = 0; i != NumInScalars; ++i) {
5380 // Ignore undef inputs.
5381 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
5383 // If this input is something other than a EXTRACT_VECTOR_ELT with a
5384 // constant index, bail out.
5385 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5386 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
5387 VecIn1 = VecIn2 = SDValue(0, 0);
5391 // If the input vector type disagrees with the result of the build_vector,
5392 // we can't make a shuffle.
5393 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
5394 if (ExtractedFromVec.getValueType() != VT) {
5395 VecIn1 = VecIn2 = SDValue(0, 0);
5399 // Otherwise, remember this. We allow up to two distinct input vectors.
5400 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
5403 if (VecIn1.getNode() == 0) {
5404 VecIn1 = ExtractedFromVec;
5405 } else if (VecIn2.getNode() == 0) {
5406 VecIn2 = ExtractedFromVec;
5409 VecIn1 = VecIn2 = SDValue(0, 0);
5414 // If everything is good, we can make a shuffle operation.
5415 if (VecIn1.getNode()) {
5416 SmallVector<int, 8> Mask;
5417 for (unsigned i = 0; i != NumInScalars; ++i) {
5418 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
5423 // If extracting from the first vector, just use the index directly.
5424 SDValue Extract = N->getOperand(i);
5425 SDValue ExtVal = Extract.getOperand(1);
5426 if (Extract.getOperand(0) == VecIn1) {
5427 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
5428 if (ExtIndex > VT.getVectorNumElements())
5431 Mask.push_back(ExtIndex);
5435 // Otherwise, use InIdx + VecSize
5436 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
5437 Mask.push_back(Idx+NumInScalars);
5440 // Add count and size info.
5441 if (!TLI.isTypeLegal(VT) && LegalTypes)
5444 // Return the new VECTOR_SHUFFLE node.
5447 Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5448 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
5454 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
5455 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
5456 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
5457 // inputs come from at most two distinct vectors, turn this into a shuffle
5460 // If we only have one input vector, we don't need to do any concatenation.
5461 if (N->getNumOperands() == 1)
5462 return N->getOperand(0);
5467 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
5470 EVT VT = N->getValueType(0);
5471 unsigned NumElts = VT.getVectorNumElements();
5473 SDValue N0 = N->getOperand(0);
5475 assert(N0.getValueType().getVectorNumElements() == NumElts &&
5476 "Vector shuffle must be normalized in DAG");
5478 // FIXME: implement canonicalizations from DAG.getVectorShuffle()
5480 // If it is a splat, check if the argument vector is a build_vector with
5481 // all scalar elements the same.
5482 if (cast<ShuffleVectorSDNode>(N)->isSplat()) {
5483 SDNode *V = N0.getNode();
5486 // If this is a bit convert that changes the element type of the vector but
5487 // not the number of vector elements, look through it. Be careful not to
5488 // look though conversions that change things like v4f32 to v2f64.
5489 if (V->getOpcode() == ISD::BIT_CONVERT) {
5490 SDValue ConvInput = V->getOperand(0);
5491 if (ConvInput.getValueType().isVector() &&
5492 ConvInput.getValueType().getVectorNumElements() == NumElts)
5493 V = ConvInput.getNode();
5496 if (V->getOpcode() == ISD::BUILD_VECTOR) {
5497 unsigned NumElems = V->getNumOperands();
5498 unsigned BaseIdx = cast<ShuffleVectorSDNode>(N)->getSplatIndex();
5499 if (NumElems > BaseIdx) {
5501 bool AllSame = true;
5502 for (unsigned i = 0; i != NumElems; ++i) {
5503 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
5504 Base = V->getOperand(i);
5508 // Splat of <u, u, u, u>, return <u, u, u, u>
5509 if (!Base.getNode())
5511 for (unsigned i = 0; i != NumElems; ++i) {
5512 if (V->getOperand(i) != Base) {
5517 // Splat of <x, x, x, x>, return <x, x, x, x>
5526 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
5527 /// an AND to a vector_shuffle with the destination vector and a zero vector.
5528 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
5529 /// vector_shuffle V, Zero, <0, 4, 2, 4>
5530 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
5531 EVT VT = N->getValueType(0);
5532 DebugLoc dl = N->getDebugLoc();
5533 SDValue LHS = N->getOperand(0);
5534 SDValue RHS = N->getOperand(1);
5535 if (N->getOpcode() == ISD::AND) {
5536 if (RHS.getOpcode() == ISD::BIT_CONVERT)
5537 RHS = RHS.getOperand(0);
5538 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
5539 SmallVector<int, 8> Indices;
5540 unsigned NumElts = RHS.getNumOperands();
5541 for (unsigned i = 0; i != NumElts; ++i) {
5542 SDValue Elt = RHS.getOperand(i);
5543 if (!isa<ConstantSDNode>(Elt))
5545 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
5546 Indices.push_back(i);
5547 else if (cast<ConstantSDNode>(Elt)->isNullValue())
5548 Indices.push_back(NumElts);
5553 // Let's see if the target supports this vector_shuffle.
5554 EVT RVT = RHS.getValueType();
5555 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
5558 // Return the new VECTOR_SHUFFLE node.
5559 EVT EltVT = RVT.getVectorElementType();
5560 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
5561 DAG.getConstant(0, EltVT));
5562 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5563 RVT, &ZeroOps[0], ZeroOps.size());
5564 LHS = DAG.getNode(ISD::BIT_CONVERT, dl, RVT, LHS);
5565 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
5566 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuf);
5573 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
5574 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
5575 // After legalize, the target may be depending on adds and other
5576 // binary ops to provide legal ways to construct constants or other
5577 // things. Simplifying them may result in a loss of legality.
5578 if (LegalOperations) return SDValue();
5580 EVT VT = N->getValueType(0);
5581 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
5583 EVT EltType = VT.getVectorElementType();
5584 SDValue LHS = N->getOperand(0);
5585 SDValue RHS = N->getOperand(1);
5586 SDValue Shuffle = XformToShuffleWithZero(N);
5587 if (Shuffle.getNode()) return Shuffle;
5589 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
5591 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
5592 RHS.getOpcode() == ISD::BUILD_VECTOR) {
5593 SmallVector<SDValue, 8> Ops;
5594 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
5595 SDValue LHSOp = LHS.getOperand(i);
5596 SDValue RHSOp = RHS.getOperand(i);
5597 // If these two elements can't be folded, bail out.
5598 if ((LHSOp.getOpcode() != ISD::UNDEF &&
5599 LHSOp.getOpcode() != ISD::Constant &&
5600 LHSOp.getOpcode() != ISD::ConstantFP) ||
5601 (RHSOp.getOpcode() != ISD::UNDEF &&
5602 RHSOp.getOpcode() != ISD::Constant &&
5603 RHSOp.getOpcode() != ISD::ConstantFP))
5606 // Can't fold divide by zero.
5607 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
5608 N->getOpcode() == ISD::FDIV) {
5609 if ((RHSOp.getOpcode() == ISD::Constant &&
5610 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
5611 (RHSOp.getOpcode() == ISD::ConstantFP &&
5612 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
5616 Ops.push_back(DAG.getNode(N->getOpcode(), LHS.getDebugLoc(),
5617 EltType, LHSOp, RHSOp));
5618 AddToWorkList(Ops.back().getNode());
5619 assert((Ops.back().getOpcode() == ISD::UNDEF ||
5620 Ops.back().getOpcode() == ISD::Constant ||
5621 Ops.back().getOpcode() == ISD::ConstantFP) &&
5622 "Scalar binop didn't fold!");
5625 if (Ops.size() == LHS.getNumOperands()) {
5626 EVT VT = LHS.getValueType();
5627 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
5628 &Ops[0], Ops.size());
5635 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
5636 SDValue N1, SDValue N2){
5637 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
5639 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
5640 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5642 // If we got a simplified select_cc node back from SimplifySelectCC, then
5643 // break it down into a new SETCC node, and a new SELECT node, and then return
5644 // the SELECT node, since we were called with a SELECT node.
5645 if (SCC.getNode()) {
5646 // Check to see if we got a select_cc back (to turn into setcc/select).
5647 // Otherwise, just return whatever node we got back, like fabs.
5648 if (SCC.getOpcode() == ISD::SELECT_CC) {
5649 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
5651 SCC.getOperand(0), SCC.getOperand(1),
5653 AddToWorkList(SETCC.getNode());
5654 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
5655 SCC.getOperand(2), SCC.getOperand(3), SETCC);
5663 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5664 /// are the two values being selected between, see if we can simplify the
5665 /// select. Callers of this should assume that TheSelect is deleted if this
5666 /// returns true. As such, they should return the appropriate thing (e.g. the
5667 /// node) back to the top-level of the DAG combiner loop to avoid it being
5669 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
5672 // If this is a select from two identical things, try to pull the operation
5673 // through the select.
5674 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5675 // If this is a load and the token chain is identical, replace the select
5676 // of two loads with a load through a select of the address to load from.
5677 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5678 // constants have been dropped into the constant pool.
5679 if (LHS.getOpcode() == ISD::LOAD &&
5680 // Do not let this transformation reduce the number of volatile loads.
5681 !cast<LoadSDNode>(LHS)->isVolatile() &&
5682 !cast<LoadSDNode>(RHS)->isVolatile() &&
5683 // Token chains must be identical.
5684 LHS.getOperand(0) == RHS.getOperand(0)) {
5685 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5686 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5688 // If this is an EXTLOAD, the VT's must match.
5689 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
5690 // FIXME: this discards src value information. This is
5691 // over-conservative. It would be beneficial to be able to remember
5692 // both potential memory locations.
5694 if (TheSelect->getOpcode() == ISD::SELECT) {
5695 // Check that the condition doesn't reach either load. If so, folding
5696 // this will induce a cycle into the DAG.
5697 if ((!LLD->hasAnyUseOfValue(1) ||
5698 !LLD->isPredecessorOf(TheSelect->getOperand(0).getNode())) &&
5699 (!RLD->hasAnyUseOfValue(1) ||
5700 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()))) {
5701 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
5702 LLD->getBasePtr().getValueType(),
5703 TheSelect->getOperand(0), LLD->getBasePtr(),
5707 // Check that the condition doesn't reach either load. If so, folding
5708 // this will induce a cycle into the DAG.
5709 if ((!LLD->hasAnyUseOfValue(1) ||
5710 (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5711 !LLD->isPredecessorOf(TheSelect->getOperand(1).getNode()))) &&
5712 (!RLD->hasAnyUseOfValue(1) ||
5713 (!RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5714 !RLD->isPredecessorOf(TheSelect->getOperand(1).getNode())))) {
5715 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
5716 LLD->getBasePtr().getValueType(),
5717 TheSelect->getOperand(0),
5718 TheSelect->getOperand(1),
5719 LLD->getBasePtr(), RLD->getBasePtr(),
5720 TheSelect->getOperand(4));
5724 if (Addr.getNode()) {
5726 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
5727 Load = DAG.getLoad(TheSelect->getValueType(0),
5728 TheSelect->getDebugLoc(),
5732 LLD->getAlignment());
5734 Load = DAG.getExtLoad(LLD->getExtensionType(),
5735 TheSelect->getDebugLoc(),
5736 TheSelect->getValueType(0),
5737 LLD->getChain(), Addr, 0, 0,
5740 LLD->getAlignment());
5743 // Users of the select now use the result of the load.
5744 CombineTo(TheSelect, Load);
5746 // Users of the old loads now use the new load's chain. We know the
5747 // old-load value is dead now.
5748 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
5749 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
5759 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
5760 /// where 'cond' is the comparison specified by CC.
5761 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
5762 SDValue N2, SDValue N3,
5763 ISD::CondCode CC, bool NotExtCompare) {
5764 // (x ? y : y) -> y.
5765 if (N2 == N3) return N2;
5767 EVT VT = N2.getValueType();
5768 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
5769 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
5770 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
5772 // Determine if the condition we're dealing with is constant
5773 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
5774 N0, N1, CC, DL, false);
5775 if (SCC.getNode()) AddToWorkList(SCC.getNode());
5776 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
5778 // fold select_cc true, x, y -> x
5779 if (SCCC && !SCCC->isNullValue())
5781 // fold select_cc false, x, y -> y
5782 if (SCCC && SCCC->isNullValue())
5785 // Check to see if we can simplify the select into an fabs node
5786 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5787 // Allow either -0.0 or 0.0
5788 if (CFP->getValueAPF().isZero()) {
5789 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5790 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5791 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5792 N2 == N3.getOperand(0))
5793 return DAG.getNode(ISD::FABS, DL, VT, N0);
5795 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5796 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5797 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5798 N2.getOperand(0) == N3)
5799 return DAG.getNode(ISD::FABS, DL, VT, N3);
5803 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
5804 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
5805 // in it. This is a win when the constant is not otherwise available because
5806 // it replaces two constant pool loads with one. We only do this if the FP
5807 // type is known to be legal, because if it isn't, then we are before legalize
5808 // types an we want the other legalization to happen first (e.g. to avoid
5809 // messing with soft float) and if the ConstantFP is not legal, because if
5810 // it is legal, we may not need to store the FP constant in a constant pool.
5811 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
5812 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
5813 if (TLI.isTypeLegal(N2.getValueType()) &&
5814 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
5815 TargetLowering::Legal) &&
5816 // If both constants have multiple uses, then we won't need to do an
5817 // extra load, they are likely around in registers for other users.
5818 (TV->hasOneUse() || FV->hasOneUse())) {
5819 Constant *Elts[] = {
5820 const_cast<ConstantFP*>(FV->getConstantFPValue()),
5821 const_cast<ConstantFP*>(TV->getConstantFPValue())
5823 const Type *FPTy = Elts[0]->getType();
5824 const TargetData &TD = *TLI.getTargetData();
5826 // Create a ConstantArray of the two constants.
5827 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2);
5828 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
5829 TD.getPrefTypeAlignment(FPTy));
5830 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
5832 // Get the offsets to the 0 and 1 element of the array so that we can
5833 // select between them.
5834 SDValue Zero = DAG.getIntPtrConstant(0);
5835 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
5836 SDValue One = DAG.getIntPtrConstant(EltSize);
5838 SDValue Cond = DAG.getSetCC(DL,
5839 TLI.getSetCCResultType(N0.getValueType()),
5841 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
5843 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
5845 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
5846 PseudoSourceValue::getConstantPool(), 0, false,
5852 // Check to see if we can perform the "gzip trick", transforming
5853 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
5854 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5855 N0.getValueType().isInteger() &&
5856 N2.getValueType().isInteger() &&
5857 (N1C->isNullValue() || // (a < 0) ? b : 0
5858 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
5859 EVT XType = N0.getValueType();
5860 EVT AType = N2.getValueType();
5861 if (XType.bitsGE(AType)) {
5862 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5863 // single-bit constant.
5864 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
5865 unsigned ShCtV = N2C->getAPIntValue().logBase2();
5866 ShCtV = XType.getSizeInBits()-ShCtV-1;
5867 SDValue ShCt = DAG.getConstant(ShCtV, getShiftAmountTy());
5868 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
5870 AddToWorkList(Shift.getNode());
5872 if (XType.bitsGT(AType)) {
5873 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
5874 AddToWorkList(Shift.getNode());
5877 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
5880 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
5882 DAG.getConstant(XType.getSizeInBits()-1,
5883 getShiftAmountTy()));
5884 AddToWorkList(Shift.getNode());
5886 if (XType.bitsGT(AType)) {
5887 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
5888 AddToWorkList(Shift.getNode());
5891 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
5895 // fold select C, 16, 0 -> shl C, 4
5896 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
5897 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
5899 // If the caller doesn't want us to simplify this into a zext of a compare,
5901 if (NotExtCompare && N2C->getAPIntValue() == 1)
5904 // Get a SetCC of the condition
5905 // FIXME: Should probably make sure that setcc is legal if we ever have a
5906 // target where it isn't.
5908 // cast from setcc result type to select result type
5910 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
5912 if (N2.getValueType().bitsLT(SCC.getValueType()))
5913 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
5915 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
5916 N2.getValueType(), SCC);
5918 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
5919 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
5920 N2.getValueType(), SCC);
5923 AddToWorkList(SCC.getNode());
5924 AddToWorkList(Temp.getNode());
5926 if (N2C->getAPIntValue() == 1)
5929 // shl setcc result by log2 n2c
5930 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
5931 DAG.getConstant(N2C->getAPIntValue().logBase2(),
5932 getShiftAmountTy()));
5935 // Check to see if this is the equivalent of setcc
5936 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5937 // otherwise, go ahead with the folds.
5938 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
5939 EVT XType = N0.getValueType();
5940 if (!LegalOperations ||
5941 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
5942 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
5943 if (Res.getValueType() != VT)
5944 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
5948 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
5949 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5950 (!LegalOperations ||
5951 TLI.isOperationLegal(ISD::CTLZ, XType))) {
5952 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
5953 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
5954 DAG.getConstant(Log2_32(XType.getSizeInBits()),
5955 getShiftAmountTy()));
5957 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
5958 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5959 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
5960 XType, DAG.getConstant(0, XType), N0);
5961 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
5962 return DAG.getNode(ISD::SRL, DL, XType,
5963 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
5964 DAG.getConstant(XType.getSizeInBits()-1,
5965 getShiftAmountTy()));
5967 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
5968 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5969 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
5970 DAG.getConstant(XType.getSizeInBits()-1,
5971 getShiftAmountTy()));
5972 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
5976 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5977 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5978 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5979 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5980 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
5981 EVT XType = N0.getValueType();
5982 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType, N0,
5983 DAG.getConstant(XType.getSizeInBits()-1,
5984 getShiftAmountTy()));
5985 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(), XType,
5987 AddToWorkList(Shift.getNode());
5988 AddToWorkList(Add.getNode());
5989 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
5991 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5992 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5993 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5994 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5995 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5996 EVT XType = N0.getValueType();
5997 if (SubC->isNullValue() && XType.isInteger()) {
5998 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
6000 DAG.getConstant(XType.getSizeInBits()-1,
6001 getShiftAmountTy()));
6002 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
6004 AddToWorkList(Shift.getNode());
6005 AddToWorkList(Add.getNode());
6006 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
6014 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
6015 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
6016 SDValue N1, ISD::CondCode Cond,
6017 DebugLoc DL, bool foldBooleans) {
6018 TargetLowering::DAGCombinerInfo
6019 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
6020 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
6023 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
6024 /// return a DAG expression to select that will generate the same value by
6025 /// multiplying by a magic number. See:
6026 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6027 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
6028 std::vector<SDNode*> Built;
6029 SDValue S = TLI.BuildSDIV(N, DAG, &Built);
6031 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6037 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
6038 /// return a DAG expression to select that will generate the same value by
6039 /// multiplying by a magic number. See:
6040 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6041 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
6042 std::vector<SDNode*> Built;
6043 SDValue S = TLI.BuildUDIV(N, DAG, &Built);
6045 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6051 /// FindBaseOffset - Return true if base is a frame index, which is known not
6052 // to alias with anything but itself. Provides base object and offset as results.
6053 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
6054 GlobalValue *&GV, void *&CV) {
6055 // Assume it is a primitive operation.
6056 Base = Ptr; Offset = 0; GV = 0; CV = 0;
6058 // If it's an adding a simple constant then integrate the offset.
6059 if (Base.getOpcode() == ISD::ADD) {
6060 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
6061 Base = Base.getOperand(0);
6062 Offset += C->getZExtValue();
6066 // Return the underlying GlobalValue, and update the Offset. Return false
6067 // for GlobalAddressSDNode since the same GlobalAddress may be represented
6068 // by multiple nodes with different offsets.
6069 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
6070 GV = G->getGlobal();
6071 Offset += G->getOffset();
6075 // Return the underlying Constant value, and update the Offset. Return false
6076 // for ConstantSDNodes since the same constant pool entry may be represented
6077 // by multiple nodes with different offsets.
6078 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
6079 CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
6080 : (void *)C->getConstVal();
6081 Offset += C->getOffset();
6084 // If it's any of the following then it can't alias with anything but itself.
6085 return isa<FrameIndexSDNode>(Base);
6088 /// isAlias - Return true if there is any possibility that the two addresses
6090 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
6091 const Value *SrcValue1, int SrcValueOffset1,
6092 unsigned SrcValueAlign1,
6093 SDValue Ptr2, int64_t Size2,
6094 const Value *SrcValue2, int SrcValueOffset2,
6095 unsigned SrcValueAlign2) const {
6096 // If they are the same then they must be aliases.
6097 if (Ptr1 == Ptr2) return true;
6099 // Gather base node and offset information.
6100 SDValue Base1, Base2;
6101 int64_t Offset1, Offset2;
6102 GlobalValue *GV1, *GV2;
6104 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
6105 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
6107 // If they have a same base address then check to see if they overlap.
6108 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
6109 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
6111 // If we know what the bases are, and they aren't identical, then we know they
6113 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
6116 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
6117 // compared to the size and offset of the access, we may be able to prove they
6118 // do not alias. This check is conservative for now to catch cases created by
6119 // splitting vector types.
6120 if ((SrcValueAlign1 == SrcValueAlign2) &&
6121 (SrcValueOffset1 != SrcValueOffset2) &&
6122 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
6123 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
6124 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
6126 // There is no overlap between these relatively aligned accesses of similar
6127 // size, return no alias.
6128 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
6132 if (CombinerGlobalAA) {
6133 // Use alias analysis information.
6134 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
6135 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
6136 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
6137 AliasAnalysis::AliasResult AAResult =
6138 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
6139 if (AAResult == AliasAnalysis::NoAlias)
6143 // Otherwise we have to assume they alias.
6147 /// FindAliasInfo - Extracts the relevant alias information from the memory
6148 /// node. Returns true if the operand was a load.
6149 bool DAGCombiner::FindAliasInfo(SDNode *N,
6150 SDValue &Ptr, int64_t &Size,
6151 const Value *&SrcValue,
6152 int &SrcValueOffset,
6153 unsigned &SrcValueAlign) const {
6154 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6155 Ptr = LD->getBasePtr();
6156 Size = LD->getMemoryVT().getSizeInBits() >> 3;
6157 SrcValue = LD->getSrcValue();
6158 SrcValueOffset = LD->getSrcValueOffset();
6159 SrcValueAlign = LD->getOriginalAlignment();
6161 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6162 Ptr = ST->getBasePtr();
6163 Size = ST->getMemoryVT().getSizeInBits() >> 3;
6164 SrcValue = ST->getSrcValue();
6165 SrcValueOffset = ST->getSrcValueOffset();
6166 SrcValueAlign = ST->getOriginalAlignment();
6168 llvm_unreachable("FindAliasInfo expected a memory operand");
6174 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
6175 /// looking for aliasing nodes and adding them to the Aliases vector.
6176 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
6177 SmallVector<SDValue, 8> &Aliases) {
6178 SmallVector<SDValue, 8> Chains; // List of chains to visit.
6179 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
6181 // Get alias information for node.
6184 const Value *SrcValue;
6186 unsigned SrcValueAlign;
6187 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
6191 Chains.push_back(OriginalChain);
6194 // Look at each chain and determine if it is an alias. If so, add it to the
6195 // aliases list. If not, then continue up the chain looking for the next
6197 while (!Chains.empty()) {
6198 SDValue Chain = Chains.back();
6201 // For TokenFactor nodes, look at each operand and only continue up the
6202 // chain until we find two aliases. If we've seen two aliases, assume we'll
6203 // find more and revert to original chain since the xform is unlikely to be
6206 // FIXME: The depth check could be made to return the last non-aliasing
6207 // chain we found before we hit a tokenfactor rather than the original
6209 if (Depth > 6 || Aliases.size() == 2) {
6211 Aliases.push_back(OriginalChain);
6215 // Don't bother if we've been before.
6216 if (!Visited.insert(Chain.getNode()))
6219 switch (Chain.getOpcode()) {
6220 case ISD::EntryToken:
6221 // Entry token is ideal chain operand, but handled in FindBetterChain.
6226 // Get alias information for Chain.
6229 const Value *OpSrcValue;
6230 int OpSrcValueOffset;
6231 unsigned OpSrcValueAlign;
6232 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
6233 OpSrcValue, OpSrcValueOffset,
6236 // If chain is alias then stop here.
6237 if (!(IsLoad && IsOpLoad) &&
6238 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
6239 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
6241 Aliases.push_back(Chain);
6243 // Look further up the chain.
6244 Chains.push_back(Chain.getOperand(0));
6250 case ISD::TokenFactor:
6251 // We have to check each of the operands of the token factor for "small"
6252 // token factors, so we queue them up. Adding the operands to the queue
6253 // (stack) in reverse order maintains the original order and increases the
6254 // likelihood that getNode will find a matching token factor (CSE.)
6255 if (Chain.getNumOperands() > 16) {
6256 Aliases.push_back(Chain);
6259 for (unsigned n = Chain.getNumOperands(); n;)
6260 Chains.push_back(Chain.getOperand(--n));
6265 // For all other instructions we will just have to take what we can get.
6266 Aliases.push_back(Chain);
6272 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
6273 /// for a better chain (aliasing node.)
6274 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
6275 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
6277 // Accumulate all the aliases to this node.
6278 GatherAllAliases(N, OldChain, Aliases);
6280 if (Aliases.size() == 0) {
6281 // If no operands then chain to entry token.
6282 return DAG.getEntryNode();
6283 } else if (Aliases.size() == 1) {
6284 // If a single operand then chain to it. We don't need to revisit it.
6288 // Construct a custom tailored token factor.
6289 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
6290 &Aliases[0], Aliases.size());
6293 // SelectionDAG::Combine - This is the entry point for the file.
6295 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
6296 CodeGenOpt::Level OptLevel) {
6297 /// run - This is the main entry point to this class.
6299 DAGCombiner(*this, AA, OptLevel).Run(Level);