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/TargetLowering.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
41 STATISTIC(NodesCombined , "Number of dag nodes combined");
42 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
43 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
44 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
45 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
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 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
123 APInt Demanded = APInt::getAllOnesValue(BitWidth);
124 return SimplifyDemandedBits(Op, Demanded);
127 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
129 bool CombineToPreIndexedLoadStore(SDNode *N);
130 bool CombineToPostIndexedLoadStore(SDNode *N);
132 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
133 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
134 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
135 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
136 SDValue PromoteIntBinOp(SDValue Op);
137 SDValue PromoteIntShiftOp(SDValue Op);
138 SDValue PromoteExtend(SDValue Op);
139 bool PromoteLoad(SDValue Op);
141 /// combine - call the node-specific routine that knows how to fold each
142 /// particular type of node. If that doesn't do anything, try the
143 /// target-specific DAG combines.
144 SDValue combine(SDNode *N);
146 // Visitation implementation - Implement dag node combining for different
147 // node types. The semantics are as follows:
149 // SDValue.getNode() == 0 - No change was made
150 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
151 // otherwise - N should be replaced by the returned Operand.
153 SDValue visitTokenFactor(SDNode *N);
154 SDValue visitMERGE_VALUES(SDNode *N);
155 SDValue visitADD(SDNode *N);
156 SDValue visitSUB(SDNode *N);
157 SDValue visitADDC(SDNode *N);
158 SDValue visitADDE(SDNode *N);
159 SDValue visitMUL(SDNode *N);
160 SDValue visitSDIV(SDNode *N);
161 SDValue visitUDIV(SDNode *N);
162 SDValue visitSREM(SDNode *N);
163 SDValue visitUREM(SDNode *N);
164 SDValue visitMULHU(SDNode *N);
165 SDValue visitMULHS(SDNode *N);
166 SDValue visitSMUL_LOHI(SDNode *N);
167 SDValue visitUMUL_LOHI(SDNode *N);
168 SDValue visitSDIVREM(SDNode *N);
169 SDValue visitUDIVREM(SDNode *N);
170 SDValue visitAND(SDNode *N);
171 SDValue visitOR(SDNode *N);
172 SDValue visitXOR(SDNode *N);
173 SDValue SimplifyVBinOp(SDNode *N);
174 SDValue visitSHL(SDNode *N);
175 SDValue visitSRA(SDNode *N);
176 SDValue visitSRL(SDNode *N);
177 SDValue visitCTLZ(SDNode *N);
178 SDValue visitCTTZ(SDNode *N);
179 SDValue visitCTPOP(SDNode *N);
180 SDValue visitSELECT(SDNode *N);
181 SDValue visitSELECT_CC(SDNode *N);
182 SDValue visitSETCC(SDNode *N);
183 SDValue visitSIGN_EXTEND(SDNode *N);
184 SDValue visitZERO_EXTEND(SDNode *N);
185 SDValue visitANY_EXTEND(SDNode *N);
186 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
187 SDValue visitTRUNCATE(SDNode *N);
188 SDValue visitBITCAST(SDNode *N);
189 SDValue visitBUILD_PAIR(SDNode *N);
190 SDValue visitFADD(SDNode *N);
191 SDValue visitFSUB(SDNode *N);
192 SDValue visitFMUL(SDNode *N);
193 SDValue visitFDIV(SDNode *N);
194 SDValue visitFREM(SDNode *N);
195 SDValue visitFCOPYSIGN(SDNode *N);
196 SDValue visitSINT_TO_FP(SDNode *N);
197 SDValue visitUINT_TO_FP(SDNode *N);
198 SDValue visitFP_TO_SINT(SDNode *N);
199 SDValue visitFP_TO_UINT(SDNode *N);
200 SDValue visitFP_ROUND(SDNode *N);
201 SDValue visitFP_ROUND_INREG(SDNode *N);
202 SDValue visitFP_EXTEND(SDNode *N);
203 SDValue visitFNEG(SDNode *N);
204 SDValue visitFABS(SDNode *N);
205 SDValue visitBRCOND(SDNode *N);
206 SDValue visitBR_CC(SDNode *N);
207 SDValue visitLOAD(SDNode *N);
208 SDValue visitSTORE(SDNode *N);
209 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
210 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
211 SDValue visitBUILD_VECTOR(SDNode *N);
212 SDValue visitCONCAT_VECTORS(SDNode *N);
213 SDValue visitVECTOR_SHUFFLE(SDNode *N);
214 SDValue visitMEMBARRIER(SDNode *N);
216 SDValue XformToShuffleWithZero(SDNode *N);
217 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
219 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
221 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
222 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
223 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
224 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
225 SDValue N3, ISD::CondCode CC,
226 bool NotExtCompare = false);
227 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
228 DebugLoc DL, bool foldBooleans = true);
229 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
231 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
232 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
233 SDValue BuildSDIV(SDNode *N);
234 SDValue BuildUDIV(SDNode *N);
235 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
236 SDValue ReduceLoadWidth(SDNode *N);
237 SDValue ReduceLoadOpStoreWidth(SDNode *N);
238 SDValue TransformFPLoadStorePair(SDNode *N);
240 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
242 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
243 /// looking for aliasing nodes and adding them to the Aliases vector.
244 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
245 SmallVector<SDValue, 8> &Aliases);
247 /// isAlias - Return true if there is any possibility that the two addresses
249 bool isAlias(SDValue Ptr1, int64_t Size1,
250 const Value *SrcValue1, int SrcValueOffset1,
251 unsigned SrcValueAlign1,
252 const MDNode *TBAAInfo1,
253 SDValue Ptr2, int64_t Size2,
254 const Value *SrcValue2, int SrcValueOffset2,
255 unsigned SrcValueAlign2,
256 const MDNode *TBAAInfo2) const;
258 /// FindAliasInfo - Extracts the relevant alias information from the memory
259 /// node. Returns true if the operand was a load.
260 bool FindAliasInfo(SDNode *N,
261 SDValue &Ptr, int64_t &Size,
262 const Value *&SrcValue, int &SrcValueOffset,
263 unsigned &SrcValueAlignment,
264 const MDNode *&TBAAInfo) const;
266 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
267 /// looking for a better chain (aliasing node.)
268 SDValue FindBetterChain(SDNode *N, SDValue Chain);
271 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
272 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(Unrestricted),
273 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
275 /// Run - runs the dag combiner on all nodes in the work list
276 void Run(CombineLevel AtLevel);
278 SelectionDAG &getDAG() const { return DAG; }
280 /// getShiftAmountTy - Returns a type large enough to hold any valid
281 /// shift amount - before type legalization these can be huge.
282 EVT getShiftAmountTy() {
283 return LegalTypes ? TLI.getShiftAmountTy() : TLI.getPointerTy();
286 /// isTypeLegal - This method returns true if we are running before type
287 /// legalization or if the specified VT is legal.
288 bool isTypeLegal(const EVT &VT) {
289 if (!LegalTypes) return true;
290 return TLI.isTypeLegal(VT);
297 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
298 /// nodes from the worklist.
299 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
302 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
304 virtual void NodeDeleted(SDNode *N, SDNode *E) {
305 DC.removeFromWorkList(N);
308 virtual void NodeUpdated(SDNode *N) {
314 //===----------------------------------------------------------------------===//
315 // TargetLowering::DAGCombinerInfo implementation
316 //===----------------------------------------------------------------------===//
318 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
319 ((DAGCombiner*)DC)->AddToWorkList(N);
322 SDValue TargetLowering::DAGCombinerInfo::
323 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
324 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
327 SDValue TargetLowering::DAGCombinerInfo::
328 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
329 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
333 SDValue TargetLowering::DAGCombinerInfo::
334 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
335 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
338 void TargetLowering::DAGCombinerInfo::
339 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
340 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
343 //===----------------------------------------------------------------------===//
345 //===----------------------------------------------------------------------===//
347 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
348 /// specified expression for the same cost as the expression itself, or 2 if we
349 /// can compute the negated form more cheaply than the expression itself.
350 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
351 unsigned Depth = 0) {
352 // No compile time optimizations on this type.
353 if (Op.getValueType() == MVT::ppcf128)
356 // fneg is removable even if it has multiple uses.
357 if (Op.getOpcode() == ISD::FNEG) return 2;
359 // Don't allow anything with multiple uses.
360 if (!Op.hasOneUse()) return 0;
362 // Don't recurse exponentially.
363 if (Depth > 6) return 0;
365 switch (Op.getOpcode()) {
366 default: return false;
367 case ISD::ConstantFP:
368 // Don't invert constant FP values after legalize. The negated constant
369 // isn't necessarily legal.
370 return LegalOperations ? 0 : 1;
372 // FIXME: determine better conditions for this xform.
373 if (!UnsafeFPMath) return 0;
375 // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
376 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
378 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
379 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
381 // We can't turn -(A-B) into B-A when we honor signed zeros.
382 if (!UnsafeFPMath) return 0;
384 // fold (fneg (fsub A, B)) -> (fsub B, A)
389 if (HonorSignDependentRoundingFPMath()) return 0;
391 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
392 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
395 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
400 return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
404 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
405 /// returns the newly negated expression.
406 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
407 bool LegalOperations, unsigned Depth = 0) {
408 // fneg is removable even if it has multiple uses.
409 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
411 // Don't allow anything with multiple uses.
412 assert(Op.hasOneUse() && "Unknown reuse!");
414 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
415 switch (Op.getOpcode()) {
416 default: llvm_unreachable("Unknown code");
417 case ISD::ConstantFP: {
418 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
420 return DAG.getConstantFP(V, Op.getValueType());
423 // FIXME: determine better conditions for this xform.
424 assert(UnsafeFPMath);
426 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
427 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
428 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
429 GetNegatedExpression(Op.getOperand(0), DAG,
430 LegalOperations, Depth+1),
432 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
433 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
434 GetNegatedExpression(Op.getOperand(1), DAG,
435 LegalOperations, Depth+1),
438 // We can't turn -(A-B) into B-A when we honor signed zeros.
439 assert(UnsafeFPMath);
441 // fold (fneg (fsub 0, B)) -> B
442 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
443 if (N0CFP->getValueAPF().isZero())
444 return Op.getOperand(1);
446 // fold (fneg (fsub A, B)) -> (fsub B, A)
447 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
448 Op.getOperand(1), Op.getOperand(0));
452 assert(!HonorSignDependentRoundingFPMath());
454 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
455 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
456 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
457 GetNegatedExpression(Op.getOperand(0), DAG,
458 LegalOperations, Depth+1),
461 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
462 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
464 GetNegatedExpression(Op.getOperand(1), DAG,
465 LegalOperations, Depth+1));
469 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
470 GetNegatedExpression(Op.getOperand(0), DAG,
471 LegalOperations, Depth+1));
473 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
474 GetNegatedExpression(Op.getOperand(0), DAG,
475 LegalOperations, Depth+1),
481 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
482 // that selects between the values 1 and 0, making it equivalent to a setcc.
483 // Also, set the incoming LHS, RHS, and CC references to the appropriate
484 // nodes based on the type of node we are checking. This simplifies life a
485 // bit for the callers.
486 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
488 if (N.getOpcode() == ISD::SETCC) {
489 LHS = N.getOperand(0);
490 RHS = N.getOperand(1);
491 CC = N.getOperand(2);
494 if (N.getOpcode() == ISD::SELECT_CC &&
495 N.getOperand(2).getOpcode() == ISD::Constant &&
496 N.getOperand(3).getOpcode() == ISD::Constant &&
497 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
498 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
499 LHS = N.getOperand(0);
500 RHS = N.getOperand(1);
501 CC = N.getOperand(4);
507 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
508 // one use. If this is true, it allows the users to invert the operation for
509 // free when it is profitable to do so.
510 static bool isOneUseSetCC(SDValue N) {
512 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
517 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
518 SDValue N0, SDValue N1) {
519 EVT VT = N0.getValueType();
520 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
521 if (isa<ConstantSDNode>(N1)) {
522 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
524 DAG.FoldConstantArithmetic(Opc, VT,
525 cast<ConstantSDNode>(N0.getOperand(1)),
526 cast<ConstantSDNode>(N1));
527 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
528 } else if (N0.hasOneUse()) {
529 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
530 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
531 N0.getOperand(0), N1);
532 AddToWorkList(OpNode.getNode());
533 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
537 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
538 if (isa<ConstantSDNode>(N0)) {
539 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
541 DAG.FoldConstantArithmetic(Opc, VT,
542 cast<ConstantSDNode>(N1.getOperand(1)),
543 cast<ConstantSDNode>(N0));
544 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
545 } else if (N1.hasOneUse()) {
546 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
547 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
548 N1.getOperand(0), N0);
549 AddToWorkList(OpNode.getNode());
550 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
557 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
559 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
561 DEBUG(dbgs() << "\nReplacing.1 ";
563 dbgs() << "\nWith: ";
564 To[0].getNode()->dump(&DAG);
565 dbgs() << " and " << NumTo-1 << " other values\n";
566 for (unsigned i = 0, e = NumTo; i != e; ++i)
567 assert((!To[i].getNode() ||
568 N->getValueType(i) == To[i].getValueType()) &&
569 "Cannot combine value to value of different type!"));
570 WorkListRemover DeadNodes(*this);
571 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
574 // Push the new nodes and any users onto the worklist
575 for (unsigned i = 0, e = NumTo; i != e; ++i) {
576 if (To[i].getNode()) {
577 AddToWorkList(To[i].getNode());
578 AddUsersToWorkList(To[i].getNode());
583 // Finally, if the node is now dead, remove it from the graph. The node
584 // may not be dead if the replacement process recursively simplified to
585 // something else needing this node.
586 if (N->use_empty()) {
587 // Nodes can be reintroduced into the worklist. Make sure we do not
588 // process a node that has been replaced.
589 removeFromWorkList(N);
591 // Finally, since the node is now dead, remove it from the graph.
594 return SDValue(N, 0);
598 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
599 // Replace all uses. If any nodes become isomorphic to other nodes and
600 // are deleted, make sure to remove them from our worklist.
601 WorkListRemover DeadNodes(*this);
602 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
604 // Push the new node and any (possibly new) users onto the worklist.
605 AddToWorkList(TLO.New.getNode());
606 AddUsersToWorkList(TLO.New.getNode());
608 // Finally, if the node is now dead, remove it from the graph. The node
609 // may not be dead if the replacement process recursively simplified to
610 // something else needing this node.
611 if (TLO.Old.getNode()->use_empty()) {
612 removeFromWorkList(TLO.Old.getNode());
614 // If the operands of this node are only used by the node, they will now
615 // be dead. Make sure to visit them first to delete dead nodes early.
616 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
617 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
618 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
620 DAG.DeleteNode(TLO.Old.getNode());
624 /// SimplifyDemandedBits - Check the specified integer node value to see if
625 /// it can be simplified or if things it uses can be simplified by bit
626 /// propagation. If so, return true.
627 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
628 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
629 APInt KnownZero, KnownOne;
630 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
634 AddToWorkList(Op.getNode());
636 // Replace the old value with the new one.
638 DEBUG(dbgs() << "\nReplacing.2 ";
639 TLO.Old.getNode()->dump(&DAG);
640 dbgs() << "\nWith: ";
641 TLO.New.getNode()->dump(&DAG);
644 CommitTargetLoweringOpt(TLO);
648 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
649 DebugLoc dl = Load->getDebugLoc();
650 EVT VT = Load->getValueType(0);
651 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
653 DEBUG(dbgs() << "\nReplacing.9 ";
655 dbgs() << "\nWith: ";
656 Trunc.getNode()->dump(&DAG);
658 WorkListRemover DeadNodes(*this);
659 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc, &DeadNodes);
660 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1),
662 removeFromWorkList(Load);
663 DAG.DeleteNode(Load);
664 AddToWorkList(Trunc.getNode());
667 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
669 DebugLoc dl = Op.getDebugLoc();
670 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
671 EVT MemVT = LD->getMemoryVT();
672 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
673 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
675 : LD->getExtensionType();
677 return DAG.getExtLoad(ExtType, PVT, dl,
678 LD->getChain(), LD->getBasePtr(),
679 LD->getPointerInfo(),
680 MemVT, LD->isVolatile(),
681 LD->isNonTemporal(), LD->getAlignment());
684 unsigned Opc = Op.getOpcode();
687 case ISD::AssertSext:
688 return DAG.getNode(ISD::AssertSext, dl, PVT,
689 SExtPromoteOperand(Op.getOperand(0), PVT),
691 case ISD::AssertZext:
692 return DAG.getNode(ISD::AssertZext, dl, PVT,
693 ZExtPromoteOperand(Op.getOperand(0), PVT),
695 case ISD::Constant: {
697 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
698 return DAG.getNode(ExtOpc, dl, PVT, Op);
702 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
704 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
707 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
708 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
710 EVT OldVT = Op.getValueType();
711 DebugLoc dl = Op.getDebugLoc();
712 bool Replace = false;
713 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
714 if (NewOp.getNode() == 0)
716 AddToWorkList(NewOp.getNode());
719 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
720 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
721 DAG.getValueType(OldVT));
724 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
725 EVT OldVT = Op.getValueType();
726 DebugLoc dl = Op.getDebugLoc();
727 bool Replace = false;
728 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
729 if (NewOp.getNode() == 0)
731 AddToWorkList(NewOp.getNode());
734 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
735 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
738 /// PromoteIntBinOp - Promote the specified integer binary operation if the
739 /// target indicates it is beneficial. e.g. On x86, it's usually better to
740 /// promote i16 operations to i32 since i16 instructions are longer.
741 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
742 if (!LegalOperations)
745 EVT VT = Op.getValueType();
746 if (VT.isVector() || !VT.isInteger())
749 // If operation type is 'undesirable', e.g. i16 on x86, consider
751 unsigned Opc = Op.getOpcode();
752 if (TLI.isTypeDesirableForOp(Opc, VT))
756 // Consult target whether it is a good idea to promote this operation and
757 // what's the right type to promote it to.
758 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
759 assert(PVT != VT && "Don't know what type to promote to!");
761 bool Replace0 = false;
762 SDValue N0 = Op.getOperand(0);
763 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
764 if (NN0.getNode() == 0)
767 bool Replace1 = false;
768 SDValue N1 = Op.getOperand(1);
773 NN1 = PromoteOperand(N1, PVT, Replace1);
774 if (NN1.getNode() == 0)
778 AddToWorkList(NN0.getNode());
780 AddToWorkList(NN1.getNode());
783 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
785 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
787 DEBUG(dbgs() << "\nPromoting ";
788 Op.getNode()->dump(&DAG));
789 DebugLoc dl = Op.getDebugLoc();
790 return DAG.getNode(ISD::TRUNCATE, dl, VT,
791 DAG.getNode(Opc, dl, PVT, NN0, NN1));
796 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
797 /// target indicates it is beneficial. e.g. On x86, it's usually better to
798 /// promote i16 operations to i32 since i16 instructions are longer.
799 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
800 if (!LegalOperations)
803 EVT VT = Op.getValueType();
804 if (VT.isVector() || !VT.isInteger())
807 // If operation type is 'undesirable', e.g. i16 on x86, consider
809 unsigned Opc = Op.getOpcode();
810 if (TLI.isTypeDesirableForOp(Opc, VT))
814 // Consult target whether it is a good idea to promote this operation and
815 // what's the right type to promote it to.
816 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
817 assert(PVT != VT && "Don't know what type to promote to!");
819 bool Replace = false;
820 SDValue N0 = Op.getOperand(0);
822 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
823 else if (Opc == ISD::SRL)
824 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
826 N0 = PromoteOperand(N0, PVT, Replace);
827 if (N0.getNode() == 0)
830 AddToWorkList(N0.getNode());
832 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
834 DEBUG(dbgs() << "\nPromoting ";
835 Op.getNode()->dump(&DAG));
836 DebugLoc dl = Op.getDebugLoc();
837 return DAG.getNode(ISD::TRUNCATE, dl, VT,
838 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
843 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
844 if (!LegalOperations)
847 EVT VT = Op.getValueType();
848 if (VT.isVector() || !VT.isInteger())
851 // If operation type is 'undesirable', e.g. i16 on x86, consider
853 unsigned Opc = Op.getOpcode();
854 if (TLI.isTypeDesirableForOp(Opc, VT))
858 // Consult target whether it is a good idea to promote this operation and
859 // what's the right type to promote it to.
860 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
861 assert(PVT != VT && "Don't know what type to promote to!");
862 // fold (aext (aext x)) -> (aext x)
863 // fold (aext (zext x)) -> (zext x)
864 // fold (aext (sext x)) -> (sext x)
865 DEBUG(dbgs() << "\nPromoting ";
866 Op.getNode()->dump(&DAG));
867 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
872 bool DAGCombiner::PromoteLoad(SDValue Op) {
873 if (!LegalOperations)
876 EVT VT = Op.getValueType();
877 if (VT.isVector() || !VT.isInteger())
880 // If operation type is 'undesirable', e.g. i16 on x86, consider
882 unsigned Opc = Op.getOpcode();
883 if (TLI.isTypeDesirableForOp(Opc, VT))
887 // Consult target whether it is a good idea to promote this operation and
888 // what's the right type to promote it to.
889 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
890 assert(PVT != VT && "Don't know what type to promote to!");
892 DebugLoc dl = Op.getDebugLoc();
893 SDNode *N = Op.getNode();
894 LoadSDNode *LD = cast<LoadSDNode>(N);
895 EVT MemVT = LD->getMemoryVT();
896 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
897 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
899 : LD->getExtensionType();
900 SDValue NewLD = DAG.getExtLoad(ExtType, PVT, dl,
901 LD->getChain(), LD->getBasePtr(),
902 LD->getPointerInfo(),
903 MemVT, LD->isVolatile(),
904 LD->isNonTemporal(), LD->getAlignment());
905 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
907 DEBUG(dbgs() << "\nPromoting ";
910 Result.getNode()->dump(&DAG);
912 WorkListRemover DeadNodes(*this);
913 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result, &DeadNodes);
914 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1), &DeadNodes);
915 removeFromWorkList(N);
917 AddToWorkList(Result.getNode());
924 //===----------------------------------------------------------------------===//
925 // Main DAG Combiner implementation
926 //===----------------------------------------------------------------------===//
928 void DAGCombiner::Run(CombineLevel AtLevel) {
929 // set the instance variables, so that the various visit routines may use it.
931 LegalOperations = Level >= NoIllegalOperations;
932 LegalTypes = Level >= NoIllegalTypes;
934 // Add all the dag nodes to the worklist.
935 WorkList.reserve(DAG.allnodes_size());
936 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
937 E = DAG.allnodes_end(); I != E; ++I)
938 WorkList.push_back(I);
940 // Create a dummy node (which is not added to allnodes), that adds a reference
941 // to the root node, preventing it from being deleted, and tracking any
942 // changes of the root.
943 HandleSDNode Dummy(DAG.getRoot());
945 // The root of the dag may dangle to deleted nodes until the dag combiner is
946 // done. Set it to null to avoid confusion.
947 DAG.setRoot(SDValue());
949 // while the worklist isn't empty, inspect the node on the end of it and
950 // try and combine it.
951 while (!WorkList.empty()) {
952 SDNode *N = WorkList.back();
955 // If N has no uses, it is dead. Make sure to revisit all N's operands once
956 // N is deleted from the DAG, since they too may now be dead or may have a
957 // reduced number of uses, allowing other xforms.
958 if (N->use_empty() && N != &Dummy) {
959 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
960 AddToWorkList(N->getOperand(i).getNode());
966 SDValue RV = combine(N);
968 if (RV.getNode() == 0)
973 // If we get back the same node we passed in, rather than a new node or
974 // zero, we know that the node must have defined multiple values and
975 // CombineTo was used. Since CombineTo takes care of the worklist
976 // mechanics for us, we have no work to do in this case.
977 if (RV.getNode() == N)
980 assert(N->getOpcode() != ISD::DELETED_NODE &&
981 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
982 "Node was deleted but visit returned new node!");
984 DEBUG(dbgs() << "\nReplacing.3 ";
986 dbgs() << "\nWith: ";
987 RV.getNode()->dump(&DAG);
989 WorkListRemover DeadNodes(*this);
990 if (N->getNumValues() == RV.getNode()->getNumValues())
991 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
993 assert(N->getValueType(0) == RV.getValueType() &&
994 N->getNumValues() == 1 && "Type mismatch");
996 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
999 // Push the new node and any users onto the worklist
1000 AddToWorkList(RV.getNode());
1001 AddUsersToWorkList(RV.getNode());
1003 // Add any uses of the old node to the worklist in case this node is the
1004 // last one that uses them. They may become dead after this node is
1006 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1007 AddToWorkList(N->getOperand(i).getNode());
1009 // Finally, if the node is now dead, remove it from the graph. The node
1010 // may not be dead if the replacement process recursively simplified to
1011 // something else needing this node.
1012 if (N->use_empty()) {
1013 // Nodes can be reintroduced into the worklist. Make sure we do not
1014 // process a node that has been replaced.
1015 removeFromWorkList(N);
1017 // Finally, since the node is now dead, remove it from the graph.
1022 // If the root changed (e.g. it was a dead load, update the root).
1023 DAG.setRoot(Dummy.getValue());
1026 SDValue DAGCombiner::visit(SDNode *N) {
1027 switch (N->getOpcode()) {
1029 case ISD::TokenFactor: return visitTokenFactor(N);
1030 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1031 case ISD::ADD: return visitADD(N);
1032 case ISD::SUB: return visitSUB(N);
1033 case ISD::ADDC: return visitADDC(N);
1034 case ISD::ADDE: return visitADDE(N);
1035 case ISD::MUL: return visitMUL(N);
1036 case ISD::SDIV: return visitSDIV(N);
1037 case ISD::UDIV: return visitUDIV(N);
1038 case ISD::SREM: return visitSREM(N);
1039 case ISD::UREM: return visitUREM(N);
1040 case ISD::MULHU: return visitMULHU(N);
1041 case ISD::MULHS: return visitMULHS(N);
1042 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1043 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1044 case ISD::SDIVREM: return visitSDIVREM(N);
1045 case ISD::UDIVREM: return visitUDIVREM(N);
1046 case ISD::AND: return visitAND(N);
1047 case ISD::OR: return visitOR(N);
1048 case ISD::XOR: return visitXOR(N);
1049 case ISD::SHL: return visitSHL(N);
1050 case ISD::SRA: return visitSRA(N);
1051 case ISD::SRL: return visitSRL(N);
1052 case ISD::CTLZ: return visitCTLZ(N);
1053 case ISD::CTTZ: return visitCTTZ(N);
1054 case ISD::CTPOP: return visitCTPOP(N);
1055 case ISD::SELECT: return visitSELECT(N);
1056 case ISD::SELECT_CC: return visitSELECT_CC(N);
1057 case ISD::SETCC: return visitSETCC(N);
1058 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1059 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1060 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1061 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1062 case ISD::TRUNCATE: return visitTRUNCATE(N);
1063 case ISD::BITCAST: return visitBITCAST(N);
1064 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1065 case ISD::FADD: return visitFADD(N);
1066 case ISD::FSUB: return visitFSUB(N);
1067 case ISD::FMUL: return visitFMUL(N);
1068 case ISD::FDIV: return visitFDIV(N);
1069 case ISD::FREM: return visitFREM(N);
1070 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1071 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1072 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1073 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1074 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1075 case ISD::FP_ROUND: return visitFP_ROUND(N);
1076 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1077 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1078 case ISD::FNEG: return visitFNEG(N);
1079 case ISD::FABS: return visitFABS(N);
1080 case ISD::BRCOND: return visitBRCOND(N);
1081 case ISD::BR_CC: return visitBR_CC(N);
1082 case ISD::LOAD: return visitLOAD(N);
1083 case ISD::STORE: return visitSTORE(N);
1084 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1085 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1086 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1087 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1088 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1089 case ISD::MEMBARRIER: return visitMEMBARRIER(N);
1094 SDValue DAGCombiner::combine(SDNode *N) {
1095 SDValue RV = visit(N);
1097 // If nothing happened, try a target-specific DAG combine.
1098 if (RV.getNode() == 0) {
1099 assert(N->getOpcode() != ISD::DELETED_NODE &&
1100 "Node was deleted but visit returned NULL!");
1102 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1103 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1105 // Expose the DAG combiner to the target combiner impls.
1106 TargetLowering::DAGCombinerInfo
1107 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1109 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1113 // If nothing happened still, try promoting the operation.
1114 if (RV.getNode() == 0) {
1115 switch (N->getOpcode()) {
1123 RV = PromoteIntBinOp(SDValue(N, 0));
1128 RV = PromoteIntShiftOp(SDValue(N, 0));
1130 case ISD::SIGN_EXTEND:
1131 case ISD::ZERO_EXTEND:
1132 case ISD::ANY_EXTEND:
1133 RV = PromoteExtend(SDValue(N, 0));
1136 if (PromoteLoad(SDValue(N, 0)))
1142 // If N is a commutative binary node, try commuting it to enable more
1144 if (RV.getNode() == 0 &&
1145 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1146 N->getNumValues() == 1) {
1147 SDValue N0 = N->getOperand(0);
1148 SDValue N1 = N->getOperand(1);
1150 // Constant operands are canonicalized to RHS.
1151 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1152 SDValue Ops[] = { N1, N0 };
1153 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1156 return SDValue(CSENode, 0);
1163 /// getInputChainForNode - Given a node, return its input chain if it has one,
1164 /// otherwise return a null sd operand.
1165 static SDValue getInputChainForNode(SDNode *N) {
1166 if (unsigned NumOps = N->getNumOperands()) {
1167 if (N->getOperand(0).getValueType() == MVT::Other)
1168 return N->getOperand(0);
1169 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1170 return N->getOperand(NumOps-1);
1171 for (unsigned i = 1; i < NumOps-1; ++i)
1172 if (N->getOperand(i).getValueType() == MVT::Other)
1173 return N->getOperand(i);
1178 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1179 // If N has two operands, where one has an input chain equal to the other,
1180 // the 'other' chain is redundant.
1181 if (N->getNumOperands() == 2) {
1182 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1183 return N->getOperand(0);
1184 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1185 return N->getOperand(1);
1188 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1189 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1190 SmallPtrSet<SDNode*, 16> SeenOps;
1191 bool Changed = false; // If we should replace this token factor.
1193 // Start out with this token factor.
1196 // Iterate through token factors. The TFs grows when new token factors are
1198 for (unsigned i = 0; i < TFs.size(); ++i) {
1199 SDNode *TF = TFs[i];
1201 // Check each of the operands.
1202 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1203 SDValue Op = TF->getOperand(i);
1205 switch (Op.getOpcode()) {
1206 case ISD::EntryToken:
1207 // Entry tokens don't need to be added to the list. They are
1212 case ISD::TokenFactor:
1213 if (Op.hasOneUse() &&
1214 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1215 // Queue up for processing.
1216 TFs.push_back(Op.getNode());
1217 // Clean up in case the token factor is removed.
1218 AddToWorkList(Op.getNode());
1225 // Only add if it isn't already in the list.
1226 if (SeenOps.insert(Op.getNode()))
1237 // If we've change things around then replace token factor.
1240 // The entry token is the only possible outcome.
1241 Result = DAG.getEntryNode();
1243 // New and improved token factor.
1244 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1245 MVT::Other, &Ops[0], Ops.size());
1248 // Don't add users to work list.
1249 return CombineTo(N, Result, false);
1255 /// MERGE_VALUES can always be eliminated.
1256 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1257 WorkListRemover DeadNodes(*this);
1258 // Replacing results may cause a different MERGE_VALUES to suddenly
1259 // be CSE'd with N, and carry its uses with it. Iterate until no
1260 // uses remain, to ensure that the node can be safely deleted.
1262 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1263 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
1265 } while (!N->use_empty());
1266 removeFromWorkList(N);
1268 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1272 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1273 SelectionDAG &DAG) {
1274 EVT VT = N0.getValueType();
1275 SDValue N00 = N0.getOperand(0);
1276 SDValue N01 = N0.getOperand(1);
1277 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1279 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1280 isa<ConstantSDNode>(N00.getOperand(1))) {
1281 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1282 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1283 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1284 N00.getOperand(0), N01),
1285 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1286 N00.getOperand(1), N01));
1287 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1293 SDValue DAGCombiner::visitADD(SDNode *N) {
1294 SDValue N0 = N->getOperand(0);
1295 SDValue N1 = N->getOperand(1);
1296 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1297 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1298 EVT VT = N0.getValueType();
1301 if (VT.isVector()) {
1302 SDValue FoldedVOp = SimplifyVBinOp(N);
1303 if (FoldedVOp.getNode()) return FoldedVOp;
1306 // fold (add x, undef) -> undef
1307 if (N0.getOpcode() == ISD::UNDEF)
1309 if (N1.getOpcode() == ISD::UNDEF)
1311 // fold (add c1, c2) -> c1+c2
1313 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1314 // canonicalize constant to RHS
1316 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1317 // fold (add x, 0) -> x
1318 if (N1C && N1C->isNullValue())
1320 // fold (add Sym, c) -> Sym+c
1321 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1322 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1323 GA->getOpcode() == ISD::GlobalAddress)
1324 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1326 (uint64_t)N1C->getSExtValue());
1327 // fold ((c1-A)+c2) -> (c1+c2)-A
1328 if (N1C && N0.getOpcode() == ISD::SUB)
1329 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1330 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1331 DAG.getConstant(N1C->getAPIntValue()+
1332 N0C->getAPIntValue(), VT),
1335 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1336 if (RADD.getNode() != 0)
1338 // fold ((0-A) + B) -> B-A
1339 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1340 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1341 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1342 // fold (A + (0-B)) -> A-B
1343 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1344 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1345 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1346 // fold (A+(B-A)) -> B
1347 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1348 return N1.getOperand(0);
1349 // fold ((B-A)+A) -> B
1350 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1351 return N0.getOperand(0);
1352 // fold (A+(B-(A+C))) to (B-C)
1353 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1354 N0 == N1.getOperand(1).getOperand(0))
1355 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1356 N1.getOperand(1).getOperand(1));
1357 // fold (A+(B-(C+A))) to (B-C)
1358 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1359 N0 == N1.getOperand(1).getOperand(1))
1360 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1361 N1.getOperand(1).getOperand(0));
1362 // fold (A+((B-A)+or-C)) to (B+or-C)
1363 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1364 N1.getOperand(0).getOpcode() == ISD::SUB &&
1365 N0 == N1.getOperand(0).getOperand(1))
1366 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1367 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1369 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1370 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1371 SDValue N00 = N0.getOperand(0);
1372 SDValue N01 = N0.getOperand(1);
1373 SDValue N10 = N1.getOperand(0);
1374 SDValue N11 = N1.getOperand(1);
1376 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1377 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1378 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1379 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1382 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1383 return SDValue(N, 0);
1385 // fold (a+b) -> (a|b) iff a and b share no bits.
1386 if (VT.isInteger() && !VT.isVector()) {
1387 APInt LHSZero, LHSOne;
1388 APInt RHSZero, RHSOne;
1389 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1390 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1392 if (LHSZero.getBoolValue()) {
1393 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1395 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1396 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1397 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1398 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1399 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1403 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1404 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1405 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1406 if (Result.getNode()) return Result;
1408 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1409 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1410 if (Result.getNode()) return Result;
1413 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1414 if (N1.getOpcode() == ISD::SHL &&
1415 N1.getOperand(0).getOpcode() == ISD::SUB)
1416 if (ConstantSDNode *C =
1417 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1418 if (C->getAPIntValue() == 0)
1419 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1420 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1421 N1.getOperand(0).getOperand(1),
1423 if (N0.getOpcode() == ISD::SHL &&
1424 N0.getOperand(0).getOpcode() == ISD::SUB)
1425 if (ConstantSDNode *C =
1426 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1427 if (C->getAPIntValue() == 0)
1428 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1429 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1430 N0.getOperand(0).getOperand(1),
1433 if (N1.getOpcode() == ISD::AND) {
1434 SDValue AndOp0 = N1.getOperand(0);
1435 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1436 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1437 unsigned DestBits = VT.getScalarType().getSizeInBits();
1439 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1440 // and similar xforms where the inner op is either ~0 or 0.
1441 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1442 DebugLoc DL = N->getDebugLoc();
1443 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1447 // add (sext i1), X -> sub X, (zext i1)
1448 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1449 N0.getOperand(0).getValueType() == MVT::i1 &&
1450 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1451 DebugLoc DL = N->getDebugLoc();
1452 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1453 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1459 SDValue DAGCombiner::visitADDC(SDNode *N) {
1460 SDValue N0 = N->getOperand(0);
1461 SDValue N1 = N->getOperand(1);
1462 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1463 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1464 EVT VT = N0.getValueType();
1466 // If the flag result is dead, turn this into an ADD.
1467 if (N->hasNUsesOfValue(0, 1))
1468 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
1469 DAG.getNode(ISD::CARRY_FALSE,
1470 N->getDebugLoc(), MVT::Glue));
1472 // canonicalize constant to RHS.
1474 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1476 // fold (addc x, 0) -> x + no carry out
1477 if (N1C && N1C->isNullValue())
1478 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1479 N->getDebugLoc(), MVT::Glue));
1481 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1482 APInt LHSZero, LHSOne;
1483 APInt RHSZero, RHSOne;
1484 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1485 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1487 if (LHSZero.getBoolValue()) {
1488 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1490 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1491 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1492 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1493 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1494 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1495 DAG.getNode(ISD::CARRY_FALSE,
1496 N->getDebugLoc(), MVT::Glue));
1502 SDValue DAGCombiner::visitADDE(SDNode *N) {
1503 SDValue N0 = N->getOperand(0);
1504 SDValue N1 = N->getOperand(1);
1505 SDValue CarryIn = N->getOperand(2);
1506 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1507 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1509 // canonicalize constant to RHS
1511 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1514 // fold (adde x, y, false) -> (addc x, y)
1515 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1516 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1521 SDValue DAGCombiner::visitSUB(SDNode *N) {
1522 SDValue N0 = N->getOperand(0);
1523 SDValue N1 = N->getOperand(1);
1524 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1525 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1526 EVT VT = N0.getValueType();
1529 if (VT.isVector()) {
1530 SDValue FoldedVOp = SimplifyVBinOp(N);
1531 if (FoldedVOp.getNode()) return FoldedVOp;
1534 // fold (sub x, x) -> 0
1536 return DAG.getConstant(0, N->getValueType(0), LegalTypes);
1537 // fold (sub c1, c2) -> c1-c2
1539 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1540 // fold (sub x, c) -> (add x, -c)
1542 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1543 DAG.getConstant(-N1C->getAPIntValue(), VT));
1544 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1545 if (N0C && N0C->isAllOnesValue())
1546 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1547 // fold A-(A-B) -> B
1548 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1549 return N1.getOperand(1);
1550 // fold (A+B)-A -> B
1551 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1552 return N0.getOperand(1);
1553 // fold (A+B)-B -> A
1554 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1555 return N0.getOperand(0);
1556 // fold ((A+(B+or-C))-B) -> A+or-C
1557 if (N0.getOpcode() == ISD::ADD &&
1558 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1559 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1560 N0.getOperand(1).getOperand(0) == N1)
1561 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1562 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1563 // fold ((A+(C+B))-B) -> A+C
1564 if (N0.getOpcode() == ISD::ADD &&
1565 N0.getOperand(1).getOpcode() == ISD::ADD &&
1566 N0.getOperand(1).getOperand(1) == N1)
1567 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1568 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1569 // fold ((A-(B-C))-C) -> A-B
1570 if (N0.getOpcode() == ISD::SUB &&
1571 N0.getOperand(1).getOpcode() == ISD::SUB &&
1572 N0.getOperand(1).getOperand(1) == N1)
1573 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1574 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1576 // If either operand of a sub is undef, the result is undef
1577 if (N0.getOpcode() == ISD::UNDEF)
1579 if (N1.getOpcode() == ISD::UNDEF)
1582 // If the relocation model supports it, consider symbol offsets.
1583 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1584 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1585 // fold (sub Sym, c) -> Sym-c
1586 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1587 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1589 (uint64_t)N1C->getSExtValue());
1590 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1591 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1592 if (GA->getGlobal() == GB->getGlobal())
1593 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1600 SDValue DAGCombiner::visitMUL(SDNode *N) {
1601 SDValue N0 = N->getOperand(0);
1602 SDValue N1 = N->getOperand(1);
1603 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1604 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1605 EVT VT = N0.getValueType();
1608 if (VT.isVector()) {
1609 SDValue FoldedVOp = SimplifyVBinOp(N);
1610 if (FoldedVOp.getNode()) return FoldedVOp;
1613 // fold (mul x, undef) -> 0
1614 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1615 return DAG.getConstant(0, VT);
1616 // fold (mul c1, c2) -> c1*c2
1618 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1619 // canonicalize constant to RHS
1621 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1622 // fold (mul x, 0) -> 0
1623 if (N1C && N1C->isNullValue())
1625 // fold (mul x, -1) -> 0-x
1626 if (N1C && N1C->isAllOnesValue())
1627 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1628 DAG.getConstant(0, VT), N0);
1629 // fold (mul x, (1 << c)) -> x << c
1630 if (N1C && N1C->getAPIntValue().isPowerOf2())
1631 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1632 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1633 getShiftAmountTy()));
1634 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1635 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1636 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1637 // FIXME: If the input is something that is easily negated (e.g. a
1638 // single-use add), we should put the negate there.
1639 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1640 DAG.getConstant(0, VT),
1641 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1642 DAG.getConstant(Log2Val, getShiftAmountTy())));
1644 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1645 if (N1C && N0.getOpcode() == ISD::SHL &&
1646 isa<ConstantSDNode>(N0.getOperand(1))) {
1647 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1648 N1, N0.getOperand(1));
1649 AddToWorkList(C3.getNode());
1650 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1651 N0.getOperand(0), C3);
1654 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1657 SDValue Sh(0,0), Y(0,0);
1658 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1659 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1660 N0.getNode()->hasOneUse()) {
1662 } else if (N1.getOpcode() == ISD::SHL &&
1663 isa<ConstantSDNode>(N1.getOperand(1)) &&
1664 N1.getNode()->hasOneUse()) {
1669 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1670 Sh.getOperand(0), Y);
1671 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1672 Mul, Sh.getOperand(1));
1676 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1677 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1678 isa<ConstantSDNode>(N0.getOperand(1)))
1679 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1680 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1681 N0.getOperand(0), N1),
1682 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1683 N0.getOperand(1), N1));
1686 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1687 if (RMUL.getNode() != 0)
1693 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1694 SDValue N0 = N->getOperand(0);
1695 SDValue N1 = N->getOperand(1);
1696 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1697 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1698 EVT VT = N->getValueType(0);
1701 if (VT.isVector()) {
1702 SDValue FoldedVOp = SimplifyVBinOp(N);
1703 if (FoldedVOp.getNode()) return FoldedVOp;
1706 // fold (sdiv c1, c2) -> c1/c2
1707 if (N0C && N1C && !N1C->isNullValue())
1708 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1709 // fold (sdiv X, 1) -> X
1710 if (N1C && N1C->getSExtValue() == 1LL)
1712 // fold (sdiv X, -1) -> 0-X
1713 if (N1C && N1C->isAllOnesValue())
1714 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1715 DAG.getConstant(0, VT), N0);
1716 // If we know the sign bits of both operands are zero, strength reduce to a
1717 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1718 if (!VT.isVector()) {
1719 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1720 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1723 // fold (sdiv X, pow2) -> simple ops after legalize
1724 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1725 (isPowerOf2_64(N1C->getSExtValue()) ||
1726 isPowerOf2_64(-N1C->getSExtValue()))) {
1727 // If dividing by powers of two is cheap, then don't perform the following
1729 if (TLI.isPow2DivCheap())
1732 int64_t pow2 = N1C->getSExtValue();
1733 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1734 unsigned lg2 = Log2_64(abs2);
1736 // Splat the sign bit into the register
1737 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1738 DAG.getConstant(VT.getSizeInBits()-1,
1739 getShiftAmountTy()));
1740 AddToWorkList(SGN.getNode());
1742 // Add (N0 < 0) ? abs2 - 1 : 0;
1743 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1744 DAG.getConstant(VT.getSizeInBits() - lg2,
1745 getShiftAmountTy()));
1746 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1747 AddToWorkList(SRL.getNode());
1748 AddToWorkList(ADD.getNode()); // Divide by pow2
1749 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1750 DAG.getConstant(lg2, getShiftAmountTy()));
1752 // If we're dividing by a positive value, we're done. Otherwise, we must
1753 // negate the result.
1757 AddToWorkList(SRA.getNode());
1758 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1759 DAG.getConstant(0, VT), SRA);
1762 // if integer divide is expensive and we satisfy the requirements, emit an
1763 // alternate sequence.
1764 if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1765 !TLI.isIntDivCheap()) {
1766 SDValue Op = BuildSDIV(N);
1767 if (Op.getNode()) return Op;
1771 if (N0.getOpcode() == ISD::UNDEF)
1772 return DAG.getConstant(0, VT);
1773 // X / undef -> undef
1774 if (N1.getOpcode() == ISD::UNDEF)
1780 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1781 SDValue N0 = N->getOperand(0);
1782 SDValue N1 = N->getOperand(1);
1783 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1784 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1785 EVT VT = N->getValueType(0);
1788 if (VT.isVector()) {
1789 SDValue FoldedVOp = SimplifyVBinOp(N);
1790 if (FoldedVOp.getNode()) return FoldedVOp;
1793 // fold (udiv c1, c2) -> c1/c2
1794 if (N0C && N1C && !N1C->isNullValue())
1795 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1796 // fold (udiv x, (1 << c)) -> x >>u c
1797 if (N1C && N1C->getAPIntValue().isPowerOf2())
1798 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1799 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1800 getShiftAmountTy()));
1801 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1802 if (N1.getOpcode() == ISD::SHL) {
1803 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1804 if (SHC->getAPIntValue().isPowerOf2()) {
1805 EVT ADDVT = N1.getOperand(1).getValueType();
1806 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1808 DAG.getConstant(SHC->getAPIntValue()
1811 AddToWorkList(Add.getNode());
1812 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1816 // fold (udiv x, c) -> alternate
1817 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1818 SDValue Op = BuildUDIV(N);
1819 if (Op.getNode()) return Op;
1823 if (N0.getOpcode() == ISD::UNDEF)
1824 return DAG.getConstant(0, VT);
1825 // X / undef -> undef
1826 if (N1.getOpcode() == ISD::UNDEF)
1832 SDValue DAGCombiner::visitSREM(SDNode *N) {
1833 SDValue N0 = N->getOperand(0);
1834 SDValue N1 = N->getOperand(1);
1835 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1836 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1837 EVT VT = N->getValueType(0);
1839 // fold (srem c1, c2) -> c1%c2
1840 if (N0C && N1C && !N1C->isNullValue())
1841 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1842 // If we know the sign bits of both operands are zero, strength reduce to a
1843 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1844 if (!VT.isVector()) {
1845 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1846 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1849 // If X/C can be simplified by the division-by-constant logic, lower
1850 // X%C to the equivalent of X-X/C*C.
1851 if (N1C && !N1C->isNullValue()) {
1852 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1853 AddToWorkList(Div.getNode());
1854 SDValue OptimizedDiv = combine(Div.getNode());
1855 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1856 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1858 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1859 AddToWorkList(Mul.getNode());
1865 if (N0.getOpcode() == ISD::UNDEF)
1866 return DAG.getConstant(0, VT);
1867 // X % undef -> undef
1868 if (N1.getOpcode() == ISD::UNDEF)
1874 SDValue DAGCombiner::visitUREM(SDNode *N) {
1875 SDValue N0 = N->getOperand(0);
1876 SDValue N1 = N->getOperand(1);
1877 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1878 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1879 EVT VT = N->getValueType(0);
1881 // fold (urem c1, c2) -> c1%c2
1882 if (N0C && N1C && !N1C->isNullValue())
1883 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1884 // fold (urem x, pow2) -> (and x, pow2-1)
1885 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1886 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
1887 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1888 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1889 if (N1.getOpcode() == ISD::SHL) {
1890 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1891 if (SHC->getAPIntValue().isPowerOf2()) {
1893 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
1894 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1896 AddToWorkList(Add.getNode());
1897 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
1902 // If X/C can be simplified by the division-by-constant logic, lower
1903 // X%C to the equivalent of X-X/C*C.
1904 if (N1C && !N1C->isNullValue()) {
1905 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
1906 AddToWorkList(Div.getNode());
1907 SDValue OptimizedDiv = combine(Div.getNode());
1908 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1909 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1911 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1912 AddToWorkList(Mul.getNode());
1918 if (N0.getOpcode() == ISD::UNDEF)
1919 return DAG.getConstant(0, VT);
1920 // X % undef -> undef
1921 if (N1.getOpcode() == ISD::UNDEF)
1927 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1928 SDValue N0 = N->getOperand(0);
1929 SDValue N1 = N->getOperand(1);
1930 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1931 EVT VT = N->getValueType(0);
1932 DebugLoc DL = N->getDebugLoc();
1934 // fold (mulhs x, 0) -> 0
1935 if (N1C && N1C->isNullValue())
1937 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1938 if (N1C && N1C->getAPIntValue() == 1)
1939 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
1940 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
1941 getShiftAmountTy()));
1942 // fold (mulhs x, undef) -> 0
1943 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1944 return DAG.getConstant(0, VT);
1946 // If the type twice as wide is legal, transform the mulhs to a wider multiply
1948 if (VT.isSimple() && !VT.isVector()) {
1949 MVT Simple = VT.getSimpleVT();
1950 unsigned SimpleSize = Simple.getSizeInBits();
1951 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
1952 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
1953 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
1954 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
1955 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
1956 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
1957 DAG.getConstant(SimpleSize, getShiftAmountTy()));
1958 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
1965 SDValue DAGCombiner::visitMULHU(SDNode *N) {
1966 SDValue N0 = N->getOperand(0);
1967 SDValue N1 = N->getOperand(1);
1968 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1969 EVT VT = N->getValueType(0);
1970 DebugLoc DL = N->getDebugLoc();
1972 // fold (mulhu x, 0) -> 0
1973 if (N1C && N1C->isNullValue())
1975 // fold (mulhu x, 1) -> 0
1976 if (N1C && N1C->getAPIntValue() == 1)
1977 return DAG.getConstant(0, N0.getValueType());
1978 // fold (mulhu x, undef) -> 0
1979 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1980 return DAG.getConstant(0, VT);
1982 // If the type twice as wide is legal, transform the mulhu to a wider multiply
1984 if (VT.isSimple() && !VT.isVector()) {
1985 MVT Simple = VT.getSimpleVT();
1986 unsigned SimpleSize = Simple.getSizeInBits();
1987 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
1988 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
1989 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
1990 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
1991 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
1992 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
1993 DAG.getConstant(SimpleSize, getShiftAmountTy()));
1994 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2001 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2002 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2003 /// that are being performed. Return true if a simplification was made.
2005 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2007 // If the high half is not needed, just compute the low half.
2008 bool HiExists = N->hasAnyUseOfValue(1);
2010 (!LegalOperations ||
2011 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2012 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2013 N->op_begin(), N->getNumOperands());
2014 return CombineTo(N, Res, Res);
2017 // If the low half is not needed, just compute the high half.
2018 bool LoExists = N->hasAnyUseOfValue(0);
2020 (!LegalOperations ||
2021 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2022 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2023 N->op_begin(), N->getNumOperands());
2024 return CombineTo(N, Res, Res);
2027 // If both halves are used, return as it is.
2028 if (LoExists && HiExists)
2031 // If the two computed results can be simplified separately, separate them.
2033 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2034 N->op_begin(), N->getNumOperands());
2035 AddToWorkList(Lo.getNode());
2036 SDValue LoOpt = combine(Lo.getNode());
2037 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2038 (!LegalOperations ||
2039 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2040 return CombineTo(N, LoOpt, LoOpt);
2044 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2045 N->op_begin(), N->getNumOperands());
2046 AddToWorkList(Hi.getNode());
2047 SDValue HiOpt = combine(Hi.getNode());
2048 if (HiOpt.getNode() && HiOpt != Hi &&
2049 (!LegalOperations ||
2050 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2051 return CombineTo(N, HiOpt, HiOpt);
2057 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2058 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2059 if (Res.getNode()) return Res;
2061 EVT VT = N->getValueType(0);
2062 DebugLoc DL = N->getDebugLoc();
2064 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2066 if (VT.isSimple() && !VT.isVector()) {
2067 MVT Simple = VT.getSimpleVT();
2068 unsigned SimpleSize = Simple.getSizeInBits();
2069 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2070 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2071 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2072 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2073 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2074 // Compute the high part as N1.
2075 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2076 DAG.getConstant(SimpleSize, getShiftAmountTy()));
2077 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2078 // Compute the low part as N0.
2079 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2080 return CombineTo(N, Lo, Hi);
2087 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2088 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2089 if (Res.getNode()) return Res;
2091 EVT VT = N->getValueType(0);
2092 DebugLoc DL = N->getDebugLoc();
2094 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2096 if (VT.isSimple() && !VT.isVector()) {
2097 MVT Simple = VT.getSimpleVT();
2098 unsigned SimpleSize = Simple.getSizeInBits();
2099 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2100 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2101 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2102 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2103 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2104 // Compute the high part as N1.
2105 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2106 DAG.getConstant(SimpleSize, getShiftAmountTy()));
2107 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2108 // Compute the low part as N0.
2109 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2110 return CombineTo(N, Lo, Hi);
2117 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2118 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2119 if (Res.getNode()) return Res;
2124 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2125 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2126 if (Res.getNode()) return Res;
2131 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2132 /// two operands of the same opcode, try to simplify it.
2133 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2134 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2135 EVT VT = N0.getValueType();
2136 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2138 // Bail early if none of these transforms apply.
2139 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2141 // For each of OP in AND/OR/XOR:
2142 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2143 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2144 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2145 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2147 // do not sink logical op inside of a vector extend, since it may combine
2149 EVT Op0VT = N0.getOperand(0).getValueType();
2150 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2151 N0.getOpcode() == ISD::SIGN_EXTEND ||
2152 // Avoid infinite looping with PromoteIntBinOp.
2153 (N0.getOpcode() == ISD::ANY_EXTEND &&
2154 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2155 (N0.getOpcode() == ISD::TRUNCATE &&
2156 (!TLI.isZExtFree(VT, Op0VT) ||
2157 !TLI.isTruncateFree(Op0VT, VT)) &&
2158 TLI.isTypeLegal(Op0VT))) &&
2160 Op0VT == N1.getOperand(0).getValueType() &&
2161 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2162 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2163 N0.getOperand(0).getValueType(),
2164 N0.getOperand(0), N1.getOperand(0));
2165 AddToWorkList(ORNode.getNode());
2166 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2169 // For each of OP in SHL/SRL/SRA/AND...
2170 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2171 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2172 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2173 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2174 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2175 N0.getOperand(1) == N1.getOperand(1)) {
2176 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2177 N0.getOperand(0).getValueType(),
2178 N0.getOperand(0), N1.getOperand(0));
2179 AddToWorkList(ORNode.getNode());
2180 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2181 ORNode, N0.getOperand(1));
2187 SDValue DAGCombiner::visitAND(SDNode *N) {
2188 SDValue N0 = N->getOperand(0);
2189 SDValue N1 = N->getOperand(1);
2190 SDValue LL, LR, RL, RR, CC0, CC1;
2191 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2192 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2193 EVT VT = N1.getValueType();
2194 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2197 if (VT.isVector()) {
2198 SDValue FoldedVOp = SimplifyVBinOp(N);
2199 if (FoldedVOp.getNode()) return FoldedVOp;
2202 // fold (and x, undef) -> 0
2203 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2204 return DAG.getConstant(0, VT);
2205 // fold (and c1, c2) -> c1&c2
2207 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2208 // canonicalize constant to RHS
2210 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2211 // fold (and x, -1) -> x
2212 if (N1C && N1C->isAllOnesValue())
2214 // if (and x, c) is known to be zero, return 0
2215 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2216 APInt::getAllOnesValue(BitWidth)))
2217 return DAG.getConstant(0, VT);
2219 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2220 if (RAND.getNode() != 0)
2222 // fold (and (or x, C), D) -> D if (C & D) == D
2223 if (N1C && N0.getOpcode() == ISD::OR)
2224 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2225 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2227 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2228 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2229 SDValue N0Op0 = N0.getOperand(0);
2230 APInt Mask = ~N1C->getAPIntValue();
2231 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2232 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2233 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2234 N0.getValueType(), N0Op0);
2236 // Replace uses of the AND with uses of the Zero extend node.
2239 // We actually want to replace all uses of the any_extend with the
2240 // zero_extend, to avoid duplicating things. This will later cause this
2241 // AND to be folded.
2242 CombineTo(N0.getNode(), Zext);
2243 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2246 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2247 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2248 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2249 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2251 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2252 LL.getValueType().isInteger()) {
2253 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2254 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2255 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2256 LR.getValueType(), LL, RL);
2257 AddToWorkList(ORNode.getNode());
2258 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2260 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2261 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2262 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2263 LR.getValueType(), LL, RL);
2264 AddToWorkList(ANDNode.getNode());
2265 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2267 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2268 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2269 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2270 LR.getValueType(), LL, RL);
2271 AddToWorkList(ORNode.getNode());
2272 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2275 // canonicalize equivalent to ll == rl
2276 if (LL == RR && LR == RL) {
2277 Op1 = ISD::getSetCCSwappedOperands(Op1);
2280 if (LL == RL && LR == RR) {
2281 bool isInteger = LL.getValueType().isInteger();
2282 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2283 if (Result != ISD::SETCC_INVALID &&
2284 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2285 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2290 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2291 if (N0.getOpcode() == N1.getOpcode()) {
2292 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2293 if (Tmp.getNode()) return Tmp;
2296 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2297 // fold (and (sra)) -> (and (srl)) when possible.
2298 if (!VT.isVector() &&
2299 SimplifyDemandedBits(SDValue(N, 0)))
2300 return SDValue(N, 0);
2302 // fold (zext_inreg (extload x)) -> (zextload x)
2303 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2304 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2305 EVT MemVT = LN0->getMemoryVT();
2306 // If we zero all the possible extended bits, then we can turn this into
2307 // a zextload if we are running before legalize or the operation is legal.
2308 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2309 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2310 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2311 ((!LegalOperations && !LN0->isVolatile()) ||
2312 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2313 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getDebugLoc(),
2314 LN0->getChain(), LN0->getBasePtr(),
2315 LN0->getPointerInfo(), MemVT,
2316 LN0->isVolatile(), LN0->isNonTemporal(),
2317 LN0->getAlignment());
2319 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2320 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2323 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2324 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2326 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2327 EVT MemVT = LN0->getMemoryVT();
2328 // If we zero all the possible extended bits, then we can turn this into
2329 // a zextload if we are running before legalize or the operation is legal.
2330 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2331 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2332 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2333 ((!LegalOperations && !LN0->isVolatile()) ||
2334 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2335 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getDebugLoc(),
2337 LN0->getBasePtr(), LN0->getPointerInfo(),
2339 LN0->isVolatile(), LN0->isNonTemporal(),
2340 LN0->getAlignment());
2342 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2343 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2347 // fold (and (load x), 255) -> (zextload x, i8)
2348 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2349 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2350 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2351 (N0.getOpcode() == ISD::ANY_EXTEND &&
2352 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2353 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2354 LoadSDNode *LN0 = HasAnyExt
2355 ? cast<LoadSDNode>(N0.getOperand(0))
2356 : cast<LoadSDNode>(N0);
2357 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2358 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2359 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2360 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2361 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2362 EVT LoadedVT = LN0->getMemoryVT();
2364 if (ExtVT == LoadedVT &&
2365 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2366 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2369 DAG.getExtLoad(ISD::ZEXTLOAD, LoadResultTy, LN0->getDebugLoc(),
2370 LN0->getChain(), LN0->getBasePtr(),
2371 LN0->getPointerInfo(),
2372 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2373 LN0->getAlignment());
2375 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2376 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2379 // Do not change the width of a volatile load.
2380 // Do not generate loads of non-round integer types since these can
2381 // be expensive (and would be wrong if the type is not byte sized).
2382 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2383 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2384 EVT PtrType = LN0->getOperand(1).getValueType();
2386 unsigned Alignment = LN0->getAlignment();
2387 SDValue NewPtr = LN0->getBasePtr();
2389 // For big endian targets, we need to add an offset to the pointer
2390 // to load the correct bytes. For little endian systems, we merely
2391 // need to read fewer bytes from the same pointer.
2392 if (TLI.isBigEndian()) {
2393 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2394 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2395 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2396 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2397 NewPtr, DAG.getConstant(PtrOff, PtrType));
2398 Alignment = MinAlign(Alignment, PtrOff);
2401 AddToWorkList(NewPtr.getNode());
2403 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2405 DAG.getExtLoad(ISD::ZEXTLOAD, LoadResultTy, LN0->getDebugLoc(),
2406 LN0->getChain(), NewPtr,
2407 LN0->getPointerInfo(),
2408 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2411 CombineTo(LN0, Load, Load.getValue(1));
2412 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2421 SDValue DAGCombiner::visitOR(SDNode *N) {
2422 SDValue N0 = N->getOperand(0);
2423 SDValue N1 = N->getOperand(1);
2424 SDValue LL, LR, RL, RR, CC0, CC1;
2425 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2426 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2427 EVT VT = N1.getValueType();
2430 if (VT.isVector()) {
2431 SDValue FoldedVOp = SimplifyVBinOp(N);
2432 if (FoldedVOp.getNode()) return FoldedVOp;
2435 // fold (or x, undef) -> -1
2436 if (!LegalOperations &&
2437 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
2438 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
2439 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
2441 // fold (or c1, c2) -> c1|c2
2443 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
2444 // canonicalize constant to RHS
2446 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
2447 // fold (or x, 0) -> x
2448 if (N1C && N1C->isNullValue())
2450 // fold (or x, -1) -> -1
2451 if (N1C && N1C->isAllOnesValue())
2453 // fold (or x, c) -> c iff (x & ~c) == 0
2454 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
2457 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
2458 if (ROR.getNode() != 0)
2460 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
2461 // iff (c1 & c2) == 0.
2462 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
2463 isa<ConstantSDNode>(N0.getOperand(1))) {
2464 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
2465 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
2466 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
2467 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2468 N0.getOperand(0), N1),
2469 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
2471 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
2472 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2473 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2474 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2476 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2477 LL.getValueType().isInteger()) {
2478 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
2479 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
2480 if (cast<ConstantSDNode>(LR)->isNullValue() &&
2481 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
2482 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
2483 LR.getValueType(), LL, RL);
2484 AddToWorkList(ORNode.getNode());
2485 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2487 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
2488 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
2489 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2490 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
2491 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
2492 LR.getValueType(), LL, RL);
2493 AddToWorkList(ANDNode.getNode());
2494 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2497 // canonicalize equivalent to ll == rl
2498 if (LL == RR && LR == RL) {
2499 Op1 = ISD::getSetCCSwappedOperands(Op1);
2502 if (LL == RL && LR == RR) {
2503 bool isInteger = LL.getValueType().isInteger();
2504 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
2505 if (Result != ISD::SETCC_INVALID &&
2506 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2507 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2512 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
2513 if (N0.getOpcode() == N1.getOpcode()) {
2514 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2515 if (Tmp.getNode()) return Tmp;
2518 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
2519 if (N0.getOpcode() == ISD::AND &&
2520 N1.getOpcode() == ISD::AND &&
2521 N0.getOperand(1).getOpcode() == ISD::Constant &&
2522 N1.getOperand(1).getOpcode() == ISD::Constant &&
2523 // Don't increase # computations.
2524 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2525 // We can only do this xform if we know that bits from X that are set in C2
2526 // but not in C1 are already zero. Likewise for Y.
2527 const APInt &LHSMask =
2528 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2529 const APInt &RHSMask =
2530 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2532 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2533 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2534 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2535 N0.getOperand(0), N1.getOperand(0));
2536 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
2537 DAG.getConstant(LHSMask | RHSMask, VT));
2541 // See if this is some rotate idiom.
2542 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
2543 return SDValue(Rot, 0);
2545 // Simplify the operands using demanded-bits information.
2546 if (!VT.isVector() &&
2547 SimplifyDemandedBits(SDValue(N, 0)))
2548 return SDValue(N, 0);
2553 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2554 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2555 if (Op.getOpcode() == ISD::AND) {
2556 if (isa<ConstantSDNode>(Op.getOperand(1))) {
2557 Mask = Op.getOperand(1);
2558 Op = Op.getOperand(0);
2564 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2572 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
2573 // idioms for rotate, and if the target supports rotation instructions, generate
2575 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
2576 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
2577 EVT VT = LHS.getValueType();
2578 if (!TLI.isTypeLegal(VT)) return 0;
2580 // The target must have at least one rotate flavor.
2581 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
2582 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
2583 if (!HasROTL && !HasROTR) return 0;
2585 // Match "(X shl/srl V1) & V2" where V2 may not be present.
2586 SDValue LHSShift; // The shift.
2587 SDValue LHSMask; // AND value if any.
2588 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2589 return 0; // Not part of a rotate.
2591 SDValue RHSShift; // The shift.
2592 SDValue RHSMask; // AND value if any.
2593 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2594 return 0; // Not part of a rotate.
2596 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2597 return 0; // Not shifting the same value.
2599 if (LHSShift.getOpcode() == RHSShift.getOpcode())
2600 return 0; // Shifts must disagree.
2602 // Canonicalize shl to left side in a shl/srl pair.
2603 if (RHSShift.getOpcode() == ISD::SHL) {
2604 std::swap(LHS, RHS);
2605 std::swap(LHSShift, RHSShift);
2606 std::swap(LHSMask , RHSMask );
2609 unsigned OpSizeInBits = VT.getSizeInBits();
2610 SDValue LHSShiftArg = LHSShift.getOperand(0);
2611 SDValue LHSShiftAmt = LHSShift.getOperand(1);
2612 SDValue RHSShiftAmt = RHSShift.getOperand(1);
2614 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2615 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2616 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2617 RHSShiftAmt.getOpcode() == ISD::Constant) {
2618 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2619 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2620 if ((LShVal + RShVal) != OpSizeInBits)
2625 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
2627 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
2629 // If there is an AND of either shifted operand, apply it to the result.
2630 if (LHSMask.getNode() || RHSMask.getNode()) {
2631 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2633 if (LHSMask.getNode()) {
2634 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2635 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2637 if (RHSMask.getNode()) {
2638 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2639 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2642 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
2645 return Rot.getNode();
2648 // If there is a mask here, and we have a variable shift, we can't be sure
2649 // that we're masking out the right stuff.
2650 if (LHSMask.getNode() || RHSMask.getNode())
2653 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2654 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2655 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2656 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2657 if (ConstantSDNode *SUBC =
2658 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2659 if (SUBC->getAPIntValue() == OpSizeInBits) {
2661 return DAG.getNode(ISD::ROTL, DL, VT,
2662 LHSShiftArg, LHSShiftAmt).getNode();
2664 return DAG.getNode(ISD::ROTR, DL, VT,
2665 LHSShiftArg, RHSShiftAmt).getNode();
2670 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2671 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2672 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2673 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2674 if (ConstantSDNode *SUBC =
2675 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2676 if (SUBC->getAPIntValue() == OpSizeInBits) {
2678 return DAG.getNode(ISD::ROTR, DL, VT,
2679 LHSShiftArg, RHSShiftAmt).getNode();
2681 return DAG.getNode(ISD::ROTL, DL, VT,
2682 LHSShiftArg, LHSShiftAmt).getNode();
2687 // Look for sign/zext/any-extended or truncate cases:
2688 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2689 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2690 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2691 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2692 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2693 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2694 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2695 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2696 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2697 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2698 if (RExtOp0.getOpcode() == ISD::SUB &&
2699 RExtOp0.getOperand(1) == LExtOp0) {
2700 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2702 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2703 // (rotr x, (sub 32, y))
2704 if (ConstantSDNode *SUBC =
2705 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2706 if (SUBC->getAPIntValue() == OpSizeInBits) {
2707 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
2709 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2712 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2713 RExtOp0 == LExtOp0.getOperand(1)) {
2714 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2716 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2717 // (rotl x, (sub 32, y))
2718 if (ConstantSDNode *SUBC =
2719 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2720 if (SUBC->getAPIntValue() == OpSizeInBits) {
2721 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
2723 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2732 SDValue DAGCombiner::visitXOR(SDNode *N) {
2733 SDValue N0 = N->getOperand(0);
2734 SDValue N1 = N->getOperand(1);
2735 SDValue LHS, RHS, CC;
2736 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2737 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2738 EVT VT = N0.getValueType();
2741 if (VT.isVector()) {
2742 SDValue FoldedVOp = SimplifyVBinOp(N);
2743 if (FoldedVOp.getNode()) return FoldedVOp;
2746 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2747 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2748 return DAG.getConstant(0, VT);
2749 // fold (xor x, undef) -> undef
2750 if (N0.getOpcode() == ISD::UNDEF)
2752 if (N1.getOpcode() == ISD::UNDEF)
2754 // fold (xor c1, c2) -> c1^c2
2756 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2757 // canonicalize constant to RHS
2759 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
2760 // fold (xor x, 0) -> x
2761 if (N1C && N1C->isNullValue())
2764 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
2765 if (RXOR.getNode() != 0)
2768 // fold !(x cc y) -> (x !cc y)
2769 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2770 bool isInt = LHS.getValueType().isInteger();
2771 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2774 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
2775 switch (N0.getOpcode()) {
2777 llvm_unreachable("Unhandled SetCC Equivalent!");
2779 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
2780 case ISD::SELECT_CC:
2781 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
2782 N0.getOperand(3), NotCC);
2787 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2788 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2789 N0.getNode()->hasOneUse() &&
2790 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2791 SDValue V = N0.getOperand(0);
2792 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
2793 DAG.getConstant(1, V.getValueType()));
2794 AddToWorkList(V.getNode());
2795 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
2798 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
2799 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2800 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2801 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2802 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2803 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2804 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2805 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2806 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2807 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2810 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
2811 if (N1C && N1C->isAllOnesValue() &&
2812 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2813 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2814 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2815 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2816 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2817 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2818 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2819 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2822 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
2823 if (N1C && N0.getOpcode() == ISD::XOR) {
2824 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2825 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2827 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
2828 DAG.getConstant(N1C->getAPIntValue() ^
2829 N00C->getAPIntValue(), VT));
2831 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
2832 DAG.getConstant(N1C->getAPIntValue() ^
2833 N01C->getAPIntValue(), VT));
2835 // fold (xor x, x) -> 0
2837 if (!VT.isVector()) {
2838 return DAG.getConstant(0, VT);
2839 } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)){
2840 // Produce a vector of zeros.
2841 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
2842 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
2843 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
2844 &Ops[0], Ops.size());
2848 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2849 if (N0.getOpcode() == N1.getOpcode()) {
2850 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2851 if (Tmp.getNode()) return Tmp;
2854 // Simplify the expression using non-local knowledge.
2855 if (!VT.isVector() &&
2856 SimplifyDemandedBits(SDValue(N, 0)))
2857 return SDValue(N, 0);
2862 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2863 /// the shift amount is a constant.
2864 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2865 SDNode *LHS = N->getOperand(0).getNode();
2866 if (!LHS->hasOneUse()) return SDValue();
2868 // We want to pull some binops through shifts, so that we have (and (shift))
2869 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2870 // thing happens with address calculations, so it's important to canonicalize
2872 bool HighBitSet = false; // Can we transform this if the high bit is set?
2874 switch (LHS->getOpcode()) {
2875 default: return SDValue();
2878 HighBitSet = false; // We can only transform sra if the high bit is clear.
2881 HighBitSet = true; // We can only transform sra if the high bit is set.
2884 if (N->getOpcode() != ISD::SHL)
2885 return SDValue(); // only shl(add) not sr[al](add).
2886 HighBitSet = false; // We can only transform sra if the high bit is clear.
2890 // We require the RHS of the binop to be a constant as well.
2891 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2892 if (!BinOpCst) return SDValue();
2894 // FIXME: disable this unless the input to the binop is a shift by a constant.
2895 // If it is not a shift, it pessimizes some common cases like:
2897 // void foo(int *X, int i) { X[i & 1235] = 1; }
2898 // int bar(int *X, int i) { return X[i & 255]; }
2899 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2900 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2901 BinOpLHSVal->getOpcode() != ISD::SRA &&
2902 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2903 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2906 EVT VT = N->getValueType(0);
2908 // If this is a signed shift right, and the high bit is modified by the
2909 // logical operation, do not perform the transformation. The highBitSet
2910 // boolean indicates the value of the high bit of the constant which would
2911 // cause it to be modified for this operation.
2912 if (N->getOpcode() == ISD::SRA) {
2913 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2914 if (BinOpRHSSignSet != HighBitSet)
2918 // Fold the constants, shifting the binop RHS by the shift amount.
2919 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
2921 LHS->getOperand(1), N->getOperand(1));
2923 // Create the new shift.
2924 SDValue NewShift = DAG.getNode(N->getOpcode(),
2925 LHS->getOperand(0).getDebugLoc(),
2926 VT, LHS->getOperand(0), N->getOperand(1));
2928 // Create the new binop.
2929 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
2932 SDValue DAGCombiner::visitSHL(SDNode *N) {
2933 SDValue N0 = N->getOperand(0);
2934 SDValue N1 = N->getOperand(1);
2935 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2936 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2937 EVT VT = N0.getValueType();
2938 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2940 // fold (shl c1, c2) -> c1<<c2
2942 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
2943 // fold (shl 0, x) -> 0
2944 if (N0C && N0C->isNullValue())
2946 // fold (shl x, c >= size(x)) -> undef
2947 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2948 return DAG.getUNDEF(VT);
2949 // fold (shl x, 0) -> x
2950 if (N1C && N1C->isNullValue())
2952 // if (shl x, c) is known to be zero, return 0
2953 if (DAG.MaskedValueIsZero(SDValue(N, 0),
2954 APInt::getAllOnesValue(OpSizeInBits)))
2955 return DAG.getConstant(0, VT);
2956 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
2957 if (N1.getOpcode() == ISD::TRUNCATE &&
2958 N1.getOperand(0).getOpcode() == ISD::AND &&
2959 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2960 SDValue N101 = N1.getOperand(0).getOperand(1);
2961 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2962 EVT TruncVT = N1.getValueType();
2963 SDValue N100 = N1.getOperand(0).getOperand(0);
2964 APInt TruncC = N101C->getAPIntValue();
2965 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
2966 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
2967 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
2968 DAG.getNode(ISD::TRUNCATE,
2971 DAG.getConstant(TruncC, TruncVT)));
2975 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2976 return SDValue(N, 0);
2978 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
2979 if (N1C && N0.getOpcode() == ISD::SHL &&
2980 N0.getOperand(1).getOpcode() == ISD::Constant) {
2981 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2982 uint64_t c2 = N1C->getZExtValue();
2983 if (c1 + c2 >= OpSizeInBits)
2984 return DAG.getConstant(0, VT);
2985 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
2986 DAG.getConstant(c1 + c2, N1.getValueType()));
2989 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
2990 // For this to be valid, the second form must not preserve any of the bits
2991 // that are shifted out by the inner shift in the first form. This means
2992 // the outer shift size must be >= the number of bits added by the ext.
2993 // As a corollary, we don't care what kind of ext it is.
2994 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
2995 N0.getOpcode() == ISD::ANY_EXTEND ||
2996 N0.getOpcode() == ISD::SIGN_EXTEND) &&
2997 N0.getOperand(0).getOpcode() == ISD::SHL &&
2998 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3000 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3001 uint64_t c2 = N1C->getZExtValue();
3002 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3003 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3004 if (c2 >= OpSizeInBits - InnerShiftSize) {
3005 if (c1 + c2 >= OpSizeInBits)
3006 return DAG.getConstant(0, VT);
3007 return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
3008 DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
3009 N0.getOperand(0)->getOperand(0)),
3010 DAG.getConstant(c1 + c2, N1.getValueType()));
3014 // fold (shl (srl x, c1), c2) -> (shl (and x, (shl -1, c1)), (sub c2, c1)) or
3015 // (srl (and x, (shl -1, c1)), (sub c1, c2))
3016 if (N1C && N0.getOpcode() == ISD::SRL &&
3017 N0.getOperand(1).getOpcode() == ISD::Constant) {
3018 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3019 if (c1 < VT.getSizeInBits()) {
3020 uint64_t c2 = N1C->getZExtValue();
3021 SDValue HiBitsMask =
3022 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3023 VT.getSizeInBits() - c1),
3025 SDValue Mask = DAG.getNode(ISD::AND, N0.getDebugLoc(), VT,
3029 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, Mask,
3030 DAG.getConstant(c2-c1, N1.getValueType()));
3032 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Mask,
3033 DAG.getConstant(c1-c2, N1.getValueType()));
3036 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3037 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3038 SDValue HiBitsMask =
3039 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3040 VT.getSizeInBits() -
3041 N1C->getZExtValue()),
3043 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3048 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3049 if (NewSHL.getNode())
3056 SDValue DAGCombiner::visitSRA(SDNode *N) {
3057 SDValue N0 = N->getOperand(0);
3058 SDValue N1 = N->getOperand(1);
3059 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3060 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3061 EVT VT = N0.getValueType();
3062 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3064 // fold (sra c1, c2) -> (sra c1, c2)
3066 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3067 // fold (sra 0, x) -> 0
3068 if (N0C && N0C->isNullValue())
3070 // fold (sra -1, x) -> -1
3071 if (N0C && N0C->isAllOnesValue())
3073 // fold (sra x, (setge c, size(x))) -> undef
3074 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3075 return DAG.getUNDEF(VT);
3076 // fold (sra x, 0) -> x
3077 if (N1C && N1C->isNullValue())
3079 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3081 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3082 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3083 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3085 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3086 ExtVT, VT.getVectorNumElements());
3087 if ((!LegalOperations ||
3088 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3089 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3090 N0.getOperand(0), DAG.getValueType(ExtVT));
3093 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3094 if (N1C && N0.getOpcode() == ISD::SRA) {
3095 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3096 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3097 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3098 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
3099 DAG.getConstant(Sum, N1C->getValueType(0)));
3103 // fold (sra (shl X, m), (sub result_size, n))
3104 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3105 // result_size - n != m.
3106 // If truncate is free for the target sext(shl) is likely to result in better
3108 if (N0.getOpcode() == ISD::SHL) {
3109 // Get the two constanst of the shifts, CN0 = m, CN = n.
3110 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3112 // Determine what the truncate's result bitsize and type would be.
3114 EVT::getIntegerVT(*DAG.getContext(),
3115 OpSizeInBits - N1C->getZExtValue());
3116 // Determine the residual right-shift amount.
3117 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3119 // If the shift is not a no-op (in which case this should be just a sign
3120 // extend already), the truncated to type is legal, sign_extend is legal
3121 // on that type, and the truncate to that type is both legal and free,
3122 // perform the transform.
3123 if ((ShiftAmt > 0) &&
3124 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3125 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3126 TLI.isTruncateFree(VT, TruncVT)) {
3128 SDValue Amt = DAG.getConstant(ShiftAmt, getShiftAmountTy());
3129 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3130 N0.getOperand(0), Amt);
3131 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3133 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3134 N->getValueType(0), Trunc);
3139 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3140 if (N1.getOpcode() == ISD::TRUNCATE &&
3141 N1.getOperand(0).getOpcode() == ISD::AND &&
3142 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3143 SDValue N101 = N1.getOperand(0).getOperand(1);
3144 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3145 EVT TruncVT = N1.getValueType();
3146 SDValue N100 = N1.getOperand(0).getOperand(0);
3147 APInt TruncC = N101C->getAPIntValue();
3148 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3149 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3150 DAG.getNode(ISD::AND, N->getDebugLoc(),
3152 DAG.getNode(ISD::TRUNCATE,
3155 DAG.getConstant(TruncC, TruncVT)));
3159 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3160 // if c1 is equal to the number of bits the trunc removes
3161 if (N0.getOpcode() == ISD::TRUNCATE &&
3162 (N0.getOperand(0).getOpcode() == ISD::SRL ||
3163 N0.getOperand(0).getOpcode() == ISD::SRA) &&
3164 N0.getOperand(0).hasOneUse() &&
3165 N0.getOperand(0).getOperand(1).hasOneUse() &&
3166 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3167 EVT LargeVT = N0.getOperand(0).getValueType();
3168 ConstantSDNode *LargeShiftAmt =
3169 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3171 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3172 LargeShiftAmt->getZExtValue()) {
3174 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3175 getShiftAmountTy());
3176 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
3177 N0.getOperand(0).getOperand(0), Amt);
3178 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
3182 // Simplify, based on bits shifted out of the LHS.
3183 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3184 return SDValue(N, 0);
3187 // If the sign bit is known to be zero, switch this to a SRL.
3188 if (DAG.SignBitIsZero(N0))
3189 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3192 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3193 if (NewSRA.getNode())
3200 SDValue DAGCombiner::visitSRL(SDNode *N) {
3201 SDValue N0 = N->getOperand(0);
3202 SDValue N1 = N->getOperand(1);
3203 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3204 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3205 EVT VT = N0.getValueType();
3206 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3208 // fold (srl c1, c2) -> c1 >>u c2
3210 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3211 // fold (srl 0, x) -> 0
3212 if (N0C && N0C->isNullValue())
3214 // fold (srl x, c >= size(x)) -> undef
3215 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3216 return DAG.getUNDEF(VT);
3217 // fold (srl x, 0) -> x
3218 if (N1C && N1C->isNullValue())
3220 // if (srl x, c) is known to be zero, return 0
3221 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3222 APInt::getAllOnesValue(OpSizeInBits)))
3223 return DAG.getConstant(0, VT);
3225 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3226 if (N1C && N0.getOpcode() == ISD::SRL &&
3227 N0.getOperand(1).getOpcode() == ISD::Constant) {
3228 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3229 uint64_t c2 = N1C->getZExtValue();
3230 if (c1 + c2 >= OpSizeInBits)
3231 return DAG.getConstant(0, VT);
3232 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3233 DAG.getConstant(c1 + c2, N1.getValueType()));
3236 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3237 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3238 N0.getOperand(0).getOpcode() == ISD::SRL &&
3239 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3241 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3242 uint64_t c2 = N1C->getZExtValue();
3243 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3244 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3245 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3246 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3247 if (c1 + OpSizeInBits == InnerShiftSize) {
3248 if (c1 + c2 >= InnerShiftSize)
3249 return DAG.getConstant(0, VT);
3250 return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
3251 DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
3252 N0.getOperand(0)->getOperand(0),
3253 DAG.getConstant(c1 + c2, ShiftCountVT)));
3257 // fold (srl (shl x, c), c) -> (and x, cst2)
3258 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3259 N0.getValueSizeInBits() <= 64) {
3260 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3261 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3262 DAG.getConstant(~0ULL >> ShAmt, VT));
3266 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3267 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3268 // Shifting in all undef bits?
3269 EVT SmallVT = N0.getOperand(0).getValueType();
3270 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3271 return DAG.getUNDEF(VT);
3273 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3274 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3275 N0.getOperand(0), N1);
3276 AddToWorkList(SmallShift.getNode());
3277 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3281 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
3282 // bit, which is unmodified by sra.
3283 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3284 if (N0.getOpcode() == ISD::SRA)
3285 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3288 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
3289 if (N1C && N0.getOpcode() == ISD::CTLZ &&
3290 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3291 APInt KnownZero, KnownOne;
3292 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
3293 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
3295 // If any of the input bits are KnownOne, then the input couldn't be all
3296 // zeros, thus the result of the srl will always be zero.
3297 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3299 // If all of the bits input the to ctlz node are known to be zero, then
3300 // the result of the ctlz is "32" and the result of the shift is one.
3301 APInt UnknownBits = ~KnownZero & Mask;
3302 if (UnknownBits == 0) return DAG.getConstant(1, VT);
3304 // Otherwise, check to see if there is exactly one bit input to the ctlz.
3305 if ((UnknownBits & (UnknownBits - 1)) == 0) {
3306 // Okay, we know that only that the single bit specified by UnknownBits
3307 // could be set on input to the CTLZ node. If this bit is set, the SRL
3308 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3309 // to an SRL/XOR pair, which is likely to simplify more.
3310 unsigned ShAmt = UnknownBits.countTrailingZeros();
3311 SDValue Op = N0.getOperand(0);
3314 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3315 DAG.getConstant(ShAmt, getShiftAmountTy()));
3316 AddToWorkList(Op.getNode());
3319 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3320 Op, DAG.getConstant(1, VT));
3324 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3325 if (N1.getOpcode() == ISD::TRUNCATE &&
3326 N1.getOperand(0).getOpcode() == ISD::AND &&
3327 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3328 SDValue N101 = N1.getOperand(0).getOperand(1);
3329 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3330 EVT TruncVT = N1.getValueType();
3331 SDValue N100 = N1.getOperand(0).getOperand(0);
3332 APInt TruncC = N101C->getAPIntValue();
3333 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3334 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3335 DAG.getNode(ISD::AND, N->getDebugLoc(),
3337 DAG.getNode(ISD::TRUNCATE,
3340 DAG.getConstant(TruncC, TruncVT)));
3344 // fold operands of srl based on knowledge that the low bits are not
3346 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3347 return SDValue(N, 0);
3350 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3351 if (NewSRL.getNode())
3355 // Attempt to convert a srl of a load into a narrower zero-extending load.
3356 SDValue NarrowLoad = ReduceLoadWidth(N);
3357 if (NarrowLoad.getNode())
3360 // Here is a common situation. We want to optimize:
3363 // %b = and i32 %a, 2
3364 // %c = srl i32 %b, 1
3365 // brcond i32 %c ...
3371 // %c = setcc eq %b, 0
3374 // However when after the source operand of SRL is optimized into AND, the SRL
3375 // itself may not be optimized further. Look for it and add the BRCOND into
3377 if (N->hasOneUse()) {
3378 SDNode *Use = *N->use_begin();
3379 if (Use->getOpcode() == ISD::BRCOND)
3381 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3382 // Also look pass the truncate.
3383 Use = *Use->use_begin();
3384 if (Use->getOpcode() == ISD::BRCOND)
3392 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3393 SDValue N0 = N->getOperand(0);
3394 EVT VT = N->getValueType(0);
3396 // fold (ctlz c1) -> c2
3397 if (isa<ConstantSDNode>(N0))
3398 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3402 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
3403 SDValue N0 = N->getOperand(0);
3404 EVT VT = N->getValueType(0);
3406 // fold (cttz c1) -> c2
3407 if (isa<ConstantSDNode>(N0))
3408 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
3412 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
3413 SDValue N0 = N->getOperand(0);
3414 EVT VT = N->getValueType(0);
3416 // fold (ctpop c1) -> c2
3417 if (isa<ConstantSDNode>(N0))
3418 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
3422 SDValue DAGCombiner::visitSELECT(SDNode *N) {
3423 SDValue N0 = N->getOperand(0);
3424 SDValue N1 = N->getOperand(1);
3425 SDValue N2 = N->getOperand(2);
3426 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3427 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3428 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3429 EVT VT = N->getValueType(0);
3430 EVT VT0 = N0.getValueType();
3432 // fold (select C, X, X) -> X
3435 // fold (select true, X, Y) -> X
3436 if (N0C && !N0C->isNullValue())
3438 // fold (select false, X, Y) -> Y
3439 if (N0C && N0C->isNullValue())
3441 // fold (select C, 1, X) -> (or C, X)
3442 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
3443 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3444 // fold (select C, 0, 1) -> (xor C, 1)
3445 if (VT.isInteger() &&
3448 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) &&
3449 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
3452 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
3453 N0, DAG.getConstant(1, VT0));
3454 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
3455 N0, DAG.getConstant(1, VT0));
3456 AddToWorkList(XORNode.getNode());
3458 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
3459 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
3461 // fold (select C, 0, X) -> (and (not C), X)
3462 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
3463 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3464 AddToWorkList(NOTNode.getNode());
3465 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
3467 // fold (select C, X, 1) -> (or (not C), X)
3468 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
3469 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3470 AddToWorkList(NOTNode.getNode());
3471 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
3473 // fold (select C, X, 0) -> (and C, X)
3474 if (VT == MVT::i1 && N2C && N2C->isNullValue())
3475 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3476 // fold (select X, X, Y) -> (or X, Y)
3477 // fold (select X, 1, Y) -> (or X, Y)
3478 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
3479 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3480 // fold (select X, Y, X) -> (and X, Y)
3481 // fold (select X, Y, 0) -> (and X, Y)
3482 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
3483 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3485 // If we can fold this based on the true/false value, do so.
3486 if (SimplifySelectOps(N, N1, N2))
3487 return SDValue(N, 0); // Don't revisit N.
3489 // fold selects based on a setcc into other things, such as min/max/abs
3490 if (N0.getOpcode() == ISD::SETCC) {
3492 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
3493 // having to say they don't support SELECT_CC on every type the DAG knows
3494 // about, since there is no way to mark an opcode illegal at all value types
3495 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
3496 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
3497 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
3498 N0.getOperand(0), N0.getOperand(1),
3499 N1, N2, N0.getOperand(2));
3500 return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
3506 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
3507 SDValue N0 = N->getOperand(0);
3508 SDValue N1 = N->getOperand(1);
3509 SDValue N2 = N->getOperand(2);
3510 SDValue N3 = N->getOperand(3);
3511 SDValue N4 = N->getOperand(4);
3512 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
3514 // fold select_cc lhs, rhs, x, x, cc -> x
3518 // Determine if the condition we're dealing with is constant
3519 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
3520 N0, N1, CC, N->getDebugLoc(), false);
3521 if (SCC.getNode()) AddToWorkList(SCC.getNode());
3523 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
3524 if (!SCCC->isNullValue())
3525 return N2; // cond always true -> true val
3527 return N3; // cond always false -> false val
3530 // Fold to a simpler select_cc
3531 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
3532 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
3533 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
3536 // If we can fold this based on the true/false value, do so.
3537 if (SimplifySelectOps(N, N2, N3))
3538 return SDValue(N, 0); // Don't revisit N.
3540 // fold select_cc into other things, such as min/max/abs
3541 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
3544 SDValue DAGCombiner::visitSETCC(SDNode *N) {
3545 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
3546 cast<CondCodeSDNode>(N->getOperand(2))->get(),
3550 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
3551 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
3552 // transformation. Returns true if extension are possible and the above
3553 // mentioned transformation is profitable.
3554 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
3556 SmallVector<SDNode*, 4> &ExtendNodes,
3557 const TargetLowering &TLI) {
3558 bool HasCopyToRegUses = false;
3559 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
3560 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
3561 UE = N0.getNode()->use_end();
3566 if (UI.getUse().getResNo() != N0.getResNo())
3568 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
3569 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
3570 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
3571 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
3572 // Sign bits will be lost after a zext.
3575 for (unsigned i = 0; i != 2; ++i) {
3576 SDValue UseOp = User->getOperand(i);
3579 if (!isa<ConstantSDNode>(UseOp))
3584 ExtendNodes.push_back(User);
3587 // If truncates aren't free and there are users we can't
3588 // extend, it isn't worthwhile.
3591 // Remember if this value is live-out.
3592 if (User->getOpcode() == ISD::CopyToReg)
3593 HasCopyToRegUses = true;
3596 if (HasCopyToRegUses) {
3597 bool BothLiveOut = false;
3598 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3600 SDUse &Use = UI.getUse();
3601 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
3607 // Both unextended and extended values are live out. There had better be
3608 // a good reason for the transformation.
3609 return ExtendNodes.size();
3614 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
3615 SDValue N0 = N->getOperand(0);
3616 EVT VT = N->getValueType(0);
3618 // fold (sext c1) -> c1
3619 if (isa<ConstantSDNode>(N0))
3620 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
3622 // fold (sext (sext x)) -> (sext x)
3623 // fold (sext (aext x)) -> (sext x)
3624 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3625 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
3628 if (N0.getOpcode() == ISD::TRUNCATE) {
3629 // fold (sext (truncate (load x))) -> (sext (smaller load x))
3630 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
3631 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3632 if (NarrowLoad.getNode()) {
3633 SDNode* oye = N0.getNode()->getOperand(0).getNode();
3634 if (NarrowLoad.getNode() != N0.getNode()) {
3635 CombineTo(N0.getNode(), NarrowLoad);
3636 // CombineTo deleted the truncate, if needed, but not what's under it.
3639 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3642 // See if the value being truncated is already sign extended. If so, just
3643 // eliminate the trunc/sext pair.
3644 SDValue Op = N0.getOperand(0);
3645 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
3646 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
3647 unsigned DestBits = VT.getScalarType().getSizeInBits();
3648 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
3650 if (OpBits == DestBits) {
3651 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
3652 // bits, it is already ready.
3653 if (NumSignBits > DestBits-MidBits)
3655 } else if (OpBits < DestBits) {
3656 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
3657 // bits, just sext from i32.
3658 if (NumSignBits > OpBits-MidBits)
3659 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
3661 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
3662 // bits, just truncate to i32.
3663 if (NumSignBits > OpBits-MidBits)
3664 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3667 // fold (sext (truncate x)) -> (sextinreg x).
3668 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
3669 N0.getValueType())) {
3670 if (OpBits < DestBits)
3671 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
3672 else if (OpBits > DestBits)
3673 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
3674 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
3675 DAG.getValueType(N0.getValueType()));
3679 // fold (sext (load x)) -> (sext (truncate (sextload x)))
3680 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3681 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3682 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
3683 bool DoXform = true;
3684 SmallVector<SDNode*, 4> SetCCs;
3685 if (!N0.hasOneUse())
3686 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
3688 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3689 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
3691 LN0->getBasePtr(), LN0->getPointerInfo(),
3693 LN0->isVolatile(), LN0->isNonTemporal(),
3694 LN0->getAlignment());
3695 CombineTo(N, ExtLoad);
3696 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3697 N0.getValueType(), ExtLoad);
3698 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3700 // Extend SetCC uses if necessary.
3701 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3702 SDNode *SetCC = SetCCs[i];
3703 SmallVector<SDValue, 4> Ops;
3705 for (unsigned j = 0; j != 2; ++j) {
3706 SDValue SOp = SetCC->getOperand(j);
3708 Ops.push_back(ExtLoad);
3710 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND,
3711 N->getDebugLoc(), VT, SOp));
3714 Ops.push_back(SetCC->getOperand(2));
3715 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3716 SetCC->getValueType(0),
3717 &Ops[0], Ops.size()));
3720 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3724 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
3725 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
3726 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3727 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3728 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3729 EVT MemVT = LN0->getMemoryVT();
3730 if ((!LegalOperations && !LN0->isVolatile()) ||
3731 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
3732 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
3734 LN0->getBasePtr(), LN0->getPointerInfo(),
3736 LN0->isVolatile(), LN0->isNonTemporal(),
3737 LN0->getAlignment());
3738 CombineTo(N, ExtLoad);
3739 CombineTo(N0.getNode(),
3740 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3741 N0.getValueType(), ExtLoad),
3742 ExtLoad.getValue(1));
3743 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3747 if (N0.getOpcode() == ISD::SETCC) {
3748 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
3749 // Only do this before legalize for now.
3750 if (VT.isVector() && !LegalOperations) {
3751 EVT N0VT = N0.getOperand(0).getValueType();
3752 // We know that the # elements of the results is the same as the
3753 // # elements of the compare (and the # elements of the compare result
3754 // for that matter). Check to see that they are the same size. If so,
3755 // we know that the element size of the sext'd result matches the
3756 // element size of the compare operands.
3757 if (VT.getSizeInBits() == N0VT.getSizeInBits())
3758 return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3760 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3761 // If the desired elements are smaller or larger than the source
3762 // elements we can use a matching integer vector type and then
3763 // truncate/sign extend
3765 EVT MatchingElementType =
3766 EVT::getIntegerVT(*DAG.getContext(),
3767 N0VT.getScalarType().getSizeInBits());
3768 EVT MatchingVectorType =
3769 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
3770 N0VT.getVectorNumElements());
3772 DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
3774 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3775 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
3779 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
3780 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
3782 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
3784 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3785 NegOne, DAG.getConstant(0, VT),
3786 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3787 if (SCC.getNode()) return SCC;
3788 if (!LegalOperations ||
3789 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
3790 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
3791 DAG.getSetCC(N->getDebugLoc(),
3792 TLI.getSetCCResultType(VT),
3793 N0.getOperand(0), N0.getOperand(1),
3794 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
3795 NegOne, DAG.getConstant(0, VT));
3798 // fold (sext x) -> (zext x) if the sign bit is known zero.
3799 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
3800 DAG.SignBitIsZero(N0))
3801 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3806 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
3807 SDValue N0 = N->getOperand(0);
3808 EVT VT = N->getValueType(0);
3810 // fold (zext c1) -> c1
3811 if (isa<ConstantSDNode>(N0))
3812 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3813 // fold (zext (zext x)) -> (zext x)
3814 // fold (zext (aext x)) -> (zext x)
3815 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3816 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
3819 // fold (zext (truncate (load x))) -> (zext (smaller load x))
3820 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
3821 if (N0.getOpcode() == ISD::TRUNCATE) {
3822 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3823 if (NarrowLoad.getNode()) {
3824 SDNode* oye = N0.getNode()->getOperand(0).getNode();
3825 if (NarrowLoad.getNode() != N0.getNode()) {
3826 CombineTo(N0.getNode(), NarrowLoad);
3827 // CombineTo deleted the truncate, if needed, but not what's under it.
3830 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3834 // fold (zext (truncate x)) -> (and x, mask)
3835 if (N0.getOpcode() == ISD::TRUNCATE &&
3836 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
3838 // fold (zext (truncate (load x))) -> (zext (smaller load x))
3839 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
3840 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3841 if (NarrowLoad.getNode()) {
3842 SDNode* oye = N0.getNode()->getOperand(0).getNode();
3843 if (NarrowLoad.getNode() != N0.getNode()) {
3844 CombineTo(N0.getNode(), NarrowLoad);
3845 // CombineTo deleted the truncate, if needed, but not what's under it.
3848 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3851 SDValue Op = N0.getOperand(0);
3852 if (Op.getValueType().bitsLT(VT)) {
3853 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
3854 } else if (Op.getValueType().bitsGT(VT)) {
3855 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3857 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
3858 N0.getValueType().getScalarType());
3861 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
3862 // if either of the casts is not free.
3863 if (N0.getOpcode() == ISD::AND &&
3864 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3865 N0.getOperand(1).getOpcode() == ISD::Constant &&
3866 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3867 N0.getValueType()) ||
3868 !TLI.isZExtFree(N0.getValueType(), VT))) {
3869 SDValue X = N0.getOperand(0).getOperand(0);
3870 if (X.getValueType().bitsLT(VT)) {
3871 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
3872 } else if (X.getValueType().bitsGT(VT)) {
3873 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3875 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3876 Mask = Mask.zext(VT.getSizeInBits());
3877 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3878 X, DAG.getConstant(Mask, VT));
3881 // fold (zext (load x)) -> (zext (truncate (zextload x)))
3882 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3883 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3884 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
3885 bool DoXform = true;
3886 SmallVector<SDNode*, 4> SetCCs;
3887 if (!N0.hasOneUse())
3888 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
3890 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3891 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N->getDebugLoc(),
3893 LN0->getBasePtr(), LN0->getPointerInfo(),
3895 LN0->isVolatile(), LN0->isNonTemporal(),
3896 LN0->getAlignment());
3897 CombineTo(N, ExtLoad);
3898 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3899 N0.getValueType(), ExtLoad);
3900 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3902 // Extend SetCC uses if necessary.
3903 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3904 SDNode *SetCC = SetCCs[i];
3905 SmallVector<SDValue, 4> Ops;
3907 for (unsigned j = 0; j != 2; ++j) {
3908 SDValue SOp = SetCC->getOperand(j);
3910 Ops.push_back(ExtLoad);
3912 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND,
3913 N->getDebugLoc(), VT, SOp));
3916 Ops.push_back(SetCC->getOperand(2));
3917 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3918 SetCC->getValueType(0),
3919 &Ops[0], Ops.size()));
3922 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3926 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
3927 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
3928 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3929 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3930 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3931 EVT MemVT = LN0->getMemoryVT();
3932 if ((!LegalOperations && !LN0->isVolatile()) ||
3933 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
3934 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N->getDebugLoc(),
3936 LN0->getBasePtr(), LN0->getPointerInfo(),
3938 LN0->isVolatile(), LN0->isNonTemporal(),
3939 LN0->getAlignment());
3940 CombineTo(N, ExtLoad);
3941 CombineTo(N0.getNode(),
3942 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
3944 ExtLoad.getValue(1));
3945 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3949 if (N0.getOpcode() == ISD::SETCC) {
3950 if (!LegalOperations && VT.isVector()) {
3951 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
3952 // Only do this before legalize for now.
3953 EVT N0VT = N0.getOperand(0).getValueType();
3954 EVT EltVT = VT.getVectorElementType();
3955 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
3956 DAG.getConstant(1, EltVT));
3957 if (VT.getSizeInBits() == N0VT.getSizeInBits()) {
3958 // We know that the # elements of the results is the same as the
3959 // # elements of the compare (and the # elements of the compare result
3960 // for that matter). Check to see that they are the same size. If so,
3961 // we know that the element size of the sext'd result matches the
3962 // element size of the compare operands.
3963 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3964 DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3966 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
3967 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
3968 &OneOps[0], OneOps.size()));
3970 // If the desired elements are smaller or larger than the source
3971 // elements we can use a matching integer vector type and then
3972 // truncate/sign extend
3973 EVT MatchingElementType =
3974 EVT::getIntegerVT(*DAG.getContext(),
3975 N0VT.getScalarType().getSizeInBits());
3976 EVT MatchingVectorType =
3977 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
3978 N0VT.getVectorNumElements());
3980 DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
3982 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3983 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3984 DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
3985 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
3986 &OneOps[0], OneOps.size()));
3990 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3992 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3993 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3994 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3995 if (SCC.getNode()) return SCC;
3998 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
3999 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4000 isa<ConstantSDNode>(N0.getOperand(1)) &&
4001 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4003 if (N0.getOpcode() == ISD::SHL) {
4004 // If the original shl may be shifting out bits, do not perform this
4006 unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4007 unsigned KnownZeroBits = N0.getOperand(0).getValueType().getSizeInBits() -
4008 N0.getOperand(0).getOperand(0).getValueType().getSizeInBits();
4009 if (ShAmt > KnownZeroBits)
4012 DebugLoc dl = N->getDebugLoc();
4013 return DAG.getNode(N0.getOpcode(), dl, VT,
4014 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0.getOperand(0)),
4015 DAG.getNode(ISD::ZERO_EXTEND, dl,
4016 N0.getOperand(1).getValueType(),
4023 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4024 SDValue N0 = N->getOperand(0);
4025 EVT VT = N->getValueType(0);
4027 // fold (aext c1) -> c1
4028 if (isa<ConstantSDNode>(N0))
4029 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
4030 // fold (aext (aext x)) -> (aext x)
4031 // fold (aext (zext x)) -> (zext x)
4032 // fold (aext (sext x)) -> (sext x)
4033 if (N0.getOpcode() == ISD::ANY_EXTEND ||
4034 N0.getOpcode() == ISD::ZERO_EXTEND ||
4035 N0.getOpcode() == ISD::SIGN_EXTEND)
4036 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
4038 // fold (aext (truncate (load x))) -> (aext (smaller load x))
4039 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4040 if (N0.getOpcode() == ISD::TRUNCATE) {
4041 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4042 if (NarrowLoad.getNode()) {
4043 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4044 if (NarrowLoad.getNode() != N0.getNode()) {
4045 CombineTo(N0.getNode(), NarrowLoad);
4046 // CombineTo deleted the truncate, if needed, but not what's under it.
4049 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
4053 // fold (aext (truncate x))
4054 if (N0.getOpcode() == ISD::TRUNCATE) {
4055 SDValue TruncOp = N0.getOperand(0);
4056 if (TruncOp.getValueType() == VT)
4057 return TruncOp; // x iff x size == zext size.
4058 if (TruncOp.getValueType().bitsGT(VT))
4059 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
4060 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
4063 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4064 // if the trunc is not free.
4065 if (N0.getOpcode() == ISD::AND &&
4066 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4067 N0.getOperand(1).getOpcode() == ISD::Constant &&
4068 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4069 N0.getValueType())) {
4070 SDValue X = N0.getOperand(0).getOperand(0);
4071 if (X.getValueType().bitsLT(VT)) {
4072 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
4073 } else if (X.getValueType().bitsGT(VT)) {
4074 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
4076 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4077 Mask = Mask.zext(VT.getSizeInBits());
4078 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4079 X, DAG.getConstant(Mask, VT));
4082 // fold (aext (load x)) -> (aext (truncate (extload x)))
4083 if (ISD::isNON_EXTLoad(N0.getNode()) &&
4084 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4085 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4086 bool DoXform = true;
4087 SmallVector<SDNode*, 4> SetCCs;
4088 if (!N0.hasOneUse())
4089 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4091 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4092 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, N->getDebugLoc(),
4094 LN0->getBasePtr(), LN0->getPointerInfo(),
4096 LN0->isVolatile(), LN0->isNonTemporal(),
4097 LN0->getAlignment());
4098 CombineTo(N, ExtLoad);
4099 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4100 N0.getValueType(), ExtLoad);
4101 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4103 // Extend SetCC uses if necessary.
4104 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4105 SDNode *SetCC = SetCCs[i];
4106 SmallVector<SDValue, 4> Ops;
4108 for (unsigned j = 0; j != 2; ++j) {
4109 SDValue SOp = SetCC->getOperand(j);
4111 Ops.push_back(ExtLoad);
4113 Ops.push_back(DAG.getNode(ISD::ANY_EXTEND,
4114 N->getDebugLoc(), VT, SOp));
4117 Ops.push_back(SetCC->getOperand(2));
4118 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
4119 SetCC->getValueType(0),
4120 &Ops[0], Ops.size()));
4123 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4127 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4128 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4129 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
4130 if (N0.getOpcode() == ISD::LOAD &&
4131 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4133 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4134 EVT MemVT = LN0->getMemoryVT();
4135 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
4137 LN0->getChain(), LN0->getBasePtr(),
4138 LN0->getPointerInfo(), MemVT,
4139 LN0->isVolatile(), LN0->isNonTemporal(),
4140 LN0->getAlignment());
4141 CombineTo(N, ExtLoad);
4142 CombineTo(N0.getNode(),
4143 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4144 N0.getValueType(), ExtLoad),
4145 ExtLoad.getValue(1));
4146 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4149 if (N0.getOpcode() == ISD::SETCC) {
4150 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4151 // Only do this before legalize for now.
4152 if (VT.isVector() && !LegalOperations) {
4153 EVT N0VT = N0.getOperand(0).getValueType();
4154 // We know that the # elements of the results is the same as the
4155 // # elements of the compare (and the # elements of the compare result
4156 // for that matter). Check to see that they are the same size. If so,
4157 // we know that the element size of the sext'd result matches the
4158 // element size of the compare operands.
4159 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4160 return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4162 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4163 // If the desired elements are smaller or larger than the source
4164 // elements we can use a matching integer vector type and then
4165 // truncate/sign extend
4167 EVT MatchingElementType =
4168 EVT::getIntegerVT(*DAG.getContext(),
4169 N0VT.getScalarType().getSizeInBits());
4170 EVT MatchingVectorType =
4171 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4172 N0VT.getVectorNumElements());
4174 DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4176 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4177 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4181 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4183 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4184 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4185 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4193 /// GetDemandedBits - See if the specified operand can be simplified with the
4194 /// knowledge that only the bits specified by Mask are used. If so, return the
4195 /// simpler operand, otherwise return a null SDValue.
4196 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
4197 switch (V.getOpcode()) {
4201 // If the LHS or RHS don't contribute bits to the or, drop them.
4202 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
4203 return V.getOperand(1);
4204 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
4205 return V.getOperand(0);
4208 // Only look at single-use SRLs.
4209 if (!V.getNode()->hasOneUse())
4211 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
4212 // See if we can recursively simplify the LHS.
4213 unsigned Amt = RHSC->getZExtValue();
4215 // Watch out for shift count overflow though.
4216 if (Amt >= Mask.getBitWidth()) break;
4217 APInt NewMask = Mask << Amt;
4218 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
4219 if (SimplifyLHS.getNode())
4220 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
4221 SimplifyLHS, V.getOperand(1));
4227 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
4228 /// bits and then truncated to a narrower type and where N is a multiple
4229 /// of number of bits of the narrower type, transform it to a narrower load
4230 /// from address + N / num of bits of new type. If the result is to be
4231 /// extended, also fold the extension to form a extending load.
4232 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
4233 unsigned Opc = N->getOpcode();
4235 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4236 SDValue N0 = N->getOperand(0);
4237 EVT VT = N->getValueType(0);
4240 // This transformation isn't valid for vector loads.
4244 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
4246 if (Opc == ISD::SIGN_EXTEND_INREG) {
4247 ExtType = ISD::SEXTLOAD;
4248 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4249 } else if (Opc == ISD::SRL) {
4250 // Another special-case: SRL is basically zero-extending a narrower value.
4251 ExtType = ISD::ZEXTLOAD;
4253 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4254 if (!N01) return SDValue();
4255 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
4256 VT.getSizeInBits() - N01->getZExtValue());
4258 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
4261 unsigned EVTBits = ExtVT.getSizeInBits();
4263 // Do not generate loads of non-round integer types since these can
4264 // be expensive (and would be wrong if the type is not byte sized).
4265 if (!ExtVT.isRound())
4269 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4270 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4271 ShAmt = N01->getZExtValue();
4272 // Is the shift amount a multiple of size of VT?
4273 if ((ShAmt & (EVTBits-1)) == 0) {
4274 N0 = N0.getOperand(0);
4275 // Is the load width a multiple of size of VT?
4276 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
4280 // At this point, we must have a load or else we can't do the transform.
4281 if (!isa<LoadSDNode>(N0)) return SDValue();
4283 // If the shift amount is larger than the input type then we're not
4284 // accessing any of the loaded bytes. If the load was a zextload/extload
4285 // then the result of the shift+trunc is zero/undef (handled elsewhere).
4286 // If the load was a sextload then the result is a splat of the sign bit
4287 // of the extended byte. This is not worth optimizing for.
4288 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
4293 // If the load is shifted left (and the result isn't shifted back right),
4294 // we can fold the truncate through the shift.
4295 unsigned ShLeftAmt = 0;
4296 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
4297 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
4298 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4299 ShLeftAmt = N01->getZExtValue();
4300 N0 = N0.getOperand(0);
4304 // If we haven't found a load, we can't narrow it. Don't transform one with
4305 // multiple uses, this would require adding a new load.
4306 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse() ||
4307 // Don't change the width of a volatile load.
4308 cast<LoadSDNode>(N0)->isVolatile())
4311 // Verify that we are actually reducing a load width here.
4312 if (cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() < EVTBits)
4315 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4316 EVT PtrType = N0.getOperand(1).getValueType();
4318 // For big endian targets, we need to adjust the offset to the pointer to
4319 // load the correct bytes.
4320 if (TLI.isBigEndian()) {
4321 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
4322 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
4323 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
4326 uint64_t PtrOff = ShAmt / 8;
4327 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
4328 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
4329 PtrType, LN0->getBasePtr(),
4330 DAG.getConstant(PtrOff, PtrType));
4331 AddToWorkList(NewPtr.getNode());
4334 if (ExtType == ISD::NON_EXTLOAD)
4335 Load = DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
4336 LN0->getPointerInfo().getWithOffset(PtrOff),
4337 LN0->isVolatile(), LN0->isNonTemporal(), NewAlign);
4339 Load = DAG.getExtLoad(ExtType, VT, N0.getDebugLoc(), LN0->getChain(),NewPtr,
4340 LN0->getPointerInfo().getWithOffset(PtrOff),
4341 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
4344 // Replace the old load's chain with the new load's chain.
4345 WorkListRemover DeadNodes(*this);
4346 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
4349 // Shift the result left, if we've swallowed a left shift.
4350 SDValue Result = Load;
4351 if (ShLeftAmt != 0) {
4352 EVT ShImmTy = getShiftAmountTy();
4353 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
4355 Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
4356 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
4359 // Return the new loaded value.
4363 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
4364 SDValue N0 = N->getOperand(0);
4365 SDValue N1 = N->getOperand(1);
4366 EVT VT = N->getValueType(0);
4367 EVT EVT = cast<VTSDNode>(N1)->getVT();
4368 unsigned VTBits = VT.getScalarType().getSizeInBits();
4369 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
4371 // fold (sext_in_reg c1) -> c1
4372 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
4373 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
4375 // If the input is already sign extended, just drop the extension.
4376 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
4379 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
4380 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4381 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
4382 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
4383 N0.getOperand(0), N1);
4386 // fold (sext_in_reg (sext x)) -> (sext x)
4387 // fold (sext_in_reg (aext x)) -> (sext x)
4388 // if x is small enough.
4389 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
4390 SDValue N00 = N0.getOperand(0);
4391 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
4392 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
4393 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
4396 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
4397 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
4398 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
4400 // fold operands of sext_in_reg based on knowledge that the top bits are not
4402 if (SimplifyDemandedBits(SDValue(N, 0)))
4403 return SDValue(N, 0);
4405 // fold (sext_in_reg (load x)) -> (smaller sextload x)
4406 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
4407 SDValue NarrowLoad = ReduceLoadWidth(N);
4408 if (NarrowLoad.getNode())
4411 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
4412 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
4413 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
4414 if (N0.getOpcode() == ISD::SRL) {
4415 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
4416 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
4417 // We can turn this into an SRA iff the input to the SRL is already sign
4419 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
4420 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
4421 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
4422 N0.getOperand(0), N0.getOperand(1));
4426 // fold (sext_inreg (extload x)) -> (sextload x)
4427 if (ISD::isEXTLoad(N0.getNode()) &&
4428 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4429 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4430 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4431 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4432 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4433 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
4435 LN0->getBasePtr(), LN0->getPointerInfo(),
4437 LN0->isVolatile(), LN0->isNonTemporal(),
4438 LN0->getAlignment());
4439 CombineTo(N, ExtLoad);
4440 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4441 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4443 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
4444 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4446 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4447 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4448 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4449 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4450 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
4452 LN0->getBasePtr(), LN0->getPointerInfo(),
4454 LN0->isVolatile(), LN0->isNonTemporal(),
4455 LN0->getAlignment());
4456 CombineTo(N, ExtLoad);
4457 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4458 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4463 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
4464 SDValue N0 = N->getOperand(0);
4465 EVT VT = N->getValueType(0);
4468 if (N0.getValueType() == N->getValueType(0))
4470 // fold (truncate c1) -> c1
4471 if (isa<ConstantSDNode>(N0))
4472 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
4473 // fold (truncate (truncate x)) -> (truncate x)
4474 if (N0.getOpcode() == ISD::TRUNCATE)
4475 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4476 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
4477 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
4478 N0.getOpcode() == ISD::SIGN_EXTEND ||
4479 N0.getOpcode() == ISD::ANY_EXTEND) {
4480 if (N0.getOperand(0).getValueType().bitsLT(VT))
4481 // if the source is smaller than the dest, we still need an extend
4482 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4484 else if (N0.getOperand(0).getValueType().bitsGT(VT))
4485 // if the source is larger than the dest, than we just need the truncate
4486 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4488 // if the source and dest are the same type, we can drop both the extend
4489 // and the truncate.
4490 return N0.getOperand(0);
4493 // See if we can simplify the input to this truncate through knowledge that
4494 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
4497 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
4498 VT.getSizeInBits()));
4499 if (Shorter.getNode())
4500 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
4502 // fold (truncate (load x)) -> (smaller load x)
4503 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
4504 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
4505 SDValue Reduced = ReduceLoadWidth(N);
4506 if (Reduced.getNode())
4510 // Simplify the operands using demanded-bits information.
4511 if (!VT.isVector() &&
4512 SimplifyDemandedBits(SDValue(N, 0)))
4513 return SDValue(N, 0);
4518 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
4519 SDValue Elt = N->getOperand(i);
4520 if (Elt.getOpcode() != ISD::MERGE_VALUES)
4521 return Elt.getNode();
4522 return Elt.getOperand(Elt.getResNo()).getNode();
4525 /// CombineConsecutiveLoads - build_pair (load, load) -> load
4526 /// if load locations are consecutive.
4527 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
4528 assert(N->getOpcode() == ISD::BUILD_PAIR);
4530 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
4531 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
4532 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
4533 LD1->getPointerInfo().getAddrSpace() !=
4534 LD2->getPointerInfo().getAddrSpace())
4536 EVT LD1VT = LD1->getValueType(0);
4538 if (ISD::isNON_EXTLoad(LD2) &&
4540 // If both are volatile this would reduce the number of volatile loads.
4541 // If one is volatile it might be ok, but play conservative and bail out.
4542 !LD1->isVolatile() &&
4543 !LD2->isVolatile() &&
4544 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
4545 unsigned Align = LD1->getAlignment();
4546 unsigned NewAlign = TLI.getTargetData()->
4547 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4549 if (NewAlign <= Align &&
4550 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
4551 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
4552 LD1->getBasePtr(), LD1->getPointerInfo(),
4553 false, false, Align);
4559 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
4560 SDValue N0 = N->getOperand(0);
4561 EVT VT = N->getValueType(0);
4563 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
4564 // Only do this before legalize, since afterward the target may be depending
4565 // on the bitconvert.
4566 // First check to see if this is all constant.
4568 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
4570 bool isSimple = true;
4571 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
4572 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
4573 N0.getOperand(i).getOpcode() != ISD::Constant &&
4574 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
4579 EVT DestEltVT = N->getValueType(0).getVectorElementType();
4580 assert(!DestEltVT.isVector() &&
4581 "Element type of vector ValueType must not be vector!");
4583 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
4586 // If the input is a constant, let getNode fold it.
4587 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
4588 SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
4589 if (Res.getNode() != N) {
4590 if (!LegalOperations ||
4591 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
4594 // Folding it resulted in an illegal node, and it's too late to
4595 // do that. Clean up the old node and forego the transformation.
4596 // Ideally this won't happen very often, because instcombine
4597 // and the earlier dagcombine runs (where illegal nodes are
4598 // permitted) should have folded most of them already.
4599 DAG.DeleteNode(Res.getNode());
4603 // (conv (conv x, t1), t2) -> (conv x, t2)
4604 if (N0.getOpcode() == ISD::BITCAST)
4605 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
4608 // fold (conv (load x)) -> (load (conv*)x)
4609 // If the resultant load doesn't need a higher alignment than the original!
4610 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
4611 // Do not change the width of a volatile load.
4612 !cast<LoadSDNode>(N0)->isVolatile() &&
4613 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
4614 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4615 unsigned Align = TLI.getTargetData()->
4616 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4617 unsigned OrigAlign = LN0->getAlignment();
4619 if (Align <= OrigAlign) {
4620 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
4621 LN0->getBasePtr(), LN0->getPointerInfo(),
4622 LN0->isVolatile(), LN0->isNonTemporal(),
4625 CombineTo(N0.getNode(),
4626 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
4627 N0.getValueType(), Load),
4633 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
4634 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
4635 // This often reduces constant pool loads.
4636 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
4637 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
4638 SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
4640 AddToWorkList(NewConv.getNode());
4642 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4643 if (N0.getOpcode() == ISD::FNEG)
4644 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
4645 NewConv, DAG.getConstant(SignBit, VT));
4646 assert(N0.getOpcode() == ISD::FABS);
4647 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4648 NewConv, DAG.getConstant(~SignBit, VT));
4651 // fold (bitconvert (fcopysign cst, x)) ->
4652 // (or (and (bitconvert x), sign), (and cst, (not sign)))
4653 // Note that we don't handle (copysign x, cst) because this can always be
4654 // folded to an fneg or fabs.
4655 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
4656 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
4657 VT.isInteger() && !VT.isVector()) {
4658 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
4659 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
4660 if (isTypeLegal(IntXVT)) {
4661 SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
4662 IntXVT, N0.getOperand(1));
4663 AddToWorkList(X.getNode());
4665 // If X has a different width than the result/lhs, sext it or truncate it.
4666 unsigned VTWidth = VT.getSizeInBits();
4667 if (OrigXWidth < VTWidth) {
4668 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
4669 AddToWorkList(X.getNode());
4670 } else if (OrigXWidth > VTWidth) {
4671 // To get the sign bit in the right place, we have to shift it right
4672 // before truncating.
4673 X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
4674 X.getValueType(), X,
4675 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
4676 AddToWorkList(X.getNode());
4677 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4678 AddToWorkList(X.getNode());
4681 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4682 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
4683 X, DAG.getConstant(SignBit, VT));
4684 AddToWorkList(X.getNode());
4686 SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
4687 VT, N0.getOperand(0));
4688 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
4689 Cst, DAG.getConstant(~SignBit, VT));
4690 AddToWorkList(Cst.getNode());
4692 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
4696 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
4697 if (N0.getOpcode() == ISD::BUILD_PAIR) {
4698 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
4699 if (CombineLD.getNode())
4706 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
4707 EVT VT = N->getValueType(0);
4708 return CombineConsecutiveLoads(N, VT);
4711 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
4712 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
4713 /// destination element value type.
4714 SDValue DAGCombiner::
4715 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
4716 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
4718 // If this is already the right type, we're done.
4719 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
4721 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
4722 unsigned DstBitSize = DstEltVT.getSizeInBits();
4724 // If this is a conversion of N elements of one type to N elements of another
4725 // type, convert each element. This handles FP<->INT cases.
4726 if (SrcBitSize == DstBitSize) {
4727 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4728 BV->getValueType(0).getVectorNumElements());
4730 // Due to the FP element handling below calling this routine recursively,
4731 // we can end up with a scalar-to-vector node here.
4732 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
4733 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4734 DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
4735 DstEltVT, BV->getOperand(0)));
4737 SmallVector<SDValue, 8> Ops;
4738 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4739 SDValue Op = BV->getOperand(i);
4740 // If the vector element type is not legal, the BUILD_VECTOR operands
4741 // are promoted and implicitly truncated. Make that explicit here.
4742 if (Op.getValueType() != SrcEltVT)
4743 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
4744 Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
4746 AddToWorkList(Ops.back().getNode());
4748 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4749 &Ops[0], Ops.size());
4752 // Otherwise, we're growing or shrinking the elements. To avoid having to
4753 // handle annoying details of growing/shrinking FP values, we convert them to
4755 if (SrcEltVT.isFloatingPoint()) {
4756 // Convert the input float vector to a int vector where the elements are the
4758 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
4759 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
4760 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
4764 // Now we know the input is an integer vector. If the output is a FP type,
4765 // convert to integer first, then to FP of the right size.
4766 if (DstEltVT.isFloatingPoint()) {
4767 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
4768 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
4769 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
4771 // Next, convert to FP elements of the same size.
4772 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
4775 // Okay, we know the src/dst types are both integers of differing types.
4776 // Handling growing first.
4777 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
4778 if (SrcBitSize < DstBitSize) {
4779 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
4781 SmallVector<SDValue, 8> Ops;
4782 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
4783 i += NumInputsPerOutput) {
4784 bool isLE = TLI.isLittleEndian();
4785 APInt NewBits = APInt(DstBitSize, 0);
4786 bool EltIsUndef = true;
4787 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
4788 // Shift the previously computed bits over.
4789 NewBits <<= SrcBitSize;
4790 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
4791 if (Op.getOpcode() == ISD::UNDEF) continue;
4794 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
4795 zextOrTrunc(SrcBitSize).zext(DstBitSize);
4799 Ops.push_back(DAG.getUNDEF(DstEltVT));
4801 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
4804 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
4805 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4806 &Ops[0], Ops.size());
4809 // Finally, this must be the case where we are shrinking elements: each input
4810 // turns into multiple outputs.
4811 bool isS2V = ISD::isScalarToVector(BV);
4812 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
4813 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4814 NumOutputsPerInput*BV->getNumOperands());
4815 SmallVector<SDValue, 8> Ops;
4817 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4818 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
4819 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
4820 Ops.push_back(DAG.getUNDEF(DstEltVT));
4824 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
4825 getAPIntValue().zextOrTrunc(SrcBitSize);
4827 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
4828 APInt ThisVal = OpVal.trunc(DstBitSize);
4829 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
4830 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
4831 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
4832 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4834 OpVal = OpVal.lshr(DstBitSize);
4837 // For big endian targets, swap the order of the pieces of each element.
4838 if (TLI.isBigEndian())
4839 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
4842 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4843 &Ops[0], Ops.size());
4846 SDValue DAGCombiner::visitFADD(SDNode *N) {
4847 SDValue N0 = N->getOperand(0);
4848 SDValue N1 = N->getOperand(1);
4849 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4850 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4851 EVT VT = N->getValueType(0);
4854 if (VT.isVector()) {
4855 SDValue FoldedVOp = SimplifyVBinOp(N);
4856 if (FoldedVOp.getNode()) return FoldedVOp;
4859 // fold (fadd c1, c2) -> (fadd c1, c2)
4860 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4861 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
4862 // canonicalize constant to RHS
4863 if (N0CFP && !N1CFP)
4864 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
4865 // fold (fadd A, 0) -> A
4866 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4868 // fold (fadd A, (fneg B)) -> (fsub A, B)
4869 if (isNegatibleForFree(N1, LegalOperations) == 2)
4870 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
4871 GetNegatedExpression(N1, DAG, LegalOperations));
4872 // fold (fadd (fneg A), B) -> (fsub B, A)
4873 if (isNegatibleForFree(N0, LegalOperations) == 2)
4874 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
4875 GetNegatedExpression(N0, DAG, LegalOperations));
4877 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
4878 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
4879 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4880 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
4881 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
4882 N0.getOperand(1), N1));
4887 SDValue DAGCombiner::visitFSUB(SDNode *N) {
4888 SDValue N0 = N->getOperand(0);
4889 SDValue N1 = N->getOperand(1);
4890 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4891 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4892 EVT VT = N->getValueType(0);
4895 if (VT.isVector()) {
4896 SDValue FoldedVOp = SimplifyVBinOp(N);
4897 if (FoldedVOp.getNode()) return FoldedVOp;
4900 // fold (fsub c1, c2) -> c1-c2
4901 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4902 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
4903 // fold (fsub A, 0) -> A
4904 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4906 // fold (fsub 0, B) -> -B
4907 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
4908 if (isNegatibleForFree(N1, LegalOperations))
4909 return GetNegatedExpression(N1, DAG, LegalOperations);
4910 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4911 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
4913 // fold (fsub A, (fneg B)) -> (fadd A, B)
4914 if (isNegatibleForFree(N1, LegalOperations))
4915 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
4916 GetNegatedExpression(N1, DAG, LegalOperations));
4921 SDValue DAGCombiner::visitFMUL(SDNode *N) {
4922 SDValue N0 = N->getOperand(0);
4923 SDValue N1 = N->getOperand(1);
4924 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4925 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4926 EVT VT = N->getValueType(0);
4929 if (VT.isVector()) {
4930 SDValue FoldedVOp = SimplifyVBinOp(N);
4931 if (FoldedVOp.getNode()) return FoldedVOp;
4934 // fold (fmul c1, c2) -> c1*c2
4935 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4936 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
4937 // canonicalize constant to RHS
4938 if (N0CFP && !N1CFP)
4939 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
4940 // fold (fmul A, 0) -> 0
4941 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4943 // fold (fmul A, 0) -> 0, vector edition.
4944 if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
4946 // fold (fmul X, 2.0) -> (fadd X, X)
4947 if (N1CFP && N1CFP->isExactlyValue(+2.0))
4948 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
4949 // fold (fmul X, -1.0) -> (fneg X)
4950 if (N1CFP && N1CFP->isExactlyValue(-1.0))
4951 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4952 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
4954 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
4955 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4956 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4957 // Both can be negated for free, check to see if at least one is cheaper
4959 if (LHSNeg == 2 || RHSNeg == 2)
4960 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4961 GetNegatedExpression(N0, DAG, LegalOperations),
4962 GetNegatedExpression(N1, DAG, LegalOperations));
4966 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
4967 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
4968 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4969 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
4970 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4971 N0.getOperand(1), N1));
4976 SDValue DAGCombiner::visitFDIV(SDNode *N) {
4977 SDValue N0 = N->getOperand(0);
4978 SDValue N1 = N->getOperand(1);
4979 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4980 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4981 EVT VT = N->getValueType(0);
4984 if (VT.isVector()) {
4985 SDValue FoldedVOp = SimplifyVBinOp(N);
4986 if (FoldedVOp.getNode()) return FoldedVOp;
4989 // fold (fdiv c1, c2) -> c1/c2
4990 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4991 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
4994 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
4995 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4996 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4997 // Both can be negated for free, check to see if at least one is cheaper
4999 if (LHSNeg == 2 || RHSNeg == 2)
5000 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
5001 GetNegatedExpression(N0, DAG, LegalOperations),
5002 GetNegatedExpression(N1, DAG, LegalOperations));
5009 SDValue DAGCombiner::visitFREM(SDNode *N) {
5010 SDValue N0 = N->getOperand(0);
5011 SDValue N1 = N->getOperand(1);
5012 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5013 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5014 EVT VT = N->getValueType(0);
5016 // fold (frem c1, c2) -> fmod(c1,c2)
5017 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5018 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
5023 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
5024 SDValue N0 = N->getOperand(0);
5025 SDValue N1 = N->getOperand(1);
5026 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5027 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5028 EVT VT = N->getValueType(0);
5030 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
5031 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
5034 const APFloat& V = N1CFP->getValueAPF();
5035 // copysign(x, c1) -> fabs(x) iff ispos(c1)
5036 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
5037 if (!V.isNegative()) {
5038 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
5039 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5041 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5042 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
5043 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
5047 // copysign(fabs(x), y) -> copysign(x, y)
5048 // copysign(fneg(x), y) -> copysign(x, y)
5049 // copysign(copysign(x,z), y) -> copysign(x, y)
5050 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
5051 N0.getOpcode() == ISD::FCOPYSIGN)
5052 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5053 N0.getOperand(0), N1);
5055 // copysign(x, abs(y)) -> abs(x)
5056 if (N1.getOpcode() == ISD::FABS)
5057 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5059 // copysign(x, copysign(y,z)) -> copysign(x, z)
5060 if (N1.getOpcode() == ISD::FCOPYSIGN)
5061 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5062 N0, N1.getOperand(1));
5064 // copysign(x, fp_extend(y)) -> copysign(x, y)
5065 // copysign(x, fp_round(y)) -> copysign(x, y)
5066 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
5067 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5068 N0, N1.getOperand(0));
5073 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
5074 SDValue N0 = N->getOperand(0);
5075 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5076 EVT VT = N->getValueType(0);
5077 EVT OpVT = N0.getValueType();
5079 // fold (sint_to_fp c1) -> c1fp
5080 if (N0C && OpVT != MVT::ppcf128)
5081 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
5083 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
5084 // but UINT_TO_FP is legal on this target, try to convert.
5085 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
5086 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
5087 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
5088 if (DAG.SignBitIsZero(N0))
5089 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
5095 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
5096 SDValue N0 = N->getOperand(0);
5097 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5098 EVT VT = N->getValueType(0);
5099 EVT OpVT = N0.getValueType();
5101 // fold (uint_to_fp c1) -> c1fp
5102 if (N0C && OpVT != MVT::ppcf128)
5103 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
5105 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
5106 // but SINT_TO_FP is legal on this target, try to convert.
5107 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
5108 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
5109 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
5110 if (DAG.SignBitIsZero(N0))
5111 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
5117 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
5118 SDValue N0 = N->getOperand(0);
5119 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5120 EVT VT = N->getValueType(0);
5122 // fold (fp_to_sint c1fp) -> c1
5124 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
5129 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
5130 SDValue N0 = N->getOperand(0);
5131 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5132 EVT VT = N->getValueType(0);
5134 // fold (fp_to_uint c1fp) -> c1
5135 if (N0CFP && VT != MVT::ppcf128)
5136 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
5141 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
5142 SDValue N0 = N->getOperand(0);
5143 SDValue N1 = N->getOperand(1);
5144 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5145 EVT VT = N->getValueType(0);
5147 // fold (fp_round c1fp) -> c1fp
5148 if (N0CFP && N0.getValueType() != MVT::ppcf128)
5149 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
5151 // fold (fp_round (fp_extend x)) -> x
5152 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
5153 return N0.getOperand(0);
5155 // fold (fp_round (fp_round x)) -> (fp_round x)
5156 if (N0.getOpcode() == ISD::FP_ROUND) {
5157 // This is a value preserving truncation if both round's are.
5158 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
5159 N0.getNode()->getConstantOperandVal(1) == 1;
5160 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
5161 DAG.getIntPtrConstant(IsTrunc));
5164 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
5165 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
5166 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
5167 N0.getOperand(0), N1);
5168 AddToWorkList(Tmp.getNode());
5169 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5170 Tmp, N0.getOperand(1));
5176 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
5177 SDValue N0 = N->getOperand(0);
5178 EVT VT = N->getValueType(0);
5179 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5180 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5182 // fold (fp_round_inreg c1fp) -> c1fp
5183 if (N0CFP && isTypeLegal(EVT)) {
5184 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
5185 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
5191 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
5192 SDValue N0 = N->getOperand(0);
5193 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5194 EVT VT = N->getValueType(0);
5196 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
5197 if (N->hasOneUse() &&
5198 N->use_begin()->getOpcode() == ISD::FP_ROUND)
5201 // fold (fp_extend c1fp) -> c1fp
5202 if (N0CFP && VT != MVT::ppcf128)
5203 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
5205 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
5207 if (N0.getOpcode() == ISD::FP_ROUND
5208 && N0.getNode()->getConstantOperandVal(1) == 1) {
5209 SDValue In = N0.getOperand(0);
5210 if (In.getValueType() == VT) return In;
5211 if (VT.bitsLT(In.getValueType()))
5212 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
5213 In, N0.getOperand(1));
5214 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
5217 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
5218 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
5219 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5220 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5221 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5222 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, N->getDebugLoc(),
5224 LN0->getBasePtr(), LN0->getPointerInfo(),
5226 LN0->isVolatile(), LN0->isNonTemporal(),
5227 LN0->getAlignment());
5228 CombineTo(N, ExtLoad);
5229 CombineTo(N0.getNode(),
5230 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
5231 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
5232 ExtLoad.getValue(1));
5233 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5239 SDValue DAGCombiner::visitFNEG(SDNode *N) {
5240 SDValue N0 = N->getOperand(0);
5241 EVT VT = N->getValueType(0);
5243 if (isNegatibleForFree(N0, LegalOperations))
5244 return GetNegatedExpression(N0, DAG, LegalOperations);
5246 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
5247 // constant pool values.
5248 if (N0.getOpcode() == ISD::BITCAST &&
5250 N0.getNode()->hasOneUse() &&
5251 N0.getOperand(0).getValueType().isInteger()) {
5252 SDValue Int = N0.getOperand(0);
5253 EVT IntVT = Int.getValueType();
5254 if (IntVT.isInteger() && !IntVT.isVector()) {
5255 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
5256 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5257 AddToWorkList(Int.getNode());
5258 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5266 SDValue DAGCombiner::visitFABS(SDNode *N) {
5267 SDValue N0 = N->getOperand(0);
5268 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5269 EVT VT = N->getValueType(0);
5271 // fold (fabs c1) -> fabs(c1)
5272 if (N0CFP && VT != MVT::ppcf128)
5273 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5274 // fold (fabs (fabs x)) -> (fabs x)
5275 if (N0.getOpcode() == ISD::FABS)
5276 return N->getOperand(0);
5277 // fold (fabs (fneg x)) -> (fabs x)
5278 // fold (fabs (fcopysign x, y)) -> (fabs x)
5279 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
5280 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
5282 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
5283 // constant pool values.
5284 if (N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
5285 N0.getOperand(0).getValueType().isInteger() &&
5286 !N0.getOperand(0).getValueType().isVector()) {
5287 SDValue Int = N0.getOperand(0);
5288 EVT IntVT = Int.getValueType();
5289 if (IntVT.isInteger() && !IntVT.isVector()) {
5290 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
5291 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5292 AddToWorkList(Int.getNode());
5293 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5294 N->getValueType(0), Int);
5301 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
5302 SDValue Chain = N->getOperand(0);
5303 SDValue N1 = N->getOperand(1);
5304 SDValue N2 = N->getOperand(2);
5306 // If N is a constant we could fold this into a fallthrough or unconditional
5307 // branch. However that doesn't happen very often in normal code, because
5308 // Instcombine/SimplifyCFG should have handled the available opportunities.
5309 // If we did this folding here, it would be necessary to update the
5310 // MachineBasicBlock CFG, which is awkward.
5312 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
5314 if (N1.getOpcode() == ISD::SETCC &&
5315 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
5316 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5317 Chain, N1.getOperand(2),
5318 N1.getOperand(0), N1.getOperand(1), N2);
5321 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
5322 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
5323 (N1.getOperand(0).hasOneUse() &&
5324 N1.getOperand(0).getOpcode() == ISD::SRL))) {
5326 if (N1.getOpcode() == ISD::TRUNCATE) {
5327 // Look pass the truncate.
5328 Trunc = N1.getNode();
5329 N1 = N1.getOperand(0);
5332 // Match this pattern so that we can generate simpler code:
5335 // %b = and i32 %a, 2
5336 // %c = srl i32 %b, 1
5337 // brcond i32 %c ...
5342 // %b = and i32 %a, 2
5343 // %c = setcc eq %b, 0
5346 // This applies only when the AND constant value has one bit set and the
5347 // SRL constant is equal to the log2 of the AND constant. The back-end is
5348 // smart enough to convert the result into a TEST/JMP sequence.
5349 SDValue Op0 = N1.getOperand(0);
5350 SDValue Op1 = N1.getOperand(1);
5352 if (Op0.getOpcode() == ISD::AND &&
5353 Op1.getOpcode() == ISD::Constant) {
5354 SDValue AndOp1 = Op0.getOperand(1);
5356 if (AndOp1.getOpcode() == ISD::Constant) {
5357 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
5359 if (AndConst.isPowerOf2() &&
5360 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
5362 DAG.getSetCC(N->getDebugLoc(),
5363 TLI.getSetCCResultType(Op0.getValueType()),
5364 Op0, DAG.getConstant(0, Op0.getValueType()),
5367 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5368 MVT::Other, Chain, SetCC, N2);
5369 // Don't add the new BRCond into the worklist or else SimplifySelectCC
5370 // will convert it back to (X & C1) >> C2.
5371 CombineTo(N, NewBRCond, false);
5372 // Truncate is dead.
5374 removeFromWorkList(Trunc);
5375 DAG.DeleteNode(Trunc);
5377 // Replace the uses of SRL with SETCC
5378 WorkListRemover DeadNodes(*this);
5379 DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5380 removeFromWorkList(N1.getNode());
5381 DAG.DeleteNode(N1.getNode());
5382 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5388 // Restore N1 if the above transformation doesn't match.
5389 N1 = N->getOperand(1);
5392 // Transform br(xor(x, y)) -> br(x != y)
5393 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
5394 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
5395 SDNode *TheXor = N1.getNode();
5396 SDValue Op0 = TheXor->getOperand(0);
5397 SDValue Op1 = TheXor->getOperand(1);
5398 if (Op0.getOpcode() == Op1.getOpcode()) {
5399 // Avoid missing important xor optimizations.
5400 SDValue Tmp = visitXOR(TheXor);
5401 if (Tmp.getNode() && Tmp.getNode() != TheXor) {
5402 DEBUG(dbgs() << "\nReplacing.8 ";
5404 dbgs() << "\nWith: ";
5405 Tmp.getNode()->dump(&DAG);
5407 WorkListRemover DeadNodes(*this);
5408 DAG.ReplaceAllUsesOfValueWith(N1, Tmp, &DeadNodes);
5409 removeFromWorkList(TheXor);
5410 DAG.DeleteNode(TheXor);
5411 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5412 MVT::Other, Chain, Tmp, N2);
5416 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
5418 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
5419 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
5420 Op0.getOpcode() == ISD::XOR) {
5421 TheXor = Op0.getNode();
5425 EVT SetCCVT = N1.getValueType();
5427 SetCCVT = TLI.getSetCCResultType(SetCCVT);
5428 SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
5431 Equal ? ISD::SETEQ : ISD::SETNE);
5432 // Replace the uses of XOR with SETCC
5433 WorkListRemover DeadNodes(*this);
5434 DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5435 removeFromWorkList(N1.getNode());
5436 DAG.DeleteNode(N1.getNode());
5437 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5438 MVT::Other, Chain, SetCC, N2);
5445 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
5447 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
5448 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
5449 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
5451 // If N is a constant we could fold this into a fallthrough or unconditional
5452 // branch. However that doesn't happen very often in normal code, because
5453 // Instcombine/SimplifyCFG should have handled the available opportunities.
5454 // If we did this folding here, it would be necessary to update the
5455 // MachineBasicBlock CFG, which is awkward.
5457 // Use SimplifySetCC to simplify SETCC's.
5458 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
5459 CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
5461 if (Simp.getNode()) AddToWorkList(Simp.getNode());
5463 // fold to a simpler setcc
5464 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
5465 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5466 N->getOperand(0), Simp.getOperand(2),
5467 Simp.getOperand(0), Simp.getOperand(1),
5473 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
5474 /// pre-indexed load / store when the base pointer is an add or subtract
5475 /// and it has other uses besides the load / store. After the
5476 /// transformation, the new indexed load / store has effectively folded
5477 /// the add / subtract in and all of its other uses are redirected to the
5478 /// new load / store.
5479 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
5480 if (!LegalOperations)
5486 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5487 if (LD->isIndexed())
5489 VT = LD->getMemoryVT();
5490 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
5491 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
5493 Ptr = LD->getBasePtr();
5494 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5495 if (ST->isIndexed())
5497 VT = ST->getMemoryVT();
5498 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
5499 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
5501 Ptr = ST->getBasePtr();
5507 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
5508 // out. There is no reason to make this a preinc/predec.
5509 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
5510 Ptr.getNode()->hasOneUse())
5513 // Ask the target to do addressing mode selection.
5516 ISD::MemIndexedMode AM = ISD::UNINDEXED;
5517 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
5519 // Don't create a indexed load / store with zero offset.
5520 if (isa<ConstantSDNode>(Offset) &&
5521 cast<ConstantSDNode>(Offset)->isNullValue())
5524 // Try turning it into a pre-indexed load / store except when:
5525 // 1) The new base ptr is a frame index.
5526 // 2) If N is a store and the new base ptr is either the same as or is a
5527 // predecessor of the value being stored.
5528 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
5529 // that would create a cycle.
5530 // 4) All uses are load / store ops that use it as old base ptr.
5532 // Check #1. Preinc'ing a frame index would require copying the stack pointer
5533 // (plus the implicit offset) to a register to preinc anyway.
5534 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5539 SDValue Val = cast<StoreSDNode>(N)->getValue();
5540 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
5544 // Now check for #3 and #4.
5545 bool RealUse = false;
5546 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5547 E = Ptr.getNode()->use_end(); I != E; ++I) {
5551 if (Use->isPredecessorOf(N))
5554 if (!((Use->getOpcode() == ISD::LOAD &&
5555 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
5556 (Use->getOpcode() == ISD::STORE &&
5557 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
5566 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5567 BasePtr, Offset, AM);
5569 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5570 BasePtr, Offset, AM);
5573 DEBUG(dbgs() << "\nReplacing.4 ";
5575 dbgs() << "\nWith: ";
5576 Result.getNode()->dump(&DAG);
5578 WorkListRemover DeadNodes(*this);
5580 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5582 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5585 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5589 // Finally, since the node is now dead, remove it from the graph.
5592 // Replace the uses of Ptr with uses of the updated base value.
5593 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
5595 removeFromWorkList(Ptr.getNode());
5596 DAG.DeleteNode(Ptr.getNode());
5601 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
5602 /// add / sub of the base pointer node into a post-indexed load / store.
5603 /// The transformation folded the add / subtract into the new indexed
5604 /// load / store effectively and all of its uses are redirected to the
5605 /// new load / store.
5606 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
5607 if (!LegalOperations)
5613 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5614 if (LD->isIndexed())
5616 VT = LD->getMemoryVT();
5617 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
5618 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
5620 Ptr = LD->getBasePtr();
5621 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5622 if (ST->isIndexed())
5624 VT = ST->getMemoryVT();
5625 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
5626 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
5628 Ptr = ST->getBasePtr();
5634 if (Ptr.getNode()->hasOneUse())
5637 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5638 E = Ptr.getNode()->use_end(); I != E; ++I) {
5641 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
5646 ISD::MemIndexedMode AM = ISD::UNINDEXED;
5647 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
5648 // Don't create a indexed load / store with zero offset.
5649 if (isa<ConstantSDNode>(Offset) &&
5650 cast<ConstantSDNode>(Offset)->isNullValue())
5653 // Try turning it into a post-indexed load / store except when
5654 // 1) All uses are load / store ops that use it as base ptr.
5655 // 2) Op must be independent of N, i.e. Op is neither a predecessor
5656 // nor a successor of N. Otherwise, if Op is folded that would
5659 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5663 bool TryNext = false;
5664 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
5665 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
5667 if (Use == Ptr.getNode())
5670 // If all the uses are load / store addresses, then don't do the
5672 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
5673 bool RealUse = false;
5674 for (SDNode::use_iterator III = Use->use_begin(),
5675 EEE = Use->use_end(); III != EEE; ++III) {
5676 SDNode *UseUse = *III;
5677 if (!((UseUse->getOpcode() == ISD::LOAD &&
5678 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
5679 (UseUse->getOpcode() == ISD::STORE &&
5680 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
5695 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
5696 SDValue Result = isLoad
5697 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5698 BasePtr, Offset, AM)
5699 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5700 BasePtr, Offset, AM);
5703 DEBUG(dbgs() << "\nReplacing.5 ";
5705 dbgs() << "\nWith: ";
5706 Result.getNode()->dump(&DAG);
5708 WorkListRemover DeadNodes(*this);
5710 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5712 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5715 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5719 // Finally, since the node is now dead, remove it from the graph.
5722 // Replace the uses of Use with uses of the updated base value.
5723 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
5724 Result.getValue(isLoad ? 1 : 0),
5726 removeFromWorkList(Op);
5736 SDValue DAGCombiner::visitLOAD(SDNode *N) {
5737 LoadSDNode *LD = cast<LoadSDNode>(N);
5738 SDValue Chain = LD->getChain();
5739 SDValue Ptr = LD->getBasePtr();
5741 // If load is not volatile and there are no uses of the loaded value (and
5742 // the updated indexed value in case of indexed loads), change uses of the
5743 // chain value into uses of the chain input (i.e. delete the dead load).
5744 if (!LD->isVolatile()) {
5745 if (N->getValueType(1) == MVT::Other) {
5747 if (N->hasNUsesOfValue(0, 0)) {
5748 // It's not safe to use the two value CombineTo variant here. e.g.
5749 // v1, chain2 = load chain1, loc
5750 // v2, chain3 = load chain2, loc
5752 // Now we replace use of chain2 with chain1. This makes the second load
5753 // isomorphic to the one we are deleting, and thus makes this load live.
5754 DEBUG(dbgs() << "\nReplacing.6 ";
5756 dbgs() << "\nWith chain: ";
5757 Chain.getNode()->dump(&DAG);
5759 WorkListRemover DeadNodes(*this);
5760 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
5762 if (N->use_empty()) {
5763 removeFromWorkList(N);
5767 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5771 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
5772 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
5773 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
5774 DEBUG(dbgs() << "\nReplacing.7 ";
5776 dbgs() << "\nWith: ";
5777 Undef.getNode()->dump(&DAG);
5778 dbgs() << " and 2 other values\n");
5779 WorkListRemover DeadNodes(*this);
5780 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
5781 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
5782 DAG.getUNDEF(N->getValueType(1)),
5784 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
5785 removeFromWorkList(N);
5787 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5792 // If this load is directly stored, replace the load value with the stored
5794 // TODO: Handle store large -> read small portion.
5795 // TODO: Handle TRUNCSTORE/LOADEXT
5796 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
5797 !LD->isVolatile()) {
5798 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
5799 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
5800 if (PrevST->getBasePtr() == Ptr &&
5801 PrevST->getValue().getValueType() == N->getValueType(0))
5802 return CombineTo(N, Chain.getOperand(1), Chain);
5806 // Try to infer better alignment information than the load already has.
5807 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
5808 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5809 if (Align > LD->getAlignment())
5810 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
5812 Chain, Ptr, LD->getPointerInfo(),
5814 LD->isVolatile(), LD->isNonTemporal(), Align);
5819 // Walk up chain skipping non-aliasing memory nodes.
5820 SDValue BetterChain = FindBetterChain(N, Chain);
5822 // If there is a better chain.
5823 if (Chain != BetterChain) {
5826 // Replace the chain to void dependency.
5827 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
5828 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
5829 BetterChain, Ptr, LD->getPointerInfo(),
5830 LD->isVolatile(), LD->isNonTemporal(),
5831 LD->getAlignment());
5833 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
5835 BetterChain, Ptr, LD->getPointerInfo(),
5838 LD->isNonTemporal(),
5839 LD->getAlignment());
5842 // Create token factor to keep old chain connected.
5843 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5844 MVT::Other, Chain, ReplLoad.getValue(1));
5846 // Make sure the new and old chains are cleaned up.
5847 AddToWorkList(Token.getNode());
5849 // Replace uses with load result and token factor. Don't add users
5851 return CombineTo(N, ReplLoad.getValue(0), Token, false);
5855 // Try transforming N to an indexed load.
5856 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5857 return SDValue(N, 0);
5862 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
5863 /// load is having specific bytes cleared out. If so, return the byte size
5864 /// being masked out and the shift amount.
5865 static std::pair<unsigned, unsigned>
5866 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
5867 std::pair<unsigned, unsigned> Result(0, 0);
5869 // Check for the structure we're looking for.
5870 if (V->getOpcode() != ISD::AND ||
5871 !isa<ConstantSDNode>(V->getOperand(1)) ||
5872 !ISD::isNormalLoad(V->getOperand(0).getNode()))
5875 // Check the chain and pointer.
5876 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
5877 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
5879 // The store should be chained directly to the load or be an operand of a
5881 if (LD == Chain.getNode())
5883 else if (Chain->getOpcode() != ISD::TokenFactor)
5884 return Result; // Fail.
5887 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
5888 if (Chain->getOperand(i).getNode() == LD) {
5892 if (!isOk) return Result;
5895 // This only handles simple types.
5896 if (V.getValueType() != MVT::i16 &&
5897 V.getValueType() != MVT::i32 &&
5898 V.getValueType() != MVT::i64)
5901 // Check the constant mask. Invert it so that the bits being masked out are
5902 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
5903 // follow the sign bit for uniformity.
5904 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
5905 unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
5906 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
5907 unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
5908 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
5909 if (NotMaskLZ == 64) return Result; // All zero mask.
5911 // See if we have a continuous run of bits. If so, we have 0*1+0*
5912 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
5915 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
5916 if (V.getValueType() != MVT::i64 && NotMaskLZ)
5917 NotMaskLZ -= 64-V.getValueSizeInBits();
5919 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
5920 switch (MaskedBytes) {
5924 default: return Result; // All one mask, or 5-byte mask.
5927 // Verify that the first bit starts at a multiple of mask so that the access
5928 // is aligned the same as the access width.
5929 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
5931 Result.first = MaskedBytes;
5932 Result.second = NotMaskTZ/8;
5937 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
5938 /// provides a value as specified by MaskInfo. If so, replace the specified
5939 /// store with a narrower store of truncated IVal.
5941 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
5942 SDValue IVal, StoreSDNode *St,
5944 unsigned NumBytes = MaskInfo.first;
5945 unsigned ByteShift = MaskInfo.second;
5946 SelectionDAG &DAG = DC->getDAG();
5948 // Check to see if IVal is all zeros in the part being masked in by the 'or'
5949 // that uses this. If not, this is not a replacement.
5950 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
5951 ByteShift*8, (ByteShift+NumBytes)*8);
5952 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
5954 // Check that it is legal on the target to do this. It is legal if the new
5955 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
5957 MVT VT = MVT::getIntegerVT(NumBytes*8);
5958 if (!DC->isTypeLegal(VT))
5961 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
5962 // shifted by ByteShift and truncated down to NumBytes.
5964 IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
5965 DAG.getConstant(ByteShift*8, DC->getShiftAmountTy()));
5967 // Figure out the offset for the store and the alignment of the access.
5969 unsigned NewAlign = St->getAlignment();
5971 if (DAG.getTargetLoweringInfo().isLittleEndian())
5972 StOffset = ByteShift;
5974 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
5976 SDValue Ptr = St->getBasePtr();
5978 Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
5979 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
5980 NewAlign = MinAlign(NewAlign, StOffset);
5983 // Truncate down to the new size.
5984 IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
5987 return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
5988 St->getPointerInfo().getWithOffset(StOffset),
5989 false, false, NewAlign).getNode();
5993 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
5994 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
5995 /// of the loaded bits, try narrowing the load and store if it would end up
5996 /// being a win for performance or code size.
5997 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
5998 StoreSDNode *ST = cast<StoreSDNode>(N);
5999 if (ST->isVolatile())
6002 SDValue Chain = ST->getChain();
6003 SDValue Value = ST->getValue();
6004 SDValue Ptr = ST->getBasePtr();
6005 EVT VT = Value.getValueType();
6007 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
6010 unsigned Opc = Value.getOpcode();
6012 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
6013 // is a byte mask indicating a consecutive number of bytes, check to see if
6014 // Y is known to provide just those bytes. If so, we try to replace the
6015 // load + replace + store sequence with a single (narrower) store, which makes
6017 if (Opc == ISD::OR) {
6018 std::pair<unsigned, unsigned> MaskedLoad;
6019 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
6020 if (MaskedLoad.first)
6021 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6022 Value.getOperand(1), ST,this))
6023 return SDValue(NewST, 0);
6025 // Or is commutative, so try swapping X and Y.
6026 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
6027 if (MaskedLoad.first)
6028 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6029 Value.getOperand(0), ST,this))
6030 return SDValue(NewST, 0);
6033 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
6034 Value.getOperand(1).getOpcode() != ISD::Constant)
6037 SDValue N0 = Value.getOperand(0);
6038 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6039 Chain == SDValue(N0.getNode(), 1)) {
6040 LoadSDNode *LD = cast<LoadSDNode>(N0);
6041 if (LD->getBasePtr() != Ptr ||
6042 LD->getPointerInfo().getAddrSpace() !=
6043 ST->getPointerInfo().getAddrSpace())
6046 // Find the type to narrow it the load / op / store to.
6047 SDValue N1 = Value.getOperand(1);
6048 unsigned BitWidth = N1.getValueSizeInBits();
6049 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
6050 if (Opc == ISD::AND)
6051 Imm ^= APInt::getAllOnesValue(BitWidth);
6052 if (Imm == 0 || Imm.isAllOnesValue())
6054 unsigned ShAmt = Imm.countTrailingZeros();
6055 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
6056 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
6057 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
6058 while (NewBW < BitWidth &&
6059 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
6060 TLI.isNarrowingProfitable(VT, NewVT))) {
6061 NewBW = NextPowerOf2(NewBW);
6062 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
6064 if (NewBW >= BitWidth)
6067 // If the lsb changed does not start at the type bitwidth boundary,
6068 // start at the previous one.
6070 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
6071 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
6072 if ((Imm & Mask) == Imm) {
6073 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
6074 if (Opc == ISD::AND)
6075 NewImm ^= APInt::getAllOnesValue(NewBW);
6076 uint64_t PtrOff = ShAmt / 8;
6077 // For big endian targets, we need to adjust the offset to the pointer to
6078 // load the correct bytes.
6079 if (TLI.isBigEndian())
6080 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
6082 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
6083 const Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
6084 if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
6087 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
6088 Ptr.getValueType(), Ptr,
6089 DAG.getConstant(PtrOff, Ptr.getValueType()));
6090 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
6091 LD->getChain(), NewPtr,
6092 LD->getPointerInfo().getWithOffset(PtrOff),
6093 LD->isVolatile(), LD->isNonTemporal(),
6095 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
6096 DAG.getConstant(NewImm, NewVT));
6097 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
6099 ST->getPointerInfo().getWithOffset(PtrOff),
6100 false, false, NewAlign);
6102 AddToWorkList(NewPtr.getNode());
6103 AddToWorkList(NewLD.getNode());
6104 AddToWorkList(NewVal.getNode());
6105 WorkListRemover DeadNodes(*this);
6106 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
6116 /// TransformFPLoadStorePair - For a given floating point load / store pair,
6117 /// if the load value isn't used by any other operations, then consider
6118 /// transforming the pair to integer load / store operations if the target
6119 /// deems the transformation profitable.
6120 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
6121 StoreSDNode *ST = cast<StoreSDNode>(N);
6122 SDValue Chain = ST->getChain();
6123 SDValue Value = ST->getValue();
6124 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
6125 Value.hasOneUse() &&
6126 Chain == SDValue(Value.getNode(), 1)) {
6127 LoadSDNode *LD = cast<LoadSDNode>(Value);
6128 EVT VT = LD->getMemoryVT();
6129 if (!VT.isFloatingPoint() ||
6130 VT != ST->getMemoryVT() ||
6131 LD->isNonTemporal() ||
6132 ST->isNonTemporal() ||
6133 LD->getPointerInfo().getAddrSpace() != 0 ||
6134 ST->getPointerInfo().getAddrSpace() != 0)
6137 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
6138 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
6139 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
6140 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
6141 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
6144 unsigned LDAlign = LD->getAlignment();
6145 unsigned STAlign = ST->getAlignment();
6146 const Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
6147 unsigned ABIAlign = TLI.getTargetData()->getABITypeAlignment(IntVTTy);
6148 if (LDAlign < ABIAlign || STAlign < ABIAlign)
6151 SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(),
6152 LD->getChain(), LD->getBasePtr(),
6153 LD->getPointerInfo(),
6154 false, false, LDAlign);
6156 SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
6157 NewLD, ST->getBasePtr(),
6158 ST->getPointerInfo(),
6159 false, false, STAlign);
6161 AddToWorkList(NewLD.getNode());
6162 AddToWorkList(NewST.getNode());
6163 WorkListRemover DeadNodes(*this);
6164 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1),
6173 SDValue DAGCombiner::visitSTORE(SDNode *N) {
6174 StoreSDNode *ST = cast<StoreSDNode>(N);
6175 SDValue Chain = ST->getChain();
6176 SDValue Value = ST->getValue();
6177 SDValue Ptr = ST->getBasePtr();
6179 // If this is a store of a bit convert, store the input value if the
6180 // resultant store does not need a higher alignment than the original.
6181 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
6182 ST->isUnindexed()) {
6183 unsigned OrigAlign = ST->getAlignment();
6184 EVT SVT = Value.getOperand(0).getValueType();
6185 unsigned Align = TLI.getTargetData()->
6186 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
6187 if (Align <= OrigAlign &&
6188 ((!LegalOperations && !ST->isVolatile()) ||
6189 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
6190 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
6191 Ptr, ST->getPointerInfo(), ST->isVolatile(),
6192 ST->isNonTemporal(), OrigAlign);
6195 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
6196 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
6197 // NOTE: If the original store is volatile, this transform must not increase
6198 // the number of stores. For example, on x86-32 an f64 can be stored in one
6199 // processor operation but an i64 (which is not legal) requires two. So the
6200 // transform should not be done in this case.
6201 if (Value.getOpcode() != ISD::TargetConstantFP) {
6203 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
6204 default: llvm_unreachable("Unknown FP type");
6205 case MVT::f80: // We don't do this for these yet.
6210 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
6211 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
6212 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
6213 bitcastToAPInt().getZExtValue(), MVT::i32);
6214 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
6215 Ptr, ST->getPointerInfo(), ST->isVolatile(),
6216 ST->isNonTemporal(), ST->getAlignment());
6220 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
6221 !ST->isVolatile()) ||
6222 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
6223 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
6224 getZExtValue(), MVT::i64);
6225 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
6226 Ptr, ST->getPointerInfo(), ST->isVolatile(),
6227 ST->isNonTemporal(), ST->getAlignment());
6228 } else if (!ST->isVolatile() &&
6229 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
6230 // Many FP stores are not made apparent until after legalize, e.g. for
6231 // argument passing. Since this is so common, custom legalize the
6232 // 64-bit integer store into two 32-bit stores.
6233 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
6234 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
6235 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
6236 if (TLI.isBigEndian()) std::swap(Lo, Hi);
6238 unsigned Alignment = ST->getAlignment();
6239 bool isVolatile = ST->isVolatile();
6240 bool isNonTemporal = ST->isNonTemporal();
6242 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
6243 Ptr, ST->getPointerInfo(),
6244 isVolatile, isNonTemporal,
6245 ST->getAlignment());
6246 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
6247 DAG.getConstant(4, Ptr.getValueType()));
6248 Alignment = MinAlign(Alignment, 4U);
6249 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
6250 Ptr, ST->getPointerInfo().getWithOffset(4),
6251 isVolatile, isNonTemporal,
6253 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
6262 // Try to infer better alignment information than the store already has.
6263 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
6264 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
6265 if (Align > ST->getAlignment())
6266 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
6267 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6268 ST->isVolatile(), ST->isNonTemporal(), Align);
6272 // Try transforming a pair floating point load / store ops to integer
6273 // load / store ops.
6274 SDValue NewST = TransformFPLoadStorePair(N);
6275 if (NewST.getNode())
6279 // Walk up chain skipping non-aliasing memory nodes.
6280 SDValue BetterChain = FindBetterChain(N, Chain);
6282 // If there is a better chain.
6283 if (Chain != BetterChain) {
6286 // Replace the chain to avoid dependency.
6287 if (ST->isTruncatingStore()) {
6288 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6289 ST->getPointerInfo(),
6290 ST->getMemoryVT(), ST->isVolatile(),
6291 ST->isNonTemporal(), ST->getAlignment());
6293 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6294 ST->getPointerInfo(),
6295 ST->isVolatile(), ST->isNonTemporal(),
6296 ST->getAlignment());
6299 // Create token to keep both nodes around.
6300 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
6301 MVT::Other, Chain, ReplStore);
6303 // Make sure the new and old chains are cleaned up.
6304 AddToWorkList(Token.getNode());
6306 // Don't add users to work list.
6307 return CombineTo(N, Token, false);
6311 // Try transforming N to an indexed store.
6312 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
6313 return SDValue(N, 0);
6315 // FIXME: is there such a thing as a truncating indexed store?
6316 if (ST->isTruncatingStore() && ST->isUnindexed() &&
6317 Value.getValueType().isInteger()) {
6318 // See if we can simplify the input to this truncstore with knowledge that
6319 // only the low bits are being used. For example:
6320 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
6322 GetDemandedBits(Value,
6323 APInt::getLowBitsSet(Value.getValueSizeInBits(),
6324 ST->getMemoryVT().getSizeInBits()));
6325 AddToWorkList(Value.getNode());
6326 if (Shorter.getNode())
6327 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
6328 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6329 ST->isVolatile(), ST->isNonTemporal(),
6330 ST->getAlignment());
6332 // Otherwise, see if we can simplify the operation with
6333 // SimplifyDemandedBits, which only works if the value has a single use.
6334 if (SimplifyDemandedBits(Value,
6335 APInt::getLowBitsSet(
6336 Value.getValueType().getScalarType().getSizeInBits(),
6337 ST->getMemoryVT().getScalarType().getSizeInBits())))
6338 return SDValue(N, 0);
6341 // If this is a load followed by a store to the same location, then the store
6343 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
6344 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
6345 ST->isUnindexed() && !ST->isVolatile() &&
6346 // There can't be any side effects between the load and store, such as
6348 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
6349 // The store is dead, remove it.
6354 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
6355 // truncating store. We can do this even if this is already a truncstore.
6356 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
6357 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
6358 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
6359 ST->getMemoryVT())) {
6360 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
6361 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6362 ST->isVolatile(), ST->isNonTemporal(),
6363 ST->getAlignment());
6366 return ReduceLoadOpStoreWidth(N);
6369 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
6370 SDValue InVec = N->getOperand(0);
6371 SDValue InVal = N->getOperand(1);
6372 SDValue EltNo = N->getOperand(2);
6374 // If the inserted element is an UNDEF, just use the input vector.
6375 if (InVal.getOpcode() == ISD::UNDEF)
6378 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
6379 // vector with the inserted element.
6380 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
6381 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6382 SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
6383 InVec.getNode()->op_end());
6384 if (Elt < Ops.size())
6386 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6387 InVec.getValueType(), &Ops[0], Ops.size());
6389 // If the invec is an UNDEF and if EltNo is a constant, create a new
6390 // BUILD_VECTOR with undef elements and the inserted element.
6391 if (!LegalOperations && InVec.getOpcode() == ISD::UNDEF &&
6392 isa<ConstantSDNode>(EltNo)) {
6393 EVT VT = InVec.getValueType();
6394 EVT EltVT = VT.getVectorElementType();
6395 unsigned NElts = VT.getVectorNumElements();
6396 SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EltVT));
6398 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6399 if (Elt < Ops.size())
6401 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6402 InVec.getValueType(), &Ops[0], Ops.size());
6407 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
6408 // (vextract (scalar_to_vector val, 0) -> val
6409 SDValue InVec = N->getOperand(0);
6411 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6412 // Check if the result type doesn't match the inserted element type. A
6413 // SCALAR_TO_VECTOR may truncate the inserted element and the
6414 // EXTRACT_VECTOR_ELT may widen the extracted vector.
6415 SDValue InOp = InVec.getOperand(0);
6416 EVT NVT = N->getValueType(0);
6417 if (InOp.getValueType() != NVT) {
6418 assert(InOp.getValueType().isInteger() && NVT.isInteger());
6419 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
6424 // Perform only after legalization to ensure build_vector / vector_shuffle
6425 // optimizations have already been done.
6426 if (!LegalOperations) return SDValue();
6428 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
6429 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
6430 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
6431 SDValue EltNo = N->getOperand(1);
6433 if (isa<ConstantSDNode>(EltNo)) {
6434 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6435 bool NewLoad = false;
6436 bool BCNumEltsChanged = false;
6437 EVT VT = InVec.getValueType();
6438 EVT ExtVT = VT.getVectorElementType();
6441 if (InVec.getOpcode() == ISD::BITCAST) {
6442 EVT BCVT = InVec.getOperand(0).getValueType();
6443 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
6445 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
6446 BCNumEltsChanged = true;
6447 InVec = InVec.getOperand(0);
6448 ExtVT = BCVT.getVectorElementType();
6452 LoadSDNode *LN0 = NULL;
6453 const ShuffleVectorSDNode *SVN = NULL;
6454 if (ISD::isNormalLoad(InVec.getNode())) {
6455 LN0 = cast<LoadSDNode>(InVec);
6456 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6457 InVec.getOperand(0).getValueType() == ExtVT &&
6458 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
6459 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
6460 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
6461 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
6463 // (load $addr+1*size)
6465 // If the bit convert changed the number of elements, it is unsafe
6466 // to examine the mask.
6467 if (BCNumEltsChanged)
6470 // Select the input vector, guarding against out of range extract vector.
6471 unsigned NumElems = VT.getVectorNumElements();
6472 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
6473 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
6475 if (InVec.getOpcode() == ISD::BITCAST)
6476 InVec = InVec.getOperand(0);
6477 if (ISD::isNormalLoad(InVec.getNode())) {
6478 LN0 = cast<LoadSDNode>(InVec);
6479 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
6483 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
6486 // If Idx was -1 above, Elt is going to be -1, so just return undef.
6488 return DAG.getUNDEF(LN0->getBasePtr().getValueType());
6490 unsigned Align = LN0->getAlignment();
6492 // Check the resultant load doesn't need a higher alignment than the
6496 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
6498 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
6504 SDValue NewPtr = LN0->getBasePtr();
6505 unsigned PtrOff = 0;
6508 PtrOff = LVT.getSizeInBits() * Elt / 8;
6509 EVT PtrType = NewPtr.getValueType();
6510 if (TLI.isBigEndian())
6511 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
6512 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
6513 DAG.getConstant(PtrOff, PtrType));
6516 return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
6517 LN0->getPointerInfo().getWithOffset(PtrOff),
6518 LN0->isVolatile(), LN0->isNonTemporal(), Align);
6524 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
6525 unsigned NumInScalars = N->getNumOperands();
6526 EVT VT = N->getValueType(0);
6528 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
6529 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
6530 // at most two distinct vectors, turn this into a shuffle node.
6531 SDValue VecIn1, VecIn2;
6532 for (unsigned i = 0; i != NumInScalars; ++i) {
6533 // Ignore undef inputs.
6534 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6536 // If this input is something other than a EXTRACT_VECTOR_ELT with a
6537 // constant index, bail out.
6538 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6539 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
6540 VecIn1 = VecIn2 = SDValue(0, 0);
6544 // If the input vector type disagrees with the result of the build_vector,
6545 // we can't make a shuffle.
6546 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
6547 if (ExtractedFromVec.getValueType() != VT) {
6548 VecIn1 = VecIn2 = SDValue(0, 0);
6552 // Otherwise, remember this. We allow up to two distinct input vectors.
6553 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
6556 if (VecIn1.getNode() == 0) {
6557 VecIn1 = ExtractedFromVec;
6558 } else if (VecIn2.getNode() == 0) {
6559 VecIn2 = ExtractedFromVec;
6562 VecIn1 = VecIn2 = SDValue(0, 0);
6567 // If everything is good, we can make a shuffle operation.
6568 if (VecIn1.getNode()) {
6569 SmallVector<int, 8> Mask;
6570 for (unsigned i = 0; i != NumInScalars; ++i) {
6571 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
6576 // If extracting from the first vector, just use the index directly.
6577 SDValue Extract = N->getOperand(i);
6578 SDValue ExtVal = Extract.getOperand(1);
6579 if (Extract.getOperand(0) == VecIn1) {
6580 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6581 if (ExtIndex > VT.getVectorNumElements())
6584 Mask.push_back(ExtIndex);
6588 // Otherwise, use InIdx + VecSize
6589 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6590 Mask.push_back(Idx+NumInScalars);
6593 // Add count and size info.
6594 if (!isTypeLegal(VT))
6597 // Return the new VECTOR_SHUFFLE node.
6600 Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6601 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
6607 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
6608 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
6609 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
6610 // inputs come from at most two distinct vectors, turn this into a shuffle
6613 // If we only have one input vector, we don't need to do any concatenation.
6614 if (N->getNumOperands() == 1)
6615 return N->getOperand(0);
6620 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
6621 EVT VT = N->getValueType(0);
6622 unsigned NumElts = VT.getVectorNumElements();
6624 SDValue N0 = N->getOperand(0);
6626 assert(N0.getValueType().getVectorNumElements() == NumElts &&
6627 "Vector shuffle must be normalized in DAG");
6629 // FIXME: implement canonicalizations from DAG.getVectorShuffle()
6631 // If it is a splat, check if the argument vector is another splat or a
6632 // build_vector with all scalar elements the same.
6633 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
6634 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
6635 SDNode *V = N0.getNode();
6637 // If this is a bit convert that changes the element type of the vector but
6638 // not the number of vector elements, look through it. Be careful not to
6639 // look though conversions that change things like v4f32 to v2f64.
6640 if (V->getOpcode() == ISD::BITCAST) {
6641 SDValue ConvInput = V->getOperand(0);
6642 if (ConvInput.getValueType().isVector() &&
6643 ConvInput.getValueType().getVectorNumElements() == NumElts)
6644 V = ConvInput.getNode();
6647 if (V->getOpcode() == ISD::BUILD_VECTOR) {
6648 assert(V->getNumOperands() == NumElts &&
6649 "BUILD_VECTOR has wrong number of operands");
6651 bool AllSame = true;
6652 for (unsigned i = 0; i != NumElts; ++i) {
6653 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
6654 Base = V->getOperand(i);
6658 // Splat of <u, u, u, u>, return <u, u, u, u>
6659 if (!Base.getNode())
6661 for (unsigned i = 0; i != NumElts; ++i) {
6662 if (V->getOperand(i) != Base) {
6667 // Splat of <x, x, x, x>, return <x, x, x, x>
6675 SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) {
6676 if (!TLI.getShouldFoldAtomicFences())
6679 SDValue atomic = N->getOperand(0);
6680 switch (atomic.getOpcode()) {
6681 case ISD::ATOMIC_CMP_SWAP:
6682 case ISD::ATOMIC_SWAP:
6683 case ISD::ATOMIC_LOAD_ADD:
6684 case ISD::ATOMIC_LOAD_SUB:
6685 case ISD::ATOMIC_LOAD_AND:
6686 case ISD::ATOMIC_LOAD_OR:
6687 case ISD::ATOMIC_LOAD_XOR:
6688 case ISD::ATOMIC_LOAD_NAND:
6689 case ISD::ATOMIC_LOAD_MIN:
6690 case ISD::ATOMIC_LOAD_MAX:
6691 case ISD::ATOMIC_LOAD_UMIN:
6692 case ISD::ATOMIC_LOAD_UMAX:
6698 SDValue fence = atomic.getOperand(0);
6699 if (fence.getOpcode() != ISD::MEMBARRIER)
6702 switch (atomic.getOpcode()) {
6703 case ISD::ATOMIC_CMP_SWAP:
6704 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
6705 fence.getOperand(0),
6706 atomic.getOperand(1), atomic.getOperand(2),
6707 atomic.getOperand(3)), atomic.getResNo());
6708 case ISD::ATOMIC_SWAP:
6709 case ISD::ATOMIC_LOAD_ADD:
6710 case ISD::ATOMIC_LOAD_SUB:
6711 case ISD::ATOMIC_LOAD_AND:
6712 case ISD::ATOMIC_LOAD_OR:
6713 case ISD::ATOMIC_LOAD_XOR:
6714 case ISD::ATOMIC_LOAD_NAND:
6715 case ISD::ATOMIC_LOAD_MIN:
6716 case ISD::ATOMIC_LOAD_MAX:
6717 case ISD::ATOMIC_LOAD_UMIN:
6718 case ISD::ATOMIC_LOAD_UMAX:
6719 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
6720 fence.getOperand(0),
6721 atomic.getOperand(1), atomic.getOperand(2)),
6728 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
6729 /// an AND to a vector_shuffle with the destination vector and a zero vector.
6730 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
6731 /// vector_shuffle V, Zero, <0, 4, 2, 4>
6732 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
6733 EVT VT = N->getValueType(0);
6734 DebugLoc dl = N->getDebugLoc();
6735 SDValue LHS = N->getOperand(0);
6736 SDValue RHS = N->getOperand(1);
6737 if (N->getOpcode() == ISD::AND) {
6738 if (RHS.getOpcode() == ISD::BITCAST)
6739 RHS = RHS.getOperand(0);
6740 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
6741 SmallVector<int, 8> Indices;
6742 unsigned NumElts = RHS.getNumOperands();
6743 for (unsigned i = 0; i != NumElts; ++i) {
6744 SDValue Elt = RHS.getOperand(i);
6745 if (!isa<ConstantSDNode>(Elt))
6747 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
6748 Indices.push_back(i);
6749 else if (cast<ConstantSDNode>(Elt)->isNullValue())
6750 Indices.push_back(NumElts);
6755 // Let's see if the target supports this vector_shuffle.
6756 EVT RVT = RHS.getValueType();
6757 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
6760 // Return the new VECTOR_SHUFFLE node.
6761 EVT EltVT = RVT.getVectorElementType();
6762 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
6763 DAG.getConstant(0, EltVT));
6764 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6765 RVT, &ZeroOps[0], ZeroOps.size());
6766 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
6767 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
6768 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
6775 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
6776 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
6777 // After legalize, the target may be depending on adds and other
6778 // binary ops to provide legal ways to construct constants or other
6779 // things. Simplifying them may result in a loss of legality.
6780 if (LegalOperations) return SDValue();
6782 assert(N->getValueType(0).isVector() &&
6783 "SimplifyVBinOp only works on vectors!");
6785 SDValue LHS = N->getOperand(0);
6786 SDValue RHS = N->getOperand(1);
6787 SDValue Shuffle = XformToShuffleWithZero(N);
6788 if (Shuffle.getNode()) return Shuffle;
6790 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
6792 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
6793 RHS.getOpcode() == ISD::BUILD_VECTOR) {
6794 SmallVector<SDValue, 8> Ops;
6795 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
6796 SDValue LHSOp = LHS.getOperand(i);
6797 SDValue RHSOp = RHS.getOperand(i);
6798 // If these two elements can't be folded, bail out.
6799 if ((LHSOp.getOpcode() != ISD::UNDEF &&
6800 LHSOp.getOpcode() != ISD::Constant &&
6801 LHSOp.getOpcode() != ISD::ConstantFP) ||
6802 (RHSOp.getOpcode() != ISD::UNDEF &&
6803 RHSOp.getOpcode() != ISD::Constant &&
6804 RHSOp.getOpcode() != ISD::ConstantFP))
6807 // Can't fold divide by zero.
6808 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
6809 N->getOpcode() == ISD::FDIV) {
6810 if ((RHSOp.getOpcode() == ISD::Constant &&
6811 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
6812 (RHSOp.getOpcode() == ISD::ConstantFP &&
6813 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
6817 EVT VT = LHSOp.getValueType();
6818 assert(RHSOp.getValueType() == VT &&
6819 "SimplifyVBinOp with different BUILD_VECTOR element types");
6820 SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
6822 if (FoldOp.getOpcode() != ISD::UNDEF &&
6823 FoldOp.getOpcode() != ISD::Constant &&
6824 FoldOp.getOpcode() != ISD::ConstantFP)
6826 Ops.push_back(FoldOp);
6827 AddToWorkList(FoldOp.getNode());
6830 if (Ops.size() == LHS.getNumOperands())
6831 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6832 LHS.getValueType(), &Ops[0], Ops.size());
6838 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
6839 SDValue N1, SDValue N2){
6840 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
6842 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
6843 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6845 // If we got a simplified select_cc node back from SimplifySelectCC, then
6846 // break it down into a new SETCC node, and a new SELECT node, and then return
6847 // the SELECT node, since we were called with a SELECT node.
6848 if (SCC.getNode()) {
6849 // Check to see if we got a select_cc back (to turn into setcc/select).
6850 // Otherwise, just return whatever node we got back, like fabs.
6851 if (SCC.getOpcode() == ISD::SELECT_CC) {
6852 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
6854 SCC.getOperand(0), SCC.getOperand(1),
6856 AddToWorkList(SETCC.getNode());
6857 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
6858 SCC.getOperand(2), SCC.getOperand(3), SETCC);
6866 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
6867 /// are the two values being selected between, see if we can simplify the
6868 /// select. Callers of this should assume that TheSelect is deleted if this
6869 /// returns true. As such, they should return the appropriate thing (e.g. the
6870 /// node) back to the top-level of the DAG combiner loop to avoid it being
6872 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
6875 // Cannot simplify select with vector condition
6876 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
6878 // If this is a select from two identical things, try to pull the operation
6879 // through the select.
6880 if (LHS.getOpcode() != RHS.getOpcode() ||
6881 !LHS.hasOneUse() || !RHS.hasOneUse())
6884 // If this is a load and the token chain is identical, replace the select
6885 // of two loads with a load through a select of the address to load from.
6886 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
6887 // constants have been dropped into the constant pool.
6888 if (LHS.getOpcode() == ISD::LOAD) {
6889 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
6890 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
6892 // Token chains must be identical.
6893 if (LHS.getOperand(0) != RHS.getOperand(0) ||
6894 // Do not let this transformation reduce the number of volatile loads.
6895 LLD->isVolatile() || RLD->isVolatile() ||
6896 // If this is an EXTLOAD, the VT's must match.
6897 LLD->getMemoryVT() != RLD->getMemoryVT() ||
6898 // If this is an EXTLOAD, the kind of extension must match.
6899 (LLD->getExtensionType() != RLD->getExtensionType() &&
6900 // The only exception is if one of the extensions is anyext.
6901 LLD->getExtensionType() != ISD::EXTLOAD &&
6902 RLD->getExtensionType() != ISD::EXTLOAD) ||
6903 // FIXME: this discards src value information. This is
6904 // over-conservative. It would be beneficial to be able to remember
6905 // both potential memory locations. Since we are discarding
6906 // src value info, don't do the transformation if the memory
6907 // locations are not in the default address space.
6908 LLD->getPointerInfo().getAddrSpace() != 0 ||
6909 RLD->getPointerInfo().getAddrSpace() != 0)
6912 // Check that the select condition doesn't reach either load. If so,
6913 // folding this will induce a cycle into the DAG. If not, this is safe to
6914 // xform, so create a select of the addresses.
6916 if (TheSelect->getOpcode() == ISD::SELECT) {
6917 SDNode *CondNode = TheSelect->getOperand(0).getNode();
6918 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
6919 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
6921 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
6922 LLD->getBasePtr().getValueType(),
6923 TheSelect->getOperand(0), LLD->getBasePtr(),
6925 } else { // Otherwise SELECT_CC
6926 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
6927 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
6929 if ((LLD->hasAnyUseOfValue(1) &&
6930 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
6931 (LLD->hasAnyUseOfValue(1) &&
6932 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))))
6935 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
6936 LLD->getBasePtr().getValueType(),
6937 TheSelect->getOperand(0),
6938 TheSelect->getOperand(1),
6939 LLD->getBasePtr(), RLD->getBasePtr(),
6940 TheSelect->getOperand(4));
6944 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
6945 Load = DAG.getLoad(TheSelect->getValueType(0),
6946 TheSelect->getDebugLoc(),
6947 // FIXME: Discards pointer info.
6948 LLD->getChain(), Addr, MachinePointerInfo(),
6949 LLD->isVolatile(), LLD->isNonTemporal(),
6950 LLD->getAlignment());
6952 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
6953 RLD->getExtensionType() : LLD->getExtensionType(),
6954 TheSelect->getValueType(0),
6955 TheSelect->getDebugLoc(),
6956 // FIXME: Discards pointer info.
6957 LLD->getChain(), Addr, MachinePointerInfo(),
6958 LLD->getMemoryVT(), LLD->isVolatile(),
6959 LLD->isNonTemporal(), LLD->getAlignment());
6962 // Users of the select now use the result of the load.
6963 CombineTo(TheSelect, Load);
6965 // Users of the old loads now use the new load's chain. We know the
6966 // old-load value is dead now.
6967 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
6968 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
6975 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
6976 /// where 'cond' is the comparison specified by CC.
6977 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
6978 SDValue N2, SDValue N3,
6979 ISD::CondCode CC, bool NotExtCompare) {
6980 // (x ? y : y) -> y.
6981 if (N2 == N3) return N2;
6983 EVT VT = N2.getValueType();
6984 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
6985 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
6986 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
6988 // Determine if the condition we're dealing with is constant
6989 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
6990 N0, N1, CC, DL, false);
6991 if (SCC.getNode()) AddToWorkList(SCC.getNode());
6992 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
6994 // fold select_cc true, x, y -> x
6995 if (SCCC && !SCCC->isNullValue())
6997 // fold select_cc false, x, y -> y
6998 if (SCCC && SCCC->isNullValue())
7001 // Check to see if we can simplify the select into an fabs node
7002 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
7003 // Allow either -0.0 or 0.0
7004 if (CFP->getValueAPF().isZero()) {
7005 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
7006 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
7007 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
7008 N2 == N3.getOperand(0))
7009 return DAG.getNode(ISD::FABS, DL, VT, N0);
7011 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
7012 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
7013 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
7014 N2.getOperand(0) == N3)
7015 return DAG.getNode(ISD::FABS, DL, VT, N3);
7019 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
7020 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
7021 // in it. This is a win when the constant is not otherwise available because
7022 // it replaces two constant pool loads with one. We only do this if the FP
7023 // type is known to be legal, because if it isn't, then we are before legalize
7024 // types an we want the other legalization to happen first (e.g. to avoid
7025 // messing with soft float) and if the ConstantFP is not legal, because if
7026 // it is legal, we may not need to store the FP constant in a constant pool.
7027 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
7028 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
7029 if (TLI.isTypeLegal(N2.getValueType()) &&
7030 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
7031 TargetLowering::Legal) &&
7032 // If both constants have multiple uses, then we won't need to do an
7033 // extra load, they are likely around in registers for other users.
7034 (TV->hasOneUse() || FV->hasOneUse())) {
7035 Constant *Elts[] = {
7036 const_cast<ConstantFP*>(FV->getConstantFPValue()),
7037 const_cast<ConstantFP*>(TV->getConstantFPValue())
7039 const Type *FPTy = Elts[0]->getType();
7040 const TargetData &TD = *TLI.getTargetData();
7042 // Create a ConstantArray of the two constants.
7043 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2);
7044 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
7045 TD.getPrefTypeAlignment(FPTy));
7046 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
7048 // Get the offsets to the 0 and 1 element of the array so that we can
7049 // select between them.
7050 SDValue Zero = DAG.getIntPtrConstant(0);
7051 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
7052 SDValue One = DAG.getIntPtrConstant(EltSize);
7054 SDValue Cond = DAG.getSetCC(DL,
7055 TLI.getSetCCResultType(N0.getValueType()),
7057 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
7059 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
7061 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
7062 MachinePointerInfo::getConstantPool(), false,
7068 // Check to see if we can perform the "gzip trick", transforming
7069 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
7070 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
7071 N0.getValueType().isInteger() &&
7072 N2.getValueType().isInteger() &&
7073 (N1C->isNullValue() || // (a < 0) ? b : 0
7074 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
7075 EVT XType = N0.getValueType();
7076 EVT AType = N2.getValueType();
7077 if (XType.bitsGE(AType)) {
7078 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
7079 // single-bit constant.
7080 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
7081 unsigned ShCtV = N2C->getAPIntValue().logBase2();
7082 ShCtV = XType.getSizeInBits()-ShCtV-1;
7083 SDValue ShCt = DAG.getConstant(ShCtV, getShiftAmountTy());
7084 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
7086 AddToWorkList(Shift.getNode());
7088 if (XType.bitsGT(AType)) {
7089 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
7090 AddToWorkList(Shift.getNode());
7093 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
7096 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
7098 DAG.getConstant(XType.getSizeInBits()-1,
7099 getShiftAmountTy()));
7100 AddToWorkList(Shift.getNode());
7102 if (XType.bitsGT(AType)) {
7103 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
7104 AddToWorkList(Shift.getNode());
7107 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
7111 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
7112 // where y is has a single bit set.
7113 // A plaintext description would be, we can turn the SELECT_CC into an AND
7114 // when the condition can be materialized as an all-ones register. Any
7115 // single bit-test can be materialized as an all-ones register with
7116 // shift-left and shift-right-arith.
7117 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
7118 N0->getValueType(0) == VT &&
7119 N1C && N1C->isNullValue() &&
7120 N2C && N2C->isNullValue()) {
7121 SDValue AndLHS = N0->getOperand(0);
7122 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7123 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
7124 // Shift the tested bit over the sign bit.
7125 APInt AndMask = ConstAndRHS->getAPIntValue();
7127 DAG.getConstant(AndMask.countLeadingZeros(), getShiftAmountTy());
7128 SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
7130 // Now arithmetic right shift it all the way over, so the result is either
7131 // all-ones, or zero.
7133 DAG.getConstant(AndMask.getBitWidth()-1, getShiftAmountTy());
7134 SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
7136 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
7140 // fold select C, 16, 0 -> shl C, 4
7141 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
7142 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
7144 // If the caller doesn't want us to simplify this into a zext of a compare,
7146 if (NotExtCompare && N2C->getAPIntValue() == 1)
7149 // Get a SetCC of the condition
7150 // FIXME: Should probably make sure that setcc is legal if we ever have a
7151 // target where it isn't.
7153 // cast from setcc result type to select result type
7155 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
7157 if (N2.getValueType().bitsLT(SCC.getValueType()))
7158 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
7160 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
7161 N2.getValueType(), SCC);
7163 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
7164 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
7165 N2.getValueType(), SCC);
7168 AddToWorkList(SCC.getNode());
7169 AddToWorkList(Temp.getNode());
7171 if (N2C->getAPIntValue() == 1)
7174 // shl setcc result by log2 n2c
7175 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
7176 DAG.getConstant(N2C->getAPIntValue().logBase2(),
7177 getShiftAmountTy()));
7180 // Check to see if this is the equivalent of setcc
7181 // FIXME: Turn all of these into setcc if setcc if setcc is legal
7182 // otherwise, go ahead with the folds.
7183 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
7184 EVT XType = N0.getValueType();
7185 if (!LegalOperations ||
7186 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
7187 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
7188 if (Res.getValueType() != VT)
7189 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
7193 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
7194 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
7195 (!LegalOperations ||
7196 TLI.isOperationLegal(ISD::CTLZ, XType))) {
7197 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
7198 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
7199 DAG.getConstant(Log2_32(XType.getSizeInBits()),
7200 getShiftAmountTy()));
7202 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
7203 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
7204 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
7205 XType, DAG.getConstant(0, XType), N0);
7206 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
7207 return DAG.getNode(ISD::SRL, DL, XType,
7208 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
7209 DAG.getConstant(XType.getSizeInBits()-1,
7210 getShiftAmountTy()));
7212 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
7213 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
7214 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
7215 DAG.getConstant(XType.getSizeInBits()-1,
7216 getShiftAmountTy()));
7217 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
7221 // Check to see if this is an integer abs.
7222 // select_cc setg[te] X, 0, X, -X ->
7223 // select_cc setgt X, -1, X, -X ->
7224 // select_cc setl[te] X, 0, -X, X ->
7225 // select_cc setlt X, 1, -X, X ->
7226 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
7228 ConstantSDNode *SubC = NULL;
7229 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
7230 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
7231 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
7232 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
7233 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
7234 (N1C->isOne() && CC == ISD::SETLT)) &&
7235 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
7236 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
7238 EVT XType = N0.getValueType();
7239 if (SubC && SubC->isNullValue() && XType.isInteger()) {
7240 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
7242 DAG.getConstant(XType.getSizeInBits()-1,
7243 getShiftAmountTy()));
7244 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
7246 AddToWorkList(Shift.getNode());
7247 AddToWorkList(Add.getNode());
7248 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
7255 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
7256 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
7257 SDValue N1, ISD::CondCode Cond,
7258 DebugLoc DL, bool foldBooleans) {
7259 TargetLowering::DAGCombinerInfo
7260 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
7261 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
7264 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
7265 /// return a DAG expression to select that will generate the same value by
7266 /// multiplying by a magic number. See:
7267 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7268 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
7269 std::vector<SDNode*> Built;
7270 SDValue S = TLI.BuildSDIV(N, DAG, &Built);
7272 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7278 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
7279 /// return a DAG expression to select that will generate the same value by
7280 /// multiplying by a magic number. See:
7281 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7282 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
7283 std::vector<SDNode*> Built;
7284 SDValue S = TLI.BuildUDIV(N, DAG, &Built);
7286 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7292 /// FindBaseOffset - Return true if base is a frame index, which is known not
7293 // to alias with anything but itself. Provides base object and offset as
7295 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
7296 const GlobalValue *&GV, void *&CV) {
7297 // Assume it is a primitive operation.
7298 Base = Ptr; Offset = 0; GV = 0; CV = 0;
7300 // If it's an adding a simple constant then integrate the offset.
7301 if (Base.getOpcode() == ISD::ADD) {
7302 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
7303 Base = Base.getOperand(0);
7304 Offset += C->getZExtValue();
7308 // Return the underlying GlobalValue, and update the Offset. Return false
7309 // for GlobalAddressSDNode since the same GlobalAddress may be represented
7310 // by multiple nodes with different offsets.
7311 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
7312 GV = G->getGlobal();
7313 Offset += G->getOffset();
7317 // Return the underlying Constant value, and update the Offset. Return false
7318 // for ConstantSDNodes since the same constant pool entry may be represented
7319 // by multiple nodes with different offsets.
7320 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
7321 CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
7322 : (void *)C->getConstVal();
7323 Offset += C->getOffset();
7326 // If it's any of the following then it can't alias with anything but itself.
7327 return isa<FrameIndexSDNode>(Base);
7330 /// isAlias - Return true if there is any possibility that the two addresses
7332 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
7333 const Value *SrcValue1, int SrcValueOffset1,
7334 unsigned SrcValueAlign1,
7335 const MDNode *TBAAInfo1,
7336 SDValue Ptr2, int64_t Size2,
7337 const Value *SrcValue2, int SrcValueOffset2,
7338 unsigned SrcValueAlign2,
7339 const MDNode *TBAAInfo2) const {
7340 // If they are the same then they must be aliases.
7341 if (Ptr1 == Ptr2) return true;
7343 // Gather base node and offset information.
7344 SDValue Base1, Base2;
7345 int64_t Offset1, Offset2;
7346 const GlobalValue *GV1, *GV2;
7348 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
7349 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
7351 // If they have a same base address then check to see if they overlap.
7352 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
7353 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7355 // It is possible for different frame indices to alias each other, mostly
7356 // when tail call optimization reuses return address slots for arguments.
7357 // To catch this case, look up the actual index of frame indices to compute
7358 // the real alias relationship.
7359 if (isFrameIndex1 && isFrameIndex2) {
7360 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7361 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
7362 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
7363 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7366 // Otherwise, if we know what the bases are, and they aren't identical, then
7367 // we know they cannot alias.
7368 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
7371 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
7372 // compared to the size and offset of the access, we may be able to prove they
7373 // do not alias. This check is conservative for now to catch cases created by
7374 // splitting vector types.
7375 if ((SrcValueAlign1 == SrcValueAlign2) &&
7376 (SrcValueOffset1 != SrcValueOffset2) &&
7377 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
7378 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
7379 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
7381 // There is no overlap between these relatively aligned accesses of similar
7382 // size, return no alias.
7383 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
7387 if (CombinerGlobalAA) {
7388 // Use alias analysis information.
7389 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
7390 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
7391 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
7392 AliasAnalysis::AliasResult AAResult =
7393 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
7394 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
7395 if (AAResult == AliasAnalysis::NoAlias)
7399 // Otherwise we have to assume they alias.
7403 /// FindAliasInfo - Extracts the relevant alias information from the memory
7404 /// node. Returns true if the operand was a load.
7405 bool DAGCombiner::FindAliasInfo(SDNode *N,
7406 SDValue &Ptr, int64_t &Size,
7407 const Value *&SrcValue,
7408 int &SrcValueOffset,
7409 unsigned &SrcValueAlign,
7410 const MDNode *&TBAAInfo) const {
7411 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7412 Ptr = LD->getBasePtr();
7413 Size = LD->getMemoryVT().getSizeInBits() >> 3;
7414 SrcValue = LD->getSrcValue();
7415 SrcValueOffset = LD->getSrcValueOffset();
7416 SrcValueAlign = LD->getOriginalAlignment();
7417 TBAAInfo = LD->getTBAAInfo();
7419 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7420 Ptr = ST->getBasePtr();
7421 Size = ST->getMemoryVT().getSizeInBits() >> 3;
7422 SrcValue = ST->getSrcValue();
7423 SrcValueOffset = ST->getSrcValueOffset();
7424 SrcValueAlign = ST->getOriginalAlignment();
7425 TBAAInfo = ST->getTBAAInfo();
7427 llvm_unreachable("FindAliasInfo expected a memory operand");
7433 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
7434 /// looking for aliasing nodes and adding them to the Aliases vector.
7435 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
7436 SmallVector<SDValue, 8> &Aliases) {
7437 SmallVector<SDValue, 8> Chains; // List of chains to visit.
7438 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
7440 // Get alias information for node.
7443 const Value *SrcValue;
7445 unsigned SrcValueAlign;
7446 const MDNode *SrcTBAAInfo;
7447 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
7448 SrcValueAlign, SrcTBAAInfo);
7451 Chains.push_back(OriginalChain);
7454 // Look at each chain and determine if it is an alias. If so, add it to the
7455 // aliases list. If not, then continue up the chain looking for the next
7457 while (!Chains.empty()) {
7458 SDValue Chain = Chains.back();
7461 // For TokenFactor nodes, look at each operand and only continue up the
7462 // chain until we find two aliases. If we've seen two aliases, assume we'll
7463 // find more and revert to original chain since the xform is unlikely to be
7466 // FIXME: The depth check could be made to return the last non-aliasing
7467 // chain we found before we hit a tokenfactor rather than the original
7469 if (Depth > 6 || Aliases.size() == 2) {
7471 Aliases.push_back(OriginalChain);
7475 // Don't bother if we've been before.
7476 if (!Visited.insert(Chain.getNode()))
7479 switch (Chain.getOpcode()) {
7480 case ISD::EntryToken:
7481 // Entry token is ideal chain operand, but handled in FindBetterChain.
7486 // Get alias information for Chain.
7489 const Value *OpSrcValue;
7490 int OpSrcValueOffset;
7491 unsigned OpSrcValueAlign;
7492 const MDNode *OpSrcTBAAInfo;
7493 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
7494 OpSrcValue, OpSrcValueOffset,
7498 // If chain is alias then stop here.
7499 if (!(IsLoad && IsOpLoad) &&
7500 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
7502 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
7503 OpSrcValueAlign, OpSrcTBAAInfo)) {
7504 Aliases.push_back(Chain);
7506 // Look further up the chain.
7507 Chains.push_back(Chain.getOperand(0));
7513 case ISD::TokenFactor:
7514 // We have to check each of the operands of the token factor for "small"
7515 // token factors, so we queue them up. Adding the operands to the queue
7516 // (stack) in reverse order maintains the original order and increases the
7517 // likelihood that getNode will find a matching token factor (CSE.)
7518 if (Chain.getNumOperands() > 16) {
7519 Aliases.push_back(Chain);
7522 for (unsigned n = Chain.getNumOperands(); n;)
7523 Chains.push_back(Chain.getOperand(--n));
7528 // For all other instructions we will just have to take what we can get.
7529 Aliases.push_back(Chain);
7535 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
7536 /// for a better chain (aliasing node.)
7537 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
7538 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
7540 // Accumulate all the aliases to this node.
7541 GatherAllAliases(N, OldChain, Aliases);
7543 if (Aliases.size() == 0) {
7544 // If no operands then chain to entry token.
7545 return DAG.getEntryNode();
7546 } else if (Aliases.size() == 1) {
7547 // If a single operand then chain to it. We don't need to revisit it.
7551 // Construct a custom tailored token factor.
7552 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
7553 &Aliases[0], Aliases.size());
7556 // SelectionDAG::Combine - This is the entry point for the file.
7558 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
7559 CodeGenOpt::Level OptLevel) {
7560 /// run - This is the main entry point to this class.
7562 DAGCombiner(*this, AA, OptLevel).Run(Level);