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/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.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.
68 // This has the semantics that when adding to the worklist,
69 // the item added must be next to be processed. It should
70 // also only appear once. The naive approach to this takes
73 // To reduce the insert/remove time to logarithmic, we use
74 // a set and a vector to maintain our worklist.
76 // The set contains the items on the worklist, but does not
77 // maintain the order they should be visited.
79 // The vector maintains the order nodes should be visited, but may
80 // contain duplicate or removed nodes. When choosing a node to
81 // visit, we pop off the order stack until we find an item that is
82 // also in the contents set. All operations are O(log N).
83 SmallPtrSet<SDNode*, 64> WorkListContents;
84 SmallVector<SDNode*, 64> WorkListOrder;
86 // AA - Used for DAG load/store alias analysis.
89 /// AddUsersToWorkList - When an instruction is simplified, add all users of
90 /// the instruction to the work lists because they might get more simplified
93 void AddUsersToWorkList(SDNode *N) {
94 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
99 /// visit - call the node-specific routine that knows how to fold each
100 /// particular type of node.
101 SDValue visit(SDNode *N);
104 /// AddToWorkList - Add to the work list making sure its instance is at the
105 /// back (next to be processed.)
106 void AddToWorkList(SDNode *N) {
107 WorkListContents.insert(N);
108 WorkListOrder.push_back(N);
111 /// removeFromWorkList - remove all instances of N from the worklist.
113 void removeFromWorkList(SDNode *N) {
114 WorkListContents.erase(N);
117 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
120 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
121 return CombineTo(N, &Res, 1, AddTo);
124 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
126 SDValue To[] = { Res0, Res1 };
127 return CombineTo(N, To, 2, AddTo);
130 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
134 /// SimplifyDemandedBits - Check the specified integer node value to see if
135 /// it can be simplified or if things it uses can be simplified by bit
136 /// propagation. If so, return true.
137 bool SimplifyDemandedBits(SDValue Op) {
138 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
139 APInt Demanded = APInt::getAllOnesValue(BitWidth);
140 return SimplifyDemandedBits(Op, Demanded);
143 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
145 bool CombineToPreIndexedLoadStore(SDNode *N);
146 bool CombineToPostIndexedLoadStore(SDNode *N);
148 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
149 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
150 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
151 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
152 SDValue PromoteIntBinOp(SDValue Op);
153 SDValue PromoteIntShiftOp(SDValue Op);
154 SDValue PromoteExtend(SDValue Op);
155 bool PromoteLoad(SDValue Op);
157 void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
158 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
159 ISD::NodeType ExtType);
161 /// combine - call the node-specific routine that knows how to fold each
162 /// particular type of node. If that doesn't do anything, try the
163 /// target-specific DAG combines.
164 SDValue combine(SDNode *N);
166 // Visitation implementation - Implement dag node combining for different
167 // node types. The semantics are as follows:
169 // SDValue.getNode() == 0 - No change was made
170 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
171 // otherwise - N should be replaced by the returned Operand.
173 SDValue visitTokenFactor(SDNode *N);
174 SDValue visitMERGE_VALUES(SDNode *N);
175 SDValue visitADD(SDNode *N);
176 SDValue visitSUB(SDNode *N);
177 SDValue visitADDC(SDNode *N);
178 SDValue visitSUBC(SDNode *N);
179 SDValue visitADDE(SDNode *N);
180 SDValue visitSUBE(SDNode *N);
181 SDValue visitMUL(SDNode *N);
182 SDValue visitSDIV(SDNode *N);
183 SDValue visitUDIV(SDNode *N);
184 SDValue visitSREM(SDNode *N);
185 SDValue visitUREM(SDNode *N);
186 SDValue visitMULHU(SDNode *N);
187 SDValue visitMULHS(SDNode *N);
188 SDValue visitSMUL_LOHI(SDNode *N);
189 SDValue visitUMUL_LOHI(SDNode *N);
190 SDValue visitSMULO(SDNode *N);
191 SDValue visitUMULO(SDNode *N);
192 SDValue visitSDIVREM(SDNode *N);
193 SDValue visitUDIVREM(SDNode *N);
194 SDValue visitAND(SDNode *N);
195 SDValue visitOR(SDNode *N);
196 SDValue visitXOR(SDNode *N);
197 SDValue SimplifyVBinOp(SDNode *N);
198 SDValue SimplifyVUnaryOp(SDNode *N);
199 SDValue visitSHL(SDNode *N);
200 SDValue visitSRA(SDNode *N);
201 SDValue visitSRL(SDNode *N);
202 SDValue visitCTLZ(SDNode *N);
203 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
204 SDValue visitCTTZ(SDNode *N);
205 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
206 SDValue visitCTPOP(SDNode *N);
207 SDValue visitSELECT(SDNode *N);
208 SDValue visitVSELECT(SDNode *N);
209 SDValue visitSELECT_CC(SDNode *N);
210 SDValue visitSETCC(SDNode *N);
211 SDValue visitSIGN_EXTEND(SDNode *N);
212 SDValue visitZERO_EXTEND(SDNode *N);
213 SDValue visitANY_EXTEND(SDNode *N);
214 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
215 SDValue visitTRUNCATE(SDNode *N);
216 SDValue visitBITCAST(SDNode *N);
217 SDValue visitBUILD_PAIR(SDNode *N);
218 SDValue visitFADD(SDNode *N);
219 SDValue visitFSUB(SDNode *N);
220 SDValue visitFMUL(SDNode *N);
221 SDValue visitFMA(SDNode *N);
222 SDValue visitFDIV(SDNode *N);
223 SDValue visitFREM(SDNode *N);
224 SDValue visitFCOPYSIGN(SDNode *N);
225 SDValue visitSINT_TO_FP(SDNode *N);
226 SDValue visitUINT_TO_FP(SDNode *N);
227 SDValue visitFP_TO_SINT(SDNode *N);
228 SDValue visitFP_TO_UINT(SDNode *N);
229 SDValue visitFP_ROUND(SDNode *N);
230 SDValue visitFP_ROUND_INREG(SDNode *N);
231 SDValue visitFP_EXTEND(SDNode *N);
232 SDValue visitFNEG(SDNode *N);
233 SDValue visitFABS(SDNode *N);
234 SDValue visitFCEIL(SDNode *N);
235 SDValue visitFTRUNC(SDNode *N);
236 SDValue visitFFLOOR(SDNode *N);
237 SDValue visitBRCOND(SDNode *N);
238 SDValue visitBR_CC(SDNode *N);
239 SDValue visitLOAD(SDNode *N);
240 SDValue visitSTORE(SDNode *N);
241 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
242 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
243 SDValue visitBUILD_VECTOR(SDNode *N);
244 SDValue visitCONCAT_VECTORS(SDNode *N);
245 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
246 SDValue visitVECTOR_SHUFFLE(SDNode *N);
248 SDValue XformToShuffleWithZero(SDNode *N);
249 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
251 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
253 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
254 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
255 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
256 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
257 SDValue N3, ISD::CondCode CC,
258 bool NotExtCompare = false);
259 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
260 SDLoc DL, bool foldBooleans = true);
261 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
263 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
264 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
265 SDValue BuildSDIV(SDNode *N);
266 SDValue BuildUDIV(SDNode *N);
267 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
268 bool DemandHighBits = true);
269 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
270 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
271 SDValue ReduceLoadWidth(SDNode *N);
272 SDValue ReduceLoadOpStoreWidth(SDNode *N);
273 SDValue TransformFPLoadStorePair(SDNode *N);
274 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
275 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
277 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
279 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
280 /// looking for aliasing nodes and adding them to the Aliases vector.
281 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
282 SmallVector<SDValue, 8> &Aliases);
284 /// isAlias - Return true if there is any possibility that the two addresses
286 bool isAlias(SDValue Ptr1, int64_t Size1,
287 const Value *SrcValue1, int SrcValueOffset1,
288 unsigned SrcValueAlign1,
289 const MDNode *TBAAInfo1,
290 SDValue Ptr2, int64_t Size2,
291 const Value *SrcValue2, int SrcValueOffset2,
292 unsigned SrcValueAlign2,
293 const MDNode *TBAAInfo2) const;
295 /// isAlias - Return true if there is any possibility that the two addresses
297 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
299 /// FindAliasInfo - Extracts the relevant alias information from the memory
300 /// node. Returns true if the operand was a load.
301 bool FindAliasInfo(SDNode *N,
302 SDValue &Ptr, int64_t &Size,
303 const Value *&SrcValue, int &SrcValueOffset,
304 unsigned &SrcValueAlignment,
305 const MDNode *&TBAAInfo) const;
307 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
308 /// looking for a better chain (aliasing node.)
309 SDValue FindBetterChain(SDNode *N, SDValue Chain);
311 /// Merge consecutive store operations into a wide store.
312 /// This optimization uses wide integers or vectors when possible.
313 /// \return True if some memory operations were changed.
314 bool MergeConsecutiveStores(StoreSDNode *N);
317 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
318 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
319 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
321 /// Run - runs the dag combiner on all nodes in the work list
322 void Run(CombineLevel AtLevel);
324 SelectionDAG &getDAG() const { return DAG; }
326 /// getShiftAmountTy - Returns a type large enough to hold any valid
327 /// shift amount - before type legalization these can be huge.
328 EVT getShiftAmountTy(EVT LHSTy) {
329 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
330 if (LHSTy.isVector())
332 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) : TLI.getPointerTy();
335 /// isTypeLegal - This method returns true if we are running before type
336 /// legalization or if the specified VT is legal.
337 bool isTypeLegal(const EVT &VT) {
338 if (!LegalTypes) return true;
339 return TLI.isTypeLegal(VT);
342 /// getSetCCResultType - Convenience wrapper around
343 /// TargetLowering::getSetCCResultType
344 EVT getSetCCResultType(EVT VT) const {
345 return TLI.getSetCCResultType(*DAG.getContext(), VT);
352 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
353 /// nodes from the worklist.
354 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
357 explicit WorkListRemover(DAGCombiner &dc)
358 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
360 virtual void NodeDeleted(SDNode *N, SDNode *E) {
361 DC.removeFromWorkList(N);
366 //===----------------------------------------------------------------------===//
367 // TargetLowering::DAGCombinerInfo implementation
368 //===----------------------------------------------------------------------===//
370 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
371 ((DAGCombiner*)DC)->AddToWorkList(N);
374 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
375 ((DAGCombiner*)DC)->removeFromWorkList(N);
378 SDValue TargetLowering::DAGCombinerInfo::
379 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
380 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
383 SDValue TargetLowering::DAGCombinerInfo::
384 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
385 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
389 SDValue TargetLowering::DAGCombinerInfo::
390 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
391 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
394 void TargetLowering::DAGCombinerInfo::
395 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
396 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
399 //===----------------------------------------------------------------------===//
401 //===----------------------------------------------------------------------===//
403 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
404 /// specified expression for the same cost as the expression itself, or 2 if we
405 /// can compute the negated form more cheaply than the expression itself.
406 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
407 const TargetLowering &TLI,
408 const TargetOptions *Options,
409 unsigned Depth = 0) {
410 // fneg is removable even if it has multiple uses.
411 if (Op.getOpcode() == ISD::FNEG) return 2;
413 // Don't allow anything with multiple uses.
414 if (!Op.hasOneUse()) return 0;
416 // Don't recurse exponentially.
417 if (Depth > 6) return 0;
419 switch (Op.getOpcode()) {
420 default: return false;
421 case ISD::ConstantFP:
422 // Don't invert constant FP values after legalize. The negated constant
423 // isn't necessarily legal.
424 return LegalOperations ? 0 : 1;
426 // FIXME: determine better conditions for this xform.
427 if (!Options->UnsafeFPMath) return 0;
429 // After operation legalization, it might not be legal to create new FSUBs.
430 if (LegalOperations &&
431 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
434 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
435 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
438 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
439 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
442 // We can't turn -(A-B) into B-A when we honor signed zeros.
443 if (!Options->UnsafeFPMath) return 0;
445 // fold (fneg (fsub A, B)) -> (fsub B, A)
450 if (Options->HonorSignDependentRoundingFPMath()) return 0;
452 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
453 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
457 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
463 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
468 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
469 /// returns the newly negated expression.
470 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
471 bool LegalOperations, unsigned Depth = 0) {
472 // fneg is removable even if it has multiple uses.
473 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
475 // Don't allow anything with multiple uses.
476 assert(Op.hasOneUse() && "Unknown reuse!");
478 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
479 switch (Op.getOpcode()) {
480 default: llvm_unreachable("Unknown code");
481 case ISD::ConstantFP: {
482 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
484 return DAG.getConstantFP(V, Op.getValueType());
487 // FIXME: determine better conditions for this xform.
488 assert(DAG.getTarget().Options.UnsafeFPMath);
490 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
491 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
492 DAG.getTargetLoweringInfo(),
493 &DAG.getTarget().Options, Depth+1))
494 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
495 GetNegatedExpression(Op.getOperand(0), DAG,
496 LegalOperations, Depth+1),
498 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
499 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
500 GetNegatedExpression(Op.getOperand(1), DAG,
501 LegalOperations, Depth+1),
504 // We can't turn -(A-B) into B-A when we honor signed zeros.
505 assert(DAG.getTarget().Options.UnsafeFPMath);
507 // fold (fneg (fsub 0, B)) -> B
508 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
509 if (N0CFP->getValueAPF().isZero())
510 return Op.getOperand(1);
512 // fold (fneg (fsub A, B)) -> (fsub B, A)
513 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
514 Op.getOperand(1), Op.getOperand(0));
518 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
520 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
521 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
522 DAG.getTargetLoweringInfo(),
523 &DAG.getTarget().Options, Depth+1))
524 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
525 GetNegatedExpression(Op.getOperand(0), DAG,
526 LegalOperations, Depth+1),
529 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
530 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
532 GetNegatedExpression(Op.getOperand(1), DAG,
533 LegalOperations, Depth+1));
537 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
538 GetNegatedExpression(Op.getOperand(0), DAG,
539 LegalOperations, Depth+1));
541 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
542 GetNegatedExpression(Op.getOperand(0), DAG,
543 LegalOperations, Depth+1),
549 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
550 // that selects between the values 1 and 0, making it equivalent to a setcc.
551 // Also, set the incoming LHS, RHS, and CC references to the appropriate
552 // nodes based on the type of node we are checking. This simplifies life a
553 // bit for the callers.
554 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
556 if (N.getOpcode() == ISD::SETCC) {
557 LHS = N.getOperand(0);
558 RHS = N.getOperand(1);
559 CC = N.getOperand(2);
562 if (N.getOpcode() == ISD::SELECT_CC &&
563 N.getOperand(2).getOpcode() == ISD::Constant &&
564 N.getOperand(3).getOpcode() == ISD::Constant &&
565 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
566 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
567 LHS = N.getOperand(0);
568 RHS = N.getOperand(1);
569 CC = N.getOperand(4);
575 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
576 // one use. If this is true, it allows the users to invert the operation for
577 // free when it is profitable to do so.
578 static bool isOneUseSetCC(SDValue N) {
580 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
585 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
586 SDValue N0, SDValue N1) {
587 EVT VT = N0.getValueType();
588 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
589 if (isa<ConstantSDNode>(N1)) {
590 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
592 DAG.FoldConstantArithmetic(Opc, VT,
593 cast<ConstantSDNode>(N0.getOperand(1)),
594 cast<ConstantSDNode>(N1));
595 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
597 if (N0.hasOneUse()) {
598 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
599 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
600 N0.getOperand(0), N1);
601 AddToWorkList(OpNode.getNode());
602 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
606 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
607 if (isa<ConstantSDNode>(N0)) {
608 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
610 DAG.FoldConstantArithmetic(Opc, VT,
611 cast<ConstantSDNode>(N1.getOperand(1)),
612 cast<ConstantSDNode>(N0));
613 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
615 if (N1.hasOneUse()) {
616 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
617 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
618 N1.getOperand(0), N0);
619 AddToWorkList(OpNode.getNode());
620 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
627 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
629 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
631 DEBUG(dbgs() << "\nReplacing.1 ";
633 dbgs() << "\nWith: ";
634 To[0].getNode()->dump(&DAG);
635 dbgs() << " and " << NumTo-1 << " other values\n";
636 for (unsigned i = 0, e = NumTo; i != e; ++i)
637 assert((!To[i].getNode() ||
638 N->getValueType(i) == To[i].getValueType()) &&
639 "Cannot combine value to value of different type!"));
640 WorkListRemover DeadNodes(*this);
641 DAG.ReplaceAllUsesWith(N, To);
643 // Push the new nodes and any users onto the worklist
644 for (unsigned i = 0, e = NumTo; i != e; ++i) {
645 if (To[i].getNode()) {
646 AddToWorkList(To[i].getNode());
647 AddUsersToWorkList(To[i].getNode());
652 // Finally, if the node is now dead, remove it from the graph. The node
653 // may not be dead if the replacement process recursively simplified to
654 // something else needing this node.
655 if (N->use_empty()) {
656 // Nodes can be reintroduced into the worklist. Make sure we do not
657 // process a node that has been replaced.
658 removeFromWorkList(N);
660 // Finally, since the node is now dead, remove it from the graph.
663 return SDValue(N, 0);
667 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
668 // Replace all uses. If any nodes become isomorphic to other nodes and
669 // are deleted, make sure to remove them from our worklist.
670 WorkListRemover DeadNodes(*this);
671 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
673 // Push the new node and any (possibly new) users onto the worklist.
674 AddToWorkList(TLO.New.getNode());
675 AddUsersToWorkList(TLO.New.getNode());
677 // Finally, if the node is now dead, remove it from the graph. The node
678 // may not be dead if the replacement process recursively simplified to
679 // something else needing this node.
680 if (TLO.Old.getNode()->use_empty()) {
681 removeFromWorkList(TLO.Old.getNode());
683 // If the operands of this node are only used by the node, they will now
684 // be dead. Make sure to visit them first to delete dead nodes early.
685 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
686 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
687 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
689 DAG.DeleteNode(TLO.Old.getNode());
693 /// SimplifyDemandedBits - Check the specified integer node value to see if
694 /// it can be simplified or if things it uses can be simplified by bit
695 /// propagation. If so, return true.
696 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
697 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
698 APInt KnownZero, KnownOne;
699 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
703 AddToWorkList(Op.getNode());
705 // Replace the old value with the new one.
707 DEBUG(dbgs() << "\nReplacing.2 ";
708 TLO.Old.getNode()->dump(&DAG);
709 dbgs() << "\nWith: ";
710 TLO.New.getNode()->dump(&DAG);
713 CommitTargetLoweringOpt(TLO);
717 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
719 EVT VT = Load->getValueType(0);
720 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
722 DEBUG(dbgs() << "\nReplacing.9 ";
724 dbgs() << "\nWith: ";
725 Trunc.getNode()->dump(&DAG);
727 WorkListRemover DeadNodes(*this);
728 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
729 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
730 removeFromWorkList(Load);
731 DAG.DeleteNode(Load);
732 AddToWorkList(Trunc.getNode());
735 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
738 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
739 EVT MemVT = LD->getMemoryVT();
740 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
741 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
743 : LD->getExtensionType();
745 return DAG.getExtLoad(ExtType, dl, PVT,
746 LD->getChain(), LD->getBasePtr(),
747 LD->getPointerInfo(),
748 MemVT, LD->isVolatile(),
749 LD->isNonTemporal(), LD->getAlignment());
752 unsigned Opc = Op.getOpcode();
755 case ISD::AssertSext:
756 return DAG.getNode(ISD::AssertSext, dl, PVT,
757 SExtPromoteOperand(Op.getOperand(0), PVT),
759 case ISD::AssertZext:
760 return DAG.getNode(ISD::AssertZext, dl, PVT,
761 ZExtPromoteOperand(Op.getOperand(0), PVT),
763 case ISD::Constant: {
765 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
766 return DAG.getNode(ExtOpc, dl, PVT, Op);
770 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
772 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
775 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
776 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
778 EVT OldVT = Op.getValueType();
780 bool Replace = false;
781 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
782 if (NewOp.getNode() == 0)
784 AddToWorkList(NewOp.getNode());
787 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
788 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
789 DAG.getValueType(OldVT));
792 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
793 EVT OldVT = Op.getValueType();
795 bool Replace = false;
796 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
797 if (NewOp.getNode() == 0)
799 AddToWorkList(NewOp.getNode());
802 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
803 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
806 /// PromoteIntBinOp - Promote the specified integer binary operation if the
807 /// target indicates it is beneficial. e.g. On x86, it's usually better to
808 /// promote i16 operations to i32 since i16 instructions are longer.
809 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
810 if (!LegalOperations)
813 EVT VT = Op.getValueType();
814 if (VT.isVector() || !VT.isInteger())
817 // If operation type is 'undesirable', e.g. i16 on x86, consider
819 unsigned Opc = Op.getOpcode();
820 if (TLI.isTypeDesirableForOp(Opc, VT))
824 // Consult target whether it is a good idea to promote this operation and
825 // what's the right type to promote it to.
826 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
827 assert(PVT != VT && "Don't know what type to promote to!");
829 bool Replace0 = false;
830 SDValue N0 = Op.getOperand(0);
831 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
832 if (NN0.getNode() == 0)
835 bool Replace1 = false;
836 SDValue N1 = Op.getOperand(1);
841 NN1 = PromoteOperand(N1, PVT, Replace1);
842 if (NN1.getNode() == 0)
846 AddToWorkList(NN0.getNode());
848 AddToWorkList(NN1.getNode());
851 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
853 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
855 DEBUG(dbgs() << "\nPromoting ";
856 Op.getNode()->dump(&DAG));
858 return DAG.getNode(ISD::TRUNCATE, dl, VT,
859 DAG.getNode(Opc, dl, PVT, NN0, NN1));
864 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
865 /// target indicates it is beneficial. e.g. On x86, it's usually better to
866 /// promote i16 operations to i32 since i16 instructions are longer.
867 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
868 if (!LegalOperations)
871 EVT VT = Op.getValueType();
872 if (VT.isVector() || !VT.isInteger())
875 // If operation type is 'undesirable', e.g. i16 on x86, consider
877 unsigned Opc = Op.getOpcode();
878 if (TLI.isTypeDesirableForOp(Opc, VT))
882 // Consult target whether it is a good idea to promote this operation and
883 // what's the right type to promote it to.
884 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
885 assert(PVT != VT && "Don't know what type to promote to!");
887 bool Replace = false;
888 SDValue N0 = Op.getOperand(0);
890 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
891 else if (Opc == ISD::SRL)
892 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
894 N0 = PromoteOperand(N0, PVT, Replace);
895 if (N0.getNode() == 0)
898 AddToWorkList(N0.getNode());
900 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
902 DEBUG(dbgs() << "\nPromoting ";
903 Op.getNode()->dump(&DAG));
905 return DAG.getNode(ISD::TRUNCATE, dl, VT,
906 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
911 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
912 if (!LegalOperations)
915 EVT VT = Op.getValueType();
916 if (VT.isVector() || !VT.isInteger())
919 // If operation type is 'undesirable', e.g. i16 on x86, consider
921 unsigned Opc = Op.getOpcode();
922 if (TLI.isTypeDesirableForOp(Opc, VT))
926 // Consult target whether it is a good idea to promote this operation and
927 // what's the right type to promote it to.
928 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
929 assert(PVT != VT && "Don't know what type to promote to!");
930 // fold (aext (aext x)) -> (aext x)
931 // fold (aext (zext x)) -> (zext x)
932 // fold (aext (sext x)) -> (sext x)
933 DEBUG(dbgs() << "\nPromoting ";
934 Op.getNode()->dump(&DAG));
935 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
940 bool DAGCombiner::PromoteLoad(SDValue Op) {
941 if (!LegalOperations)
944 EVT VT = Op.getValueType();
945 if (VT.isVector() || !VT.isInteger())
948 // If operation type is 'undesirable', e.g. i16 on x86, consider
950 unsigned Opc = Op.getOpcode();
951 if (TLI.isTypeDesirableForOp(Opc, VT))
955 // Consult target whether it is a good idea to promote this operation and
956 // what's the right type to promote it to.
957 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
958 assert(PVT != VT && "Don't know what type to promote to!");
961 SDNode *N = Op.getNode();
962 LoadSDNode *LD = cast<LoadSDNode>(N);
963 EVT MemVT = LD->getMemoryVT();
964 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
965 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
967 : LD->getExtensionType();
968 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
969 LD->getChain(), LD->getBasePtr(),
970 LD->getPointerInfo(),
971 MemVT, LD->isVolatile(),
972 LD->isNonTemporal(), LD->getAlignment());
973 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
975 DEBUG(dbgs() << "\nPromoting ";
978 Result.getNode()->dump(&DAG);
980 WorkListRemover DeadNodes(*this);
981 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
982 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
983 removeFromWorkList(N);
985 AddToWorkList(Result.getNode());
992 //===----------------------------------------------------------------------===//
993 // Main DAG Combiner implementation
994 //===----------------------------------------------------------------------===//
996 void DAGCombiner::Run(CombineLevel AtLevel) {
997 // set the instance variables, so that the various visit routines may use it.
999 LegalOperations = Level >= AfterLegalizeVectorOps;
1000 LegalTypes = Level >= AfterLegalizeTypes;
1002 // Add all the dag nodes to the worklist.
1003 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1004 E = DAG.allnodes_end(); I != E; ++I)
1007 // Create a dummy node (which is not added to allnodes), that adds a reference
1008 // to the root node, preventing it from being deleted, and tracking any
1009 // changes of the root.
1010 HandleSDNode Dummy(DAG.getRoot());
1012 // The root of the dag may dangle to deleted nodes until the dag combiner is
1013 // done. Set it to null to avoid confusion.
1014 DAG.setRoot(SDValue());
1016 // while the worklist isn't empty, find a node and
1017 // try and combine it.
1018 while (!WorkListContents.empty()) {
1020 // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1021 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1022 // worklist *should* contain, and check the node we want to visit is should
1023 // actually be visited.
1025 N = WorkListOrder.pop_back_val();
1026 } while (!WorkListContents.erase(N));
1028 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1029 // N is deleted from the DAG, since they too may now be dead or may have a
1030 // reduced number of uses, allowing other xforms.
1031 if (N->use_empty() && N != &Dummy) {
1032 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1033 AddToWorkList(N->getOperand(i).getNode());
1039 SDValue RV = combine(N);
1041 if (RV.getNode() == 0)
1046 // If we get back the same node we passed in, rather than a new node or
1047 // zero, we know that the node must have defined multiple values and
1048 // CombineTo was used. Since CombineTo takes care of the worklist
1049 // mechanics for us, we have no work to do in this case.
1050 if (RV.getNode() == N)
1053 assert(N->getOpcode() != ISD::DELETED_NODE &&
1054 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1055 "Node was deleted but visit returned new node!");
1057 DEBUG(dbgs() << "\nReplacing.3 ";
1059 dbgs() << "\nWith: ";
1060 RV.getNode()->dump(&DAG);
1063 // Transfer debug value.
1064 DAG.TransferDbgValues(SDValue(N, 0), RV);
1065 WorkListRemover DeadNodes(*this);
1066 if (N->getNumValues() == RV.getNode()->getNumValues())
1067 DAG.ReplaceAllUsesWith(N, RV.getNode());
1069 assert(N->getValueType(0) == RV.getValueType() &&
1070 N->getNumValues() == 1 && "Type mismatch");
1072 DAG.ReplaceAllUsesWith(N, &OpV);
1075 // Push the new node and any users onto the worklist
1076 AddToWorkList(RV.getNode());
1077 AddUsersToWorkList(RV.getNode());
1079 // Add any uses of the old node to the worklist in case this node is the
1080 // last one that uses them. They may become dead after this node is
1082 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1083 AddToWorkList(N->getOperand(i).getNode());
1085 // Finally, if the node is now dead, remove it from the graph. The node
1086 // may not be dead if the replacement process recursively simplified to
1087 // something else needing this node.
1088 if (N->use_empty()) {
1089 // Nodes can be reintroduced into the worklist. Make sure we do not
1090 // process a node that has been replaced.
1091 removeFromWorkList(N);
1093 // Finally, since the node is now dead, remove it from the graph.
1098 // If the root changed (e.g. it was a dead load, update the root).
1099 DAG.setRoot(Dummy.getValue());
1100 DAG.RemoveDeadNodes();
1103 SDValue DAGCombiner::visit(SDNode *N) {
1104 switch (N->getOpcode()) {
1106 case ISD::TokenFactor: return visitTokenFactor(N);
1107 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1108 case ISD::ADD: return visitADD(N);
1109 case ISD::SUB: return visitSUB(N);
1110 case ISD::ADDC: return visitADDC(N);
1111 case ISD::SUBC: return visitSUBC(N);
1112 case ISD::ADDE: return visitADDE(N);
1113 case ISD::SUBE: return visitSUBE(N);
1114 case ISD::MUL: return visitMUL(N);
1115 case ISD::SDIV: return visitSDIV(N);
1116 case ISD::UDIV: return visitUDIV(N);
1117 case ISD::SREM: return visitSREM(N);
1118 case ISD::UREM: return visitUREM(N);
1119 case ISD::MULHU: return visitMULHU(N);
1120 case ISD::MULHS: return visitMULHS(N);
1121 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1122 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1123 case ISD::SMULO: return visitSMULO(N);
1124 case ISD::UMULO: return visitUMULO(N);
1125 case ISD::SDIVREM: return visitSDIVREM(N);
1126 case ISD::UDIVREM: return visitUDIVREM(N);
1127 case ISD::AND: return visitAND(N);
1128 case ISD::OR: return visitOR(N);
1129 case ISD::XOR: return visitXOR(N);
1130 case ISD::SHL: return visitSHL(N);
1131 case ISD::SRA: return visitSRA(N);
1132 case ISD::SRL: return visitSRL(N);
1133 case ISD::CTLZ: return visitCTLZ(N);
1134 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1135 case ISD::CTTZ: return visitCTTZ(N);
1136 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1137 case ISD::CTPOP: return visitCTPOP(N);
1138 case ISD::SELECT: return visitSELECT(N);
1139 case ISD::VSELECT: return visitVSELECT(N);
1140 case ISD::SELECT_CC: return visitSELECT_CC(N);
1141 case ISD::SETCC: return visitSETCC(N);
1142 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1143 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1144 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1145 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1146 case ISD::TRUNCATE: return visitTRUNCATE(N);
1147 case ISD::BITCAST: return visitBITCAST(N);
1148 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1149 case ISD::FADD: return visitFADD(N);
1150 case ISD::FSUB: return visitFSUB(N);
1151 case ISD::FMUL: return visitFMUL(N);
1152 case ISD::FMA: return visitFMA(N);
1153 case ISD::FDIV: return visitFDIV(N);
1154 case ISD::FREM: return visitFREM(N);
1155 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1156 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1157 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1158 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1159 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1160 case ISD::FP_ROUND: return visitFP_ROUND(N);
1161 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1162 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1163 case ISD::FNEG: return visitFNEG(N);
1164 case ISD::FABS: return visitFABS(N);
1165 case ISD::FFLOOR: return visitFFLOOR(N);
1166 case ISD::FCEIL: return visitFCEIL(N);
1167 case ISD::FTRUNC: return visitFTRUNC(N);
1168 case ISD::BRCOND: return visitBRCOND(N);
1169 case ISD::BR_CC: return visitBR_CC(N);
1170 case ISD::LOAD: return visitLOAD(N);
1171 case ISD::STORE: return visitSTORE(N);
1172 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1173 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1174 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1175 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1176 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1177 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1182 SDValue DAGCombiner::combine(SDNode *N) {
1183 SDValue RV = visit(N);
1185 // If nothing happened, try a target-specific DAG combine.
1186 if (RV.getNode() == 0) {
1187 assert(N->getOpcode() != ISD::DELETED_NODE &&
1188 "Node was deleted but visit returned NULL!");
1190 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1191 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1193 // Expose the DAG combiner to the target combiner impls.
1194 TargetLowering::DAGCombinerInfo
1195 DagCombineInfo(DAG, Level, false, this);
1197 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1201 // If nothing happened still, try promoting the operation.
1202 if (RV.getNode() == 0) {
1203 switch (N->getOpcode()) {
1211 RV = PromoteIntBinOp(SDValue(N, 0));
1216 RV = PromoteIntShiftOp(SDValue(N, 0));
1218 case ISD::SIGN_EXTEND:
1219 case ISD::ZERO_EXTEND:
1220 case ISD::ANY_EXTEND:
1221 RV = PromoteExtend(SDValue(N, 0));
1224 if (PromoteLoad(SDValue(N, 0)))
1230 // If N is a commutative binary node, try commuting it to enable more
1232 if (RV.getNode() == 0 &&
1233 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1234 N->getNumValues() == 1) {
1235 SDValue N0 = N->getOperand(0);
1236 SDValue N1 = N->getOperand(1);
1238 // Constant operands are canonicalized to RHS.
1239 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1240 SDValue Ops[] = { N1, N0 };
1241 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1244 return SDValue(CSENode, 0);
1251 /// getInputChainForNode - Given a node, return its input chain if it has one,
1252 /// otherwise return a null sd operand.
1253 static SDValue getInputChainForNode(SDNode *N) {
1254 if (unsigned NumOps = N->getNumOperands()) {
1255 if (N->getOperand(0).getValueType() == MVT::Other)
1256 return N->getOperand(0);
1257 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1258 return N->getOperand(NumOps-1);
1259 for (unsigned i = 1; i < NumOps-1; ++i)
1260 if (N->getOperand(i).getValueType() == MVT::Other)
1261 return N->getOperand(i);
1266 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1267 // If N has two operands, where one has an input chain equal to the other,
1268 // the 'other' chain is redundant.
1269 if (N->getNumOperands() == 2) {
1270 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1271 return N->getOperand(0);
1272 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1273 return N->getOperand(1);
1276 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1277 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1278 SmallPtrSet<SDNode*, 16> SeenOps;
1279 bool Changed = false; // If we should replace this token factor.
1281 // Start out with this token factor.
1284 // Iterate through token factors. The TFs grows when new token factors are
1286 for (unsigned i = 0; i < TFs.size(); ++i) {
1287 SDNode *TF = TFs[i];
1289 // Check each of the operands.
1290 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1291 SDValue Op = TF->getOperand(i);
1293 switch (Op.getOpcode()) {
1294 case ISD::EntryToken:
1295 // Entry tokens don't need to be added to the list. They are
1300 case ISD::TokenFactor:
1301 if (Op.hasOneUse() &&
1302 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1303 // Queue up for processing.
1304 TFs.push_back(Op.getNode());
1305 // Clean up in case the token factor is removed.
1306 AddToWorkList(Op.getNode());
1313 // Only add if it isn't already in the list.
1314 if (SeenOps.insert(Op.getNode()))
1325 // If we've change things around then replace token factor.
1328 // The entry token is the only possible outcome.
1329 Result = DAG.getEntryNode();
1331 // New and improved token factor.
1332 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1333 MVT::Other, &Ops[0], Ops.size());
1336 // Don't add users to work list.
1337 return CombineTo(N, Result, false);
1343 /// MERGE_VALUES can always be eliminated.
1344 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1345 WorkListRemover DeadNodes(*this);
1346 // Replacing results may cause a different MERGE_VALUES to suddenly
1347 // be CSE'd with N, and carry its uses with it. Iterate until no
1348 // uses remain, to ensure that the node can be safely deleted.
1349 // First add the users of this node to the work list so that they
1350 // can be tried again once they have new operands.
1351 AddUsersToWorkList(N);
1353 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1354 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1355 } while (!N->use_empty());
1356 removeFromWorkList(N);
1358 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1362 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1363 SelectionDAG &DAG) {
1364 EVT VT = N0.getValueType();
1365 SDValue N00 = N0.getOperand(0);
1366 SDValue N01 = N0.getOperand(1);
1367 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1369 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1370 isa<ConstantSDNode>(N00.getOperand(1))) {
1371 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1372 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1373 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1374 N00.getOperand(0), N01),
1375 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1376 N00.getOperand(1), N01));
1377 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1383 SDValue DAGCombiner::visitADD(SDNode *N) {
1384 SDValue N0 = N->getOperand(0);
1385 SDValue N1 = N->getOperand(1);
1386 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1387 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1388 EVT VT = N0.getValueType();
1391 if (VT.isVector()) {
1392 SDValue FoldedVOp = SimplifyVBinOp(N);
1393 if (FoldedVOp.getNode()) return FoldedVOp;
1395 // fold (add x, 0) -> x, vector edition
1396 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1398 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1402 // fold (add x, undef) -> undef
1403 if (N0.getOpcode() == ISD::UNDEF)
1405 if (N1.getOpcode() == ISD::UNDEF)
1407 // fold (add c1, c2) -> c1+c2
1409 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1410 // canonicalize constant to RHS
1412 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1413 // fold (add x, 0) -> x
1414 if (N1C && N1C->isNullValue())
1416 // fold (add Sym, c) -> Sym+c
1417 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1418 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1419 GA->getOpcode() == ISD::GlobalAddress)
1420 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1422 (uint64_t)N1C->getSExtValue());
1423 // fold ((c1-A)+c2) -> (c1+c2)-A
1424 if (N1C && N0.getOpcode() == ISD::SUB)
1425 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1426 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1427 DAG.getConstant(N1C->getAPIntValue()+
1428 N0C->getAPIntValue(), VT),
1431 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1432 if (RADD.getNode() != 0)
1434 // fold ((0-A) + B) -> B-A
1435 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1436 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1437 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1438 // fold (A + (0-B)) -> A-B
1439 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1440 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1441 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1442 // fold (A+(B-A)) -> B
1443 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1444 return N1.getOperand(0);
1445 // fold ((B-A)+A) -> B
1446 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1447 return N0.getOperand(0);
1448 // fold (A+(B-(A+C))) to (B-C)
1449 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1450 N0 == N1.getOperand(1).getOperand(0))
1451 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1452 N1.getOperand(1).getOperand(1));
1453 // fold (A+(B-(C+A))) to (B-C)
1454 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1455 N0 == N1.getOperand(1).getOperand(1))
1456 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1457 N1.getOperand(1).getOperand(0));
1458 // fold (A+((B-A)+or-C)) to (B+or-C)
1459 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1460 N1.getOperand(0).getOpcode() == ISD::SUB &&
1461 N0 == N1.getOperand(0).getOperand(1))
1462 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1463 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1465 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1466 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1467 SDValue N00 = N0.getOperand(0);
1468 SDValue N01 = N0.getOperand(1);
1469 SDValue N10 = N1.getOperand(0);
1470 SDValue N11 = N1.getOperand(1);
1472 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1473 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1474 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1475 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1478 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1479 return SDValue(N, 0);
1481 // fold (a+b) -> (a|b) iff a and b share no bits.
1482 if (VT.isInteger() && !VT.isVector()) {
1483 APInt LHSZero, LHSOne;
1484 APInt RHSZero, RHSOne;
1485 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1487 if (LHSZero.getBoolValue()) {
1488 DAG.ComputeMaskedBits(N1, 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) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1493 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1497 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1498 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1499 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1500 if (Result.getNode()) return Result;
1502 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1503 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1504 if (Result.getNode()) return Result;
1507 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1508 if (N1.getOpcode() == ISD::SHL &&
1509 N1.getOperand(0).getOpcode() == ISD::SUB)
1510 if (ConstantSDNode *C =
1511 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1512 if (C->getAPIntValue() == 0)
1513 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1514 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1515 N1.getOperand(0).getOperand(1),
1517 if (N0.getOpcode() == ISD::SHL &&
1518 N0.getOperand(0).getOpcode() == ISD::SUB)
1519 if (ConstantSDNode *C =
1520 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1521 if (C->getAPIntValue() == 0)
1522 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1523 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1524 N0.getOperand(0).getOperand(1),
1527 if (N1.getOpcode() == ISD::AND) {
1528 SDValue AndOp0 = N1.getOperand(0);
1529 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1530 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1531 unsigned DestBits = VT.getScalarType().getSizeInBits();
1533 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1534 // and similar xforms where the inner op is either ~0 or 0.
1535 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1537 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1541 // add (sext i1), X -> sub X, (zext i1)
1542 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1543 N0.getOperand(0).getValueType() == MVT::i1 &&
1544 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1546 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1547 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1553 SDValue DAGCombiner::visitADDC(SDNode *N) {
1554 SDValue N0 = N->getOperand(0);
1555 SDValue N1 = N->getOperand(1);
1556 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1557 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1558 EVT VT = N0.getValueType();
1560 // If the flag result is dead, turn this into an ADD.
1561 if (!N->hasAnyUseOfValue(1))
1562 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1563 DAG.getNode(ISD::CARRY_FALSE,
1564 SDLoc(N), MVT::Glue));
1566 // canonicalize constant to RHS.
1568 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1570 // fold (addc x, 0) -> x + no carry out
1571 if (N1C && N1C->isNullValue())
1572 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1573 SDLoc(N), MVT::Glue));
1575 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1576 APInt LHSZero, LHSOne;
1577 APInt RHSZero, RHSOne;
1578 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1580 if (LHSZero.getBoolValue()) {
1581 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1583 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1584 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1585 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1586 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1587 DAG.getNode(ISD::CARRY_FALSE,
1588 SDLoc(N), MVT::Glue));
1594 SDValue DAGCombiner::visitADDE(SDNode *N) {
1595 SDValue N0 = N->getOperand(0);
1596 SDValue N1 = N->getOperand(1);
1597 SDValue CarryIn = N->getOperand(2);
1598 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1599 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1601 // canonicalize constant to RHS
1603 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1606 // fold (adde x, y, false) -> (addc x, y)
1607 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1608 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1613 // Since it may not be valid to emit a fold to zero for vector initializers
1614 // check if we can before folding.
1615 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1616 SelectionDAG &DAG, bool LegalOperations) {
1618 return DAG.getConstant(0, VT);
1619 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1620 // Produce a vector of zeros.
1621 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
1622 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1623 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1624 &Ops[0], Ops.size());
1629 SDValue DAGCombiner::visitSUB(SDNode *N) {
1630 SDValue N0 = N->getOperand(0);
1631 SDValue N1 = N->getOperand(1);
1632 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1633 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1634 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1635 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1636 EVT VT = N0.getValueType();
1639 if (VT.isVector()) {
1640 SDValue FoldedVOp = SimplifyVBinOp(N);
1641 if (FoldedVOp.getNode()) return FoldedVOp;
1643 // fold (sub x, 0) -> x, vector edition
1644 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1648 // fold (sub x, x) -> 0
1649 // FIXME: Refactor this and xor and other similar operations together.
1651 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations);
1652 // fold (sub c1, c2) -> c1-c2
1654 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1655 // fold (sub x, c) -> (add x, -c)
1657 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1658 DAG.getConstant(-N1C->getAPIntValue(), VT));
1659 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1660 if (N0C && N0C->isAllOnesValue())
1661 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1662 // fold A-(A-B) -> B
1663 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1664 return N1.getOperand(1);
1665 // fold (A+B)-A -> B
1666 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1667 return N0.getOperand(1);
1668 // fold (A+B)-B -> A
1669 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1670 return N0.getOperand(0);
1671 // fold C2-(A+C1) -> (C2-C1)-A
1672 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1673 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1675 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1678 // fold ((A+(B+or-C))-B) -> A+or-C
1679 if (N0.getOpcode() == ISD::ADD &&
1680 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1681 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1682 N0.getOperand(1).getOperand(0) == N1)
1683 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1684 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1685 // fold ((A+(C+B))-B) -> A+C
1686 if (N0.getOpcode() == ISD::ADD &&
1687 N0.getOperand(1).getOpcode() == ISD::ADD &&
1688 N0.getOperand(1).getOperand(1) == N1)
1689 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1690 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1691 // fold ((A-(B-C))-C) -> A-B
1692 if (N0.getOpcode() == ISD::SUB &&
1693 N0.getOperand(1).getOpcode() == ISD::SUB &&
1694 N0.getOperand(1).getOperand(1) == N1)
1695 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1696 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1698 // If either operand of a sub is undef, the result is undef
1699 if (N0.getOpcode() == ISD::UNDEF)
1701 if (N1.getOpcode() == ISD::UNDEF)
1704 // If the relocation model supports it, consider symbol offsets.
1705 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1706 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1707 // fold (sub Sym, c) -> Sym-c
1708 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1709 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1711 (uint64_t)N1C->getSExtValue());
1712 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1713 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1714 if (GA->getGlobal() == GB->getGlobal())
1715 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1722 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1723 SDValue N0 = N->getOperand(0);
1724 SDValue N1 = N->getOperand(1);
1725 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1726 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1727 EVT VT = N0.getValueType();
1729 // If the flag result is dead, turn this into an SUB.
1730 if (!N->hasAnyUseOfValue(1))
1731 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1732 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1735 // fold (subc x, x) -> 0 + no borrow
1737 return CombineTo(N, DAG.getConstant(0, VT),
1738 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1741 // fold (subc x, 0) -> x + no borrow
1742 if (N1C && N1C->isNullValue())
1743 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1746 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1747 if (N0C && N0C->isAllOnesValue())
1748 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1749 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1755 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1756 SDValue N0 = N->getOperand(0);
1757 SDValue N1 = N->getOperand(1);
1758 SDValue CarryIn = N->getOperand(2);
1760 // fold (sube x, y, false) -> (subc x, y)
1761 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1762 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1767 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
1768 /// all the same constant or undefined.
1769 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1770 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1775 unsigned SplatBitSize;
1777 EVT EltVT = N->getValueType(0).getVectorElementType();
1778 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1780 EltVT.getSizeInBits() >= SplatBitSize);
1783 SDValue DAGCombiner::visitMUL(SDNode *N) {
1784 SDValue N0 = N->getOperand(0);
1785 SDValue N1 = N->getOperand(1);
1786 EVT VT = N0.getValueType();
1788 // fold (mul x, undef) -> 0
1789 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1790 return DAG.getConstant(0, VT);
1792 bool N0IsConst = false;
1793 bool N1IsConst = false;
1794 APInt ConstValue0, ConstValue1;
1796 if (VT.isVector()) {
1797 SDValue FoldedVOp = SimplifyVBinOp(N);
1798 if (FoldedVOp.getNode()) return FoldedVOp;
1800 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1801 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1803 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1804 ConstValue0 = N0IsConst? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() : APInt();
1805 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1806 ConstValue1 = N1IsConst? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() : APInt();
1809 // fold (mul c1, c2) -> c1*c2
1810 if (N0IsConst && N1IsConst)
1811 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1813 // canonicalize constant to RHS
1814 if (N0IsConst && !N1IsConst)
1815 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1816 // fold (mul x, 0) -> 0
1817 if (N1IsConst && ConstValue1 == 0)
1819 // fold (mul x, 1) -> x
1820 if (N1IsConst && ConstValue1 == 1)
1822 // fold (mul x, -1) -> 0-x
1823 if (N1IsConst && ConstValue1.isAllOnesValue())
1824 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1825 DAG.getConstant(0, VT), N0);
1826 // fold (mul x, (1 << c)) -> x << c
1827 if (N1IsConst && ConstValue1.isPowerOf2())
1828 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1829 DAG.getConstant(ConstValue1.logBase2(),
1830 getShiftAmountTy(N0.getValueType())));
1831 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1832 if (N1IsConst && (-ConstValue1).isPowerOf2()) {
1833 unsigned Log2Val = (-ConstValue1).logBase2();
1834 // FIXME: If the input is something that is easily negated (e.g. a
1835 // single-use add), we should put the negate there.
1836 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1837 DAG.getConstant(0, VT),
1838 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1839 DAG.getConstant(Log2Val,
1840 getShiftAmountTy(N0.getValueType()))));
1844 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1845 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1846 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1847 isa<ConstantSDNode>(N0.getOperand(1)))) {
1848 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1849 N1, N0.getOperand(1));
1850 AddToWorkList(C3.getNode());
1851 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1852 N0.getOperand(0), C3);
1855 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1858 SDValue Sh(0,0), Y(0,0);
1859 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1860 if (N0.getOpcode() == ISD::SHL &&
1861 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1862 isa<ConstantSDNode>(N0.getOperand(1))) &&
1863 N0.getNode()->hasOneUse()) {
1865 } else if (N1.getOpcode() == ISD::SHL &&
1866 isa<ConstantSDNode>(N1.getOperand(1)) &&
1867 N1.getNode()->hasOneUse()) {
1872 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1873 Sh.getOperand(0), Y);
1874 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1875 Mul, Sh.getOperand(1));
1879 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1880 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1881 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1882 isa<ConstantSDNode>(N0.getOperand(1))))
1883 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1884 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1885 N0.getOperand(0), N1),
1886 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1887 N0.getOperand(1), N1));
1890 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1891 if (RMUL.getNode() != 0)
1897 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1898 SDValue N0 = N->getOperand(0);
1899 SDValue N1 = N->getOperand(1);
1900 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1901 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1902 EVT VT = N->getValueType(0);
1905 if (VT.isVector()) {
1906 SDValue FoldedVOp = SimplifyVBinOp(N);
1907 if (FoldedVOp.getNode()) return FoldedVOp;
1910 // fold (sdiv c1, c2) -> c1/c2
1911 if (N0C && N1C && !N1C->isNullValue())
1912 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1913 // fold (sdiv X, 1) -> X
1914 if (N1C && N1C->getAPIntValue() == 1LL)
1916 // fold (sdiv X, -1) -> 0-X
1917 if (N1C && N1C->isAllOnesValue())
1918 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1919 DAG.getConstant(0, VT), N0);
1920 // If we know the sign bits of both operands are zero, strength reduce to a
1921 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1922 if (!VT.isVector()) {
1923 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1924 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1927 // fold (sdiv X, pow2) -> simple ops after legalize
1928 if (N1C && !N1C->isNullValue() &&
1929 (N1C->getAPIntValue().isPowerOf2() ||
1930 (-N1C->getAPIntValue()).isPowerOf2())) {
1931 // If dividing by powers of two is cheap, then don't perform the following
1933 if (TLI.isPow2DivCheap())
1936 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1938 // Splat the sign bit into the register
1939 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1940 DAG.getConstant(VT.getSizeInBits()-1,
1941 getShiftAmountTy(N0.getValueType())));
1942 AddToWorkList(SGN.getNode());
1944 // Add (N0 < 0) ? abs2 - 1 : 0;
1945 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1946 DAG.getConstant(VT.getSizeInBits() - lg2,
1947 getShiftAmountTy(SGN.getValueType())));
1948 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1949 AddToWorkList(SRL.getNode());
1950 AddToWorkList(ADD.getNode()); // Divide by pow2
1951 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1952 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1954 // If we're dividing by a positive value, we're done. Otherwise, we must
1955 // negate the result.
1956 if (N1C->getAPIntValue().isNonNegative())
1959 AddToWorkList(SRA.getNode());
1960 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1961 DAG.getConstant(0, VT), SRA);
1964 // if integer divide is expensive and we satisfy the requirements, emit an
1965 // alternate sequence.
1966 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1967 SDValue Op = BuildSDIV(N);
1968 if (Op.getNode()) return Op;
1972 if (N0.getOpcode() == ISD::UNDEF)
1973 return DAG.getConstant(0, VT);
1974 // X / undef -> undef
1975 if (N1.getOpcode() == ISD::UNDEF)
1981 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1982 SDValue N0 = N->getOperand(0);
1983 SDValue N1 = N->getOperand(1);
1984 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1985 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1986 EVT VT = N->getValueType(0);
1989 if (VT.isVector()) {
1990 SDValue FoldedVOp = SimplifyVBinOp(N);
1991 if (FoldedVOp.getNode()) return FoldedVOp;
1994 // fold (udiv c1, c2) -> c1/c2
1995 if (N0C && N1C && !N1C->isNullValue())
1996 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1997 // fold (udiv x, (1 << c)) -> x >>u c
1998 if (N1C && N1C->getAPIntValue().isPowerOf2())
1999 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2000 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2001 getShiftAmountTy(N0.getValueType())));
2002 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2003 if (N1.getOpcode() == ISD::SHL) {
2004 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2005 if (SHC->getAPIntValue().isPowerOf2()) {
2006 EVT ADDVT = N1.getOperand(1).getValueType();
2007 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2009 DAG.getConstant(SHC->getAPIntValue()
2012 AddToWorkList(Add.getNode());
2013 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2017 // fold (udiv x, c) -> alternate
2018 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2019 SDValue Op = BuildUDIV(N);
2020 if (Op.getNode()) return Op;
2024 if (N0.getOpcode() == ISD::UNDEF)
2025 return DAG.getConstant(0, VT);
2026 // X / undef -> undef
2027 if (N1.getOpcode() == ISD::UNDEF)
2033 SDValue DAGCombiner::visitSREM(SDNode *N) {
2034 SDValue N0 = N->getOperand(0);
2035 SDValue N1 = N->getOperand(1);
2036 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2037 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2038 EVT VT = N->getValueType(0);
2040 // fold (srem c1, c2) -> c1%c2
2041 if (N0C && N1C && !N1C->isNullValue())
2042 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2043 // If we know the sign bits of both operands are zero, strength reduce to a
2044 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2045 if (!VT.isVector()) {
2046 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2047 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2050 // If X/C can be simplified by the division-by-constant logic, lower
2051 // X%C to the equivalent of X-X/C*C.
2052 if (N1C && !N1C->isNullValue()) {
2053 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2054 AddToWorkList(Div.getNode());
2055 SDValue OptimizedDiv = combine(Div.getNode());
2056 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2057 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2059 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2060 AddToWorkList(Mul.getNode());
2066 if (N0.getOpcode() == ISD::UNDEF)
2067 return DAG.getConstant(0, VT);
2068 // X % undef -> undef
2069 if (N1.getOpcode() == ISD::UNDEF)
2075 SDValue DAGCombiner::visitUREM(SDNode *N) {
2076 SDValue N0 = N->getOperand(0);
2077 SDValue N1 = N->getOperand(1);
2078 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2079 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2080 EVT VT = N->getValueType(0);
2082 // fold (urem c1, c2) -> c1%c2
2083 if (N0C && N1C && !N1C->isNullValue())
2084 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2085 // fold (urem x, pow2) -> (and x, pow2-1)
2086 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2087 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2088 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2089 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2090 if (N1.getOpcode() == ISD::SHL) {
2091 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2092 if (SHC->getAPIntValue().isPowerOf2()) {
2094 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2095 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2097 AddToWorkList(Add.getNode());
2098 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2103 // If X/C can be simplified by the division-by-constant logic, lower
2104 // X%C to the equivalent of X-X/C*C.
2105 if (N1C && !N1C->isNullValue()) {
2106 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2107 AddToWorkList(Div.getNode());
2108 SDValue OptimizedDiv = combine(Div.getNode());
2109 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2110 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2112 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2113 AddToWorkList(Mul.getNode());
2119 if (N0.getOpcode() == ISD::UNDEF)
2120 return DAG.getConstant(0, VT);
2121 // X % undef -> undef
2122 if (N1.getOpcode() == ISD::UNDEF)
2128 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2129 SDValue N0 = N->getOperand(0);
2130 SDValue N1 = N->getOperand(1);
2131 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2132 EVT VT = N->getValueType(0);
2135 // fold (mulhs x, 0) -> 0
2136 if (N1C && N1C->isNullValue())
2138 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2139 if (N1C && N1C->getAPIntValue() == 1)
2140 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2141 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2142 getShiftAmountTy(N0.getValueType())));
2143 // fold (mulhs x, undef) -> 0
2144 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2145 return DAG.getConstant(0, VT);
2147 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2149 if (VT.isSimple() && !VT.isVector()) {
2150 MVT Simple = VT.getSimpleVT();
2151 unsigned SimpleSize = Simple.getSizeInBits();
2152 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2153 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2154 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2155 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2156 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2157 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2158 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2159 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2166 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2167 SDValue N0 = N->getOperand(0);
2168 SDValue N1 = N->getOperand(1);
2169 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2170 EVT VT = N->getValueType(0);
2173 // fold (mulhu x, 0) -> 0
2174 if (N1C && N1C->isNullValue())
2176 // fold (mulhu x, 1) -> 0
2177 if (N1C && N1C->getAPIntValue() == 1)
2178 return DAG.getConstant(0, N0.getValueType());
2179 // fold (mulhu x, undef) -> 0
2180 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2181 return DAG.getConstant(0, VT);
2183 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2185 if (VT.isSimple() && !VT.isVector()) {
2186 MVT Simple = VT.getSimpleVT();
2187 unsigned SimpleSize = Simple.getSizeInBits();
2188 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2189 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2190 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2191 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2192 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2193 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2194 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2195 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2202 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2203 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2204 /// that are being performed. Return true if a simplification was made.
2206 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2208 // If the high half is not needed, just compute the low half.
2209 bool HiExists = N->hasAnyUseOfValue(1);
2211 (!LegalOperations ||
2212 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2213 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2214 N->op_begin(), N->getNumOperands());
2215 return CombineTo(N, Res, Res);
2218 // If the low half is not needed, just compute the high half.
2219 bool LoExists = N->hasAnyUseOfValue(0);
2221 (!LegalOperations ||
2222 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2223 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2224 N->op_begin(), N->getNumOperands());
2225 return CombineTo(N, Res, Res);
2228 // If both halves are used, return as it is.
2229 if (LoExists && HiExists)
2232 // If the two computed results can be simplified separately, separate them.
2234 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2235 N->op_begin(), N->getNumOperands());
2236 AddToWorkList(Lo.getNode());
2237 SDValue LoOpt = combine(Lo.getNode());
2238 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2239 (!LegalOperations ||
2240 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2241 return CombineTo(N, LoOpt, LoOpt);
2245 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2246 N->op_begin(), N->getNumOperands());
2247 AddToWorkList(Hi.getNode());
2248 SDValue HiOpt = combine(Hi.getNode());
2249 if (HiOpt.getNode() && HiOpt != Hi &&
2250 (!LegalOperations ||
2251 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2252 return CombineTo(N, HiOpt, HiOpt);
2258 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2259 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2260 if (Res.getNode()) return Res;
2262 EVT VT = N->getValueType(0);
2265 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2267 if (VT.isSimple() && !VT.isVector()) {
2268 MVT Simple = VT.getSimpleVT();
2269 unsigned SimpleSize = Simple.getSizeInBits();
2270 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2271 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2272 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2273 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2274 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2275 // Compute the high part as N1.
2276 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2277 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2278 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2279 // Compute the low part as N0.
2280 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2281 return CombineTo(N, Lo, Hi);
2288 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2289 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2290 if (Res.getNode()) return Res;
2292 EVT VT = N->getValueType(0);
2295 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2297 if (VT.isSimple() && !VT.isVector()) {
2298 MVT Simple = VT.getSimpleVT();
2299 unsigned SimpleSize = Simple.getSizeInBits();
2300 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2301 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2302 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2303 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2304 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2305 // Compute the high part as N1.
2306 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2307 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2308 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2309 // Compute the low part as N0.
2310 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2311 return CombineTo(N, Lo, Hi);
2318 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2319 // (smulo x, 2) -> (saddo x, x)
2320 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2321 if (C2->getAPIntValue() == 2)
2322 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2323 N->getOperand(0), N->getOperand(0));
2328 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2329 // (umulo x, 2) -> (uaddo x, x)
2330 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2331 if (C2->getAPIntValue() == 2)
2332 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2333 N->getOperand(0), N->getOperand(0));
2338 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2339 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2340 if (Res.getNode()) return Res;
2345 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2346 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2347 if (Res.getNode()) return Res;
2352 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2353 /// two operands of the same opcode, try to simplify it.
2354 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2355 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2356 EVT VT = N0.getValueType();
2357 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2359 // Bail early if none of these transforms apply.
2360 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2362 // For each of OP in AND/OR/XOR:
2363 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2364 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2365 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2366 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2368 // do not sink logical op inside of a vector extend, since it may combine
2370 EVT Op0VT = N0.getOperand(0).getValueType();
2371 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2372 N0.getOpcode() == ISD::SIGN_EXTEND ||
2373 // Avoid infinite looping with PromoteIntBinOp.
2374 (N0.getOpcode() == ISD::ANY_EXTEND &&
2375 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2376 (N0.getOpcode() == ISD::TRUNCATE &&
2377 (!TLI.isZExtFree(VT, Op0VT) ||
2378 !TLI.isTruncateFree(Op0VT, VT)) &&
2379 TLI.isTypeLegal(Op0VT))) &&
2381 Op0VT == N1.getOperand(0).getValueType() &&
2382 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2383 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2384 N0.getOperand(0).getValueType(),
2385 N0.getOperand(0), N1.getOperand(0));
2386 AddToWorkList(ORNode.getNode());
2387 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2390 // For each of OP in SHL/SRL/SRA/AND...
2391 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2392 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2393 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2394 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2395 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2396 N0.getOperand(1) == N1.getOperand(1)) {
2397 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2398 N0.getOperand(0).getValueType(),
2399 N0.getOperand(0), N1.getOperand(0));
2400 AddToWorkList(ORNode.getNode());
2401 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2402 ORNode, N0.getOperand(1));
2405 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2406 // Only perform this optimization after type legalization and before
2407 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2408 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2409 // we don't want to undo this promotion.
2410 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2412 if ((N0.getOpcode() == ISD::BITCAST ||
2413 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2414 Level == AfterLegalizeTypes) {
2415 SDValue In0 = N0.getOperand(0);
2416 SDValue In1 = N1.getOperand(0);
2417 EVT In0Ty = In0.getValueType();
2418 EVT In1Ty = In1.getValueType();
2420 // If both incoming values are integers, and the original types are the
2422 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2423 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2424 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2425 AddToWorkList(Op.getNode());
2430 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2431 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2432 // If both shuffles use the same mask, and both shuffle within a single
2433 // vector, then it is worthwhile to move the swizzle after the operation.
2434 // The type-legalizer generates this pattern when loading illegal
2435 // vector types from memory. In many cases this allows additional shuffle
2437 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2438 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2439 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2440 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2441 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2443 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2444 "Inputs to shuffles are not the same type");
2446 unsigned NumElts = VT.getVectorNumElements();
2448 // Check that both shuffles use the same mask. The masks are known to be of
2449 // the same length because the result vector type is the same.
2450 bool SameMask = true;
2451 for (unsigned i = 0; i != NumElts; ++i) {
2452 int Idx0 = SVN0->getMaskElt(i);
2453 int Idx1 = SVN1->getMaskElt(i);
2461 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2462 N0.getOperand(0), N1.getOperand(0));
2463 AddToWorkList(Op.getNode());
2464 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2465 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2472 SDValue DAGCombiner::visitAND(SDNode *N) {
2473 SDValue N0 = N->getOperand(0);
2474 SDValue N1 = N->getOperand(1);
2475 SDValue LL, LR, RL, RR, CC0, CC1;
2476 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2477 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2478 EVT VT = N1.getValueType();
2479 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2482 if (VT.isVector()) {
2483 SDValue FoldedVOp = SimplifyVBinOp(N);
2484 if (FoldedVOp.getNode()) return FoldedVOp;
2486 // fold (and x, 0) -> 0, vector edition
2487 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2489 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2492 // fold (and x, -1) -> x, vector edition
2493 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2495 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2499 // fold (and x, undef) -> 0
2500 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2501 return DAG.getConstant(0, VT);
2502 // fold (and c1, c2) -> c1&c2
2504 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2505 // canonicalize constant to RHS
2507 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2508 // fold (and x, -1) -> x
2509 if (N1C && N1C->isAllOnesValue())
2511 // if (and x, c) is known to be zero, return 0
2512 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2513 APInt::getAllOnesValue(BitWidth)))
2514 return DAG.getConstant(0, VT);
2516 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2517 if (RAND.getNode() != 0)
2519 // fold (and (or x, C), D) -> D if (C & D) == D
2520 if (N1C && N0.getOpcode() == ISD::OR)
2521 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2522 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2524 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2525 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2526 SDValue N0Op0 = N0.getOperand(0);
2527 APInt Mask = ~N1C->getAPIntValue();
2528 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2529 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2530 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2531 N0.getValueType(), N0Op0);
2533 // Replace uses of the AND with uses of the Zero extend node.
2536 // We actually want to replace all uses of the any_extend with the
2537 // zero_extend, to avoid duplicating things. This will later cause this
2538 // AND to be folded.
2539 CombineTo(N0.getNode(), Zext);
2540 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2543 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2544 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2545 // already be zero by virtue of the width of the base type of the load.
2547 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2549 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2550 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2551 N0.getOpcode() == ISD::LOAD) {
2552 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2553 N0 : N0.getOperand(0) );
2555 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2556 // This can be a pure constant or a vector splat, in which case we treat the
2557 // vector as a scalar and use the splat value.
2558 APInt Constant = APInt::getNullValue(1);
2559 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2560 Constant = C->getAPIntValue();
2561 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2562 APInt SplatValue, SplatUndef;
2563 unsigned SplatBitSize;
2565 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2566 SplatBitSize, HasAnyUndefs);
2568 // Undef bits can contribute to a possible optimisation if set, so
2570 SplatValue |= SplatUndef;
2572 // The splat value may be something like "0x00FFFFFF", which means 0 for
2573 // the first vector value and FF for the rest, repeating. We need a mask
2574 // that will apply equally to all members of the vector, so AND all the
2575 // lanes of the constant together.
2576 EVT VT = Vector->getValueType(0);
2577 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2579 // If the splat value has been compressed to a bitlength lower
2580 // than the size of the vector lane, we need to re-expand it to
2582 if (BitWidth > SplatBitSize)
2583 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2584 SplatBitSize < BitWidth;
2585 SplatBitSize = SplatBitSize * 2)
2586 SplatValue |= SplatValue.shl(SplatBitSize);
2588 Constant = APInt::getAllOnesValue(BitWidth);
2589 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2590 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2594 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2595 // actually legal and isn't going to get expanded, else this is a false
2597 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2598 Load->getMemoryVT());
2600 // Resize the constant to the same size as the original memory access before
2601 // extension. If it is still the AllOnesValue then this AND is completely
2604 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2607 switch (Load->getExtensionType()) {
2608 default: B = false; break;
2609 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2611 case ISD::NON_EXTLOAD: B = true; break;
2614 if (B && Constant.isAllOnesValue()) {
2615 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2616 // preserve semantics once we get rid of the AND.
2617 SDValue NewLoad(Load, 0);
2618 if (Load->getExtensionType() == ISD::EXTLOAD) {
2619 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2620 Load->getValueType(0), SDLoc(Load),
2621 Load->getChain(), Load->getBasePtr(),
2622 Load->getOffset(), Load->getMemoryVT(),
2623 Load->getMemOperand());
2624 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2625 if (Load->getNumValues() == 3) {
2626 // PRE/POST_INC loads have 3 values.
2627 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2628 NewLoad.getValue(2) };
2629 CombineTo(Load, To, 3, true);
2631 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2635 // Fold the AND away, taking care not to fold to the old load node if we
2637 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2639 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2642 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2643 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2644 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2645 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2647 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2648 LL.getValueType().isInteger()) {
2649 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2650 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2651 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2652 LR.getValueType(), LL, RL);
2653 AddToWorkList(ORNode.getNode());
2654 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2656 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2657 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2658 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2659 LR.getValueType(), LL, RL);
2660 AddToWorkList(ANDNode.getNode());
2661 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2663 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2664 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2665 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2666 LR.getValueType(), LL, RL);
2667 AddToWorkList(ORNode.getNode());
2668 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2671 // canonicalize equivalent to ll == rl
2672 if (LL == RR && LR == RL) {
2673 Op1 = ISD::getSetCCSwappedOperands(Op1);
2676 if (LL == RL && LR == RR) {
2677 bool isInteger = LL.getValueType().isInteger();
2678 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2679 if (Result != ISD::SETCC_INVALID &&
2680 (!LegalOperations ||
2681 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2682 TLI.isOperationLegal(ISD::SETCC,
2683 getSetCCResultType(N0.getSimpleValueType())))))
2684 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2689 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2690 if (N0.getOpcode() == N1.getOpcode()) {
2691 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2692 if (Tmp.getNode()) return Tmp;
2695 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2696 // fold (and (sra)) -> (and (srl)) when possible.
2697 if (!VT.isVector() &&
2698 SimplifyDemandedBits(SDValue(N, 0)))
2699 return SDValue(N, 0);
2701 // fold (zext_inreg (extload x)) -> (zextload x)
2702 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2703 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2704 EVT MemVT = LN0->getMemoryVT();
2705 // If we zero all the possible extended bits, then we can turn this into
2706 // a zextload if we are running before legalize or the operation is legal.
2707 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2708 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2709 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2710 ((!LegalOperations && !LN0->isVolatile()) ||
2711 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2712 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2713 LN0->getChain(), LN0->getBasePtr(),
2714 LN0->getPointerInfo(), MemVT,
2715 LN0->isVolatile(), LN0->isNonTemporal(),
2716 LN0->getAlignment());
2718 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2719 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2722 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2723 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2725 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2726 EVT MemVT = LN0->getMemoryVT();
2727 // If we zero all the possible extended bits, then we can turn this into
2728 // a zextload if we are running before legalize or the operation is legal.
2729 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2730 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2731 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2732 ((!LegalOperations && !LN0->isVolatile()) ||
2733 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2734 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2736 LN0->getBasePtr(), LN0->getPointerInfo(),
2738 LN0->isVolatile(), LN0->isNonTemporal(),
2739 LN0->getAlignment());
2741 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2742 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2746 // fold (and (load x), 255) -> (zextload x, i8)
2747 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2748 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2749 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2750 (N0.getOpcode() == ISD::ANY_EXTEND &&
2751 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2752 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2753 LoadSDNode *LN0 = HasAnyExt
2754 ? cast<LoadSDNode>(N0.getOperand(0))
2755 : cast<LoadSDNode>(N0);
2756 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2757 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2758 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2759 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2760 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2761 EVT LoadedVT = LN0->getMemoryVT();
2763 if (ExtVT == LoadedVT &&
2764 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2765 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2768 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2769 LN0->getChain(), LN0->getBasePtr(),
2770 LN0->getPointerInfo(),
2771 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2772 LN0->getAlignment());
2774 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2775 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2778 // Do not change the width of a volatile load.
2779 // Do not generate loads of non-round integer types since these can
2780 // be expensive (and would be wrong if the type is not byte sized).
2781 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2782 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2783 EVT PtrType = LN0->getOperand(1).getValueType();
2785 unsigned Alignment = LN0->getAlignment();
2786 SDValue NewPtr = LN0->getBasePtr();
2788 // For big endian targets, we need to add an offset to the pointer
2789 // to load the correct bytes. For little endian systems, we merely
2790 // need to read fewer bytes from the same pointer.
2791 if (TLI.isBigEndian()) {
2792 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2793 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2794 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2795 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2796 NewPtr, DAG.getConstant(PtrOff, PtrType));
2797 Alignment = MinAlign(Alignment, PtrOff);
2800 AddToWorkList(NewPtr.getNode());
2802 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2804 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2805 LN0->getChain(), NewPtr,
2806 LN0->getPointerInfo(),
2807 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2810 CombineTo(LN0, Load, Load.getValue(1));
2811 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2817 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2818 VT.getSizeInBits() <= 64) {
2819 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2820 APInt ADDC = ADDI->getAPIntValue();
2821 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2822 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2823 // immediate for an add, but it is legal if its top c2 bits are set,
2824 // transform the ADD so the immediate doesn't need to be materialized
2826 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2827 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2828 SRLI->getZExtValue());
2829 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2831 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2833 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2834 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2835 CombineTo(N0.getNode(), NewAdd);
2836 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2847 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2849 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2850 bool DemandHighBits) {
2851 if (!LegalOperations)
2854 EVT VT = N->getValueType(0);
2855 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2857 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2860 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2861 bool LookPassAnd0 = false;
2862 bool LookPassAnd1 = false;
2863 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2865 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2867 if (N0.getOpcode() == ISD::AND) {
2868 if (!N0.getNode()->hasOneUse())
2870 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2871 if (!N01C || N01C->getZExtValue() != 0xFF00)
2873 N0 = N0.getOperand(0);
2874 LookPassAnd0 = true;
2877 if (N1.getOpcode() == ISD::AND) {
2878 if (!N1.getNode()->hasOneUse())
2880 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2881 if (!N11C || N11C->getZExtValue() != 0xFF)
2883 N1 = N1.getOperand(0);
2884 LookPassAnd1 = true;
2887 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2889 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2891 if (!N0.getNode()->hasOneUse() ||
2892 !N1.getNode()->hasOneUse())
2895 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2896 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2899 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2902 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2903 SDValue N00 = N0->getOperand(0);
2904 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2905 if (!N00.getNode()->hasOneUse())
2907 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2908 if (!N001C || N001C->getZExtValue() != 0xFF)
2910 N00 = N00.getOperand(0);
2911 LookPassAnd0 = true;
2914 SDValue N10 = N1->getOperand(0);
2915 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2916 if (!N10.getNode()->hasOneUse())
2918 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2919 if (!N101C || N101C->getZExtValue() != 0xFF00)
2921 N10 = N10.getOperand(0);
2922 LookPassAnd1 = true;
2928 // Make sure everything beyond the low halfword is zero since the SRL 16
2929 // will clear the top bits.
2930 unsigned OpSizeInBits = VT.getSizeInBits();
2931 if (DemandHighBits && OpSizeInBits > 16 &&
2932 (!LookPassAnd0 || !LookPassAnd1) &&
2933 !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16)))
2936 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
2937 if (OpSizeInBits > 16)
2938 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
2939 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2943 /// isBSwapHWordElement - Return true if the specified node is an element
2944 /// that makes up a 32-bit packed halfword byteswap. i.e.
2945 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2946 static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) {
2947 if (!N.getNode()->hasOneUse())
2950 unsigned Opc = N.getOpcode();
2951 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2954 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2959 switch (N1C->getZExtValue()) {
2962 case 0xFF: Num = 0; break;
2963 case 0xFF00: Num = 1; break;
2964 case 0xFF0000: Num = 2; break;
2965 case 0xFF000000: Num = 3; break;
2968 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
2969 SDValue N0 = N.getOperand(0);
2970 if (Opc == ISD::AND) {
2971 if (Num == 0 || Num == 2) {
2973 // (x >> 8) & 0xff0000
2974 if (N0.getOpcode() != ISD::SRL)
2976 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2977 if (!C || C->getZExtValue() != 8)
2980 // (x << 8) & 0xff00
2981 // (x << 8) & 0xff000000
2982 if (N0.getOpcode() != ISD::SHL)
2984 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2985 if (!C || C->getZExtValue() != 8)
2988 } else if (Opc == ISD::SHL) {
2990 // (x & 0xff0000) << 8
2991 if (Num != 0 && Num != 2)
2993 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2994 if (!C || C->getZExtValue() != 8)
2996 } else { // Opc == ISD::SRL
2997 // (x & 0xff00) >> 8
2998 // (x & 0xff000000) >> 8
2999 if (Num != 1 && Num != 3)
3001 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3002 if (!C || C->getZExtValue() != 8)
3009 Parts[Num] = N0.getOperand(0).getNode();
3013 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3014 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3015 /// => (rotl (bswap x), 16)
3016 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3017 if (!LegalOperations)
3020 EVT VT = N->getValueType(0);
3023 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3026 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3028 // (or (or (and), (and)), (or (and), (and)))
3029 // (or (or (or (and), (and)), (and)), (and))
3030 if (N0.getOpcode() != ISD::OR)
3032 SDValue N00 = N0.getOperand(0);
3033 SDValue N01 = N0.getOperand(1);
3035 if (N1.getOpcode() == ISD::OR &&
3036 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3037 // (or (or (and), (and)), (or (and), (and)))
3038 SDValue N000 = N00.getOperand(0);
3039 if (!isBSwapHWordElement(N000, Parts))
3042 SDValue N001 = N00.getOperand(1);
3043 if (!isBSwapHWordElement(N001, Parts))
3045 SDValue N010 = N01.getOperand(0);
3046 if (!isBSwapHWordElement(N010, Parts))
3048 SDValue N011 = N01.getOperand(1);
3049 if (!isBSwapHWordElement(N011, Parts))
3052 // (or (or (or (and), (and)), (and)), (and))
3053 if (!isBSwapHWordElement(N1, Parts))
3055 if (!isBSwapHWordElement(N01, Parts))
3057 if (N00.getOpcode() != ISD::OR)
3059 SDValue N000 = N00.getOperand(0);
3060 if (!isBSwapHWordElement(N000, Parts))
3062 SDValue N001 = N00.getOperand(1);
3063 if (!isBSwapHWordElement(N001, Parts))
3067 // Make sure the parts are all coming from the same node.
3068 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3071 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3072 SDValue(Parts[0],0));
3074 // Result of the bswap should be rotated by 16. If it's not legal, than
3075 // do (x << 16) | (x >> 16).
3076 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3077 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3078 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3079 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3080 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3081 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3082 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3083 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3086 SDValue DAGCombiner::visitOR(SDNode *N) {
3087 SDValue N0 = N->getOperand(0);
3088 SDValue N1 = N->getOperand(1);
3089 SDValue LL, LR, RL, RR, CC0, CC1;
3090 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3091 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3092 EVT VT = N1.getValueType();
3095 if (VT.isVector()) {
3096 SDValue FoldedVOp = SimplifyVBinOp(N);
3097 if (FoldedVOp.getNode()) return FoldedVOp;
3099 // fold (or x, 0) -> x, vector edition
3100 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3102 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3105 // fold (or x, -1) -> -1, vector edition
3106 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3108 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3112 // fold (or x, undef) -> -1
3113 if (!LegalOperations &&
3114 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3115 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3116 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3118 // fold (or c1, c2) -> c1|c2
3120 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3121 // canonicalize constant to RHS
3123 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3124 // fold (or x, 0) -> x
3125 if (N1C && N1C->isNullValue())
3127 // fold (or x, -1) -> -1
3128 if (N1C && N1C->isAllOnesValue())
3130 // fold (or x, c) -> c iff (x & ~c) == 0
3131 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3134 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3135 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3136 if (BSwap.getNode() != 0)
3138 BSwap = MatchBSwapHWordLow(N, N0, N1);
3139 if (BSwap.getNode() != 0)
3143 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3144 if (ROR.getNode() != 0)
3146 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3147 // iff (c1 & c2) == 0.
3148 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3149 isa<ConstantSDNode>(N0.getOperand(1))) {
3150 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3151 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3152 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3153 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3154 N0.getOperand(0), N1),
3155 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3157 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3158 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3159 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3160 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3162 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3163 LL.getValueType().isInteger()) {
3164 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3165 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3166 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3167 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3168 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3169 LR.getValueType(), LL, RL);
3170 AddToWorkList(ORNode.getNode());
3171 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3173 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3174 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3175 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3176 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3177 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3178 LR.getValueType(), LL, RL);
3179 AddToWorkList(ANDNode.getNode());
3180 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3183 // canonicalize equivalent to ll == rl
3184 if (LL == RR && LR == RL) {
3185 Op1 = ISD::getSetCCSwappedOperands(Op1);
3188 if (LL == RL && LR == RR) {
3189 bool isInteger = LL.getValueType().isInteger();
3190 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3191 if (Result != ISD::SETCC_INVALID &&
3192 (!LegalOperations ||
3193 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3194 TLI.isOperationLegal(ISD::SETCC,
3195 getSetCCResultType(N0.getValueType())))))
3196 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3201 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3202 if (N0.getOpcode() == N1.getOpcode()) {
3203 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3204 if (Tmp.getNode()) return Tmp;
3207 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3208 if (N0.getOpcode() == ISD::AND &&
3209 N1.getOpcode() == ISD::AND &&
3210 N0.getOperand(1).getOpcode() == ISD::Constant &&
3211 N1.getOperand(1).getOpcode() == ISD::Constant &&
3212 // Don't increase # computations.
3213 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3214 // We can only do this xform if we know that bits from X that are set in C2
3215 // but not in C1 are already zero. Likewise for Y.
3216 const APInt &LHSMask =
3217 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3218 const APInt &RHSMask =
3219 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3221 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3222 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3223 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3224 N0.getOperand(0), N1.getOperand(0));
3225 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3226 DAG.getConstant(LHSMask | RHSMask, VT));
3230 // See if this is some rotate idiom.
3231 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3232 return SDValue(Rot, 0);
3234 // Simplify the operands using demanded-bits information.
3235 if (!VT.isVector() &&
3236 SimplifyDemandedBits(SDValue(N, 0)))
3237 return SDValue(N, 0);
3242 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3243 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3244 if (Op.getOpcode() == ISD::AND) {
3245 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3246 Mask = Op.getOperand(1);
3247 Op = Op.getOperand(0);
3253 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3261 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3262 // idioms for rotate, and if the target supports rotation instructions, generate
3264 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3265 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3266 EVT VT = LHS.getValueType();
3267 if (!TLI.isTypeLegal(VT)) return 0;
3269 // The target must have at least one rotate flavor.
3270 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3271 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3272 if (!HasROTL && !HasROTR) return 0;
3274 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3275 SDValue LHSShift; // The shift.
3276 SDValue LHSMask; // AND value if any.
3277 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3278 return 0; // Not part of a rotate.
3280 SDValue RHSShift; // The shift.
3281 SDValue RHSMask; // AND value if any.
3282 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3283 return 0; // Not part of a rotate.
3285 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3286 return 0; // Not shifting the same value.
3288 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3289 return 0; // Shifts must disagree.
3291 // Canonicalize shl to left side in a shl/srl pair.
3292 if (RHSShift.getOpcode() == ISD::SHL) {
3293 std::swap(LHS, RHS);
3294 std::swap(LHSShift, RHSShift);
3295 std::swap(LHSMask , RHSMask );
3298 unsigned OpSizeInBits = VT.getSizeInBits();
3299 SDValue LHSShiftArg = LHSShift.getOperand(0);
3300 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3301 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3303 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3304 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3305 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3306 RHSShiftAmt.getOpcode() == ISD::Constant) {
3307 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3308 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3309 if ((LShVal + RShVal) != OpSizeInBits)
3312 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3313 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3315 // If there is an AND of either shifted operand, apply it to the result.
3316 if (LHSMask.getNode() || RHSMask.getNode()) {
3317 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3319 if (LHSMask.getNode()) {
3320 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3321 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3323 if (RHSMask.getNode()) {
3324 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3325 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3328 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3331 return Rot.getNode();
3334 // If there is a mask here, and we have a variable shift, we can't be sure
3335 // that we're masking out the right stuff.
3336 if (LHSMask.getNode() || RHSMask.getNode())
3339 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
3340 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
3341 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
3342 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
3343 if (ConstantSDNode *SUBC =
3344 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
3345 if (SUBC->getAPIntValue() == OpSizeInBits)
3346 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3347 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3351 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
3352 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
3353 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
3354 RHSShiftAmt == LHSShiftAmt.getOperand(1))
3355 if (ConstantSDNode *SUBC =
3356 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0)))
3357 if (SUBC->getAPIntValue() == OpSizeInBits)
3358 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3359 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3361 // Look for sign/zext/any-extended or truncate cases:
3362 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3363 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3364 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3365 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3366 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3367 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3368 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3369 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3370 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3371 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3372 if (RExtOp0.getOpcode() == ISD::SUB &&
3373 RExtOp0.getOperand(1) == LExtOp0) {
3374 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3376 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3377 // (rotr x, (sub 32, y))
3378 if (ConstantSDNode *SUBC =
3379 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0)))
3380 if (SUBC->getAPIntValue() == OpSizeInBits)
3381 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3383 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3384 } else if (LExtOp0.getOpcode() == ISD::SUB &&
3385 RExtOp0 == LExtOp0.getOperand(1)) {
3386 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3388 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3389 // (rotl x, (sub 32, y))
3390 if (ConstantSDNode *SUBC =
3391 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0)))
3392 if (SUBC->getAPIntValue() == OpSizeInBits)
3393 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3395 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3402 SDValue DAGCombiner::visitXOR(SDNode *N) {
3403 SDValue N0 = N->getOperand(0);
3404 SDValue N1 = N->getOperand(1);
3405 SDValue LHS, RHS, CC;
3406 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3407 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3408 EVT VT = N0.getValueType();
3411 if (VT.isVector()) {
3412 SDValue FoldedVOp = SimplifyVBinOp(N);
3413 if (FoldedVOp.getNode()) return FoldedVOp;
3415 // fold (xor x, 0) -> x, vector edition
3416 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3418 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3422 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3423 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3424 return DAG.getConstant(0, VT);
3425 // fold (xor x, undef) -> undef
3426 if (N0.getOpcode() == ISD::UNDEF)
3428 if (N1.getOpcode() == ISD::UNDEF)
3430 // fold (xor c1, c2) -> c1^c2
3432 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3433 // canonicalize constant to RHS
3435 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3436 // fold (xor x, 0) -> x
3437 if (N1C && N1C->isNullValue())
3440 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3441 if (RXOR.getNode() != 0)
3444 // fold !(x cc y) -> (x !cc y)
3445 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3446 bool isInt = LHS.getValueType().isInteger();
3447 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3450 if (!LegalOperations ||
3451 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3452 switch (N0.getOpcode()) {
3454 llvm_unreachable("Unhandled SetCC Equivalent!");
3456 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3457 case ISD::SELECT_CC:
3458 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3459 N0.getOperand(3), NotCC);
3464 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3465 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3466 N0.getNode()->hasOneUse() &&
3467 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3468 SDValue V = N0.getOperand(0);
3469 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3470 DAG.getConstant(1, V.getValueType()));
3471 AddToWorkList(V.getNode());
3472 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3475 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3476 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3477 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3478 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3479 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3480 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3481 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3482 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3483 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3484 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3487 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3488 if (N1C && N1C->isAllOnesValue() &&
3489 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3490 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3491 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3492 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3493 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3494 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3495 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3496 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3499 // fold (xor (and x, y), y) -> (and (not x), y)
3500 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3501 N0->getOperand(1) == N1) {
3502 SDValue X = N0->getOperand(0);
3503 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3504 AddToWorkList(NotX.getNode());
3505 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3507 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3508 if (N1C && N0.getOpcode() == ISD::XOR) {
3509 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3510 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3512 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3513 DAG.getConstant(N1C->getAPIntValue() ^
3514 N00C->getAPIntValue(), VT));
3516 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3517 DAG.getConstant(N1C->getAPIntValue() ^
3518 N01C->getAPIntValue(), VT));
3520 // fold (xor x, x) -> 0
3522 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations);
3524 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3525 if (N0.getOpcode() == N1.getOpcode()) {
3526 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3527 if (Tmp.getNode()) return Tmp;
3530 // Simplify the expression using non-local knowledge.
3531 if (!VT.isVector() &&
3532 SimplifyDemandedBits(SDValue(N, 0)))
3533 return SDValue(N, 0);
3538 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3539 /// the shift amount is a constant.
3540 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3541 SDNode *LHS = N->getOperand(0).getNode();
3542 if (!LHS->hasOneUse()) return SDValue();
3544 // We want to pull some binops through shifts, so that we have (and (shift))
3545 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3546 // thing happens with address calculations, so it's important to canonicalize
3548 bool HighBitSet = false; // Can we transform this if the high bit is set?
3550 switch (LHS->getOpcode()) {
3551 default: return SDValue();
3554 HighBitSet = false; // We can only transform sra if the high bit is clear.
3557 HighBitSet = true; // We can only transform sra if the high bit is set.
3560 if (N->getOpcode() != ISD::SHL)
3561 return SDValue(); // only shl(add) not sr[al](add).
3562 HighBitSet = false; // We can only transform sra if the high bit is clear.
3566 // We require the RHS of the binop to be a constant as well.
3567 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3568 if (!BinOpCst) return SDValue();
3570 // FIXME: disable this unless the input to the binop is a shift by a constant.
3571 // If it is not a shift, it pessimizes some common cases like:
3573 // void foo(int *X, int i) { X[i & 1235] = 1; }
3574 // int bar(int *X, int i) { return X[i & 255]; }
3575 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3576 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3577 BinOpLHSVal->getOpcode() != ISD::SRA &&
3578 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3579 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3582 EVT VT = N->getValueType(0);
3584 // If this is a signed shift right, and the high bit is modified by the
3585 // logical operation, do not perform the transformation. The highBitSet
3586 // boolean indicates the value of the high bit of the constant which would
3587 // cause it to be modified for this operation.
3588 if (N->getOpcode() == ISD::SRA) {
3589 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3590 if (BinOpRHSSignSet != HighBitSet)
3594 // Fold the constants, shifting the binop RHS by the shift amount.
3595 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3597 LHS->getOperand(1), N->getOperand(1));
3599 // Create the new shift.
3600 SDValue NewShift = DAG.getNode(N->getOpcode(),
3601 SDLoc(LHS->getOperand(0)),
3602 VT, LHS->getOperand(0), N->getOperand(1));
3604 // Create the new binop.
3605 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3608 SDValue DAGCombiner::visitSHL(SDNode *N) {
3609 SDValue N0 = N->getOperand(0);
3610 SDValue N1 = N->getOperand(1);
3611 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3612 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3613 EVT VT = N0.getValueType();
3614 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3616 // fold (shl c1, c2) -> c1<<c2
3618 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3619 // fold (shl 0, x) -> 0
3620 if (N0C && N0C->isNullValue())
3622 // fold (shl x, c >= size(x)) -> undef
3623 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3624 return DAG.getUNDEF(VT);
3625 // fold (shl x, 0) -> x
3626 if (N1C && N1C->isNullValue())
3628 // fold (shl undef, x) -> 0
3629 if (N0.getOpcode() == ISD::UNDEF)
3630 return DAG.getConstant(0, VT);
3631 // if (shl x, c) is known to be zero, return 0
3632 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3633 APInt::getAllOnesValue(OpSizeInBits)))
3634 return DAG.getConstant(0, VT);
3635 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3636 if (N1.getOpcode() == ISD::TRUNCATE &&
3637 N1.getOperand(0).getOpcode() == ISD::AND &&
3638 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3639 SDValue N101 = N1.getOperand(0).getOperand(1);
3640 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3641 EVT TruncVT = N1.getValueType();
3642 SDValue N100 = N1.getOperand(0).getOperand(0);
3643 APInt TruncC = N101C->getAPIntValue();
3644 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3645 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3646 DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3647 DAG.getNode(ISD::TRUNCATE,
3650 DAG.getConstant(TruncC, TruncVT)));
3654 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3655 return SDValue(N, 0);
3657 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3658 if (N1C && N0.getOpcode() == ISD::SHL &&
3659 N0.getOperand(1).getOpcode() == ISD::Constant) {
3660 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3661 uint64_t c2 = N1C->getZExtValue();
3662 if (c1 + c2 >= OpSizeInBits)
3663 return DAG.getConstant(0, VT);
3664 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3665 DAG.getConstant(c1 + c2, N1.getValueType()));
3668 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3669 // For this to be valid, the second form must not preserve any of the bits
3670 // that are shifted out by the inner shift in the first form. This means
3671 // the outer shift size must be >= the number of bits added by the ext.
3672 // As a corollary, we don't care what kind of ext it is.
3673 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3674 N0.getOpcode() == ISD::ANY_EXTEND ||
3675 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3676 N0.getOperand(0).getOpcode() == ISD::SHL &&
3677 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3679 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3680 uint64_t c2 = N1C->getZExtValue();
3681 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3682 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3683 if (c2 >= OpSizeInBits - InnerShiftSize) {
3684 if (c1 + c2 >= OpSizeInBits)
3685 return DAG.getConstant(0, VT);
3686 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3687 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3688 N0.getOperand(0)->getOperand(0)),
3689 DAG.getConstant(c1 + c2, N1.getValueType()));
3693 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3694 // (and (srl x, (sub c1, c2), MASK)
3695 // Only fold this if the inner shift has no other uses -- if it does, folding
3696 // this will increase the total number of instructions.
3697 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3698 N0.getOperand(1).getOpcode() == ISD::Constant) {
3699 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3700 if (c1 < VT.getSizeInBits()) {
3701 uint64_t c2 = N1C->getZExtValue();
3702 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3703 VT.getSizeInBits() - c1);
3706 Mask = Mask.shl(c2-c1);
3707 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3708 DAG.getConstant(c2-c1, N1.getValueType()));
3710 Mask = Mask.lshr(c1-c2);
3711 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3712 DAG.getConstant(c1-c2, N1.getValueType()));
3714 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3715 DAG.getConstant(Mask, VT));
3718 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3719 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3720 SDValue HiBitsMask =
3721 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3722 VT.getSizeInBits() -
3723 N1C->getZExtValue()),
3725 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3730 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3731 if (NewSHL.getNode())
3738 SDValue DAGCombiner::visitSRA(SDNode *N) {
3739 SDValue N0 = N->getOperand(0);
3740 SDValue N1 = N->getOperand(1);
3741 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3742 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3743 EVT VT = N0.getValueType();
3744 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3746 // fold (sra c1, c2) -> (sra c1, c2)
3748 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3749 // fold (sra 0, x) -> 0
3750 if (N0C && N0C->isNullValue())
3752 // fold (sra -1, x) -> -1
3753 if (N0C && N0C->isAllOnesValue())
3755 // fold (sra x, (setge c, size(x))) -> undef
3756 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3757 return DAG.getUNDEF(VT);
3758 // fold (sra x, 0) -> x
3759 if (N1C && N1C->isNullValue())
3761 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3763 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3764 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3765 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3767 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3768 ExtVT, VT.getVectorNumElements());
3769 if ((!LegalOperations ||
3770 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3771 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3772 N0.getOperand(0), DAG.getValueType(ExtVT));
3775 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3776 if (N1C && N0.getOpcode() == ISD::SRA) {
3777 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3778 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3779 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3780 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3781 DAG.getConstant(Sum, N1C->getValueType(0)));
3785 // fold (sra (shl X, m), (sub result_size, n))
3786 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3787 // result_size - n != m.
3788 // If truncate is free for the target sext(shl) is likely to result in better
3790 if (N0.getOpcode() == ISD::SHL) {
3791 // Get the two constanst of the shifts, CN0 = m, CN = n.
3792 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3794 // Determine what the truncate's result bitsize and type would be.
3796 EVT::getIntegerVT(*DAG.getContext(),
3797 OpSizeInBits - N1C->getZExtValue());
3798 // Determine the residual right-shift amount.
3799 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3801 // If the shift is not a no-op (in which case this should be just a sign
3802 // extend already), the truncated to type is legal, sign_extend is legal
3803 // on that type, and the truncate to that type is both legal and free,
3804 // perform the transform.
3805 if ((ShiftAmt > 0) &&
3806 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3807 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3808 TLI.isTruncateFree(VT, TruncVT)) {
3810 SDValue Amt = DAG.getConstant(ShiftAmt,
3811 getShiftAmountTy(N0.getOperand(0).getValueType()));
3812 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3813 N0.getOperand(0), Amt);
3814 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3816 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3817 N->getValueType(0), Trunc);
3822 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3823 if (N1.getOpcode() == ISD::TRUNCATE &&
3824 N1.getOperand(0).getOpcode() == ISD::AND &&
3825 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3826 SDValue N101 = N1.getOperand(0).getOperand(1);
3827 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3828 EVT TruncVT = N1.getValueType();
3829 SDValue N100 = N1.getOperand(0).getOperand(0);
3830 APInt TruncC = N101C->getAPIntValue();
3831 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3832 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3833 DAG.getNode(ISD::AND, SDLoc(N),
3835 DAG.getNode(ISD::TRUNCATE,
3838 DAG.getConstant(TruncC, TruncVT)));
3842 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3843 // if c1 is equal to the number of bits the trunc removes
3844 if (N0.getOpcode() == ISD::TRUNCATE &&
3845 (N0.getOperand(0).getOpcode() == ISD::SRL ||
3846 N0.getOperand(0).getOpcode() == ISD::SRA) &&
3847 N0.getOperand(0).hasOneUse() &&
3848 N0.getOperand(0).getOperand(1).hasOneUse() &&
3849 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3850 EVT LargeVT = N0.getOperand(0).getValueType();
3851 ConstantSDNode *LargeShiftAmt =
3852 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3854 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3855 LargeShiftAmt->getZExtValue()) {
3857 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3858 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3859 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3860 N0.getOperand(0).getOperand(0), Amt);
3861 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3865 // Simplify, based on bits shifted out of the LHS.
3866 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3867 return SDValue(N, 0);
3870 // If the sign bit is known to be zero, switch this to a SRL.
3871 if (DAG.SignBitIsZero(N0))
3872 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
3875 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3876 if (NewSRA.getNode())
3883 SDValue DAGCombiner::visitSRL(SDNode *N) {
3884 SDValue N0 = N->getOperand(0);
3885 SDValue N1 = N->getOperand(1);
3886 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3887 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3888 EVT VT = N0.getValueType();
3889 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3891 // fold (srl c1, c2) -> c1 >>u c2
3893 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3894 // fold (srl 0, x) -> 0
3895 if (N0C && N0C->isNullValue())
3897 // fold (srl x, c >= size(x)) -> undef
3898 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3899 return DAG.getUNDEF(VT);
3900 // fold (srl x, 0) -> x
3901 if (N1C && N1C->isNullValue())
3903 // if (srl x, c) is known to be zero, return 0
3904 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3905 APInt::getAllOnesValue(OpSizeInBits)))
3906 return DAG.getConstant(0, VT);
3908 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3909 if (N1C && N0.getOpcode() == ISD::SRL &&
3910 N0.getOperand(1).getOpcode() == ISD::Constant) {
3911 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3912 uint64_t c2 = N1C->getZExtValue();
3913 if (c1 + c2 >= OpSizeInBits)
3914 return DAG.getConstant(0, VT);
3915 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3916 DAG.getConstant(c1 + c2, N1.getValueType()));
3919 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3920 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3921 N0.getOperand(0).getOpcode() == ISD::SRL &&
3922 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3924 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3925 uint64_t c2 = N1C->getZExtValue();
3926 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3927 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3928 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3929 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3930 if (c1 + OpSizeInBits == InnerShiftSize) {
3931 if (c1 + c2 >= InnerShiftSize)
3932 return DAG.getConstant(0, VT);
3933 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
3934 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
3935 N0.getOperand(0)->getOperand(0),
3936 DAG.getConstant(c1 + c2, ShiftCountVT)));
3940 // fold (srl (shl x, c), c) -> (and x, cst2)
3941 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3942 N0.getValueSizeInBits() <= 64) {
3943 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3944 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3945 DAG.getConstant(~0ULL >> ShAmt, VT));
3948 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
3949 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3950 // Shifting in all undef bits?
3951 EVT SmallVT = N0.getOperand(0).getValueType();
3952 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3953 return DAG.getUNDEF(VT);
3955 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3956 uint64_t ShiftAmt = N1C->getZExtValue();
3957 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
3959 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3960 AddToWorkList(SmallShift.getNode());
3961 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
3962 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3963 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
3964 DAG.getConstant(Mask, VT));
3968 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
3969 // bit, which is unmodified by sra.
3970 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3971 if (N0.getOpcode() == ISD::SRA)
3972 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
3975 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
3976 if (N1C && N0.getOpcode() == ISD::CTLZ &&
3977 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3978 APInt KnownZero, KnownOne;
3979 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
3981 // If any of the input bits are KnownOne, then the input couldn't be all
3982 // zeros, thus the result of the srl will always be zero.
3983 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3985 // If all of the bits input the to ctlz node are known to be zero, then
3986 // the result of the ctlz is "32" and the result of the shift is one.
3987 APInt UnknownBits = ~KnownZero;
3988 if (UnknownBits == 0) return DAG.getConstant(1, VT);
3990 // Otherwise, check to see if there is exactly one bit input to the ctlz.
3991 if ((UnknownBits & (UnknownBits - 1)) == 0) {
3992 // Okay, we know that only that the single bit specified by UnknownBits
3993 // could be set on input to the CTLZ node. If this bit is set, the SRL
3994 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3995 // to an SRL/XOR pair, which is likely to simplify more.
3996 unsigned ShAmt = UnknownBits.countTrailingZeros();
3997 SDValue Op = N0.getOperand(0);
4000 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4001 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4002 AddToWorkList(Op.getNode());
4005 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4006 Op, DAG.getConstant(1, VT));
4010 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4011 if (N1.getOpcode() == ISD::TRUNCATE &&
4012 N1.getOperand(0).getOpcode() == ISD::AND &&
4013 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4014 SDValue N101 = N1.getOperand(0).getOperand(1);
4015 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4016 EVT TruncVT = N1.getValueType();
4017 SDValue N100 = N1.getOperand(0).getOperand(0);
4018 APInt TruncC = N101C->getAPIntValue();
4019 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4020 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4021 DAG.getNode(ISD::AND, SDLoc(N),
4023 DAG.getNode(ISD::TRUNCATE,
4026 DAG.getConstant(TruncC, TruncVT)));
4030 // fold operands of srl based on knowledge that the low bits are not
4032 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4033 return SDValue(N, 0);
4036 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4037 if (NewSRL.getNode())
4041 // Attempt to convert a srl of a load into a narrower zero-extending load.
4042 SDValue NarrowLoad = ReduceLoadWidth(N);
4043 if (NarrowLoad.getNode())
4046 // Here is a common situation. We want to optimize:
4049 // %b = and i32 %a, 2
4050 // %c = srl i32 %b, 1
4051 // brcond i32 %c ...
4057 // %c = setcc eq %b, 0
4060 // However when after the source operand of SRL is optimized into AND, the SRL
4061 // itself may not be optimized further. Look for it and add the BRCOND into
4063 if (N->hasOneUse()) {
4064 SDNode *Use = *N->use_begin();
4065 if (Use->getOpcode() == ISD::BRCOND)
4067 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4068 // Also look pass the truncate.
4069 Use = *Use->use_begin();
4070 if (Use->getOpcode() == ISD::BRCOND)
4078 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4079 SDValue N0 = N->getOperand(0);
4080 EVT VT = N->getValueType(0);
4082 // fold (ctlz c1) -> c2
4083 if (isa<ConstantSDNode>(N0))
4084 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4088 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4089 SDValue N0 = N->getOperand(0);
4090 EVT VT = N->getValueType(0);
4092 // fold (ctlz_zero_undef c1) -> c2
4093 if (isa<ConstantSDNode>(N0))
4094 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4098 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4099 SDValue N0 = N->getOperand(0);
4100 EVT VT = N->getValueType(0);
4102 // fold (cttz c1) -> c2
4103 if (isa<ConstantSDNode>(N0))
4104 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4108 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4109 SDValue N0 = N->getOperand(0);
4110 EVT VT = N->getValueType(0);
4112 // fold (cttz_zero_undef c1) -> c2
4113 if (isa<ConstantSDNode>(N0))
4114 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4118 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4119 SDValue N0 = N->getOperand(0);
4120 EVT VT = N->getValueType(0);
4122 // fold (ctpop c1) -> c2
4123 if (isa<ConstantSDNode>(N0))
4124 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4128 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4129 SDValue N0 = N->getOperand(0);
4130 SDValue N1 = N->getOperand(1);
4131 SDValue N2 = N->getOperand(2);
4132 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4133 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4134 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4135 EVT VT = N->getValueType(0);
4136 EVT VT0 = N0.getValueType();
4138 // fold (select C, X, X) -> X
4141 // fold (select true, X, Y) -> X
4142 if (N0C && !N0C->isNullValue())
4144 // fold (select false, X, Y) -> Y
4145 if (N0C && N0C->isNullValue())
4147 // fold (select C, 1, X) -> (or C, X)
4148 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4149 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4150 // fold (select C, 0, 1) -> (xor C, 1)
4151 if (VT.isInteger() &&
4154 TLI.getBooleanContents(false) ==
4155 TargetLowering::ZeroOrOneBooleanContent)) &&
4156 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4159 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4160 N0, DAG.getConstant(1, VT0));
4161 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4162 N0, DAG.getConstant(1, VT0));
4163 AddToWorkList(XORNode.getNode());
4165 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4166 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4168 // fold (select C, 0, X) -> (and (not C), X)
4169 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4170 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4171 AddToWorkList(NOTNode.getNode());
4172 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4174 // fold (select C, X, 1) -> (or (not C), X)
4175 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4176 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4177 AddToWorkList(NOTNode.getNode());
4178 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4180 // fold (select C, X, 0) -> (and C, X)
4181 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4182 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4183 // fold (select X, X, Y) -> (or X, Y)
4184 // fold (select X, 1, Y) -> (or X, Y)
4185 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4186 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4187 // fold (select X, Y, X) -> (and X, Y)
4188 // fold (select X, Y, 0) -> (and X, Y)
4189 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4190 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4192 // If we can fold this based on the true/false value, do so.
4193 if (SimplifySelectOps(N, N1, N2))
4194 return SDValue(N, 0); // Don't revisit N.
4196 // fold selects based on a setcc into other things, such as min/max/abs
4197 if (N0.getOpcode() == ISD::SETCC) {
4199 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4200 // having to say they don't support SELECT_CC on every type the DAG knows
4201 // about, since there is no way to mark an opcode illegal at all value types
4202 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4203 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4204 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4205 N0.getOperand(0), N0.getOperand(1),
4206 N1, N2, N0.getOperand(2));
4207 return SimplifySelect(SDLoc(N), N0, N1, N2);
4213 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4214 SDValue N0 = N->getOperand(0);
4215 SDValue N1 = N->getOperand(1);
4216 SDValue N2 = N->getOperand(2);
4219 // Canonicalize integer abs.
4220 // vselect (setg[te] X, 0), X, -X ->
4221 // vselect (setgt X, -1), X, -X ->
4222 // vselect (setl[te] X, 0), -X, X ->
4223 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4224 if (N0.getOpcode() == ISD::SETCC) {
4225 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4226 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4228 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4230 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4231 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4232 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4233 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4234 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4235 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4236 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4239 EVT VT = LHS.getValueType();
4240 SDValue Shift = DAG.getNode(
4241 ISD::SRA, DL, VT, LHS,
4242 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4243 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4244 AddToWorkList(Shift.getNode());
4245 AddToWorkList(Add.getNode());
4246 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4253 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4254 SDValue N0 = N->getOperand(0);
4255 SDValue N1 = N->getOperand(1);
4256 SDValue N2 = N->getOperand(2);
4257 SDValue N3 = N->getOperand(3);
4258 SDValue N4 = N->getOperand(4);
4259 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4261 // fold select_cc lhs, rhs, x, x, cc -> x
4265 // Determine if the condition we're dealing with is constant
4266 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4267 N0, N1, CC, SDLoc(N), false);
4268 if (SCC.getNode()) {
4269 AddToWorkList(SCC.getNode());
4271 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4272 if (!SCCC->isNullValue())
4273 return N2; // cond always true -> true val
4275 return N3; // cond always false -> false val
4278 // Fold to a simpler select_cc
4279 if (SCC.getOpcode() == ISD::SETCC)
4280 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4281 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4285 // If we can fold this based on the true/false value, do so.
4286 if (SimplifySelectOps(N, N2, N3))
4287 return SDValue(N, 0); // Don't revisit N.
4289 // fold select_cc into other things, such as min/max/abs
4290 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4293 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4294 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4295 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4299 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4300 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4301 // transformation. Returns true if extension are possible and the above
4302 // mentioned transformation is profitable.
4303 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4305 SmallVector<SDNode*, 4> &ExtendNodes,
4306 const TargetLowering &TLI) {
4307 bool HasCopyToRegUses = false;
4308 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4309 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4310 UE = N0.getNode()->use_end();
4315 if (UI.getUse().getResNo() != N0.getResNo())
4317 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4318 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4319 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4320 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4321 // Sign bits will be lost after a zext.
4324 for (unsigned i = 0; i != 2; ++i) {
4325 SDValue UseOp = User->getOperand(i);
4328 if (!isa<ConstantSDNode>(UseOp))
4333 ExtendNodes.push_back(User);
4336 // If truncates aren't free and there are users we can't
4337 // extend, it isn't worthwhile.
4340 // Remember if this value is live-out.
4341 if (User->getOpcode() == ISD::CopyToReg)
4342 HasCopyToRegUses = true;
4345 if (HasCopyToRegUses) {
4346 bool BothLiveOut = false;
4347 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4349 SDUse &Use = UI.getUse();
4350 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4356 // Both unextended and extended values are live out. There had better be
4357 // a good reason for the transformation.
4358 return ExtendNodes.size();
4363 void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
4364 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4365 ISD::NodeType ExtType) {
4366 // Extend SetCC uses if necessary.
4367 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4368 SDNode *SetCC = SetCCs[i];
4369 SmallVector<SDValue, 4> Ops;
4371 for (unsigned j = 0; j != 2; ++j) {
4372 SDValue SOp = SetCC->getOperand(j);
4374 Ops.push_back(ExtLoad);
4376 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4379 Ops.push_back(SetCC->getOperand(2));
4380 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4381 &Ops[0], Ops.size()));
4385 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4386 SDValue N0 = N->getOperand(0);
4387 EVT VT = N->getValueType(0);
4389 // fold (sext c1) -> c1
4390 if (isa<ConstantSDNode>(N0))
4391 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4393 // fold (sext (sext x)) -> (sext x)
4394 // fold (sext (aext x)) -> (sext x)
4395 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4396 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4399 if (N0.getOpcode() == ISD::TRUNCATE) {
4400 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4401 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4402 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4403 if (NarrowLoad.getNode()) {
4404 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4405 if (NarrowLoad.getNode() != N0.getNode()) {
4406 CombineTo(N0.getNode(), NarrowLoad);
4407 // CombineTo deleted the truncate, if needed, but not what's under it.
4410 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4413 // See if the value being truncated is already sign extended. If so, just
4414 // eliminate the trunc/sext pair.
4415 SDValue Op = N0.getOperand(0);
4416 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4417 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4418 unsigned DestBits = VT.getScalarType().getSizeInBits();
4419 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4421 if (OpBits == DestBits) {
4422 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4423 // bits, it is already ready.
4424 if (NumSignBits > DestBits-MidBits)
4426 } else if (OpBits < DestBits) {
4427 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4428 // bits, just sext from i32.
4429 if (NumSignBits > OpBits-MidBits)
4430 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4432 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4433 // bits, just truncate to i32.
4434 if (NumSignBits > OpBits-MidBits)
4435 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4438 // fold (sext (truncate x)) -> (sextinreg x).
4439 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4440 N0.getValueType())) {
4441 if (OpBits < DestBits)
4442 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4443 else if (OpBits > DestBits)
4444 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4445 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4446 DAG.getValueType(N0.getValueType()));
4450 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4451 // None of the supported targets knows how to perform load and sign extend
4452 // on vectors in one instruction. We only perform this transformation on
4454 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4455 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4456 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4457 bool DoXform = true;
4458 SmallVector<SDNode*, 4> SetCCs;
4459 if (!N0.hasOneUse())
4460 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4462 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4463 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4465 LN0->getBasePtr(), LN0->getPointerInfo(),
4467 LN0->isVolatile(), LN0->isNonTemporal(),
4468 LN0->getAlignment());
4469 CombineTo(N, ExtLoad);
4470 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4471 N0.getValueType(), ExtLoad);
4472 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4473 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4475 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4479 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4480 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4481 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4482 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4483 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4484 EVT MemVT = LN0->getMemoryVT();
4485 if ((!LegalOperations && !LN0->isVolatile()) ||
4486 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4487 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4489 LN0->getBasePtr(), LN0->getPointerInfo(),
4491 LN0->isVolatile(), LN0->isNonTemporal(),
4492 LN0->getAlignment());
4493 CombineTo(N, ExtLoad);
4494 CombineTo(N0.getNode(),
4495 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4496 N0.getValueType(), ExtLoad),
4497 ExtLoad.getValue(1));
4498 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4502 // fold (sext (and/or/xor (load x), cst)) ->
4503 // (and/or/xor (sextload x), (sext cst))
4504 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4505 N0.getOpcode() == ISD::XOR) &&
4506 isa<LoadSDNode>(N0.getOperand(0)) &&
4507 N0.getOperand(1).getOpcode() == ISD::Constant &&
4508 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4509 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4510 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4511 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4512 bool DoXform = true;
4513 SmallVector<SDNode*, 4> SetCCs;
4514 if (!N0.hasOneUse())
4515 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4518 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4519 LN0->getChain(), LN0->getBasePtr(),
4520 LN0->getPointerInfo(),
4523 LN0->isNonTemporal(),
4524 LN0->getAlignment());
4525 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4526 Mask = Mask.sext(VT.getSizeInBits());
4527 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4528 ExtLoad, DAG.getConstant(Mask, VT));
4529 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4530 SDLoc(N0.getOperand(0)),
4531 N0.getOperand(0).getValueType(), ExtLoad);
4533 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4534 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4536 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4541 if (N0.getOpcode() == ISD::SETCC) {
4542 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4543 // Only do this before legalize for now.
4544 if (VT.isVector() && !LegalOperations &&
4545 TLI.getBooleanContents(true) ==
4546 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4547 EVT N0VT = N0.getOperand(0).getValueType();
4548 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4549 // of the same size as the compared operands. Only optimize sext(setcc())
4550 // if this is the case.
4551 EVT SVT = getSetCCResultType(N0VT);
4553 // We know that the # elements of the results is the same as the
4554 // # elements of the compare (and the # elements of the compare result
4555 // for that matter). Check to see that they are the same size. If so,
4556 // we know that the element size of the sext'd result matches the
4557 // element size of the compare operands.
4558 if (VT.getSizeInBits() == SVT.getSizeInBits())
4559 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4561 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4563 // If the desired elements are smaller or larger than the source
4564 // elements we can use a matching integer vector type and then
4565 // truncate/sign extend
4566 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4567 if (SVT == MatchingVectorType) {
4568 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4569 N0.getOperand(0), N0.getOperand(1),
4570 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4571 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4575 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4576 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4578 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4580 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4581 NegOne, DAG.getConstant(0, VT),
4582 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4583 if (SCC.getNode()) return SCC;
4584 if (!VT.isVector() &&
4585 (!LegalOperations ||
4586 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4587 return DAG.getSelect(SDLoc(N), VT,
4588 DAG.getSetCC(SDLoc(N),
4589 getSetCCResultType(VT),
4590 N0.getOperand(0), N0.getOperand(1),
4591 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4592 NegOne, DAG.getConstant(0, VT));
4596 // fold (sext x) -> (zext x) if the sign bit is known zero.
4597 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4598 DAG.SignBitIsZero(N0))
4599 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4604 // isTruncateOf - If N is a truncate of some other value, return true, record
4605 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4606 // This function computes KnownZero to avoid a duplicated call to
4607 // ComputeMaskedBits in the caller.
4608 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4611 if (N->getOpcode() == ISD::TRUNCATE) {
4612 Op = N->getOperand(0);
4613 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4617 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4618 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4621 SDValue Op0 = N->getOperand(0);
4622 SDValue Op1 = N->getOperand(1);
4623 assert(Op0.getValueType() == Op1.getValueType());
4625 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4626 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4627 if (COp0 && COp0->isNullValue())
4629 else if (COp1 && COp1->isNullValue())
4634 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4636 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4642 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4643 SDValue N0 = N->getOperand(0);
4644 EVT VT = N->getValueType(0);
4646 // fold (zext c1) -> c1
4647 if (isa<ConstantSDNode>(N0))
4648 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4649 // fold (zext (zext x)) -> (zext x)
4650 // fold (zext (aext x)) -> (zext x)
4651 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4652 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4655 // fold (zext (truncate x)) -> (zext x) or
4656 // (zext (truncate x)) -> (truncate x)
4657 // This is valid when the truncated bits of x are already zero.
4658 // FIXME: We should extend this to work for vectors too.
4661 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4662 APInt TruncatedBits =
4663 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4664 APInt(Op.getValueSizeInBits(), 0) :
4665 APInt::getBitsSet(Op.getValueSizeInBits(),
4666 N0.getValueSizeInBits(),
4667 std::min(Op.getValueSizeInBits(),
4668 VT.getSizeInBits()));
4669 if (TruncatedBits == (KnownZero & TruncatedBits)) {
4670 if (VT.bitsGT(Op.getValueType()))
4671 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4672 if (VT.bitsLT(Op.getValueType()))
4673 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4679 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4680 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4681 if (N0.getOpcode() == ISD::TRUNCATE) {
4682 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4683 if (NarrowLoad.getNode()) {
4684 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4685 if (NarrowLoad.getNode() != N0.getNode()) {
4686 CombineTo(N0.getNode(), NarrowLoad);
4687 // CombineTo deleted the truncate, if needed, but not what's under it.
4690 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4694 // fold (zext (truncate x)) -> (and x, mask)
4695 if (N0.getOpcode() == ISD::TRUNCATE &&
4696 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4698 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4699 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4700 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4701 if (NarrowLoad.getNode()) {
4702 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4703 if (NarrowLoad.getNode() != N0.getNode()) {
4704 CombineTo(N0.getNode(), NarrowLoad);
4705 // CombineTo deleted the truncate, if needed, but not what's under it.
4708 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4711 SDValue Op = N0.getOperand(0);
4712 if (Op.getValueType().bitsLT(VT)) {
4713 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4714 AddToWorkList(Op.getNode());
4715 } else if (Op.getValueType().bitsGT(VT)) {
4716 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4717 AddToWorkList(Op.getNode());
4719 return DAG.getZeroExtendInReg(Op, SDLoc(N),
4720 N0.getValueType().getScalarType());
4723 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4724 // if either of the casts is not free.
4725 if (N0.getOpcode() == ISD::AND &&
4726 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4727 N0.getOperand(1).getOpcode() == ISD::Constant &&
4728 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4729 N0.getValueType()) ||
4730 !TLI.isZExtFree(N0.getValueType(), VT))) {
4731 SDValue X = N0.getOperand(0).getOperand(0);
4732 if (X.getValueType().bitsLT(VT)) {
4733 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4734 } else if (X.getValueType().bitsGT(VT)) {
4735 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4737 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4738 Mask = Mask.zext(VT.getSizeInBits());
4739 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4740 X, DAG.getConstant(Mask, VT));
4743 // fold (zext (load x)) -> (zext (truncate (zextload x)))
4744 // None of the supported targets knows how to perform load and vector_zext
4745 // on vectors in one instruction. We only perform this transformation on
4747 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4748 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4749 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4750 bool DoXform = true;
4751 SmallVector<SDNode*, 4> SetCCs;
4752 if (!N0.hasOneUse())
4753 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4755 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4756 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4758 LN0->getBasePtr(), LN0->getPointerInfo(),
4760 LN0->isVolatile(), LN0->isNonTemporal(),
4761 LN0->getAlignment());
4762 CombineTo(N, ExtLoad);
4763 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4764 N0.getValueType(), ExtLoad);
4765 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4767 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4769 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4773 // fold (zext (and/or/xor (load x), cst)) ->
4774 // (and/or/xor (zextload x), (zext cst))
4775 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4776 N0.getOpcode() == ISD::XOR) &&
4777 isa<LoadSDNode>(N0.getOperand(0)) &&
4778 N0.getOperand(1).getOpcode() == ISD::Constant &&
4779 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4780 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4781 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4782 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4783 bool DoXform = true;
4784 SmallVector<SDNode*, 4> SetCCs;
4785 if (!N0.hasOneUse())
4786 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4789 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4790 LN0->getChain(), LN0->getBasePtr(),
4791 LN0->getPointerInfo(),
4794 LN0->isNonTemporal(),
4795 LN0->getAlignment());
4796 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4797 Mask = Mask.zext(VT.getSizeInBits());
4798 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4799 ExtLoad, DAG.getConstant(Mask, VT));
4800 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4801 SDLoc(N0.getOperand(0)),
4802 N0.getOperand(0).getValueType(), ExtLoad);
4804 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4805 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4807 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4812 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4813 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4814 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4815 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4816 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4817 EVT MemVT = LN0->getMemoryVT();
4818 if ((!LegalOperations && !LN0->isVolatile()) ||
4819 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4820 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4822 LN0->getBasePtr(), LN0->getPointerInfo(),
4824 LN0->isVolatile(), LN0->isNonTemporal(),
4825 LN0->getAlignment());
4826 CombineTo(N, ExtLoad);
4827 CombineTo(N0.getNode(),
4828 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
4830 ExtLoad.getValue(1));
4831 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4835 if (N0.getOpcode() == ISD::SETCC) {
4836 if (!LegalOperations && VT.isVector()) {
4837 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4838 // Only do this before legalize for now.
4839 EVT N0VT = N0.getOperand(0).getValueType();
4840 EVT EltVT = VT.getVectorElementType();
4841 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4842 DAG.getConstant(1, EltVT));
4843 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4844 // We know that the # elements of the results is the same as the
4845 // # elements of the compare (and the # elements of the compare result
4846 // for that matter). Check to see that they are the same size. If so,
4847 // we know that the element size of the sext'd result matches the
4848 // element size of the compare operands.
4849 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4850 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4852 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4853 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4854 &OneOps[0], OneOps.size()));
4856 // If the desired elements are smaller or larger than the source
4857 // elements we can use a matching integer vector type and then
4858 // truncate/sign extend
4859 EVT MatchingElementType =
4860 EVT::getIntegerVT(*DAG.getContext(),
4861 N0VT.getScalarType().getSizeInBits());
4862 EVT MatchingVectorType =
4863 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4864 N0VT.getVectorNumElements());
4866 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
4868 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4869 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4870 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
4871 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4872 &OneOps[0], OneOps.size()));
4875 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4877 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4878 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4879 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4880 if (SCC.getNode()) return SCC;
4883 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4884 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4885 isa<ConstantSDNode>(N0.getOperand(1)) &&
4886 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4888 SDValue ShAmt = N0.getOperand(1);
4889 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4890 if (N0.getOpcode() == ISD::SHL) {
4891 SDValue InnerZExt = N0.getOperand(0);
4892 // If the original shl may be shifting out bits, do not perform this
4894 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4895 InnerZExt.getOperand(0).getValueType().getSizeInBits();
4896 if (ShAmtVal > KnownZeroBits)
4902 // Ensure that the shift amount is wide enough for the shifted value.
4903 if (VT.getSizeInBits() >= 256)
4904 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4906 return DAG.getNode(N0.getOpcode(), DL, VT,
4907 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4914 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4915 SDValue N0 = N->getOperand(0);
4916 EVT VT = N->getValueType(0);
4918 // fold (aext c1) -> c1
4919 if (isa<ConstantSDNode>(N0))
4920 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
4921 // fold (aext (aext x)) -> (aext x)
4922 // fold (aext (zext x)) -> (zext x)
4923 // fold (aext (sext x)) -> (sext x)
4924 if (N0.getOpcode() == ISD::ANY_EXTEND ||
4925 N0.getOpcode() == ISD::ZERO_EXTEND ||
4926 N0.getOpcode() == ISD::SIGN_EXTEND)
4927 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
4929 // fold (aext (truncate (load x))) -> (aext (smaller load x))
4930 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4931 if (N0.getOpcode() == ISD::TRUNCATE) {
4932 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4933 if (NarrowLoad.getNode()) {
4934 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4935 if (NarrowLoad.getNode() != N0.getNode()) {
4936 CombineTo(N0.getNode(), NarrowLoad);
4937 // CombineTo deleted the truncate, if needed, but not what's under it.
4940 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4944 // fold (aext (truncate x))
4945 if (N0.getOpcode() == ISD::TRUNCATE) {
4946 SDValue TruncOp = N0.getOperand(0);
4947 if (TruncOp.getValueType() == VT)
4948 return TruncOp; // x iff x size == zext size.
4949 if (TruncOp.getValueType().bitsGT(VT))
4950 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
4951 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
4954 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4955 // if the trunc is not free.
4956 if (N0.getOpcode() == ISD::AND &&
4957 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4958 N0.getOperand(1).getOpcode() == ISD::Constant &&
4959 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4960 N0.getValueType())) {
4961 SDValue X = N0.getOperand(0).getOperand(0);
4962 if (X.getValueType().bitsLT(VT)) {
4963 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
4964 } else if (X.getValueType().bitsGT(VT)) {
4965 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
4967 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4968 Mask = Mask.zext(VT.getSizeInBits());
4969 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4970 X, DAG.getConstant(Mask, VT));
4973 // fold (aext (load x)) -> (aext (truncate (extload x)))
4974 // None of the supported targets knows how to perform load and any_ext
4975 // on vectors in one instruction. We only perform this transformation on
4977 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4978 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4979 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4980 bool DoXform = true;
4981 SmallVector<SDNode*, 4> SetCCs;
4982 if (!N0.hasOneUse())
4983 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4985 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4986 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
4988 LN0->getBasePtr(), LN0->getPointerInfo(),
4990 LN0->isVolatile(), LN0->isNonTemporal(),
4991 LN0->getAlignment());
4992 CombineTo(N, ExtLoad);
4993 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4994 N0.getValueType(), ExtLoad);
4995 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4996 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4998 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5002 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5003 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5004 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5005 if (N0.getOpcode() == ISD::LOAD &&
5006 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5008 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5009 EVT MemVT = LN0->getMemoryVT();
5010 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5011 VT, LN0->getChain(), LN0->getBasePtr(),
5012 LN0->getPointerInfo(), MemVT,
5013 LN0->isVolatile(), LN0->isNonTemporal(),
5014 LN0->getAlignment());
5015 CombineTo(N, ExtLoad);
5016 CombineTo(N0.getNode(),
5017 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5018 N0.getValueType(), ExtLoad),
5019 ExtLoad.getValue(1));
5020 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5023 if (N0.getOpcode() == ISD::SETCC) {
5024 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5025 // Only do this before legalize for now.
5026 if (VT.isVector() && !LegalOperations) {
5027 EVT N0VT = N0.getOperand(0).getValueType();
5028 // We know that the # elements of the results is the same as the
5029 // # elements of the compare (and the # elements of the compare result
5030 // for that matter). Check to see that they are the same size. If so,
5031 // we know that the element size of the sext'd result matches the
5032 // element size of the compare operands.
5033 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5034 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5036 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5037 // If the desired elements are smaller or larger than the source
5038 // elements we can use a matching integer vector type and then
5039 // truncate/sign extend
5041 EVT MatchingElementType =
5042 EVT::getIntegerVT(*DAG.getContext(),
5043 N0VT.getScalarType().getSizeInBits());
5044 EVT MatchingVectorType =
5045 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5046 N0VT.getVectorNumElements());
5048 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5050 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5051 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5055 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5057 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5058 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5059 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5067 /// GetDemandedBits - See if the specified operand can be simplified with the
5068 /// knowledge that only the bits specified by Mask are used. If so, return the
5069 /// simpler operand, otherwise return a null SDValue.
5070 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5071 switch (V.getOpcode()) {
5073 case ISD::Constant: {
5074 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5075 assert(CV != 0 && "Const value should be ConstSDNode.");
5076 const APInt &CVal = CV->getAPIntValue();
5077 APInt NewVal = CVal & Mask;
5079 return DAG.getConstant(NewVal, V.getValueType());
5084 // If the LHS or RHS don't contribute bits to the or, drop them.
5085 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5086 return V.getOperand(1);
5087 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5088 return V.getOperand(0);
5091 // Only look at single-use SRLs.
5092 if (!V.getNode()->hasOneUse())
5094 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5095 // See if we can recursively simplify the LHS.
5096 unsigned Amt = RHSC->getZExtValue();
5098 // Watch out for shift count overflow though.
5099 if (Amt >= Mask.getBitWidth()) break;
5100 APInt NewMask = Mask << Amt;
5101 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5102 if (SimplifyLHS.getNode())
5103 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5104 SimplifyLHS, V.getOperand(1));
5110 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5111 /// bits and then truncated to a narrower type and where N is a multiple
5112 /// of number of bits of the narrower type, transform it to a narrower load
5113 /// from address + N / num of bits of new type. If the result is to be
5114 /// extended, also fold the extension to form a extending load.
5115 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5116 unsigned Opc = N->getOpcode();
5118 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5119 SDValue N0 = N->getOperand(0);
5120 EVT VT = N->getValueType(0);
5123 // This transformation isn't valid for vector loads.
5127 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5129 if (Opc == ISD::SIGN_EXTEND_INREG) {
5130 ExtType = ISD::SEXTLOAD;
5131 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5132 } else if (Opc == ISD::SRL) {
5133 // Another special-case: SRL is basically zero-extending a narrower value.
5134 ExtType = ISD::ZEXTLOAD;
5136 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5137 if (!N01) return SDValue();
5138 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5139 VT.getSizeInBits() - N01->getZExtValue());
5141 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5144 unsigned EVTBits = ExtVT.getSizeInBits();
5146 // Do not generate loads of non-round integer types since these can
5147 // be expensive (and would be wrong if the type is not byte sized).
5148 if (!ExtVT.isRound())
5152 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5153 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5154 ShAmt = N01->getZExtValue();
5155 // Is the shift amount a multiple of size of VT?
5156 if ((ShAmt & (EVTBits-1)) == 0) {
5157 N0 = N0.getOperand(0);
5158 // Is the load width a multiple of size of VT?
5159 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5163 // At this point, we must have a load or else we can't do the transform.
5164 if (!isa<LoadSDNode>(N0)) return SDValue();
5166 // Because a SRL must be assumed to *need* to zero-extend the high bits
5167 // (as opposed to anyext the high bits), we can't combine the zextload
5168 // lowering of SRL and an sextload.
5169 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5172 // If the shift amount is larger than the input type then we're not
5173 // accessing any of the loaded bytes. If the load was a zextload/extload
5174 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5175 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5180 // If the load is shifted left (and the result isn't shifted back right),
5181 // we can fold the truncate through the shift.
5182 unsigned ShLeftAmt = 0;
5183 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5184 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5185 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5186 ShLeftAmt = N01->getZExtValue();
5187 N0 = N0.getOperand(0);
5191 // If we haven't found a load, we can't narrow it. Don't transform one with
5192 // multiple uses, this would require adding a new load.
5193 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5196 // Don't change the width of a volatile load.
5197 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5198 if (LN0->isVolatile())
5201 // Verify that we are actually reducing a load width here.
5202 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5205 // For the transform to be legal, the load must produce only two values
5206 // (the value loaded and the chain). Don't transform a pre-increment
5207 // load, for example, which produces an extra value. Otherwise the
5208 // transformation is not equivalent, and the downstream logic to replace
5209 // uses gets things wrong.
5210 if (LN0->getNumValues() > 2)
5213 // If the load that we're shrinking is an extload and we're not just
5214 // discarding the extension we can't simply shrink the load. Bail.
5215 // TODO: It would be possible to merge the extensions in some cases.
5216 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5217 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5220 EVT PtrType = N0.getOperand(1).getValueType();
5222 if (PtrType == MVT::Untyped || PtrType.isExtended())
5223 // It's not possible to generate a constant of extended or untyped type.
5226 // For big endian targets, we need to adjust the offset to the pointer to
5227 // load the correct bytes.
5228 if (TLI.isBigEndian()) {
5229 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5230 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5231 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5234 uint64_t PtrOff = ShAmt / 8;
5235 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5236 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5237 PtrType, LN0->getBasePtr(),
5238 DAG.getConstant(PtrOff, PtrType));
5239 AddToWorkList(NewPtr.getNode());
5242 if (ExtType == ISD::NON_EXTLOAD)
5243 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5244 LN0->getPointerInfo().getWithOffset(PtrOff),
5245 LN0->isVolatile(), LN0->isNonTemporal(),
5246 LN0->isInvariant(), NewAlign);
5248 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5249 LN0->getPointerInfo().getWithOffset(PtrOff),
5250 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5253 // Replace the old load's chain with the new load's chain.
5254 WorkListRemover DeadNodes(*this);
5255 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5257 // Shift the result left, if we've swallowed a left shift.
5258 SDValue Result = Load;
5259 if (ShLeftAmt != 0) {
5260 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5261 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5263 // If the shift amount is as large as the result size (but, presumably,
5264 // no larger than the source) then the useful bits of the result are
5265 // zero; we can't simply return the shortened shift, because the result
5266 // of that operation is undefined.
5267 if (ShLeftAmt >= VT.getSizeInBits())
5268 Result = DAG.getConstant(0, VT);
5270 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5271 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5274 // Return the new loaded value.
5278 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5279 SDValue N0 = N->getOperand(0);
5280 SDValue N1 = N->getOperand(1);
5281 EVT VT = N->getValueType(0);
5282 EVT EVT = cast<VTSDNode>(N1)->getVT();
5283 unsigned VTBits = VT.getScalarType().getSizeInBits();
5284 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5286 // fold (sext_in_reg c1) -> c1
5287 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5288 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5290 // If the input is already sign extended, just drop the extension.
5291 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5294 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5295 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5296 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5297 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5298 N0.getOperand(0), N1);
5300 // fold (sext_in_reg (sext x)) -> (sext x)
5301 // fold (sext_in_reg (aext x)) -> (sext x)
5302 // if x is small enough.
5303 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5304 SDValue N00 = N0.getOperand(0);
5305 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5306 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5307 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5310 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5311 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5312 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5314 // fold operands of sext_in_reg based on knowledge that the top bits are not
5316 if (SimplifyDemandedBits(SDValue(N, 0)))
5317 return SDValue(N, 0);
5319 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5320 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5321 SDValue NarrowLoad = ReduceLoadWidth(N);
5322 if (NarrowLoad.getNode())
5325 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5326 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5327 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5328 if (N0.getOpcode() == ISD::SRL) {
5329 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5330 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5331 // We can turn this into an SRA iff the input to the SRL is already sign
5333 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5334 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5335 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5336 N0.getOperand(0), N0.getOperand(1));
5340 // fold (sext_inreg (extload x)) -> (sextload x)
5341 if (ISD::isEXTLoad(N0.getNode()) &&
5342 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5343 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5344 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5345 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5346 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5347 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5349 LN0->getBasePtr(), LN0->getPointerInfo(),
5351 LN0->isVolatile(), LN0->isNonTemporal(),
5352 LN0->getAlignment());
5353 CombineTo(N, ExtLoad);
5354 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5355 AddToWorkList(ExtLoad.getNode());
5356 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5358 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5359 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5361 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5362 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5363 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5364 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5365 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5367 LN0->getBasePtr(), LN0->getPointerInfo(),
5369 LN0->isVolatile(), LN0->isNonTemporal(),
5370 LN0->getAlignment());
5371 CombineTo(N, ExtLoad);
5372 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5373 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5376 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5377 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5378 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5379 N0.getOperand(1), false);
5380 if (BSwap.getNode() != 0)
5381 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5388 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5389 SDValue N0 = N->getOperand(0);
5390 EVT VT = N->getValueType(0);
5391 bool isLE = TLI.isLittleEndian();
5394 if (N0.getValueType() == N->getValueType(0))
5396 // fold (truncate c1) -> c1
5397 if (isa<ConstantSDNode>(N0))
5398 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5399 // fold (truncate (truncate x)) -> (truncate x)
5400 if (N0.getOpcode() == ISD::TRUNCATE)
5401 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5402 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5403 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5404 N0.getOpcode() == ISD::SIGN_EXTEND ||
5405 N0.getOpcode() == ISD::ANY_EXTEND) {
5406 if (N0.getOperand(0).getValueType().bitsLT(VT))
5407 // if the source is smaller than the dest, we still need an extend
5408 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5410 if (N0.getOperand(0).getValueType().bitsGT(VT))
5411 // if the source is larger than the dest, than we just need the truncate
5412 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5413 // if the source and dest are the same type, we can drop both the extend
5414 // and the truncate.
5415 return N0.getOperand(0);
5418 // Fold extract-and-trunc into a narrow extract. For example:
5419 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5420 // i32 y = TRUNCATE(i64 x)
5422 // v16i8 b = BITCAST (v2i64 val)
5423 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5425 // Note: We only run this optimization after type legalization (which often
5426 // creates this pattern) and before operation legalization after which
5427 // we need to be more careful about the vector instructions that we generate.
5428 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5429 LegalTypes && !LegalOperations && N0->hasOneUse()) {
5431 EVT VecTy = N0.getOperand(0).getValueType();
5432 EVT ExTy = N0.getValueType();
5433 EVT TrTy = N->getValueType(0);
5435 unsigned NumElem = VecTy.getVectorNumElements();
5436 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5438 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5439 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5441 SDValue EltNo = N0->getOperand(1);
5442 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5443 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5444 EVT IndexTy = N0->getOperand(1).getValueType();
5445 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5447 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5448 NVT, N0.getOperand(0));
5450 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5452 DAG.getConstant(Index, IndexTy));
5456 // Fold a series of buildvector, bitcast, and truncate if possible.
5458 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5459 // (2xi32 (buildvector x, y)).
5460 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5461 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5462 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5463 N0.getOperand(0).hasOneUse()) {
5465 SDValue BuildVect = N0.getOperand(0);
5466 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5467 EVT TruncVecEltTy = VT.getVectorElementType();
5469 // Check that the element types match.
5470 if (BuildVectEltTy == TruncVecEltTy) {
5471 // Now we only need to compute the offset of the truncated elements.
5472 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5473 unsigned TruncVecNumElts = VT.getVectorNumElements();
5474 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5476 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5477 "Invalid number of elements");
5479 SmallVector<SDValue, 8> Opnds;
5480 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5481 Opnds.push_back(BuildVect.getOperand(i));
5483 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5488 // See if we can simplify the input to this truncate through knowledge that
5489 // only the low bits are being used.
5490 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5491 // Currently we only perform this optimization on scalars because vectors
5492 // may have different active low bits.
5493 if (!VT.isVector()) {
5495 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5496 VT.getSizeInBits()));
5497 if (Shorter.getNode())
5498 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5500 // fold (truncate (load x)) -> (smaller load x)
5501 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5502 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5503 SDValue Reduced = ReduceLoadWidth(N);
5504 if (Reduced.getNode())
5507 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5508 // where ... are all 'undef'.
5509 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5510 SmallVector<EVT, 8> VTs;
5513 unsigned NumDefs = 0;
5515 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5516 SDValue X = N0.getOperand(i);
5517 if (X.getOpcode() != ISD::UNDEF) {
5522 // Stop if more than one members are non-undef.
5525 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5526 VT.getVectorElementType(),
5527 X.getValueType().getVectorNumElements()));
5531 return DAG.getUNDEF(VT);
5534 assert(V.getNode() && "The single defined operand is empty!");
5535 SmallVector<SDValue, 8> Opnds;
5536 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5538 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5541 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5542 AddToWorkList(NV.getNode());
5543 Opnds.push_back(NV);
5545 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5546 &Opnds[0], Opnds.size());
5550 // Simplify the operands using demanded-bits information.
5551 if (!VT.isVector() &&
5552 SimplifyDemandedBits(SDValue(N, 0)))
5553 return SDValue(N, 0);
5558 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5559 SDValue Elt = N->getOperand(i);
5560 if (Elt.getOpcode() != ISD::MERGE_VALUES)
5561 return Elt.getNode();
5562 return Elt.getOperand(Elt.getResNo()).getNode();
5565 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5566 /// if load locations are consecutive.
5567 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5568 assert(N->getOpcode() == ISD::BUILD_PAIR);
5570 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5571 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5572 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5573 LD1->getPointerInfo().getAddrSpace() !=
5574 LD2->getPointerInfo().getAddrSpace())
5576 EVT LD1VT = LD1->getValueType(0);
5578 if (ISD::isNON_EXTLoad(LD2) &&
5580 // If both are volatile this would reduce the number of volatile loads.
5581 // If one is volatile it might be ok, but play conservative and bail out.
5582 !LD1->isVolatile() &&
5583 !LD2->isVolatile() &&
5584 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5585 unsigned Align = LD1->getAlignment();
5586 unsigned NewAlign = TLI.getDataLayout()->
5587 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5589 if (NewAlign <= Align &&
5590 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5591 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5592 LD1->getBasePtr(), LD1->getPointerInfo(),
5593 false, false, false, Align);
5599 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5600 SDValue N0 = N->getOperand(0);
5601 EVT VT = N->getValueType(0);
5603 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5604 // Only do this before legalize, since afterward the target may be depending
5605 // on the bitconvert.
5606 // First check to see if this is all constant.
5608 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5610 bool isSimple = true;
5611 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5612 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5613 N0.getOperand(i).getOpcode() != ISD::Constant &&
5614 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5619 EVT DestEltVT = N->getValueType(0).getVectorElementType();
5620 assert(!DestEltVT.isVector() &&
5621 "Element type of vector ValueType must not be vector!");
5623 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5626 // If the input is a constant, let getNode fold it.
5627 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5628 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5629 if (Res.getNode() != N) {
5630 if (!LegalOperations ||
5631 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5634 // Folding it resulted in an illegal node, and it's too late to
5635 // do that. Clean up the old node and forego the transformation.
5636 // Ideally this won't happen very often, because instcombine
5637 // and the earlier dagcombine runs (where illegal nodes are
5638 // permitted) should have folded most of them already.
5639 DAG.DeleteNode(Res.getNode());
5643 // (conv (conv x, t1), t2) -> (conv x, t2)
5644 if (N0.getOpcode() == ISD::BITCAST)
5645 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5648 // fold (conv (load x)) -> (load (conv*)x)
5649 // If the resultant load doesn't need a higher alignment than the original!
5650 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5651 // Do not change the width of a volatile load.
5652 !cast<LoadSDNode>(N0)->isVolatile() &&
5653 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5654 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5655 unsigned Align = TLI.getDataLayout()->
5656 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5657 unsigned OrigAlign = LN0->getAlignment();
5659 if (Align <= OrigAlign) {
5660 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5661 LN0->getBasePtr(), LN0->getPointerInfo(),
5662 LN0->isVolatile(), LN0->isNonTemporal(),
5663 LN0->isInvariant(), OrigAlign);
5665 CombineTo(N0.getNode(),
5666 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5667 N0.getValueType(), Load),
5673 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5674 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5675 // This often reduces constant pool loads.
5676 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(VT)) ||
5677 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(VT))) &&
5678 N0.getNode()->hasOneUse() && VT.isInteger() &&
5679 !VT.isVector() && !N0.getValueType().isVector()) {
5680 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5682 AddToWorkList(NewConv.getNode());
5684 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5685 if (N0.getOpcode() == ISD::FNEG)
5686 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5687 NewConv, DAG.getConstant(SignBit, VT));
5688 assert(N0.getOpcode() == ISD::FABS);
5689 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5690 NewConv, DAG.getConstant(~SignBit, VT));
5693 // fold (bitconvert (fcopysign cst, x)) ->
5694 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5695 // Note that we don't handle (copysign x, cst) because this can always be
5696 // folded to an fneg or fabs.
5697 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5698 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5699 VT.isInteger() && !VT.isVector()) {
5700 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5701 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5702 if (isTypeLegal(IntXVT)) {
5703 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5704 IntXVT, N0.getOperand(1));
5705 AddToWorkList(X.getNode());
5707 // If X has a different width than the result/lhs, sext it or truncate it.
5708 unsigned VTWidth = VT.getSizeInBits();
5709 if (OrigXWidth < VTWidth) {
5710 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5711 AddToWorkList(X.getNode());
5712 } else if (OrigXWidth > VTWidth) {
5713 // To get the sign bit in the right place, we have to shift it right
5714 // before truncating.
5715 X = DAG.getNode(ISD::SRL, SDLoc(X),
5716 X.getValueType(), X,
5717 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5718 AddToWorkList(X.getNode());
5719 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5720 AddToWorkList(X.getNode());
5723 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5724 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5725 X, DAG.getConstant(SignBit, VT));
5726 AddToWorkList(X.getNode());
5728 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5729 VT, N0.getOperand(0));
5730 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5731 Cst, DAG.getConstant(~SignBit, VT));
5732 AddToWorkList(Cst.getNode());
5734 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5738 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5739 if (N0.getOpcode() == ISD::BUILD_PAIR) {
5740 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5741 if (CombineLD.getNode())
5748 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5749 EVT VT = N->getValueType(0);
5750 return CombineConsecutiveLoads(N, VT);
5753 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5754 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
5755 /// destination element value type.
5756 SDValue DAGCombiner::
5757 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5758 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5760 // If this is already the right type, we're done.
5761 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5763 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5764 unsigned DstBitSize = DstEltVT.getSizeInBits();
5766 // If this is a conversion of N elements of one type to N elements of another
5767 // type, convert each element. This handles FP<->INT cases.
5768 if (SrcBitSize == DstBitSize) {
5769 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5770 BV->getValueType(0).getVectorNumElements());
5772 // Due to the FP element handling below calling this routine recursively,
5773 // we can end up with a scalar-to-vector node here.
5774 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5775 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5776 DAG.getNode(ISD::BITCAST, SDLoc(BV),
5777 DstEltVT, BV->getOperand(0)));
5779 SmallVector<SDValue, 8> Ops;
5780 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5781 SDValue Op = BV->getOperand(i);
5782 // If the vector element type is not legal, the BUILD_VECTOR operands
5783 // are promoted and implicitly truncated. Make that explicit here.
5784 if (Op.getValueType() != SrcEltVT)
5785 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5786 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5788 AddToWorkList(Ops.back().getNode());
5790 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5791 &Ops[0], Ops.size());
5794 // Otherwise, we're growing or shrinking the elements. To avoid having to
5795 // handle annoying details of growing/shrinking FP values, we convert them to
5797 if (SrcEltVT.isFloatingPoint()) {
5798 // Convert the input float vector to a int vector where the elements are the
5800 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5801 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5802 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5806 // Now we know the input is an integer vector. If the output is a FP type,
5807 // convert to integer first, then to FP of the right size.
5808 if (DstEltVT.isFloatingPoint()) {
5809 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5810 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5811 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5813 // Next, convert to FP elements of the same size.
5814 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5817 // Okay, we know the src/dst types are both integers of differing types.
5818 // Handling growing first.
5819 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5820 if (SrcBitSize < DstBitSize) {
5821 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5823 SmallVector<SDValue, 8> Ops;
5824 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5825 i += NumInputsPerOutput) {
5826 bool isLE = TLI.isLittleEndian();
5827 APInt NewBits = APInt(DstBitSize, 0);
5828 bool EltIsUndef = true;
5829 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5830 // Shift the previously computed bits over.
5831 NewBits <<= SrcBitSize;
5832 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5833 if (Op.getOpcode() == ISD::UNDEF) continue;
5836 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5837 zextOrTrunc(SrcBitSize).zext(DstBitSize);
5841 Ops.push_back(DAG.getUNDEF(DstEltVT));
5843 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5846 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5847 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5848 &Ops[0], Ops.size());
5851 // Finally, this must be the case where we are shrinking elements: each input
5852 // turns into multiple outputs.
5853 bool isS2V = ISD::isScalarToVector(BV);
5854 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5855 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5856 NumOutputsPerInput*BV->getNumOperands());
5857 SmallVector<SDValue, 8> Ops;
5859 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5860 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5861 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5862 Ops.push_back(DAG.getUNDEF(DstEltVT));
5866 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5867 getAPIntValue().zextOrTrunc(SrcBitSize);
5869 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5870 APInt ThisVal = OpVal.trunc(DstBitSize);
5871 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5872 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5873 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5874 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5876 OpVal = OpVal.lshr(DstBitSize);
5879 // For big endian targets, swap the order of the pieces of each element.
5880 if (TLI.isBigEndian())
5881 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5884 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5885 &Ops[0], Ops.size());
5888 SDValue DAGCombiner::visitFADD(SDNode *N) {
5889 SDValue N0 = N->getOperand(0);
5890 SDValue N1 = N->getOperand(1);
5891 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5892 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5893 EVT VT = N->getValueType(0);
5896 if (VT.isVector()) {
5897 SDValue FoldedVOp = SimplifyVBinOp(N);
5898 if (FoldedVOp.getNode()) return FoldedVOp;
5901 // fold (fadd c1, c2) -> c1 + c2
5903 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
5904 // canonicalize constant to RHS
5905 if (N0CFP && !N1CFP)
5906 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
5907 // fold (fadd A, 0) -> A
5908 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5909 N1CFP->getValueAPF().isZero())
5911 // fold (fadd A, (fneg B)) -> (fsub A, B)
5912 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5913 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5914 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
5915 GetNegatedExpression(N1, DAG, LegalOperations));
5916 // fold (fadd (fneg A), B) -> (fsub B, A)
5917 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5918 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5919 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
5920 GetNegatedExpression(N0, DAG, LegalOperations));
5922 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5923 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5924 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5925 isa<ConstantFPSDNode>(N0.getOperand(1)))
5926 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
5927 DAG.getNode(ISD::FADD, SDLoc(N), VT,
5928 N0.getOperand(1), N1));
5930 // No FP constant should be created after legalization as Instruction
5931 // Selection pass has hard time in dealing with FP constant.
5933 // We don't need test this condition for transformation like following, as
5934 // the DAG being transformed implies it is legal to take FP constant as
5937 // (fadd (fmul c, x), x) -> (fmul c+1, x)
5939 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
5941 // If allow, fold (fadd (fneg x), x) -> 0.0
5942 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5943 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
5944 return DAG.getConstantFP(0.0, VT);
5946 // If allow, fold (fadd x, (fneg x)) -> 0.0
5947 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5948 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
5949 return DAG.getConstantFP(0.0, VT);
5951 // In unsafe math mode, we can fold chains of FADD's of the same value
5952 // into multiplications. This transform is not safe in general because
5953 // we are reducing the number of rounding steps.
5954 if (DAG.getTarget().Options.UnsafeFPMath &&
5955 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
5957 if (N0.getOpcode() == ISD::FMUL) {
5958 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
5959 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
5961 // (fadd (fmul c, x), x) -> (fmul x, c+1)
5962 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
5963 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
5965 DAG.getConstantFP(1.0, VT));
5966 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
5970 // (fadd (fmul x, c), x) -> (fmul x, c+1)
5971 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
5972 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
5974 DAG.getConstantFP(1.0, VT));
5975 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
5979 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
5980 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
5981 N1.getOperand(0) == N1.getOperand(1) &&
5982 N0.getOperand(1) == N1.getOperand(0)) {
5983 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
5985 DAG.getConstantFP(2.0, VT));
5986 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
5987 N0.getOperand(1), NewCFP);
5990 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
5991 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
5992 N1.getOperand(0) == N1.getOperand(1) &&
5993 N0.getOperand(0) == N1.getOperand(0)) {
5994 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
5996 DAG.getConstantFP(2.0, VT));
5997 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
5998 N0.getOperand(0), NewCFP);
6002 if (N1.getOpcode() == ISD::FMUL) {
6003 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6004 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6006 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6007 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6008 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6010 DAG.getConstantFP(1.0, VT));
6011 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6015 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6016 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6017 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6019 DAG.getConstantFP(1.0, VT));
6020 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6025 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6026 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6027 N0.getOperand(0) == N0.getOperand(1) &&
6028 N1.getOperand(1) == N0.getOperand(0)) {
6029 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6031 DAG.getConstantFP(2.0, VT));
6032 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6033 N1.getOperand(1), NewCFP);
6036 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6037 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6038 N0.getOperand(0) == N0.getOperand(1) &&
6039 N1.getOperand(0) == N0.getOperand(0)) {
6040 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6042 DAG.getConstantFP(2.0, VT));
6043 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6044 N1.getOperand(0), NewCFP);
6048 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6049 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6050 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6051 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6052 (N0.getOperand(0) == N1))
6053 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6054 N1, DAG.getConstantFP(3.0, VT));
6057 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6058 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6059 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6060 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6061 N1.getOperand(0) == N0)
6062 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6063 N0, DAG.getConstantFP(3.0, VT));
6066 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6067 if (AllowNewFpConst &&
6068 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6069 N0.getOperand(0) == N0.getOperand(1) &&
6070 N1.getOperand(0) == N1.getOperand(1) &&
6071 N0.getOperand(0) == N1.getOperand(0))
6072 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6074 DAG.getConstantFP(4.0, VT));
6077 // FADD -> FMA combines:
6078 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6079 DAG.getTarget().Options.UnsafeFPMath) &&
6080 DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
6081 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
6083 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6084 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6085 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6086 N0.getOperand(0), N0.getOperand(1), N1);
6088 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6089 // Note: Commutes FADD operands.
6090 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6091 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6092 N1.getOperand(0), N1.getOperand(1), N0);
6098 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6099 SDValue N0 = N->getOperand(0);
6100 SDValue N1 = N->getOperand(1);
6101 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6102 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6103 EVT VT = N->getValueType(0);
6107 if (VT.isVector()) {
6108 SDValue FoldedVOp = SimplifyVBinOp(N);
6109 if (FoldedVOp.getNode()) return FoldedVOp;
6112 // fold (fsub c1, c2) -> c1-c2
6114 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6115 // fold (fsub A, 0) -> A
6116 if (DAG.getTarget().Options.UnsafeFPMath &&
6117 N1CFP && N1CFP->getValueAPF().isZero())
6119 // fold (fsub 0, B) -> -B
6120 if (DAG.getTarget().Options.UnsafeFPMath &&
6121 N0CFP && N0CFP->getValueAPF().isZero()) {
6122 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6123 return GetNegatedExpression(N1, DAG, LegalOperations);
6124 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6125 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6127 // fold (fsub A, (fneg B)) -> (fadd A, B)
6128 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6129 return DAG.getNode(ISD::FADD, dl, VT, N0,
6130 GetNegatedExpression(N1, DAG, LegalOperations));
6132 // If 'unsafe math' is enabled, fold
6133 // (fsub x, x) -> 0.0 &
6134 // (fsub x, (fadd x, y)) -> (fneg y) &
6135 // (fsub x, (fadd y, x)) -> (fneg y)
6136 if (DAG.getTarget().Options.UnsafeFPMath) {
6138 return DAG.getConstantFP(0.0f, VT);
6140 if (N1.getOpcode() == ISD::FADD) {
6141 SDValue N10 = N1->getOperand(0);
6142 SDValue N11 = N1->getOperand(1);
6144 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6145 &DAG.getTarget().Options))
6146 return GetNegatedExpression(N11, DAG, LegalOperations);
6148 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6149 &DAG.getTarget().Options))
6150 return GetNegatedExpression(N10, DAG, LegalOperations);
6154 // FSUB -> FMA combines:
6155 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6156 DAG.getTarget().Options.UnsafeFPMath) &&
6157 DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
6158 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
6160 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6161 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6162 return DAG.getNode(ISD::FMA, dl, VT,
6163 N0.getOperand(0), N0.getOperand(1),
6164 DAG.getNode(ISD::FNEG, dl, VT, N1));
6166 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6167 // Note: Commutes FSUB operands.
6168 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6169 return DAG.getNode(ISD::FMA, dl, VT,
6170 DAG.getNode(ISD::FNEG, dl, VT,
6172 N1.getOperand(1), N0);
6174 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6175 if (N0.getOpcode() == ISD::FNEG &&
6176 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6177 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6178 SDValue N00 = N0.getOperand(0).getOperand(0);
6179 SDValue N01 = N0.getOperand(0).getOperand(1);
6180 return DAG.getNode(ISD::FMA, dl, VT,
6181 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6182 DAG.getNode(ISD::FNEG, dl, VT, N1));
6189 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6190 SDValue N0 = N->getOperand(0);
6191 SDValue N1 = N->getOperand(1);
6192 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6193 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6194 EVT VT = N->getValueType(0);
6195 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6198 if (VT.isVector()) {
6199 SDValue FoldedVOp = SimplifyVBinOp(N);
6200 if (FoldedVOp.getNode()) return FoldedVOp;
6203 // fold (fmul c1, c2) -> c1*c2
6205 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6206 // canonicalize constant to RHS
6207 if (N0CFP && !N1CFP)
6208 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6209 // fold (fmul A, 0) -> 0
6210 if (DAG.getTarget().Options.UnsafeFPMath &&
6211 N1CFP && N1CFP->getValueAPF().isZero())
6213 // fold (fmul A, 0) -> 0, vector edition.
6214 if (DAG.getTarget().Options.UnsafeFPMath &&
6215 ISD::isBuildVectorAllZeros(N1.getNode()))
6217 // fold (fmul A, 1.0) -> A
6218 if (N1CFP && N1CFP->isExactlyValue(1.0))
6220 // fold (fmul X, 2.0) -> (fadd X, X)
6221 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6222 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6223 // fold (fmul X, -1.0) -> (fneg X)
6224 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6225 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6226 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6228 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6229 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6230 &DAG.getTarget().Options)) {
6231 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6232 &DAG.getTarget().Options)) {
6233 // Both can be negated for free, check to see if at least one is cheaper
6235 if (LHSNeg == 2 || RHSNeg == 2)
6236 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6237 GetNegatedExpression(N0, DAG, LegalOperations),
6238 GetNegatedExpression(N1, DAG, LegalOperations));
6242 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6243 if (DAG.getTarget().Options.UnsafeFPMath &&
6244 N1CFP && N0.getOpcode() == ISD::FMUL &&
6245 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6246 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6247 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6248 N0.getOperand(1), N1));
6253 SDValue DAGCombiner::visitFMA(SDNode *N) {
6254 SDValue N0 = N->getOperand(0);
6255 SDValue N1 = N->getOperand(1);
6256 SDValue N2 = N->getOperand(2);
6257 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6258 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6259 EVT VT = N->getValueType(0);
6262 if (DAG.getTarget().Options.UnsafeFPMath) {
6263 if (N0CFP && N0CFP->isZero())
6265 if (N1CFP && N1CFP->isZero())
6268 if (N0CFP && N0CFP->isExactlyValue(1.0))
6269 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6270 if (N1CFP && N1CFP->isExactlyValue(1.0))
6271 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6273 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6274 if (N0CFP && !N1CFP)
6275 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6277 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6278 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6279 N2.getOpcode() == ISD::FMUL &&
6280 N0 == N2.getOperand(0) &&
6281 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6282 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6283 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6287 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6288 if (DAG.getTarget().Options.UnsafeFPMath &&
6289 N0.getOpcode() == ISD::FMUL && N1CFP &&
6290 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6291 return DAG.getNode(ISD::FMA, dl, VT,
6293 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6297 // (fma x, 1, y) -> (fadd x, y)
6298 // (fma x, -1, y) -> (fadd (fneg x), y)
6300 if (N1CFP->isExactlyValue(1.0))
6301 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6303 if (N1CFP->isExactlyValue(-1.0) &&
6304 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6305 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6306 AddToWorkList(RHSNeg.getNode());
6307 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6311 // (fma x, c, x) -> (fmul x, (c+1))
6312 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6313 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6314 DAG.getNode(ISD::FADD, dl, VT,
6315 N1, DAG.getConstantFP(1.0, VT)));
6317 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6318 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6319 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6320 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6321 DAG.getNode(ISD::FADD, dl, VT,
6322 N1, DAG.getConstantFP(-1.0, VT)));
6328 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6329 SDValue N0 = N->getOperand(0);
6330 SDValue N1 = N->getOperand(1);
6331 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6332 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6333 EVT VT = N->getValueType(0);
6334 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6337 if (VT.isVector()) {
6338 SDValue FoldedVOp = SimplifyVBinOp(N);
6339 if (FoldedVOp.getNode()) return FoldedVOp;
6342 // fold (fdiv c1, c2) -> c1/c2
6344 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6346 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6347 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6348 // Compute the reciprocal 1.0 / c2.
6349 APFloat N1APF = N1CFP->getValueAPF();
6350 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6351 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6352 // Only do the transform if the reciprocal is a legal fp immediate that
6353 // isn't too nasty (eg NaN, denormal, ...).
6354 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6355 (!LegalOperations ||
6356 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6357 // backend)... we should handle this gracefully after Legalize.
6358 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6359 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6360 TLI.isFPImmLegal(Recip, VT)))
6361 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6362 DAG.getConstantFP(Recip, VT));
6365 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6366 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6367 &DAG.getTarget().Options)) {
6368 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6369 &DAG.getTarget().Options)) {
6370 // Both can be negated for free, check to see if at least one is cheaper
6372 if (LHSNeg == 2 || RHSNeg == 2)
6373 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6374 GetNegatedExpression(N0, DAG, LegalOperations),
6375 GetNegatedExpression(N1, DAG, LegalOperations));
6382 SDValue DAGCombiner::visitFREM(SDNode *N) {
6383 SDValue N0 = N->getOperand(0);
6384 SDValue N1 = N->getOperand(1);
6385 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6386 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6387 EVT VT = N->getValueType(0);
6389 // fold (frem c1, c2) -> fmod(c1,c2)
6391 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6396 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6397 SDValue N0 = N->getOperand(0);
6398 SDValue N1 = N->getOperand(1);
6399 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6400 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6401 EVT VT = N->getValueType(0);
6403 if (N0CFP && N1CFP) // Constant fold
6404 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6407 const APFloat& V = N1CFP->getValueAPF();
6408 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6409 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6410 if (!V.isNegative()) {
6411 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6412 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6414 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6415 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6416 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6420 // copysign(fabs(x), y) -> copysign(x, y)
6421 // copysign(fneg(x), y) -> copysign(x, y)
6422 // copysign(copysign(x,z), y) -> copysign(x, y)
6423 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6424 N0.getOpcode() == ISD::FCOPYSIGN)
6425 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6426 N0.getOperand(0), N1);
6428 // copysign(x, abs(y)) -> abs(x)
6429 if (N1.getOpcode() == ISD::FABS)
6430 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6432 // copysign(x, copysign(y,z)) -> copysign(x, z)
6433 if (N1.getOpcode() == ISD::FCOPYSIGN)
6434 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6435 N0, N1.getOperand(1));
6437 // copysign(x, fp_extend(y)) -> copysign(x, y)
6438 // copysign(x, fp_round(y)) -> copysign(x, y)
6439 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6440 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6441 N0, N1.getOperand(0));
6446 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6447 SDValue N0 = N->getOperand(0);
6448 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6449 EVT VT = N->getValueType(0);
6450 EVT OpVT = N0.getValueType();
6452 // fold (sint_to_fp c1) -> c1fp
6454 // ...but only if the target supports immediate floating-point values
6455 (!LegalOperations ||
6456 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6457 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6459 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6460 // but UINT_TO_FP is legal on this target, try to convert.
6461 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6462 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6463 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6464 if (DAG.SignBitIsZero(N0))
6465 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6468 // The next optimizations are desireable only if SELECT_CC can be lowered.
6469 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6470 // having to say they don't support SELECT_CC on every type the DAG knows
6471 // about, since there is no way to mark an opcode illegal at all value types
6472 // (See also visitSELECT)
6473 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6474 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6475 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6477 (!LegalOperations ||
6478 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6480 { N0.getOperand(0), N0.getOperand(1),
6481 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6483 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6486 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6487 // (select_cc x, y, 1.0, 0.0,, cc)
6488 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6489 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6490 (!LegalOperations ||
6491 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6493 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6494 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6495 N0.getOperand(0).getOperand(2) };
6496 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6503 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6504 SDValue N0 = N->getOperand(0);
6505 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6506 EVT VT = N->getValueType(0);
6507 EVT OpVT = N0.getValueType();
6509 // fold (uint_to_fp c1) -> c1fp
6511 // ...but only if the target supports immediate floating-point values
6512 (!LegalOperations ||
6513 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6514 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6516 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6517 // but SINT_TO_FP is legal on this target, try to convert.
6518 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6519 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6520 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6521 if (DAG.SignBitIsZero(N0))
6522 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6525 // The next optimizations are desireable only if SELECT_CC can be lowered.
6526 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6527 // having to say they don't support SELECT_CC on every type the DAG knows
6528 // about, since there is no way to mark an opcode illegal at all value types
6529 // (See also visitSELECT)
6530 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6531 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6533 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6534 (!LegalOperations ||
6535 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6537 { N0.getOperand(0), N0.getOperand(1),
6538 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6540 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6547 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6548 SDValue N0 = N->getOperand(0);
6549 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6550 EVT VT = N->getValueType(0);
6552 // fold (fp_to_sint c1fp) -> c1
6554 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6559 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6560 SDValue N0 = N->getOperand(0);
6561 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6562 EVT VT = N->getValueType(0);
6564 // fold (fp_to_uint c1fp) -> c1
6566 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6571 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6572 SDValue N0 = N->getOperand(0);
6573 SDValue N1 = N->getOperand(1);
6574 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6575 EVT VT = N->getValueType(0);
6577 // fold (fp_round c1fp) -> c1fp
6579 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6581 // fold (fp_round (fp_extend x)) -> x
6582 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6583 return N0.getOperand(0);
6585 // fold (fp_round (fp_round x)) -> (fp_round x)
6586 if (N0.getOpcode() == ISD::FP_ROUND) {
6587 // This is a value preserving truncation if both round's are.
6588 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6589 N0.getNode()->getConstantOperandVal(1) == 1;
6590 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6591 DAG.getIntPtrConstant(IsTrunc));
6594 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6595 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6596 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6597 N0.getOperand(0), N1);
6598 AddToWorkList(Tmp.getNode());
6599 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6600 Tmp, N0.getOperand(1));
6606 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6607 SDValue N0 = N->getOperand(0);
6608 EVT VT = N->getValueType(0);
6609 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6610 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6612 // fold (fp_round_inreg c1fp) -> c1fp
6613 if (N0CFP && isTypeLegal(EVT)) {
6614 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6615 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6621 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6622 SDValue N0 = N->getOperand(0);
6623 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6624 EVT VT = N->getValueType(0);
6626 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6627 if (N->hasOneUse() &&
6628 N->use_begin()->getOpcode() == ISD::FP_ROUND)
6631 // fold (fp_extend c1fp) -> c1fp
6633 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6635 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6637 if (N0.getOpcode() == ISD::FP_ROUND
6638 && N0.getNode()->getConstantOperandVal(1) == 1) {
6639 SDValue In = N0.getOperand(0);
6640 if (In.getValueType() == VT) return In;
6641 if (VT.bitsLT(In.getValueType()))
6642 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6643 In, N0.getOperand(1));
6644 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6647 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6648 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6649 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6650 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6651 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6652 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6654 LN0->getBasePtr(), LN0->getPointerInfo(),
6656 LN0->isVolatile(), LN0->isNonTemporal(),
6657 LN0->getAlignment());
6658 CombineTo(N, ExtLoad);
6659 CombineTo(N0.getNode(),
6660 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6661 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6662 ExtLoad.getValue(1));
6663 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6669 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6670 SDValue N0 = N->getOperand(0);
6671 EVT VT = N->getValueType(0);
6673 if (VT.isVector()) {
6674 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6675 if (FoldedVOp.getNode()) return FoldedVOp;
6678 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6679 &DAG.getTarget().Options))
6680 return GetNegatedExpression(N0, DAG, LegalOperations);
6682 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6683 // constant pool values.
6684 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6686 N0.getNode()->hasOneUse() &&
6687 N0.getOperand(0).getValueType().isInteger()) {
6688 SDValue Int = N0.getOperand(0);
6689 EVT IntVT = Int.getValueType();
6690 if (IntVT.isInteger() && !IntVT.isVector()) {
6691 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6692 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6693 AddToWorkList(Int.getNode());
6694 return DAG.getNode(ISD::BITCAST, SDLoc(N),
6699 // (fneg (fmul c, x)) -> (fmul -c, x)
6700 if (N0.getOpcode() == ISD::FMUL) {
6701 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6703 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6705 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6712 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6713 SDValue N0 = N->getOperand(0);
6714 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6715 EVT VT = N->getValueType(0);
6717 // fold (fceil c1) -> fceil(c1)
6719 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6724 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6725 SDValue N0 = N->getOperand(0);
6726 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6727 EVT VT = N->getValueType(0);
6729 // fold (ftrunc c1) -> ftrunc(c1)
6731 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6736 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6737 SDValue N0 = N->getOperand(0);
6738 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6739 EVT VT = N->getValueType(0);
6741 // fold (ffloor c1) -> ffloor(c1)
6743 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6748 SDValue DAGCombiner::visitFABS(SDNode *N) {
6749 SDValue N0 = N->getOperand(0);
6750 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6751 EVT VT = N->getValueType(0);
6753 if (VT.isVector()) {
6754 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6755 if (FoldedVOp.getNode()) return FoldedVOp;
6758 // fold (fabs c1) -> fabs(c1)
6760 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6761 // fold (fabs (fabs x)) -> (fabs x)
6762 if (N0.getOpcode() == ISD::FABS)
6763 return N->getOperand(0);
6764 // fold (fabs (fneg x)) -> (fabs x)
6765 // fold (fabs (fcopysign x, y)) -> (fabs x)
6766 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6767 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6769 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6770 // constant pool values.
6771 if (!TLI.isFAbsFree(VT) &&
6772 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6773 N0.getOperand(0).getValueType().isInteger() &&
6774 !N0.getOperand(0).getValueType().isVector()) {
6775 SDValue Int = N0.getOperand(0);
6776 EVT IntVT = Int.getValueType();
6777 if (IntVT.isInteger() && !IntVT.isVector()) {
6778 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6779 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6780 AddToWorkList(Int.getNode());
6781 return DAG.getNode(ISD::BITCAST, SDLoc(N),
6782 N->getValueType(0), Int);
6789 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6790 SDValue Chain = N->getOperand(0);
6791 SDValue N1 = N->getOperand(1);
6792 SDValue N2 = N->getOperand(2);
6794 // If N is a constant we could fold this into a fallthrough or unconditional
6795 // branch. However that doesn't happen very often in normal code, because
6796 // Instcombine/SimplifyCFG should have handled the available opportunities.
6797 // If we did this folding here, it would be necessary to update the
6798 // MachineBasicBlock CFG, which is awkward.
6800 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6802 if (N1.getOpcode() == ISD::SETCC &&
6803 TLI.isOperationLegalOrCustom(ISD::BR_CC,
6804 N1.getOperand(0).getValueType())) {
6805 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6806 Chain, N1.getOperand(2),
6807 N1.getOperand(0), N1.getOperand(1), N2);
6810 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6811 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6812 (N1.getOperand(0).hasOneUse() &&
6813 N1.getOperand(0).getOpcode() == ISD::SRL))) {
6815 if (N1.getOpcode() == ISD::TRUNCATE) {
6816 // Look pass the truncate.
6817 Trunc = N1.getNode();
6818 N1 = N1.getOperand(0);
6821 // Match this pattern so that we can generate simpler code:
6824 // %b = and i32 %a, 2
6825 // %c = srl i32 %b, 1
6826 // brcond i32 %c ...
6831 // %b = and i32 %a, 2
6832 // %c = setcc eq %b, 0
6835 // This applies only when the AND constant value has one bit set and the
6836 // SRL constant is equal to the log2 of the AND constant. The back-end is
6837 // smart enough to convert the result into a TEST/JMP sequence.
6838 SDValue Op0 = N1.getOperand(0);
6839 SDValue Op1 = N1.getOperand(1);
6841 if (Op0.getOpcode() == ISD::AND &&
6842 Op1.getOpcode() == ISD::Constant) {
6843 SDValue AndOp1 = Op0.getOperand(1);
6845 if (AndOp1.getOpcode() == ISD::Constant) {
6846 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6848 if (AndConst.isPowerOf2() &&
6849 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6851 DAG.getSetCC(SDLoc(N),
6852 getSetCCResultType(Op0.getValueType()),
6853 Op0, DAG.getConstant(0, Op0.getValueType()),
6856 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
6857 MVT::Other, Chain, SetCC, N2);
6858 // Don't add the new BRCond into the worklist or else SimplifySelectCC
6859 // will convert it back to (X & C1) >> C2.
6860 CombineTo(N, NewBRCond, false);
6861 // Truncate is dead.
6863 removeFromWorkList(Trunc);
6864 DAG.DeleteNode(Trunc);
6866 // Replace the uses of SRL with SETCC
6867 WorkListRemover DeadNodes(*this);
6868 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6869 removeFromWorkList(N1.getNode());
6870 DAG.DeleteNode(N1.getNode());
6871 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6877 // Restore N1 if the above transformation doesn't match.
6878 N1 = N->getOperand(1);
6881 // Transform br(xor(x, y)) -> br(x != y)
6882 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6883 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6884 SDNode *TheXor = N1.getNode();
6885 SDValue Op0 = TheXor->getOperand(0);
6886 SDValue Op1 = TheXor->getOperand(1);
6887 if (Op0.getOpcode() == Op1.getOpcode()) {
6888 // Avoid missing important xor optimizations.
6889 SDValue Tmp = visitXOR(TheXor);
6890 if (Tmp.getNode()) {
6891 if (Tmp.getNode() != TheXor) {
6892 DEBUG(dbgs() << "\nReplacing.8 ";
6894 dbgs() << "\nWith: ";
6895 Tmp.getNode()->dump(&DAG);
6897 WorkListRemover DeadNodes(*this);
6898 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6899 removeFromWorkList(TheXor);
6900 DAG.DeleteNode(TheXor);
6901 return DAG.getNode(ISD::BRCOND, SDLoc(N),
6902 MVT::Other, Chain, Tmp, N2);
6905 // visitXOR has changed XOR's operands or replaced the XOR completely,
6907 return SDValue(N, 0);
6911 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6913 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6914 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6915 Op0.getOpcode() == ISD::XOR) {
6916 TheXor = Op0.getNode();
6920 EVT SetCCVT = N1.getValueType();
6922 SetCCVT = getSetCCResultType(SetCCVT);
6923 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
6926 Equal ? ISD::SETEQ : ISD::SETNE);
6927 // Replace the uses of XOR with SETCC
6928 WorkListRemover DeadNodes(*this);
6929 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6930 removeFromWorkList(N1.getNode());
6931 DAG.DeleteNode(N1.getNode());
6932 return DAG.getNode(ISD::BRCOND, SDLoc(N),
6933 MVT::Other, Chain, SetCC, N2);
6940 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
6942 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
6943 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
6944 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
6946 // If N is a constant we could fold this into a fallthrough or unconditional
6947 // branch. However that doesn't happen very often in normal code, because
6948 // Instcombine/SimplifyCFG should have handled the available opportunities.
6949 // If we did this folding here, it would be necessary to update the
6950 // MachineBasicBlock CFG, which is awkward.
6952 // Use SimplifySetCC to simplify SETCC's.
6953 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
6954 CondLHS, CondRHS, CC->get(), SDLoc(N),
6956 if (Simp.getNode()) AddToWorkList(Simp.getNode());
6958 // fold to a simpler setcc
6959 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
6960 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6961 N->getOperand(0), Simp.getOperand(2),
6962 Simp.getOperand(0), Simp.getOperand(1),
6968 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
6969 /// uses N as its base pointer and that N may be folded in the load / store
6970 /// addressing mode.
6971 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
6973 const TargetLowering &TLI) {
6975 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
6976 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
6978 VT = Use->getValueType(0);
6979 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
6980 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
6982 VT = ST->getValue().getValueType();
6986 TargetLowering::AddrMode AM;
6987 if (N->getOpcode() == ISD::ADD) {
6988 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6991 AM.BaseOffs = Offset->getSExtValue();
6995 } else if (N->getOpcode() == ISD::SUB) {
6996 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6999 AM.BaseOffs = -Offset->getSExtValue();
7006 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7009 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7010 /// pre-indexed load / store when the base pointer is an add or subtract
7011 /// and it has other uses besides the load / store. After the
7012 /// transformation, the new indexed load / store has effectively folded
7013 /// the add / subtract in and all of its other uses are redirected to the
7014 /// new load / store.
7015 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7016 if (Level < AfterLegalizeDAG)
7022 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7023 if (LD->isIndexed())
7025 VT = LD->getMemoryVT();
7026 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7027 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7029 Ptr = LD->getBasePtr();
7030 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7031 if (ST->isIndexed())
7033 VT = ST->getMemoryVT();
7034 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7035 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7037 Ptr = ST->getBasePtr();
7043 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7044 // out. There is no reason to make this a preinc/predec.
7045 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7046 Ptr.getNode()->hasOneUse())
7049 // Ask the target to do addressing mode selection.
7052 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7053 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7056 // Backends without true r+i pre-indexed forms may need to pass a
7057 // constant base with a variable offset so that constant coercion
7058 // will work with the patterns in canonical form.
7059 bool Swapped = false;
7060 if (isa<ConstantSDNode>(BasePtr)) {
7061 std::swap(BasePtr, Offset);
7065 // Don't create a indexed load / store with zero offset.
7066 if (isa<ConstantSDNode>(Offset) &&
7067 cast<ConstantSDNode>(Offset)->isNullValue())
7070 // Try turning it into a pre-indexed load / store except when:
7071 // 1) The new base ptr is a frame index.
7072 // 2) If N is a store and the new base ptr is either the same as or is a
7073 // predecessor of the value being stored.
7074 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7075 // that would create a cycle.
7076 // 4) All uses are load / store ops that use it as old base ptr.
7078 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7079 // (plus the implicit offset) to a register to preinc anyway.
7080 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7085 SDValue Val = cast<StoreSDNode>(N)->getValue();
7086 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7090 // If the offset is a constant, there may be other adds of constants that
7091 // can be folded with this one. We should do this to avoid having to keep
7092 // a copy of the original base pointer.
7093 SmallVector<SDNode *, 16> OtherUses;
7094 if (isa<ConstantSDNode>(Offset))
7095 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7096 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7098 if (Use == Ptr.getNode())
7101 if (Use->isPredecessorOf(N))
7104 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7109 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7110 if (Op1.getNode() == BasePtr.getNode())
7111 std::swap(Op0, Op1);
7112 assert(Op0.getNode() == BasePtr.getNode() &&
7113 "Use of ADD/SUB but not an operand");
7115 if (!isa<ConstantSDNode>(Op1)) {
7120 // FIXME: In some cases, we can be smarter about this.
7121 if (Op1.getValueType() != Offset.getValueType()) {
7126 OtherUses.push_back(Use);
7130 std::swap(BasePtr, Offset);
7132 // Now check for #3 and #4.
7133 bool RealUse = false;
7135 // Caches for hasPredecessorHelper
7136 SmallPtrSet<const SDNode *, 32> Visited;
7137 SmallVector<const SDNode *, 16> Worklist;
7139 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7140 E = Ptr.getNode()->use_end(); I != E; ++I) {
7144 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7147 // If Ptr may be folded in addressing mode of other use, then it's
7148 // not profitable to do this transformation.
7149 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7158 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7159 BasePtr, Offset, AM);
7161 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7162 BasePtr, Offset, AM);
7165 DEBUG(dbgs() << "\nReplacing.4 ";
7167 dbgs() << "\nWith: ";
7168 Result.getNode()->dump(&DAG);
7170 WorkListRemover DeadNodes(*this);
7172 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7173 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7175 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7178 // Finally, since the node is now dead, remove it from the graph.
7182 std::swap(BasePtr, Offset);
7184 // Replace other uses of BasePtr that can be updated to use Ptr
7185 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7186 unsigned OffsetIdx = 1;
7187 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7189 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7190 BasePtr.getNode() && "Expected BasePtr operand");
7192 // We need to replace ptr0 in the following expression:
7193 // x0 * offset0 + y0 * ptr0 = t0
7195 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7197 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7198 // indexed load/store and the expresion that needs to be re-written.
7200 // Therefore, we have:
7201 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7203 ConstantSDNode *CN =
7204 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7206 APInt Offset0 = CN->getAPIntValue();
7207 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7209 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7210 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7211 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7212 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7214 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7216 APInt CNV = Offset0;
7217 if (X0 < 0) CNV = -CNV;
7218 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7219 else CNV = CNV - Offset1;
7221 // We can now generate the new expression.
7222 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7223 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7225 SDValue NewUse = DAG.getNode(Opcode,
7226 SDLoc(OtherUses[i]),
7227 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7228 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7229 removeFromWorkList(OtherUses[i]);
7230 DAG.DeleteNode(OtherUses[i]);
7233 // Replace the uses of Ptr with uses of the updated base value.
7234 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7235 removeFromWorkList(Ptr.getNode());
7236 DAG.DeleteNode(Ptr.getNode());
7241 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7242 /// add / sub of the base pointer node into a post-indexed load / store.
7243 /// The transformation folded the add / subtract into the new indexed
7244 /// load / store effectively and all of its uses are redirected to the
7245 /// new load / store.
7246 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7247 if (Level < AfterLegalizeDAG)
7253 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7254 if (LD->isIndexed())
7256 VT = LD->getMemoryVT();
7257 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7258 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7260 Ptr = LD->getBasePtr();
7261 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7262 if (ST->isIndexed())
7264 VT = ST->getMemoryVT();
7265 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7266 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7268 Ptr = ST->getBasePtr();
7274 if (Ptr.getNode()->hasOneUse())
7277 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7278 E = Ptr.getNode()->use_end(); I != E; ++I) {
7281 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7286 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7287 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7288 // Don't create a indexed load / store with zero offset.
7289 if (isa<ConstantSDNode>(Offset) &&
7290 cast<ConstantSDNode>(Offset)->isNullValue())
7293 // Try turning it into a post-indexed load / store except when
7294 // 1) All uses are load / store ops that use it as base ptr (and
7295 // it may be folded as addressing mmode).
7296 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7297 // nor a successor of N. Otherwise, if Op is folded that would
7300 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7304 bool TryNext = false;
7305 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7306 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7308 if (Use == Ptr.getNode())
7311 // If all the uses are load / store addresses, then don't do the
7313 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7314 bool RealUse = false;
7315 for (SDNode::use_iterator III = Use->use_begin(),
7316 EEE = Use->use_end(); III != EEE; ++III) {
7317 SDNode *UseUse = *III;
7318 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7333 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7334 SDValue Result = isLoad
7335 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7336 BasePtr, Offset, AM)
7337 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7338 BasePtr, Offset, AM);
7341 DEBUG(dbgs() << "\nReplacing.5 ";
7343 dbgs() << "\nWith: ";
7344 Result.getNode()->dump(&DAG);
7346 WorkListRemover DeadNodes(*this);
7348 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7349 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7351 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7354 // Finally, since the node is now dead, remove it from the graph.
7357 // Replace the uses of Use with uses of the updated base value.
7358 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7359 Result.getValue(isLoad ? 1 : 0));
7360 removeFromWorkList(Op);
7370 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7371 LoadSDNode *LD = cast<LoadSDNode>(N);
7372 SDValue Chain = LD->getChain();
7373 SDValue Ptr = LD->getBasePtr();
7375 // If load is not volatile and there are no uses of the loaded value (and
7376 // the updated indexed value in case of indexed loads), change uses of the
7377 // chain value into uses of the chain input (i.e. delete the dead load).
7378 if (!LD->isVolatile()) {
7379 if (N->getValueType(1) == MVT::Other) {
7381 if (!N->hasAnyUseOfValue(0)) {
7382 // It's not safe to use the two value CombineTo variant here. e.g.
7383 // v1, chain2 = load chain1, loc
7384 // v2, chain3 = load chain2, loc
7386 // Now we replace use of chain2 with chain1. This makes the second load
7387 // isomorphic to the one we are deleting, and thus makes this load live.
7388 DEBUG(dbgs() << "\nReplacing.6 ";
7390 dbgs() << "\nWith chain: ";
7391 Chain.getNode()->dump(&DAG);
7393 WorkListRemover DeadNodes(*this);
7394 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7396 if (N->use_empty()) {
7397 removeFromWorkList(N);
7401 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7405 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7406 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7407 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7408 DEBUG(dbgs() << "\nReplacing.7 ";
7410 dbgs() << "\nWith: ";
7411 Undef.getNode()->dump(&DAG);
7412 dbgs() << " and 2 other values\n");
7413 WorkListRemover DeadNodes(*this);
7414 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7415 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7416 DAG.getUNDEF(N->getValueType(1)));
7417 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7418 removeFromWorkList(N);
7420 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7425 // If this load is directly stored, replace the load value with the stored
7427 // TODO: Handle store large -> read small portion.
7428 // TODO: Handle TRUNCSTORE/LOADEXT
7429 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7430 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7431 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7432 if (PrevST->getBasePtr() == Ptr &&
7433 PrevST->getValue().getValueType() == N->getValueType(0))
7434 return CombineTo(N, Chain.getOperand(1), Chain);
7438 // Try to infer better alignment information than the load already has.
7439 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7440 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7441 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7443 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7444 LD->getValueType(0),
7445 Chain, Ptr, LD->getPointerInfo(),
7447 LD->isVolatile(), LD->isNonTemporal(), Align);
7448 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7454 // Walk up chain skipping non-aliasing memory nodes.
7455 SDValue BetterChain = FindBetterChain(N, Chain);
7457 // If there is a better chain.
7458 if (Chain != BetterChain) {
7461 // Replace the chain to void dependency.
7462 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7463 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7464 BetterChain, Ptr, LD->getPointerInfo(),
7465 LD->isVolatile(), LD->isNonTemporal(),
7466 LD->isInvariant(), LD->getAlignment());
7468 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7469 LD->getValueType(0),
7470 BetterChain, Ptr, LD->getPointerInfo(),
7473 LD->isNonTemporal(),
7474 LD->getAlignment());
7477 // Create token factor to keep old chain connected.
7478 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7479 MVT::Other, Chain, ReplLoad.getValue(1));
7481 // Make sure the new and old chains are cleaned up.
7482 AddToWorkList(Token.getNode());
7484 // Replace uses with load result and token factor. Don't add users
7486 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7490 // Try transforming N to an indexed load.
7491 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7492 return SDValue(N, 0);
7497 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
7498 /// load is having specific bytes cleared out. If so, return the byte size
7499 /// being masked out and the shift amount.
7500 static std::pair<unsigned, unsigned>
7501 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
7502 std::pair<unsigned, unsigned> Result(0, 0);
7504 // Check for the structure we're looking for.
7505 if (V->getOpcode() != ISD::AND ||
7506 !isa<ConstantSDNode>(V->getOperand(1)) ||
7507 !ISD::isNormalLoad(V->getOperand(0).getNode()))
7510 // Check the chain and pointer.
7511 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
7512 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
7514 // The store should be chained directly to the load or be an operand of a
7516 if (LD == Chain.getNode())
7518 else if (Chain->getOpcode() != ISD::TokenFactor)
7519 return Result; // Fail.
7522 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
7523 if (Chain->getOperand(i).getNode() == LD) {
7527 if (!isOk) return Result;
7530 // This only handles simple types.
7531 if (V.getValueType() != MVT::i16 &&
7532 V.getValueType() != MVT::i32 &&
7533 V.getValueType() != MVT::i64)
7536 // Check the constant mask. Invert it so that the bits being masked out are
7537 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
7538 // follow the sign bit for uniformity.
7539 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
7540 unsigned NotMaskLZ = countLeadingZeros(NotMask);
7541 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
7542 unsigned NotMaskTZ = countTrailingZeros(NotMask);
7543 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
7544 if (NotMaskLZ == 64) return Result; // All zero mask.
7546 // See if we have a continuous run of bits. If so, we have 0*1+0*
7547 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
7550 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
7551 if (V.getValueType() != MVT::i64 && NotMaskLZ)
7552 NotMaskLZ -= 64-V.getValueSizeInBits();
7554 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
7555 switch (MaskedBytes) {
7559 default: return Result; // All one mask, or 5-byte mask.
7562 // Verify that the first bit starts at a multiple of mask so that the access
7563 // is aligned the same as the access width.
7564 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
7566 Result.first = MaskedBytes;
7567 Result.second = NotMaskTZ/8;
7572 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
7573 /// provides a value as specified by MaskInfo. If so, replace the specified
7574 /// store with a narrower store of truncated IVal.
7576 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
7577 SDValue IVal, StoreSDNode *St,
7579 unsigned NumBytes = MaskInfo.first;
7580 unsigned ByteShift = MaskInfo.second;
7581 SelectionDAG &DAG = DC->getDAG();
7583 // Check to see if IVal is all zeros in the part being masked in by the 'or'
7584 // that uses this. If not, this is not a replacement.
7585 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
7586 ByteShift*8, (ByteShift+NumBytes)*8);
7587 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
7589 // Check that it is legal on the target to do this. It is legal if the new
7590 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
7592 MVT VT = MVT::getIntegerVT(NumBytes*8);
7593 if (!DC->isTypeLegal(VT))
7596 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
7597 // shifted by ByteShift and truncated down to NumBytes.
7599 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
7600 DAG.getConstant(ByteShift*8,
7601 DC->getShiftAmountTy(IVal.getValueType())));
7603 // Figure out the offset for the store and the alignment of the access.
7605 unsigned NewAlign = St->getAlignment();
7607 if (DAG.getTargetLoweringInfo().isLittleEndian())
7608 StOffset = ByteShift;
7610 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
7612 SDValue Ptr = St->getBasePtr();
7614 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
7615 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
7616 NewAlign = MinAlign(NewAlign, StOffset);
7619 // Truncate down to the new size.
7620 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
7623 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
7624 St->getPointerInfo().getWithOffset(StOffset),
7625 false, false, NewAlign).getNode();
7629 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7630 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7631 /// of the loaded bits, try narrowing the load and store if it would end up
7632 /// being a win for performance or code size.
7633 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7634 StoreSDNode *ST = cast<StoreSDNode>(N);
7635 if (ST->isVolatile())
7638 SDValue Chain = ST->getChain();
7639 SDValue Value = ST->getValue();
7640 SDValue Ptr = ST->getBasePtr();
7641 EVT VT = Value.getValueType();
7643 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7646 unsigned Opc = Value.getOpcode();
7648 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7649 // is a byte mask indicating a consecutive number of bytes, check to see if
7650 // Y is known to provide just those bytes. If so, we try to replace the
7651 // load + replace + store sequence with a single (narrower) store, which makes
7653 if (Opc == ISD::OR) {
7654 std::pair<unsigned, unsigned> MaskedLoad;
7655 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7656 if (MaskedLoad.first)
7657 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7658 Value.getOperand(1), ST,this))
7659 return SDValue(NewST, 0);
7661 // Or is commutative, so try swapping X and Y.
7662 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7663 if (MaskedLoad.first)
7664 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7665 Value.getOperand(0), ST,this))
7666 return SDValue(NewST, 0);
7669 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7670 Value.getOperand(1).getOpcode() != ISD::Constant)
7673 SDValue N0 = Value.getOperand(0);
7674 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7675 Chain == SDValue(N0.getNode(), 1)) {
7676 LoadSDNode *LD = cast<LoadSDNode>(N0);
7677 if (LD->getBasePtr() != Ptr ||
7678 LD->getPointerInfo().getAddrSpace() !=
7679 ST->getPointerInfo().getAddrSpace())
7682 // Find the type to narrow it the load / op / store to.
7683 SDValue N1 = Value.getOperand(1);
7684 unsigned BitWidth = N1.getValueSizeInBits();
7685 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7686 if (Opc == ISD::AND)
7687 Imm ^= APInt::getAllOnesValue(BitWidth);
7688 if (Imm == 0 || Imm.isAllOnesValue())
7690 unsigned ShAmt = Imm.countTrailingZeros();
7691 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7692 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7693 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7694 while (NewBW < BitWidth &&
7695 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7696 TLI.isNarrowingProfitable(VT, NewVT))) {
7697 NewBW = NextPowerOf2(NewBW);
7698 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7700 if (NewBW >= BitWidth)
7703 // If the lsb changed does not start at the type bitwidth boundary,
7704 // start at the previous one.
7706 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7707 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
7708 std::min(BitWidth, ShAmt + NewBW));
7709 if ((Imm & Mask) == Imm) {
7710 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7711 if (Opc == ISD::AND)
7712 NewImm ^= APInt::getAllOnesValue(NewBW);
7713 uint64_t PtrOff = ShAmt / 8;
7714 // For big endian targets, we need to adjust the offset to the pointer to
7715 // load the correct bytes.
7716 if (TLI.isBigEndian())
7717 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7719 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7720 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7721 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
7724 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
7725 Ptr.getValueType(), Ptr,
7726 DAG.getConstant(PtrOff, Ptr.getValueType()));
7727 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
7728 LD->getChain(), NewPtr,
7729 LD->getPointerInfo().getWithOffset(PtrOff),
7730 LD->isVolatile(), LD->isNonTemporal(),
7731 LD->isInvariant(), NewAlign);
7732 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
7733 DAG.getConstant(NewImm, NewVT));
7734 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
7736 ST->getPointerInfo().getWithOffset(PtrOff),
7737 false, false, NewAlign);
7739 AddToWorkList(NewPtr.getNode());
7740 AddToWorkList(NewLD.getNode());
7741 AddToWorkList(NewVal.getNode());
7742 WorkListRemover DeadNodes(*this);
7743 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7752 /// TransformFPLoadStorePair - For a given floating point load / store pair,
7753 /// if the load value isn't used by any other operations, then consider
7754 /// transforming the pair to integer load / store operations if the target
7755 /// deems the transformation profitable.
7756 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7757 StoreSDNode *ST = cast<StoreSDNode>(N);
7758 SDValue Chain = ST->getChain();
7759 SDValue Value = ST->getValue();
7760 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7761 Value.hasOneUse() &&
7762 Chain == SDValue(Value.getNode(), 1)) {
7763 LoadSDNode *LD = cast<LoadSDNode>(Value);
7764 EVT VT = LD->getMemoryVT();
7765 if (!VT.isFloatingPoint() ||
7766 VT != ST->getMemoryVT() ||
7767 LD->isNonTemporal() ||
7768 ST->isNonTemporal() ||
7769 LD->getPointerInfo().getAddrSpace() != 0 ||
7770 ST->getPointerInfo().getAddrSpace() != 0)
7773 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7774 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7775 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7776 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7777 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7780 unsigned LDAlign = LD->getAlignment();
7781 unsigned STAlign = ST->getAlignment();
7782 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7783 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
7784 if (LDAlign < ABIAlign || STAlign < ABIAlign)
7787 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
7788 LD->getChain(), LD->getBasePtr(),
7789 LD->getPointerInfo(),
7790 false, false, false, LDAlign);
7792 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
7793 NewLD, ST->getBasePtr(),
7794 ST->getPointerInfo(),
7795 false, false, STAlign);
7797 AddToWorkList(NewLD.getNode());
7798 AddToWorkList(NewST.getNode());
7799 WorkListRemover DeadNodes(*this);
7800 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7808 /// Helper struct to parse and store a memory address as base + index + offset.
7809 /// We ignore sign extensions when it is safe to do so.
7810 /// The following two expressions are not equivalent. To differentiate we need
7811 /// to store whether there was a sign extension involved in the index
7813 /// (load (i64 add (i64 copyfromreg %c)
7814 /// (i64 signextend (add (i8 load %index)
7818 /// (load (i64 add (i64 copyfromreg %c)
7819 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
7821 struct BaseIndexOffset {
7825 bool IsIndexSignExt;
7827 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
7829 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
7830 bool IsIndexSignExt) :
7831 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
7833 bool equalBaseIndex(const BaseIndexOffset &Other) {
7834 return Other.Base == Base && Other.Index == Index &&
7835 Other.IsIndexSignExt == IsIndexSignExt;
7838 /// Parses tree in Ptr for base, index, offset addresses.
7839 static BaseIndexOffset match(SDValue Ptr) {
7840 bool IsIndexSignExt = false;
7842 // Just Base or possibly anything else.
7843 if (Ptr->getOpcode() != ISD::ADD)
7844 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7847 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
7848 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
7849 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
7853 // Look at Base + Index + Offset cases.
7854 SDValue Base = Ptr->getOperand(0);
7855 SDValue IndexOffset = Ptr->getOperand(1);
7857 // Skip signextends.
7858 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
7859 IndexOffset = IndexOffset->getOperand(0);
7860 IsIndexSignExt = true;
7863 // Either the case of Base + Index (no offset) or something else.
7864 if (IndexOffset->getOpcode() != ISD::ADD)
7865 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
7867 // Now we have the case of Base + Index + offset.
7868 SDValue Index = IndexOffset->getOperand(0);
7869 SDValue Offset = IndexOffset->getOperand(1);
7871 if (!isa<ConstantSDNode>(Offset))
7872 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7874 // Ignore signextends.
7875 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
7876 Index = Index->getOperand(0);
7877 IsIndexSignExt = true;
7878 } else IsIndexSignExt = false;
7880 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
7881 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
7885 /// Holds a pointer to an LSBaseSDNode as well as information on where it
7886 /// is located in a sequence of memory operations connected by a chain.
7888 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
7889 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
7890 // Ptr to the mem node.
7891 LSBaseSDNode *MemNode;
7892 // Offset from the base ptr.
7893 int64_t OffsetFromBase;
7894 // What is the sequence number of this mem node.
7895 // Lowest mem operand in the DAG starts at zero.
7896 unsigned SequenceNum;
7899 /// Sorts store nodes in a link according to their offset from a shared
7901 struct ConsecutiveMemoryChainSorter {
7902 bool operator()(MemOpLink LHS, MemOpLink RHS) {
7903 return LHS.OffsetFromBase < RHS.OffsetFromBase;
7907 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
7908 EVT MemVT = St->getMemoryVT();
7909 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
7910 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
7911 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
7913 // Don't merge vectors into wider inputs.
7914 if (MemVT.isVector() || !MemVT.isSimple())
7917 // Perform an early exit check. Do not bother looking at stored values that
7918 // are not constants or loads.
7919 SDValue StoredVal = St->getValue();
7920 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
7921 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
7925 // Only look at ends of store sequences.
7926 SDValue Chain = SDValue(St, 1);
7927 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
7930 // This holds the base pointer, index, and the offset in bytes from the base
7932 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
7934 // We must have a base and an offset.
7935 if (!BasePtr.Base.getNode())
7938 // Do not handle stores to undef base pointers.
7939 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
7942 // Save the LoadSDNodes that we find in the chain.
7943 // We need to make sure that these nodes do not interfere with
7944 // any of the store nodes.
7945 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
7947 // Save the StoreSDNodes that we find in the chain.
7948 SmallVector<MemOpLink, 8> StoreNodes;
7950 // Walk up the chain and look for nodes with offsets from the same
7951 // base pointer. Stop when reaching an instruction with a different kind
7952 // or instruction which has a different base pointer.
7954 StoreSDNode *Index = St;
7956 // If the chain has more than one use, then we can't reorder the mem ops.
7957 if (Index != St && !SDValue(Index, 1)->hasOneUse())
7960 // Find the base pointer and offset for this memory node.
7961 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
7963 // Check that the base pointer is the same as the original one.
7964 if (!Ptr.equalBaseIndex(BasePtr))
7967 // Check that the alignment is the same.
7968 if (Index->getAlignment() != St->getAlignment())
7971 // The memory operands must not be volatile.
7972 if (Index->isVolatile() || Index->isIndexed())
7976 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
7977 if (St->isTruncatingStore())
7980 // The stored memory type must be the same.
7981 if (Index->getMemoryVT() != MemVT)
7984 // We do not allow unaligned stores because we want to prevent overriding
7986 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
7989 // We found a potential memory operand to merge.
7990 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
7992 // Find the next memory operand in the chain. If the next operand in the
7993 // chain is a store then move up and continue the scan with the next
7994 // memory operand. If the next operand is a load save it and use alias
7995 // information to check if it interferes with anything.
7996 SDNode *NextInChain = Index->getChain().getNode();
7998 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
7999 // We found a store node. Use it for the next iteration.
8002 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8003 // Save the load node for later. Continue the scan.
8004 AliasLoadNodes.push_back(Ldn);
8005 NextInChain = Ldn->getChain().getNode();
8014 // Check if there is anything to merge.
8015 if (StoreNodes.size() < 2)
8018 // Sort the memory operands according to their distance from the base pointer.
8019 std::sort(StoreNodes.begin(), StoreNodes.end(),
8020 ConsecutiveMemoryChainSorter());
8022 // Scan the memory operations on the chain and find the first non-consecutive
8023 // store memory address.
8024 unsigned LastConsecutiveStore = 0;
8025 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8026 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8028 // Check that the addresses are consecutive starting from the second
8029 // element in the list of stores.
8031 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8032 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8037 // Check if this store interferes with any of the loads that we found.
8038 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8039 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8043 // We found a load that alias with this store. Stop the sequence.
8047 // Mark this node as useful.
8048 LastConsecutiveStore = i;
8051 // The node with the lowest store address.
8052 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8054 // Store the constants into memory as one consecutive store.
8056 unsigned LastLegalType = 0;
8057 unsigned LastLegalVectorType = 0;
8058 bool NonZero = false;
8059 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8060 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8061 SDValue StoredVal = St->getValue();
8063 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8064 NonZero |= !C->isNullValue();
8065 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8066 NonZero |= !C->getConstantFPValue()->isNullValue();
8072 // Find a legal type for the constant store.
8073 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8074 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8075 if (TLI.isTypeLegal(StoreTy))
8076 LastLegalType = i+1;
8077 // Or check whether a truncstore is legal.
8078 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8079 TargetLowering::TypePromoteInteger) {
8080 EVT LegalizedStoredValueTy =
8081 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8082 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8083 LastLegalType = i+1;
8086 // Find a legal type for the vector store.
8087 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8088 if (TLI.isTypeLegal(Ty))
8089 LastLegalVectorType = i + 1;
8092 // We only use vectors if the constant is known to be zero and the
8093 // function is not marked with the noimplicitfloat attribute.
8094 if (NonZero || NoVectors)
8095 LastLegalVectorType = 0;
8097 // Check if we found a legal integer type to store.
8098 if (LastLegalType == 0 && LastLegalVectorType == 0)
8101 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8102 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8104 // Make sure we have something to merge.
8108 unsigned EarliestNodeUsed = 0;
8109 for (unsigned i=0; i < NumElem; ++i) {
8110 // Find a chain for the new wide-store operand. Notice that some
8111 // of the store nodes that we found may not be selected for inclusion
8112 // in the wide store. The chain we use needs to be the chain of the
8113 // earliest store node which is *used* and replaced by the wide store.
8114 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8115 EarliestNodeUsed = i;
8118 // The earliest Node in the DAG.
8119 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8120 SDLoc DL(StoreNodes[0].MemNode);
8124 // Find a legal type for the vector store.
8125 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8126 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8127 StoredVal = DAG.getConstant(0, Ty);
8129 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8130 APInt StoreInt(StoreBW, 0);
8132 // Construct a single integer constant which is made of the smaller
8134 bool IsLE = TLI.isLittleEndian();
8135 for (unsigned i = 0; i < NumElem ; ++i) {
8136 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8137 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8138 SDValue Val = St->getValue();
8139 StoreInt<<=ElementSizeBytes*8;
8140 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8141 StoreInt|=C->getAPIntValue().zext(StoreBW);
8142 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8143 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8145 assert(false && "Invalid constant element type");
8149 // Create the new Load and Store operations.
8150 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8151 StoredVal = DAG.getConstant(StoreInt, StoreTy);
8154 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8155 FirstInChain->getBasePtr(),
8156 FirstInChain->getPointerInfo(),
8158 FirstInChain->getAlignment());
8160 // Replace the first store with the new store
8161 CombineTo(EarliestOp, NewStore);
8162 // Erase all other stores.
8163 for (unsigned i = 0; i < NumElem ; ++i) {
8164 if (StoreNodes[i].MemNode == EarliestOp)
8166 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8167 // ReplaceAllUsesWith will replace all uses that existed when it was
8168 // called, but graph optimizations may cause new ones to appear. For
8169 // example, the case in pr14333 looks like
8171 // St's chain -> St -> another store -> X
8173 // And the only difference from St to the other store is the chain.
8174 // When we change it's chain to be St's chain they become identical,
8175 // get CSEed and the net result is that X is now a use of St.
8176 // Since we know that St is redundant, just iterate.
8177 while (!St->use_empty())
8178 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8179 removeFromWorkList(St);
8186 // Below we handle the case of multiple consecutive stores that
8187 // come from multiple consecutive loads. We merge them into a single
8188 // wide load and a single wide store.
8190 // Look for load nodes which are used by the stored values.
8191 SmallVector<MemOpLink, 8> LoadNodes;
8193 // Find acceptable loads. Loads need to have the same chain (token factor),
8194 // must not be zext, volatile, indexed, and they must be consecutive.
8195 BaseIndexOffset LdBasePtr;
8196 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8197 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8198 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8201 // Loads must only have one use.
8202 if (!Ld->hasNUsesOfValue(1, 0))
8205 // Check that the alignment is the same as the stores.
8206 if (Ld->getAlignment() != St->getAlignment())
8209 // The memory operands must not be volatile.
8210 if (Ld->isVolatile() || Ld->isIndexed())
8213 // We do not accept ext loads.
8214 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8217 // The stored memory type must be the same.
8218 if (Ld->getMemoryVT() != MemVT)
8221 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8222 // If this is not the first ptr that we check.
8223 if (LdBasePtr.Base.getNode()) {
8224 // The base ptr must be the same.
8225 if (!LdPtr.equalBaseIndex(LdBasePtr))
8228 // Check that all other base pointers are the same as this one.
8232 // We found a potential memory operand to merge.
8233 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8236 if (LoadNodes.size() < 2)
8239 // Scan the memory operations on the chain and find the first non-consecutive
8240 // load memory address. These variables hold the index in the store node
8242 unsigned LastConsecutiveLoad = 0;
8243 // This variable refers to the size and not index in the array.
8244 unsigned LastLegalVectorType = 0;
8245 unsigned LastLegalIntegerType = 0;
8246 StartAddress = LoadNodes[0].OffsetFromBase;
8247 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8248 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8249 // All loads much share the same chain.
8250 if (LoadNodes[i].MemNode->getChain() != FirstChain)
8253 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8254 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8256 LastConsecutiveLoad = i;
8258 // Find a legal type for the vector store.
8259 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8260 if (TLI.isTypeLegal(StoreTy))
8261 LastLegalVectorType = i + 1;
8263 // Find a legal type for the integer store.
8264 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8265 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8266 if (TLI.isTypeLegal(StoreTy))
8267 LastLegalIntegerType = i + 1;
8268 // Or check whether a truncstore and extload is legal.
8269 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8270 TargetLowering::TypePromoteInteger) {
8271 EVT LegalizedStoredValueTy =
8272 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8273 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8274 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8275 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8276 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8277 LastLegalIntegerType = i+1;
8281 // Only use vector types if the vector type is larger than the integer type.
8282 // If they are the same, use integers.
8283 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8284 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8286 // We add +1 here because the LastXXX variables refer to location while
8287 // the NumElem refers to array/index size.
8288 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8289 NumElem = std::min(LastLegalType, NumElem);
8294 // The earliest Node in the DAG.
8295 unsigned EarliestNodeUsed = 0;
8296 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8297 for (unsigned i=1; i<NumElem; ++i) {
8298 // Find a chain for the new wide-store operand. Notice that some
8299 // of the store nodes that we found may not be selected for inclusion
8300 // in the wide store. The chain we use needs to be the chain of the
8301 // earliest store node which is *used* and replaced by the wide store.
8302 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8303 EarliestNodeUsed = i;
8306 // Find if it is better to use vectors or integers to load and store
8310 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8312 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8313 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8316 SDLoc LoadDL(LoadNodes[0].MemNode);
8317 SDLoc StoreDL(StoreNodes[0].MemNode);
8319 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8320 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8321 FirstLoad->getChain(),
8322 FirstLoad->getBasePtr(),
8323 FirstLoad->getPointerInfo(),
8324 false, false, false,
8325 FirstLoad->getAlignment());
8327 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
8328 FirstInChain->getBasePtr(),
8329 FirstInChain->getPointerInfo(), false, false,
8330 FirstInChain->getAlignment());
8332 // Replace one of the loads with the new load.
8333 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
8334 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
8335 SDValue(NewLoad.getNode(), 1));
8337 // Remove the rest of the load chains.
8338 for (unsigned i = 1; i < NumElem ; ++i) {
8339 // Replace all chain users of the old load nodes with the chain of the new
8341 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
8342 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
8345 // Replace the first store with the new store.
8346 CombineTo(EarliestOp, NewStore);
8347 // Erase all other stores.
8348 for (unsigned i = 0; i < NumElem ; ++i) {
8349 // Remove all Store nodes.
8350 if (StoreNodes[i].MemNode == EarliestOp)
8352 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8353 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
8354 removeFromWorkList(St);
8361 SDValue DAGCombiner::visitSTORE(SDNode *N) {
8362 StoreSDNode *ST = cast<StoreSDNode>(N);
8363 SDValue Chain = ST->getChain();
8364 SDValue Value = ST->getValue();
8365 SDValue Ptr = ST->getBasePtr();
8367 // If this is a store of a bit convert, store the input value if the
8368 // resultant store does not need a higher alignment than the original.
8369 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
8370 ST->isUnindexed()) {
8371 unsigned OrigAlign = ST->getAlignment();
8372 EVT SVT = Value.getOperand(0).getValueType();
8373 unsigned Align = TLI.getDataLayout()->
8374 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
8375 if (Align <= OrigAlign &&
8376 ((!LegalOperations && !ST->isVolatile()) ||
8377 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
8378 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
8379 Ptr, ST->getPointerInfo(), ST->isVolatile(),
8380 ST->isNonTemporal(), OrigAlign);
8383 // Turn 'store undef, Ptr' -> nothing.
8384 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
8387 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
8388 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
8389 // NOTE: If the original store is volatile, this transform must not increase
8390 // the number of stores. For example, on x86-32 an f64 can be stored in one
8391 // processor operation but an i64 (which is not legal) requires two. So the
8392 // transform should not be done in this case.
8393 if (Value.getOpcode() != ISD::TargetConstantFP) {
8395 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
8396 default: llvm_unreachable("Unknown FP type");
8397 case MVT::f16: // We don't do this for these yet.
8403 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
8404 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8405 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
8406 bitcastToAPInt().getZExtValue(), MVT::i32);
8407 return DAG.getStore(Chain, SDLoc(N), Tmp,
8408 Ptr, ST->getPointerInfo(), ST->isVolatile(),
8409 ST->isNonTemporal(), ST->getAlignment());
8413 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
8414 !ST->isVolatile()) ||
8415 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
8416 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
8417 getZExtValue(), MVT::i64);
8418 return DAG.getStore(Chain, SDLoc(N), Tmp,
8419 Ptr, ST->getPointerInfo(), ST->isVolatile(),
8420 ST->isNonTemporal(), ST->getAlignment());
8423 if (!ST->isVolatile() &&
8424 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8425 // Many FP stores are not made apparent until after legalize, e.g. for
8426 // argument passing. Since this is so common, custom legalize the
8427 // 64-bit integer store into two 32-bit stores.
8428 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
8429 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
8430 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
8431 if (TLI.isBigEndian()) std::swap(Lo, Hi);
8433 unsigned Alignment = ST->getAlignment();
8434 bool isVolatile = ST->isVolatile();
8435 bool isNonTemporal = ST->isNonTemporal();
8437 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
8438 Ptr, ST->getPointerInfo(),
8439 isVolatile, isNonTemporal,
8440 ST->getAlignment());
8441 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
8442 DAG.getConstant(4, Ptr.getValueType()));
8443 Alignment = MinAlign(Alignment, 4U);
8444 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
8445 Ptr, ST->getPointerInfo().getWithOffset(4),
8446 isVolatile, isNonTemporal,
8448 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
8457 // Try to infer better alignment information than the store already has.
8458 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
8459 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8460 if (Align > ST->getAlignment())
8461 return DAG.getTruncStore(Chain, SDLoc(N), Value,
8462 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8463 ST->isVolatile(), ST->isNonTemporal(), Align);
8467 // Try transforming a pair floating point load / store ops to integer
8468 // load / store ops.
8469 SDValue NewST = TransformFPLoadStorePair(N);
8470 if (NewST.getNode())
8474 // Walk up chain skipping non-aliasing memory nodes.
8475 SDValue BetterChain = FindBetterChain(N, Chain);
8477 // If there is a better chain.
8478 if (Chain != BetterChain) {
8481 // Replace the chain to avoid dependency.
8482 if (ST->isTruncatingStore()) {
8483 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
8484 ST->getPointerInfo(),
8485 ST->getMemoryVT(), ST->isVolatile(),
8486 ST->isNonTemporal(), ST->getAlignment());
8488 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
8489 ST->getPointerInfo(),
8490 ST->isVolatile(), ST->isNonTemporal(),
8491 ST->getAlignment());
8494 // Create token to keep both nodes around.
8495 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8496 MVT::Other, Chain, ReplStore);
8498 // Make sure the new and old chains are cleaned up.
8499 AddToWorkList(Token.getNode());
8501 // Don't add users to work list.
8502 return CombineTo(N, Token, false);
8506 // Try transforming N to an indexed store.
8507 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8508 return SDValue(N, 0);
8510 // FIXME: is there such a thing as a truncating indexed store?
8511 if (ST->isTruncatingStore() && ST->isUnindexed() &&
8512 Value.getValueType().isInteger()) {
8513 // See if we can simplify the input to this truncstore with knowledge that
8514 // only the low bits are being used. For example:
8515 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
8517 GetDemandedBits(Value,
8518 APInt::getLowBitsSet(
8519 Value.getValueType().getScalarType().getSizeInBits(),
8520 ST->getMemoryVT().getScalarType().getSizeInBits()));
8521 AddToWorkList(Value.getNode());
8522 if (Shorter.getNode())
8523 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
8524 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8525 ST->isVolatile(), ST->isNonTemporal(),
8526 ST->getAlignment());
8528 // Otherwise, see if we can simplify the operation with
8529 // SimplifyDemandedBits, which only works if the value has a single use.
8530 if (SimplifyDemandedBits(Value,
8531 APInt::getLowBitsSet(
8532 Value.getValueType().getScalarType().getSizeInBits(),
8533 ST->getMemoryVT().getScalarType().getSizeInBits())))
8534 return SDValue(N, 0);
8537 // If this is a load followed by a store to the same location, then the store
8539 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
8540 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
8541 ST->isUnindexed() && !ST->isVolatile() &&
8542 // There can't be any side effects between the load and store, such as
8544 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
8545 // The store is dead, remove it.
8550 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
8551 // truncating store. We can do this even if this is already a truncstore.
8552 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
8553 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
8554 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
8555 ST->getMemoryVT())) {
8556 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
8557 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8558 ST->isVolatile(), ST->isNonTemporal(),
8559 ST->getAlignment());
8562 // Only perform this optimization before the types are legal, because we
8563 // don't want to perform this optimization on every DAGCombine invocation.
8565 bool EverChanged = false;
8568 // There can be multiple store sequences on the same chain.
8569 // Keep trying to merge store sequences until we are unable to do so
8570 // or until we merge the last store on the chain.
8571 bool Changed = MergeConsecutiveStores(ST);
8572 EverChanged |= Changed;
8573 if (!Changed) break;
8574 } while (ST->getOpcode() != ISD::DELETED_NODE);
8577 return SDValue(N, 0);
8580 return ReduceLoadOpStoreWidth(N);
8583 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
8584 SDValue InVec = N->getOperand(0);
8585 SDValue InVal = N->getOperand(1);
8586 SDValue EltNo = N->getOperand(2);
8589 // If the inserted element is an UNDEF, just use the input vector.
8590 if (InVal.getOpcode() == ISD::UNDEF)
8593 EVT VT = InVec.getValueType();
8595 // If we can't generate a legal BUILD_VECTOR, exit
8596 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
8599 // Check that we know which element is being inserted
8600 if (!isa<ConstantSDNode>(EltNo))
8602 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8604 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
8605 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
8607 SmallVector<SDValue, 8> Ops;
8608 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
8609 Ops.append(InVec.getNode()->op_begin(),
8610 InVec.getNode()->op_end());
8611 } else if (InVec.getOpcode() == ISD::UNDEF) {
8612 unsigned NElts = VT.getVectorNumElements();
8613 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
8618 // Insert the element
8619 if (Elt < Ops.size()) {
8620 // All the operands of BUILD_VECTOR must have the same type;
8621 // we enforce that here.
8622 EVT OpVT = Ops[0].getValueType();
8623 if (InVal.getValueType() != OpVT)
8624 InVal = OpVT.bitsGT(InVal.getValueType()) ?
8625 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
8626 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
8630 // Return the new vector
8631 return DAG.getNode(ISD::BUILD_VECTOR, dl,
8632 VT, &Ops[0], Ops.size());
8635 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
8636 // (vextract (scalar_to_vector val, 0) -> val
8637 SDValue InVec = N->getOperand(0);
8638 EVT VT = InVec.getValueType();
8639 EVT NVT = N->getValueType(0);
8641 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8642 // Check if the result type doesn't match the inserted element type. A
8643 // SCALAR_TO_VECTOR may truncate the inserted element and the
8644 // EXTRACT_VECTOR_ELT may widen the extracted vector.
8645 SDValue InOp = InVec.getOperand(0);
8646 if (InOp.getValueType() != NVT) {
8647 assert(InOp.getValueType().isInteger() && NVT.isInteger());
8648 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
8653 SDValue EltNo = N->getOperand(1);
8654 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
8656 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
8657 // We only perform this optimization before the op legalization phase because
8658 // we may introduce new vector instructions which are not backed by TD
8659 // patterns. For example on AVX, extracting elements from a wide vector
8660 // without using extract_subvector.
8661 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
8662 && ConstEltNo && !LegalOperations) {
8663 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8664 int NumElem = VT.getVectorNumElements();
8665 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
8666 // Find the new index to extract from.
8667 int OrigElt = SVOp->getMaskElt(Elt);
8669 // Extracting an undef index is undef.
8671 return DAG.getUNDEF(NVT);
8673 // Select the right vector half to extract from.
8674 if (OrigElt < NumElem) {
8675 InVec = InVec->getOperand(0);
8677 InVec = InVec->getOperand(1);
8681 EVT IndexTy = N->getOperand(1).getValueType();
8682 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
8683 InVec, DAG.getConstant(OrigElt, IndexTy));
8686 // Perform only after legalization to ensure build_vector / vector_shuffle
8687 // optimizations have already been done.
8688 if (!LegalOperations) return SDValue();
8690 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
8691 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
8692 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
8695 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8696 bool NewLoad = false;
8697 bool BCNumEltsChanged = false;
8698 EVT ExtVT = VT.getVectorElementType();
8701 // If the result of load has to be truncated, then it's not necessarily
8703 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
8706 if (InVec.getOpcode() == ISD::BITCAST) {
8707 // Don't duplicate a load with other uses.
8708 if (!InVec.hasOneUse())
8711 EVT BCVT = InVec.getOperand(0).getValueType();
8712 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
8714 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
8715 BCNumEltsChanged = true;
8716 InVec = InVec.getOperand(0);
8717 ExtVT = BCVT.getVectorElementType();
8721 LoadSDNode *LN0 = NULL;
8722 const ShuffleVectorSDNode *SVN = NULL;
8723 if (ISD::isNormalLoad(InVec.getNode())) {
8724 LN0 = cast<LoadSDNode>(InVec);
8725 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8726 InVec.getOperand(0).getValueType() == ExtVT &&
8727 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
8728 // Don't duplicate a load with other uses.
8729 if (!InVec.hasOneUse())
8732 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
8733 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
8734 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
8736 // (load $addr+1*size)
8738 // Don't duplicate a load with other uses.
8739 if (!InVec.hasOneUse())
8742 // If the bit convert changed the number of elements, it is unsafe
8743 // to examine the mask.
8744 if (BCNumEltsChanged)
8747 // Select the input vector, guarding against out of range extract vector.
8748 unsigned NumElems = VT.getVectorNumElements();
8749 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
8750 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
8752 if (InVec.getOpcode() == ISD::BITCAST) {
8753 // Don't duplicate a load with other uses.
8754 if (!InVec.hasOneUse())
8757 InVec = InVec.getOperand(0);
8759 if (ISD::isNormalLoad(InVec.getNode())) {
8760 LN0 = cast<LoadSDNode>(InVec);
8761 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
8765 // Make sure we found a non-volatile load and the extractelement is
8767 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
8770 // If Idx was -1 above, Elt is going to be -1, so just return undef.
8772 return DAG.getUNDEF(LVT);
8774 unsigned Align = LN0->getAlignment();
8776 // Check the resultant load doesn't need a higher alignment than the
8780 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
8782 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
8788 SDValue NewPtr = LN0->getBasePtr();
8789 unsigned PtrOff = 0;
8792 PtrOff = LVT.getSizeInBits() * Elt / 8;
8793 EVT PtrType = NewPtr.getValueType();
8794 if (TLI.isBigEndian())
8795 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
8796 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
8797 DAG.getConstant(PtrOff, PtrType));
8800 // The replacement we need to do here is a little tricky: we need to
8801 // replace an extractelement of a load with a load.
8802 // Use ReplaceAllUsesOfValuesWith to do the replacement.
8803 // Note that this replacement assumes that the extractvalue is the only
8804 // use of the load; that's okay because we don't want to perform this
8805 // transformation in other cases anyway.
8808 if (NVT.bitsGT(LVT)) {
8809 // If the result type of vextract is wider than the load, then issue an
8810 // extending load instead.
8811 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
8812 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
8813 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
8814 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
8815 LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
8816 Chain = Load.getValue(1);
8818 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
8819 LN0->getPointerInfo().getWithOffset(PtrOff),
8820 LN0->isVolatile(), LN0->isNonTemporal(),
8821 LN0->isInvariant(), Align);
8822 Chain = Load.getValue(1);
8823 if (NVT.bitsLT(LVT))
8824 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
8826 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
8828 WorkListRemover DeadNodes(*this);
8829 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
8830 SDValue To[] = { Load, Chain };
8831 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8832 // Since we're explcitly calling ReplaceAllUses, add the new node to the
8833 // worklist explicitly as well.
8834 AddToWorkList(Load.getNode());
8835 AddUsersToWorkList(Load.getNode()); // Add users too
8836 // Make sure to revisit this node to clean it up; it will usually be dead.
8838 return SDValue(N, 0);
8844 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
8845 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
8846 // We perform this optimization post type-legalization because
8847 // the type-legalizer often scalarizes integer-promoted vectors.
8848 // Performing this optimization before may create bit-casts which
8849 // will be type-legalized to complex code sequences.
8850 // We perform this optimization only before the operation legalizer because we
8851 // may introduce illegal operations.
8852 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
8855 unsigned NumInScalars = N->getNumOperands();
8857 EVT VT = N->getValueType(0);
8859 // Check to see if this is a BUILD_VECTOR of a bunch of values
8860 // which come from any_extend or zero_extend nodes. If so, we can create
8861 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
8862 // optimizations. We do not handle sign-extend because we can't fill the sign
8864 EVT SourceType = MVT::Other;
8865 bool AllAnyExt = true;
8867 for (unsigned i = 0; i != NumInScalars; ++i) {
8868 SDValue In = N->getOperand(i);
8869 // Ignore undef inputs.
8870 if (In.getOpcode() == ISD::UNDEF) continue;
8872 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
8873 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
8875 // Abort if the element is not an extension.
8876 if (!ZeroExt && !AnyExt) {
8877 SourceType = MVT::Other;
8881 // The input is a ZeroExt or AnyExt. Check the original type.
8882 EVT InTy = In.getOperand(0).getValueType();
8884 // Check that all of the widened source types are the same.
8885 if (SourceType == MVT::Other)
8888 else if (InTy != SourceType) {
8889 // Multiple income types. Abort.
8890 SourceType = MVT::Other;
8894 // Check if all of the extends are ANY_EXTENDs.
8895 AllAnyExt &= AnyExt;
8898 // In order to have valid types, all of the inputs must be extended from the
8899 // same source type and all of the inputs must be any or zero extend.
8900 // Scalar sizes must be a power of two.
8901 EVT OutScalarTy = VT.getScalarType();
8902 bool ValidTypes = SourceType != MVT::Other &&
8903 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
8904 isPowerOf2_32(SourceType.getSizeInBits());
8906 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
8907 // turn into a single shuffle instruction.
8911 bool isLE = TLI.isLittleEndian();
8912 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
8913 assert(ElemRatio > 1 && "Invalid element size ratio");
8914 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
8915 DAG.getConstant(0, SourceType);
8917 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
8918 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
8920 // Populate the new build_vector
8921 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8922 SDValue Cast = N->getOperand(i);
8923 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
8924 Cast.getOpcode() == ISD::ZERO_EXTEND ||
8925 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
8927 if (Cast.getOpcode() == ISD::UNDEF)
8928 In = DAG.getUNDEF(SourceType);
8930 In = Cast->getOperand(0);
8931 unsigned Index = isLE ? (i * ElemRatio) :
8932 (i * ElemRatio + (ElemRatio - 1));
8934 assert(Index < Ops.size() && "Invalid index");
8938 // The type of the new BUILD_VECTOR node.
8939 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
8940 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
8941 "Invalid vector size");
8942 // Check if the new vector type is legal.
8943 if (!isTypeLegal(VecVT)) return SDValue();
8945 // Make the new BUILD_VECTOR.
8946 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
8948 // The new BUILD_VECTOR node has the potential to be further optimized.
8949 AddToWorkList(BV.getNode());
8950 // Bitcast to the desired type.
8951 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8954 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
8955 EVT VT = N->getValueType(0);
8957 unsigned NumInScalars = N->getNumOperands();
8960 EVT SrcVT = MVT::Other;
8961 unsigned Opcode = ISD::DELETED_NODE;
8962 unsigned NumDefs = 0;
8964 for (unsigned i = 0; i != NumInScalars; ++i) {
8965 SDValue In = N->getOperand(i);
8966 unsigned Opc = In.getOpcode();
8968 if (Opc == ISD::UNDEF)
8971 // If all scalar values are floats and converted from integers.
8972 if (Opcode == ISD::DELETED_NODE &&
8973 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
8980 EVT InVT = In.getOperand(0).getValueType();
8982 // If all scalar values are typed differently, bail out. It's chosen to
8983 // simplify BUILD_VECTOR of integer types.
8984 if (SrcVT == MVT::Other)
8991 // If the vector has just one element defined, it's not worth to fold it into
8992 // a vectorized one.
8996 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
8997 && "Should only handle conversion from integer to float.");
8998 assert(SrcVT != MVT::Other && "Cannot determine source type!");
9000 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9002 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9005 SmallVector<SDValue, 8> Opnds;
9006 for (unsigned i = 0; i != NumInScalars; ++i) {
9007 SDValue In = N->getOperand(i);
9009 if (In.getOpcode() == ISD::UNDEF)
9010 Opnds.push_back(DAG.getUNDEF(SrcVT));
9012 Opnds.push_back(In.getOperand(0));
9014 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9015 &Opnds[0], Opnds.size());
9016 AddToWorkList(BV.getNode());
9018 return DAG.getNode(Opcode, dl, VT, BV);
9021 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9022 unsigned NumInScalars = N->getNumOperands();
9024 EVT VT = N->getValueType(0);
9026 // A vector built entirely of undefs is undef.
9027 if (ISD::allOperandsUndef(N))
9028 return DAG.getUNDEF(VT);
9030 SDValue V = reduceBuildVecExtToExtBuildVec(N);
9034 V = reduceBuildVecConvertToConvertBuildVec(N);
9038 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9039 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9040 // at most two distinct vectors, turn this into a shuffle node.
9042 // May only combine to shuffle after legalize if shuffle is legal.
9043 if (LegalOperations &&
9044 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9047 SDValue VecIn1, VecIn2;
9048 for (unsigned i = 0; i != NumInScalars; ++i) {
9049 // Ignore undef inputs.
9050 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9052 // If this input is something other than a EXTRACT_VECTOR_ELT with a
9053 // constant index, bail out.
9054 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9055 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9056 VecIn1 = VecIn2 = SDValue(0, 0);
9060 // We allow up to two distinct input vectors.
9061 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9062 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9065 if (VecIn1.getNode() == 0) {
9066 VecIn1 = ExtractedFromVec;
9067 } else if (VecIn2.getNode() == 0) {
9068 VecIn2 = ExtractedFromVec;
9071 VecIn1 = VecIn2 = SDValue(0, 0);
9076 // If everything is good, we can make a shuffle operation.
9077 if (VecIn1.getNode()) {
9078 SmallVector<int, 8> Mask;
9079 for (unsigned i = 0; i != NumInScalars; ++i) {
9080 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9085 // If extracting from the first vector, just use the index directly.
9086 SDValue Extract = N->getOperand(i);
9087 SDValue ExtVal = Extract.getOperand(1);
9088 if (Extract.getOperand(0) == VecIn1) {
9089 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9090 if (ExtIndex > VT.getVectorNumElements())
9093 Mask.push_back(ExtIndex);
9097 // Otherwise, use InIdx + VecSize
9098 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9099 Mask.push_back(Idx+NumInScalars);
9102 // We can't generate a shuffle node with mismatched input and output types.
9103 // Attempt to transform a single input vector to the correct type.
9104 if ((VT != VecIn1.getValueType())) {
9105 // We don't support shuffeling between TWO values of different types.
9106 if (VecIn2.getNode() != 0)
9109 // We only support widening of vectors which are half the size of the
9110 // output registers. For example XMM->YMM widening on X86 with AVX.
9111 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9114 // If the input vector type has a different base type to the output
9115 // vector type, bail out.
9116 if (VecIn1.getValueType().getVectorElementType() !=
9117 VT.getVectorElementType())
9120 // Widen the input vector by adding undef values.
9121 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9122 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9125 // If VecIn2 is unused then change it to undef.
9126 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9128 // Check that we were able to transform all incoming values to the same
9130 if (VecIn2.getValueType() != VecIn1.getValueType() ||
9131 VecIn1.getValueType() != VT)
9134 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9135 if (!isTypeLegal(VT))
9138 // Return the new VECTOR_SHUFFLE node.
9142 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9148 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9149 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9150 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
9151 // inputs come from at most two distinct vectors, turn this into a shuffle
9154 // If we only have one input vector, we don't need to do any concatenation.
9155 if (N->getNumOperands() == 1)
9156 return N->getOperand(0);
9158 // Check if all of the operands are undefs.
9159 if (ISD::allOperandsUndef(N))
9160 return DAG.getUNDEF(N->getValueType(0));
9162 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9163 // nodes often generate nop CONCAT_VECTOR nodes.
9164 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9165 // place the incoming vectors at the exact same location.
9166 SDValue SingleSource = SDValue();
9167 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9169 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9170 SDValue Op = N->getOperand(i);
9172 if (Op.getOpcode() == ISD::UNDEF)
9175 // Check if this is the identity extract:
9176 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9179 // Find the single incoming vector for the extract_subvector.
9180 if (SingleSource.getNode()) {
9181 if (Op.getOperand(0) != SingleSource)
9184 SingleSource = Op.getOperand(0);
9186 // Check the source type is the same as the type of the result.
9187 // If not, this concat may extend the vector, so we can not
9188 // optimize it away.
9189 if (SingleSource.getValueType() != N->getValueType(0))
9193 unsigned IdentityIndex = i * PartNumElem;
9194 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9195 // The extract index must be constant.
9199 // Check that we are reading from the identity index.
9200 if (CS->getZExtValue() != IdentityIndex)
9204 if (SingleSource.getNode())
9205 return SingleSource;
9210 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9211 EVT NVT = N->getValueType(0);
9212 SDValue V = N->getOperand(0);
9214 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9216 // (extract_subvec (concat V1, V2, ...), i)
9219 // Only operand 0 is checked as 'concat' assumes all inputs of the same type.
9220 if (V->getOperand(0).getValueType() != NVT)
9222 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9223 unsigned NumElems = NVT.getVectorNumElements();
9224 assert((Idx % NumElems) == 0 &&
9225 "IDX in concat is not a multiple of the result vector length.");
9226 return V->getOperand(Idx / NumElems);
9230 if (V->getOpcode() == ISD::BITCAST)
9231 V = V.getOperand(0);
9233 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9235 // Handle only simple case where vector being inserted and vector
9236 // being extracted are of same type, and are half size of larger vectors.
9237 EVT BigVT = V->getOperand(0).getValueType();
9238 EVT SmallVT = V->getOperand(1).getValueType();
9239 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9242 // Only handle cases where both indexes are constants with the same type.
9243 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9244 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9246 if (InsIdx && ExtIdx &&
9247 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9248 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9250 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9252 // indices are equal or bit offsets are equal => V1
9253 // otherwise => (extract_subvec V1, ExtIdx)
9254 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9255 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9256 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9257 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9258 DAG.getNode(ISD::BITCAST, dl,
9259 N->getOperand(0).getValueType(),
9260 V->getOperand(0)), N->getOperand(1));
9267 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9268 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9269 EVT VT = N->getValueType(0);
9270 unsigned NumElts = VT.getVectorNumElements();
9272 SDValue N0 = N->getOperand(0);
9273 SDValue N1 = N->getOperand(1);
9274 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9276 SmallVector<SDValue, 4> Ops;
9277 EVT ConcatVT = N0.getOperand(0).getValueType();
9278 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9279 unsigned NumConcats = NumElts / NumElemsPerConcat;
9281 // Look at every vector that's inserted. We're looking for exact
9282 // subvector-sized copies from a concatenated vector
9283 for (unsigned I = 0; I != NumConcats; ++I) {
9284 // Make sure we're dealing with a copy.
9285 unsigned Begin = I * NumElemsPerConcat;
9286 bool AllUndef = true, NoUndef = true;
9287 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
9288 if (SVN->getMaskElt(J) >= 0)
9295 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9298 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
9299 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9302 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9303 if (FirstElt < N0.getNumOperands())
9304 Ops.push_back(N0.getOperand(FirstElt));
9306 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9308 } else if (AllUndef) {
9309 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
9310 } else { // Mixed with general masks and undefs, can't do optimization.
9315 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
9319 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
9320 EVT VT = N->getValueType(0);
9321 unsigned NumElts = VT.getVectorNumElements();
9323 SDValue N0 = N->getOperand(0);
9324 SDValue N1 = N->getOperand(1);
9326 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
9328 // Canonicalize shuffle undef, undef -> undef
9329 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
9330 return DAG.getUNDEF(VT);
9332 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9334 // Canonicalize shuffle v, v -> v, undef
9336 SmallVector<int, 8> NewMask;
9337 for (unsigned i = 0; i != NumElts; ++i) {
9338 int Idx = SVN->getMaskElt(i);
9339 if (Idx >= (int)NumElts) Idx -= NumElts;
9340 NewMask.push_back(Idx);
9342 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
9346 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
9347 if (N0.getOpcode() == ISD::UNDEF) {
9348 SmallVector<int, 8> NewMask;
9349 for (unsigned i = 0; i != NumElts; ++i) {
9350 int Idx = SVN->getMaskElt(i);
9352 if (Idx < (int)NumElts)
9357 NewMask.push_back(Idx);
9359 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
9363 // Remove references to rhs if it is undef
9364 if (N1.getOpcode() == ISD::UNDEF) {
9365 bool Changed = false;
9366 SmallVector<int, 8> NewMask;
9367 for (unsigned i = 0; i != NumElts; ++i) {
9368 int Idx = SVN->getMaskElt(i);
9369 if (Idx >= (int)NumElts) {
9373 NewMask.push_back(Idx);
9376 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
9379 // If it is a splat, check if the argument vector is another splat or a
9380 // build_vector with all scalar elements the same.
9381 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
9382 SDNode *V = N0.getNode();
9384 // If this is a bit convert that changes the element type of the vector but
9385 // not the number of vector elements, look through it. Be careful not to
9386 // look though conversions that change things like v4f32 to v2f64.
9387 if (V->getOpcode() == ISD::BITCAST) {
9388 SDValue ConvInput = V->getOperand(0);
9389 if (ConvInput.getValueType().isVector() &&
9390 ConvInput.getValueType().getVectorNumElements() == NumElts)
9391 V = ConvInput.getNode();
9394 if (V->getOpcode() == ISD::BUILD_VECTOR) {
9395 assert(V->getNumOperands() == NumElts &&
9396 "BUILD_VECTOR has wrong number of operands");
9398 bool AllSame = true;
9399 for (unsigned i = 0; i != NumElts; ++i) {
9400 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
9401 Base = V->getOperand(i);
9405 // Splat of <u, u, u, u>, return <u, u, u, u>
9406 if (!Base.getNode())
9408 for (unsigned i = 0; i != NumElts; ++i) {
9409 if (V->getOperand(i) != Base) {
9414 // Splat of <x, x, x, x>, return <x, x, x, x>
9420 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
9421 Level < AfterLegalizeVectorOps &&
9422 (N1.getOpcode() == ISD::UNDEF ||
9423 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9424 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
9425 SDValue V = partitionShuffleOfConcats(N, DAG);
9431 // If this shuffle node is simply a swizzle of another shuffle node,
9432 // and it reverses the swizzle of the previous shuffle then we can
9433 // optimize shuffle(shuffle(x, undef), undef) -> x.
9434 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
9435 N1.getOpcode() == ISD::UNDEF) {
9437 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
9439 // Shuffle nodes can only reverse shuffles with a single non-undef value.
9440 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
9443 // The incoming shuffle must be of the same type as the result of the
9445 assert(OtherSV->getOperand(0).getValueType() == VT &&
9446 "Shuffle types don't match");
9448 for (unsigned i = 0; i != NumElts; ++i) {
9449 int Idx = SVN->getMaskElt(i);
9450 assert(Idx < (int)NumElts && "Index references undef operand");
9451 // Next, this index comes from the first value, which is the incoming
9452 // shuffle. Adopt the incoming index.
9454 Idx = OtherSV->getMaskElt(Idx);
9456 // The combined shuffle must map each index to itself.
9457 if (Idx >= 0 && (unsigned)Idx != i)
9461 return OtherSV->getOperand(0);
9467 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
9468 /// an AND to a vector_shuffle with the destination vector and a zero vector.
9469 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
9470 /// vector_shuffle V, Zero, <0, 4, 2, 4>
9471 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
9472 EVT VT = N->getValueType(0);
9474 SDValue LHS = N->getOperand(0);
9475 SDValue RHS = N->getOperand(1);
9476 if (N->getOpcode() == ISD::AND) {
9477 if (RHS.getOpcode() == ISD::BITCAST)
9478 RHS = RHS.getOperand(0);
9479 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
9480 SmallVector<int, 8> Indices;
9481 unsigned NumElts = RHS.getNumOperands();
9482 for (unsigned i = 0; i != NumElts; ++i) {
9483 SDValue Elt = RHS.getOperand(i);
9484 if (!isa<ConstantSDNode>(Elt))
9487 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
9488 Indices.push_back(i);
9489 else if (cast<ConstantSDNode>(Elt)->isNullValue())
9490 Indices.push_back(NumElts);
9495 // Let's see if the target supports this vector_shuffle.
9496 EVT RVT = RHS.getValueType();
9497 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
9500 // Return the new VECTOR_SHUFFLE node.
9501 EVT EltVT = RVT.getVectorElementType();
9502 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
9503 DAG.getConstant(0, EltVT));
9504 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9505 RVT, &ZeroOps[0], ZeroOps.size());
9506 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
9507 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
9508 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
9515 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
9516 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
9517 assert(N->getValueType(0).isVector() &&
9518 "SimplifyVBinOp only works on vectors!");
9520 SDValue LHS = N->getOperand(0);
9521 SDValue RHS = N->getOperand(1);
9522 SDValue Shuffle = XformToShuffleWithZero(N);
9523 if (Shuffle.getNode()) return Shuffle;
9525 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
9527 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
9528 RHS.getOpcode() == ISD::BUILD_VECTOR) {
9529 SmallVector<SDValue, 8> Ops;
9530 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
9531 SDValue LHSOp = LHS.getOperand(i);
9532 SDValue RHSOp = RHS.getOperand(i);
9533 // If these two elements can't be folded, bail out.
9534 if ((LHSOp.getOpcode() != ISD::UNDEF &&
9535 LHSOp.getOpcode() != ISD::Constant &&
9536 LHSOp.getOpcode() != ISD::ConstantFP) ||
9537 (RHSOp.getOpcode() != ISD::UNDEF &&
9538 RHSOp.getOpcode() != ISD::Constant &&
9539 RHSOp.getOpcode() != ISD::ConstantFP))
9542 // Can't fold divide by zero.
9543 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
9544 N->getOpcode() == ISD::FDIV) {
9545 if ((RHSOp.getOpcode() == ISD::Constant &&
9546 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
9547 (RHSOp.getOpcode() == ISD::ConstantFP &&
9548 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
9552 EVT VT = LHSOp.getValueType();
9553 EVT RVT = RHSOp.getValueType();
9555 // Integer BUILD_VECTOR operands may have types larger than the element
9556 // size (e.g., when the element type is not legal). Prior to type
9557 // legalization, the types may not match between the two BUILD_VECTORS.
9558 // Truncate one of the operands to make them match.
9559 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
9560 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
9562 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
9566 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
9568 if (FoldOp.getOpcode() != ISD::UNDEF &&
9569 FoldOp.getOpcode() != ISD::Constant &&
9570 FoldOp.getOpcode() != ISD::ConstantFP)
9572 Ops.push_back(FoldOp);
9573 AddToWorkList(FoldOp.getNode());
9576 if (Ops.size() == LHS.getNumOperands())
9577 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9578 LHS.getValueType(), &Ops[0], Ops.size());
9584 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
9585 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
9586 assert(N->getValueType(0).isVector() &&
9587 "SimplifyVUnaryOp only works on vectors!");
9589 SDValue N0 = N->getOperand(0);
9591 if (N0.getOpcode() != ISD::BUILD_VECTOR)
9594 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
9595 SmallVector<SDValue, 8> Ops;
9596 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
9597 SDValue Op = N0.getOperand(i);
9598 if (Op.getOpcode() != ISD::UNDEF &&
9599 Op.getOpcode() != ISD::ConstantFP)
9601 EVT EltVT = Op.getValueType();
9602 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
9603 if (FoldOp.getOpcode() != ISD::UNDEF &&
9604 FoldOp.getOpcode() != ISD::ConstantFP)
9606 Ops.push_back(FoldOp);
9607 AddToWorkList(FoldOp.getNode());
9610 if (Ops.size() != N0.getNumOperands())
9613 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9614 N0.getValueType(), &Ops[0], Ops.size());
9617 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
9618 SDValue N1, SDValue N2){
9619 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
9621 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
9622 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9624 // If we got a simplified select_cc node back from SimplifySelectCC, then
9625 // break it down into a new SETCC node, and a new SELECT node, and then return
9626 // the SELECT node, since we were called with a SELECT node.
9627 if (SCC.getNode()) {
9628 // Check to see if we got a select_cc back (to turn into setcc/select).
9629 // Otherwise, just return whatever node we got back, like fabs.
9630 if (SCC.getOpcode() == ISD::SELECT_CC) {
9631 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
9633 SCC.getOperand(0), SCC.getOperand(1),
9635 AddToWorkList(SETCC.getNode());
9636 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
9637 SCC.getOperand(2), SCC.getOperand(3), SETCC);
9645 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
9646 /// are the two values being selected between, see if we can simplify the
9647 /// select. Callers of this should assume that TheSelect is deleted if this
9648 /// returns true. As such, they should return the appropriate thing (e.g. the
9649 /// node) back to the top-level of the DAG combiner loop to avoid it being
9651 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
9654 // Cannot simplify select with vector condition
9655 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
9657 // If this is a select from two identical things, try to pull the operation
9658 // through the select.
9659 if (LHS.getOpcode() != RHS.getOpcode() ||
9660 !LHS.hasOneUse() || !RHS.hasOneUse())
9663 // If this is a load and the token chain is identical, replace the select
9664 // of two loads with a load through a select of the address to load from.
9665 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
9666 // constants have been dropped into the constant pool.
9667 if (LHS.getOpcode() == ISD::LOAD) {
9668 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
9669 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
9671 // Token chains must be identical.
9672 if (LHS.getOperand(0) != RHS.getOperand(0) ||
9673 // Do not let this transformation reduce the number of volatile loads.
9674 LLD->isVolatile() || RLD->isVolatile() ||
9675 // If this is an EXTLOAD, the VT's must match.
9676 LLD->getMemoryVT() != RLD->getMemoryVT() ||
9677 // If this is an EXTLOAD, the kind of extension must match.
9678 (LLD->getExtensionType() != RLD->getExtensionType() &&
9679 // The only exception is if one of the extensions is anyext.
9680 LLD->getExtensionType() != ISD::EXTLOAD &&
9681 RLD->getExtensionType() != ISD::EXTLOAD) ||
9682 // FIXME: this discards src value information. This is
9683 // over-conservative. It would be beneficial to be able to remember
9684 // both potential memory locations. Since we are discarding
9685 // src value info, don't do the transformation if the memory
9686 // locations are not in the default address space.
9687 LLD->getPointerInfo().getAddrSpace() != 0 ||
9688 RLD->getPointerInfo().getAddrSpace() != 0 ||
9689 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
9690 LLD->getBasePtr().getValueType()))
9693 // Check that the select condition doesn't reach either load. If so,
9694 // folding this will induce a cycle into the DAG. If not, this is safe to
9695 // xform, so create a select of the addresses.
9697 if (TheSelect->getOpcode() == ISD::SELECT) {
9698 SDNode *CondNode = TheSelect->getOperand(0).getNode();
9699 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
9700 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
9702 // The loads must not depend on one another.
9703 if (LLD->isPredecessorOf(RLD) ||
9704 RLD->isPredecessorOf(LLD))
9706 Addr = DAG.getSelect(SDLoc(TheSelect),
9707 LLD->getBasePtr().getValueType(),
9708 TheSelect->getOperand(0), LLD->getBasePtr(),
9710 } else { // Otherwise SELECT_CC
9711 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
9712 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
9714 if ((LLD->hasAnyUseOfValue(1) &&
9715 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
9716 (RLD->hasAnyUseOfValue(1) &&
9717 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
9720 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
9721 LLD->getBasePtr().getValueType(),
9722 TheSelect->getOperand(0),
9723 TheSelect->getOperand(1),
9724 LLD->getBasePtr(), RLD->getBasePtr(),
9725 TheSelect->getOperand(4));
9729 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
9730 Load = DAG.getLoad(TheSelect->getValueType(0),
9732 // FIXME: Discards pointer info.
9733 LLD->getChain(), Addr, MachinePointerInfo(),
9734 LLD->isVolatile(), LLD->isNonTemporal(),
9735 LLD->isInvariant(), LLD->getAlignment());
9737 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
9738 RLD->getExtensionType() : LLD->getExtensionType(),
9740 TheSelect->getValueType(0),
9741 // FIXME: Discards pointer info.
9742 LLD->getChain(), Addr, MachinePointerInfo(),
9743 LLD->getMemoryVT(), LLD->isVolatile(),
9744 LLD->isNonTemporal(), LLD->getAlignment());
9747 // Users of the select now use the result of the load.
9748 CombineTo(TheSelect, Load);
9750 // Users of the old loads now use the new load's chain. We know the
9751 // old-load value is dead now.
9752 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
9753 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
9760 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
9761 /// where 'cond' is the comparison specified by CC.
9762 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
9763 SDValue N2, SDValue N3,
9764 ISD::CondCode CC, bool NotExtCompare) {
9765 // (x ? y : y) -> y.
9766 if (N2 == N3) return N2;
9768 EVT VT = N2.getValueType();
9769 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
9770 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
9771 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
9773 // Determine if the condition we're dealing with is constant
9774 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
9775 N0, N1, CC, DL, false);
9776 if (SCC.getNode()) AddToWorkList(SCC.getNode());
9777 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
9779 // fold select_cc true, x, y -> x
9780 if (SCCC && !SCCC->isNullValue())
9782 // fold select_cc false, x, y -> y
9783 if (SCCC && SCCC->isNullValue())
9786 // Check to see if we can simplify the select into an fabs node
9787 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
9788 // Allow either -0.0 or 0.0
9789 if (CFP->getValueAPF().isZero()) {
9790 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
9791 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
9792 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
9793 N2 == N3.getOperand(0))
9794 return DAG.getNode(ISD::FABS, DL, VT, N0);
9796 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
9797 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
9798 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
9799 N2.getOperand(0) == N3)
9800 return DAG.getNode(ISD::FABS, DL, VT, N3);
9804 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
9805 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
9806 // in it. This is a win when the constant is not otherwise available because
9807 // it replaces two constant pool loads with one. We only do this if the FP
9808 // type is known to be legal, because if it isn't, then we are before legalize
9809 // types an we want the other legalization to happen first (e.g. to avoid
9810 // messing with soft float) and if the ConstantFP is not legal, because if
9811 // it is legal, we may not need to store the FP constant in a constant pool.
9812 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
9813 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
9814 if (TLI.isTypeLegal(N2.getValueType()) &&
9815 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
9816 TargetLowering::Legal) &&
9817 // If both constants have multiple uses, then we won't need to do an
9818 // extra load, they are likely around in registers for other users.
9819 (TV->hasOneUse() || FV->hasOneUse())) {
9820 Constant *Elts[] = {
9821 const_cast<ConstantFP*>(FV->getConstantFPValue()),
9822 const_cast<ConstantFP*>(TV->getConstantFPValue())
9824 Type *FPTy = Elts[0]->getType();
9825 const DataLayout &TD = *TLI.getDataLayout();
9827 // Create a ConstantArray of the two constants.
9828 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
9829 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
9830 TD.getPrefTypeAlignment(FPTy));
9831 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9833 // Get the offsets to the 0 and 1 element of the array so that we can
9834 // select between them.
9835 SDValue Zero = DAG.getIntPtrConstant(0);
9836 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
9837 SDValue One = DAG.getIntPtrConstant(EltSize);
9839 SDValue Cond = DAG.getSetCC(DL,
9840 getSetCCResultType(N0.getValueType()),
9842 AddToWorkList(Cond.getNode());
9843 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
9845 AddToWorkList(CstOffset.getNode());
9846 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
9848 AddToWorkList(CPIdx.getNode());
9849 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
9850 MachinePointerInfo::getConstantPool(), false,
9851 false, false, Alignment);
9856 // Check to see if we can perform the "gzip trick", transforming
9857 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
9858 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
9859 (N1C->isNullValue() || // (a < 0) ? b : 0
9860 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
9861 EVT XType = N0.getValueType();
9862 EVT AType = N2.getValueType();
9863 if (XType.bitsGE(AType)) {
9864 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
9865 // single-bit constant.
9866 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
9867 unsigned ShCtV = N2C->getAPIntValue().logBase2();
9868 ShCtV = XType.getSizeInBits()-ShCtV-1;
9869 SDValue ShCt = DAG.getConstant(ShCtV,
9870 getShiftAmountTy(N0.getValueType()));
9871 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
9873 AddToWorkList(Shift.getNode());
9875 if (XType.bitsGT(AType)) {
9876 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9877 AddToWorkList(Shift.getNode());
9880 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9883 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
9885 DAG.getConstant(XType.getSizeInBits()-1,
9886 getShiftAmountTy(N0.getValueType())));
9887 AddToWorkList(Shift.getNode());
9889 if (XType.bitsGT(AType)) {
9890 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9891 AddToWorkList(Shift.getNode());
9894 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9898 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
9899 // where y is has a single bit set.
9900 // A plaintext description would be, we can turn the SELECT_CC into an AND
9901 // when the condition can be materialized as an all-ones register. Any
9902 // single bit-test can be materialized as an all-ones register with
9903 // shift-left and shift-right-arith.
9904 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
9905 N0->getValueType(0) == VT &&
9906 N1C && N1C->isNullValue() &&
9907 N2C && N2C->isNullValue()) {
9908 SDValue AndLHS = N0->getOperand(0);
9909 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9910 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
9911 // Shift the tested bit over the sign bit.
9912 APInt AndMask = ConstAndRHS->getAPIntValue();
9914 DAG.getConstant(AndMask.countLeadingZeros(),
9915 getShiftAmountTy(AndLHS.getValueType()));
9916 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
9918 // Now arithmetic right shift it all the way over, so the result is either
9919 // all-ones, or zero.
9921 DAG.getConstant(AndMask.getBitWidth()-1,
9922 getShiftAmountTy(Shl.getValueType()));
9923 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
9925 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
9929 // fold select C, 16, 0 -> shl C, 4
9930 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
9931 TLI.getBooleanContents(N0.getValueType().isVector()) ==
9932 TargetLowering::ZeroOrOneBooleanContent) {
9934 // If the caller doesn't want us to simplify this into a zext of a compare,
9936 if (NotExtCompare && N2C->getAPIntValue() == 1)
9939 // Get a SetCC of the condition
9940 // NOTE: Don't create a SETCC if it's not legal on this target.
9941 if (!LegalOperations ||
9942 TLI.isOperationLegal(ISD::SETCC,
9943 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
9945 // cast from setcc result type to select result type
9947 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
9949 if (N2.getValueType().bitsLT(SCC.getValueType()))
9950 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
9953 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
9954 N2.getValueType(), SCC);
9956 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
9957 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
9958 N2.getValueType(), SCC);
9961 AddToWorkList(SCC.getNode());
9962 AddToWorkList(Temp.getNode());
9964 if (N2C->getAPIntValue() == 1)
9967 // shl setcc result by log2 n2c
9968 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
9969 DAG.getConstant(N2C->getAPIntValue().logBase2(),
9970 getShiftAmountTy(Temp.getValueType())));
9974 // Check to see if this is the equivalent of setcc
9975 // FIXME: Turn all of these into setcc if setcc if setcc is legal
9976 // otherwise, go ahead with the folds.
9977 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
9978 EVT XType = N0.getValueType();
9979 if (!LegalOperations ||
9980 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
9981 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
9982 if (Res.getValueType() != VT)
9983 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
9987 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
9988 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
9989 (!LegalOperations ||
9990 TLI.isOperationLegal(ISD::CTLZ, XType))) {
9991 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
9992 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
9993 DAG.getConstant(Log2_32(XType.getSizeInBits()),
9994 getShiftAmountTy(Ctlz.getValueType())));
9996 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
9997 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
9998 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
9999 XType, DAG.getConstant(0, XType), N0);
10000 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10001 return DAG.getNode(ISD::SRL, DL, XType,
10002 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10003 DAG.getConstant(XType.getSizeInBits()-1,
10004 getShiftAmountTy(XType)));
10006 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10007 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10008 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10009 DAG.getConstant(XType.getSizeInBits()-1,
10010 getShiftAmountTy(N0.getValueType())));
10011 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10015 // Check to see if this is an integer abs.
10016 // select_cc setg[te] X, 0, X, -X ->
10017 // select_cc setgt X, -1, X, -X ->
10018 // select_cc setl[te] X, 0, -X, X ->
10019 // select_cc setlt X, 1, -X, X ->
10020 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10022 ConstantSDNode *SubC = NULL;
10023 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10024 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10025 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10026 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10027 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10028 (N1C->isOne() && CC == ISD::SETLT)) &&
10029 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10030 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10032 EVT XType = N0.getValueType();
10033 if (SubC && SubC->isNullValue() && XType.isInteger()) {
10034 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10036 DAG.getConstant(XType.getSizeInBits()-1,
10037 getShiftAmountTy(N0.getValueType())));
10038 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10040 AddToWorkList(Shift.getNode());
10041 AddToWorkList(Add.getNode());
10042 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10049 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10050 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10051 SDValue N1, ISD::CondCode Cond,
10052 SDLoc DL, bool foldBooleans) {
10053 TargetLowering::DAGCombinerInfo
10054 DagCombineInfo(DAG, Level, false, this);
10055 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10058 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10059 /// return a DAG expression to select that will generate the same value by
10060 /// multiplying by a magic number. See:
10061 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10062 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10063 std::vector<SDNode*> Built;
10064 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10066 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10068 AddToWorkList(*ii);
10072 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10073 /// return a DAG expression to select that will generate the same value by
10074 /// multiplying by a magic number. See:
10075 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10076 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10077 std::vector<SDNode*> Built;
10078 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10080 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10082 AddToWorkList(*ii);
10086 /// FindBaseOffset - Return true if base is a frame index, which is known not
10087 // to alias with anything but itself. Provides base object and offset as
10089 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10090 const GlobalValue *&GV, const void *&CV) {
10091 // Assume it is a primitive operation.
10092 Base = Ptr; Offset = 0; GV = 0; CV = 0;
10094 // If it's an adding a simple constant then integrate the offset.
10095 if (Base.getOpcode() == ISD::ADD) {
10096 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10097 Base = Base.getOperand(0);
10098 Offset += C->getZExtValue();
10102 // Return the underlying GlobalValue, and update the Offset. Return false
10103 // for GlobalAddressSDNode since the same GlobalAddress may be represented
10104 // by multiple nodes with different offsets.
10105 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10106 GV = G->getGlobal();
10107 Offset += G->getOffset();
10111 // Return the underlying Constant value, and update the Offset. Return false
10112 // for ConstantSDNodes since the same constant pool entry may be represented
10113 // by multiple nodes with different offsets.
10114 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10115 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10116 : (const void *)C->getConstVal();
10117 Offset += C->getOffset();
10120 // If it's any of the following then it can't alias with anything but itself.
10121 return isa<FrameIndexSDNode>(Base);
10124 /// isAlias - Return true if there is any possibility that the two addresses
10126 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
10127 const Value *SrcValue1, int SrcValueOffset1,
10128 unsigned SrcValueAlign1,
10129 const MDNode *TBAAInfo1,
10130 SDValue Ptr2, int64_t Size2,
10131 const Value *SrcValue2, int SrcValueOffset2,
10132 unsigned SrcValueAlign2,
10133 const MDNode *TBAAInfo2) const {
10134 // If they are the same then they must be aliases.
10135 if (Ptr1 == Ptr2) return true;
10137 // Gather base node and offset information.
10138 SDValue Base1, Base2;
10139 int64_t Offset1, Offset2;
10140 const GlobalValue *GV1, *GV2;
10141 const void *CV1, *CV2;
10142 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10143 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10145 // If they have a same base address then check to see if they overlap.
10146 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10147 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10149 // It is possible for different frame indices to alias each other, mostly
10150 // when tail call optimization reuses return address slots for arguments.
10151 // To catch this case, look up the actual index of frame indices to compute
10152 // the real alias relationship.
10153 if (isFrameIndex1 && isFrameIndex2) {
10154 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10155 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10156 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10157 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10160 // Otherwise, if we know what the bases are, and they aren't identical, then
10161 // we know they cannot alias.
10162 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10165 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10166 // compared to the size and offset of the access, we may be able to prove they
10167 // do not alias. This check is conservative for now to catch cases created by
10168 // splitting vector types.
10169 if ((SrcValueAlign1 == SrcValueAlign2) &&
10170 (SrcValueOffset1 != SrcValueOffset2) &&
10171 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10172 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10173 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10175 // There is no overlap between these relatively aligned accesses of similar
10176 // size, return no alias.
10177 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10181 if (CombinerGlobalAA) {
10182 // Use alias analysis information.
10183 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10184 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10185 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10186 AliasAnalysis::AliasResult AAResult =
10187 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10188 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10189 if (AAResult == AliasAnalysis::NoAlias)
10193 // Otherwise we have to assume they alias.
10197 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10198 SDValue Ptr0, Ptr1;
10199 int64_t Size0, Size1;
10200 const Value *SrcValue0, *SrcValue1;
10201 int SrcValueOffset0, SrcValueOffset1;
10202 unsigned SrcValueAlign0, SrcValueAlign1;
10203 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10204 FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
10205 SrcValueAlign0, SrcTBAAInfo0);
10206 FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
10207 SrcValueAlign1, SrcTBAAInfo1);
10208 return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
10209 SrcValueAlign0, SrcTBAAInfo0,
10210 Ptr1, Size1, SrcValue1, SrcValueOffset1,
10211 SrcValueAlign1, SrcTBAAInfo1);
10214 /// FindAliasInfo - Extracts the relevant alias information from the memory
10215 /// node. Returns true if the operand was a load.
10216 bool DAGCombiner::FindAliasInfo(SDNode *N,
10217 SDValue &Ptr, int64_t &Size,
10218 const Value *&SrcValue,
10219 int &SrcValueOffset,
10220 unsigned &SrcValueAlign,
10221 const MDNode *&TBAAInfo) const {
10222 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10224 Ptr = LS->getBasePtr();
10225 Size = LS->getMemoryVT().getSizeInBits() >> 3;
10226 SrcValue = LS->getSrcValue();
10227 SrcValueOffset = LS->getSrcValueOffset();
10228 SrcValueAlign = LS->getOriginalAlignment();
10229 TBAAInfo = LS->getTBAAInfo();
10230 return isa<LoadSDNode>(LS);
10233 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10234 /// looking for aliasing nodes and adding them to the Aliases vector.
10235 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10236 SmallVector<SDValue, 8> &Aliases) {
10237 SmallVector<SDValue, 8> Chains; // List of chains to visit.
10238 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
10240 // Get alias information for node.
10243 const Value *SrcValue;
10244 int SrcValueOffset;
10245 unsigned SrcValueAlign;
10246 const MDNode *SrcTBAAInfo;
10247 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
10248 SrcValueAlign, SrcTBAAInfo);
10251 Chains.push_back(OriginalChain);
10252 unsigned Depth = 0;
10254 // Look at each chain and determine if it is an alias. If so, add it to the
10255 // aliases list. If not, then continue up the chain looking for the next
10257 while (!Chains.empty()) {
10258 SDValue Chain = Chains.back();
10261 // For TokenFactor nodes, look at each operand and only continue up the
10262 // chain until we find two aliases. If we've seen two aliases, assume we'll
10263 // find more and revert to original chain since the xform is unlikely to be
10266 // FIXME: The depth check could be made to return the last non-aliasing
10267 // chain we found before we hit a tokenfactor rather than the original
10269 if (Depth > 6 || Aliases.size() == 2) {
10271 Aliases.push_back(OriginalChain);
10275 // Don't bother if we've been before.
10276 if (!Visited.insert(Chain.getNode()))
10279 switch (Chain.getOpcode()) {
10280 case ISD::EntryToken:
10281 // Entry token is ideal chain operand, but handled in FindBetterChain.
10286 // Get alias information for Chain.
10289 const Value *OpSrcValue;
10290 int OpSrcValueOffset;
10291 unsigned OpSrcValueAlign;
10292 const MDNode *OpSrcTBAAInfo;
10293 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10294 OpSrcValue, OpSrcValueOffset,
10298 // If chain is alias then stop here.
10299 if (!(IsLoad && IsOpLoad) &&
10300 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
10302 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
10303 OpSrcValueAlign, OpSrcTBAAInfo)) {
10304 Aliases.push_back(Chain);
10306 // Look further up the chain.
10307 Chains.push_back(Chain.getOperand(0));
10313 case ISD::TokenFactor:
10314 // We have to check each of the operands of the token factor for "small"
10315 // token factors, so we queue them up. Adding the operands to the queue
10316 // (stack) in reverse order maintains the original order and increases the
10317 // likelihood that getNode will find a matching token factor (CSE.)
10318 if (Chain.getNumOperands() > 16) {
10319 Aliases.push_back(Chain);
10322 for (unsigned n = Chain.getNumOperands(); n;)
10323 Chains.push_back(Chain.getOperand(--n));
10328 // For all other instructions we will just have to take what we can get.
10329 Aliases.push_back(Chain);
10335 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
10336 /// for a better chain (aliasing node.)
10337 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
10338 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
10340 // Accumulate all the aliases to this node.
10341 GatherAllAliases(N, OldChain, Aliases);
10343 // If no operands then chain to entry token.
10344 if (Aliases.size() == 0)
10345 return DAG.getEntryNode();
10347 // If a single operand then chain to it. We don't need to revisit it.
10348 if (Aliases.size() == 1)
10351 // Construct a custom tailored token factor.
10352 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10353 &Aliases[0], Aliases.size());
10356 // SelectionDAG::Combine - This is the entry point for the file.
10358 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
10359 CodeGenOpt::Level OptLevel) {
10360 /// run - This is the main entry point to this class.
10362 DAGCombiner(*this, AA, OptLevel).Run(Level);