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 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SetVector.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"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
80 //------------------------------ DAGCombiner ---------------------------------//
84 const TargetLowering &TLI;
86 CodeGenOpt::Level OptLevel;
91 /// \brief Worklist of all of the nodes that need to be simplified.
93 /// This must behave as a stack -- new nodes to process are pushed onto the
94 /// back and when processing we pop off of the back.
96 /// The worklist will not contain duplicates but may contain null entries
97 /// due to nodes being deleted from the underlying DAG.
98 SmallVector<SDNode *, 64> Worklist;
100 /// \brief Mapping from an SDNode to its position on the worklist.
102 /// This is used to find and remove nodes from the worklist (by nulling
103 /// them) when they are deleted from the underlying DAG. It relies on
104 /// stable indices of nodes within the worklist.
105 DenseMap<SDNode *, unsigned> WorklistMap;
107 /// \brief Set of nodes which have been combined (at least once).
109 /// This is used to allow us to reliably add any operands of a DAG node
110 /// which have not yet been combined to the worklist.
111 SmallPtrSet<SDNode *, 64> CombinedNodes;
113 // AA - Used for DAG load/store alias analysis.
116 /// AddUsersToWorklist - When an instruction is simplified, add all users of
117 /// the instruction to the work lists because they might get more simplified
120 void AddUsersToWorklist(SDNode *N) {
121 for (SDNode *Node : N->uses())
125 /// visit - call the node-specific routine that knows how to fold each
126 /// particular type of node.
127 SDValue visit(SDNode *N);
130 /// AddToWorklist - Add to the work list making sure its instance is at the
131 /// back (next to be processed.)
132 void AddToWorklist(SDNode *N) {
133 // Skip handle nodes as they can't usefully be combined and confuse the
134 // zero-use deletion strategy.
135 if (N->getOpcode() == ISD::HANDLENODE)
138 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
139 Worklist.push_back(N);
142 /// removeFromWorklist - remove all instances of N from the worklist.
144 void removeFromWorklist(SDNode *N) {
145 CombinedNodes.erase(N);
147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163 return CombineTo(N, &Res, 1, AddTo);
166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
168 SDValue To[] = { Res0, Res1 };
169 return CombineTo(N, To, 2, AddTo);
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176 /// SimplifyDemandedBits - Check the specified integer node value to see if
177 /// it can be simplified or if things it uses can be simplified by bit
178 /// propagation. If so, return true.
179 bool SimplifyDemandedBits(SDValue Op) {
180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
182 return SimplifyDemandedBits(Op, Demanded);
185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
189 bool SliceUpLoad(SDNode *N);
191 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
194 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
195 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
196 /// \param EltNo index of the vector element to load.
197 /// \param OriginalLoad load that EVE came from to be replaced.
198 /// \returns EVE on success SDValue() on failure.
199 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
200 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
201 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
202 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
203 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
204 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue PromoteIntBinOp(SDValue Op);
206 SDValue PromoteIntShiftOp(SDValue Op);
207 SDValue PromoteExtend(SDValue Op);
208 bool PromoteLoad(SDValue Op);
210 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
211 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
212 ISD::NodeType ExtType);
214 /// combine - call the node-specific routine that knows how to fold each
215 /// particular type of node. If that doesn't do anything, try the
216 /// target-specific DAG combines.
217 SDValue combine(SDNode *N);
219 // Visitation implementation - Implement dag node combining for different
220 // node types. The semantics are as follows:
222 // SDValue.getNode() == 0 - No change was made
223 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
224 // otherwise - N should be replaced by the returned Operand.
226 SDValue visitTokenFactor(SDNode *N);
227 SDValue visitMERGE_VALUES(SDNode *N);
228 SDValue visitADD(SDNode *N);
229 SDValue visitSUB(SDNode *N);
230 SDValue visitADDC(SDNode *N);
231 SDValue visitSUBC(SDNode *N);
232 SDValue visitADDE(SDNode *N);
233 SDValue visitSUBE(SDNode *N);
234 SDValue visitMUL(SDNode *N);
235 SDValue visitSDIV(SDNode *N);
236 SDValue visitUDIV(SDNode *N);
237 SDValue visitSREM(SDNode *N);
238 SDValue visitUREM(SDNode *N);
239 SDValue visitMULHU(SDNode *N);
240 SDValue visitMULHS(SDNode *N);
241 SDValue visitSMUL_LOHI(SDNode *N);
242 SDValue visitUMUL_LOHI(SDNode *N);
243 SDValue visitSMULO(SDNode *N);
244 SDValue visitUMULO(SDNode *N);
245 SDValue visitSDIVREM(SDNode *N);
246 SDValue visitUDIVREM(SDNode *N);
247 SDValue visitAND(SDNode *N);
248 SDValue visitOR(SDNode *N);
249 SDValue visitXOR(SDNode *N);
250 SDValue SimplifyVBinOp(SDNode *N);
251 SDValue SimplifyVUnaryOp(SDNode *N);
252 SDValue visitSHL(SDNode *N);
253 SDValue visitSRA(SDNode *N);
254 SDValue visitSRL(SDNode *N);
255 SDValue visitRotate(SDNode *N);
256 SDValue visitCTLZ(SDNode *N);
257 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
258 SDValue visitCTTZ(SDNode *N);
259 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
260 SDValue visitCTPOP(SDNode *N);
261 SDValue visitSELECT(SDNode *N);
262 SDValue visitVSELECT(SDNode *N);
263 SDValue visitSELECT_CC(SDNode *N);
264 SDValue visitSETCC(SDNode *N);
265 SDValue visitSIGN_EXTEND(SDNode *N);
266 SDValue visitZERO_EXTEND(SDNode *N);
267 SDValue visitANY_EXTEND(SDNode *N);
268 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
269 SDValue visitTRUNCATE(SDNode *N);
270 SDValue visitBITCAST(SDNode *N);
271 SDValue visitBUILD_PAIR(SDNode *N);
272 SDValue visitFADD(SDNode *N);
273 SDValue visitFSUB(SDNode *N);
274 SDValue visitFMUL(SDNode *N);
275 SDValue visitFMA(SDNode *N);
276 SDValue visitFDIV(SDNode *N);
277 SDValue visitFREM(SDNode *N);
278 SDValue visitFCOPYSIGN(SDNode *N);
279 SDValue visitSINT_TO_FP(SDNode *N);
280 SDValue visitUINT_TO_FP(SDNode *N);
281 SDValue visitFP_TO_SINT(SDNode *N);
282 SDValue visitFP_TO_UINT(SDNode *N);
283 SDValue visitFP_ROUND(SDNode *N);
284 SDValue visitFP_ROUND_INREG(SDNode *N);
285 SDValue visitFP_EXTEND(SDNode *N);
286 SDValue visitFNEG(SDNode *N);
287 SDValue visitFABS(SDNode *N);
288 SDValue visitFCEIL(SDNode *N);
289 SDValue visitFTRUNC(SDNode *N);
290 SDValue visitFFLOOR(SDNode *N);
291 SDValue visitBRCOND(SDNode *N);
292 SDValue visitBR_CC(SDNode *N);
293 SDValue visitLOAD(SDNode *N);
294 SDValue visitSTORE(SDNode *N);
295 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
296 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
297 SDValue visitBUILD_VECTOR(SDNode *N);
298 SDValue visitCONCAT_VECTORS(SDNode *N);
299 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
300 SDValue visitVECTOR_SHUFFLE(SDNode *N);
301 SDValue visitINSERT_SUBVECTOR(SDNode *N);
303 SDValue XformToShuffleWithZero(SDNode *N);
304 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
306 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
308 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
309 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
310 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
311 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
312 SDValue N3, ISD::CondCode CC,
313 bool NotExtCompare = false);
314 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
315 SDLoc DL, bool foldBooleans = true);
317 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
319 bool isOneUseSetCC(SDValue N) const;
321 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
323 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
324 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
325 SDValue BuildSDIV(SDNode *N);
326 SDValue BuildSDIVPow2(SDNode *N);
327 SDValue BuildUDIV(SDNode *N);
328 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
329 bool DemandHighBits = true);
330 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
331 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
332 SDValue InnerPos, SDValue InnerNeg,
333 unsigned PosOpcode, unsigned NegOpcode,
335 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
336 SDValue ReduceLoadWidth(SDNode *N);
337 SDValue ReduceLoadOpStoreWidth(SDNode *N);
338 SDValue TransformFPLoadStorePair(SDNode *N);
339 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
340 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
342 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
344 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
345 /// looking for aliasing nodes and adding them to the Aliases vector.
346 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
347 SmallVectorImpl<SDValue> &Aliases);
349 /// isAlias - Return true if there is any possibility that the two addresses
351 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
353 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
354 /// looking for a better chain (aliasing node.)
355 SDValue FindBetterChain(SDNode *N, SDValue Chain);
357 /// Merge consecutive store operations into a wide store.
358 /// This optimization uses wide integers or vectors when possible.
359 /// \return True if some memory operations were changed.
360 bool MergeConsecutiveStores(StoreSDNode *N);
362 /// \brief Try to transform a truncation where C is a constant:
363 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
365 /// \p N needs to be a truncation and its first operand an AND. Other
366 /// requirements are checked by the function (e.g. that trunc is
367 /// single-use) and if missed an empty SDValue is returned.
368 SDValue distributeTruncateThroughAnd(SDNode *N);
371 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
372 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
373 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
374 AttributeSet FnAttrs =
375 DAG.getMachineFunction().getFunction()->getAttributes();
377 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
378 Attribute::OptimizeForSize) ||
379 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
382 /// Run - runs the dag combiner on all nodes in the work list
383 void Run(CombineLevel AtLevel);
385 SelectionDAG &getDAG() const { return DAG; }
387 /// getShiftAmountTy - Returns a type large enough to hold any valid
388 /// shift amount - before type legalization these can be huge.
389 EVT getShiftAmountTy(EVT LHSTy) {
390 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
391 if (LHSTy.isVector())
393 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
394 : TLI.getPointerTy();
397 /// isTypeLegal - This method returns true if we are running before type
398 /// legalization or if the specified VT is legal.
399 bool isTypeLegal(const EVT &VT) {
400 if (!LegalTypes) return true;
401 return TLI.isTypeLegal(VT);
404 /// getSetCCResultType - Convenience wrapper around
405 /// TargetLowering::getSetCCResultType
406 EVT getSetCCResultType(EVT VT) const {
407 return TLI.getSetCCResultType(*DAG.getContext(), VT);
414 /// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
415 /// nodes from the worklist.
416 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
419 explicit WorklistRemover(DAGCombiner &dc)
420 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
422 void NodeDeleted(SDNode *N, SDNode *E) override {
423 DC.removeFromWorklist(N);
428 //===----------------------------------------------------------------------===//
429 // TargetLowering::DAGCombinerInfo implementation
430 //===----------------------------------------------------------------------===//
432 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
433 ((DAGCombiner*)DC)->AddToWorklist(N);
436 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
437 ((DAGCombiner*)DC)->removeFromWorklist(N);
440 SDValue TargetLowering::DAGCombinerInfo::
441 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
442 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
445 SDValue TargetLowering::DAGCombinerInfo::
446 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
447 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
451 SDValue TargetLowering::DAGCombinerInfo::
452 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
453 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
456 void TargetLowering::DAGCombinerInfo::
457 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
458 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
461 //===----------------------------------------------------------------------===//
463 //===----------------------------------------------------------------------===//
465 void DAGCombiner::deleteAndRecombine(SDNode *N) {
466 removeFromWorklist(N);
468 // If the operands of this node are only used by the node, they will now be
469 // dead. Make sure to re-visit them and recursively delete dead nodes.
470 for (const SDValue &Op : N->ops())
472 AddToWorklist(Op.getNode());
477 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
478 /// specified expression for the same cost as the expression itself, or 2 if we
479 /// can compute the negated form more cheaply than the expression itself.
480 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
481 const TargetLowering &TLI,
482 const TargetOptions *Options,
483 unsigned Depth = 0) {
484 // fneg is removable even if it has multiple uses.
485 if (Op.getOpcode() == ISD::FNEG) return 2;
487 // Don't allow anything with multiple uses.
488 if (!Op.hasOneUse()) return 0;
490 // Don't recurse exponentially.
491 if (Depth > 6) return 0;
493 switch (Op.getOpcode()) {
494 default: return false;
495 case ISD::ConstantFP:
496 // Don't invert constant FP values after legalize. The negated constant
497 // isn't necessarily legal.
498 return LegalOperations ? 0 : 1;
500 // FIXME: determine better conditions for this xform.
501 if (!Options->UnsafeFPMath) return 0;
503 // After operation legalization, it might not be legal to create new FSUBs.
504 if (LegalOperations &&
505 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
508 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
509 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
512 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
513 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
516 // We can't turn -(A-B) into B-A when we honor signed zeros.
517 if (!Options->UnsafeFPMath) return 0;
519 // fold (fneg (fsub A, B)) -> (fsub B, A)
524 if (Options->HonorSignDependentRoundingFPMath()) return 0;
526 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
527 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
531 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
537 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
542 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
543 /// returns the newly negated expression.
544 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
545 bool LegalOperations, unsigned Depth = 0) {
546 // fneg is removable even if it has multiple uses.
547 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
549 // Don't allow anything with multiple uses.
550 assert(Op.hasOneUse() && "Unknown reuse!");
552 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
553 switch (Op.getOpcode()) {
554 default: llvm_unreachable("Unknown code");
555 case ISD::ConstantFP: {
556 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
558 return DAG.getConstantFP(V, Op.getValueType());
561 // FIXME: determine better conditions for this xform.
562 assert(DAG.getTarget().Options.UnsafeFPMath);
564 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
565 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
566 DAG.getTargetLoweringInfo(),
567 &DAG.getTarget().Options, Depth+1))
568 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
569 GetNegatedExpression(Op.getOperand(0), DAG,
570 LegalOperations, Depth+1),
572 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
573 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
574 GetNegatedExpression(Op.getOperand(1), DAG,
575 LegalOperations, Depth+1),
578 // We can't turn -(A-B) into B-A when we honor signed zeros.
579 assert(DAG.getTarget().Options.UnsafeFPMath);
581 // fold (fneg (fsub 0, B)) -> B
582 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
583 if (N0CFP->getValueAPF().isZero())
584 return Op.getOperand(1);
586 // fold (fneg (fsub A, B)) -> (fsub B, A)
587 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
588 Op.getOperand(1), Op.getOperand(0));
592 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
594 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
595 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
596 DAG.getTargetLoweringInfo(),
597 &DAG.getTarget().Options, Depth+1))
598 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
599 GetNegatedExpression(Op.getOperand(0), DAG,
600 LegalOperations, Depth+1),
603 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
604 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
606 GetNegatedExpression(Op.getOperand(1), DAG,
607 LegalOperations, Depth+1));
611 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
612 GetNegatedExpression(Op.getOperand(0), DAG,
613 LegalOperations, Depth+1));
615 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
616 GetNegatedExpression(Op.getOperand(0), DAG,
617 LegalOperations, Depth+1),
622 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
623 // that selects between the target values used for true and false, making it
624 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
625 // the appropriate nodes based on the type of node we are checking. This
626 // simplifies life a bit for the callers.
627 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
629 if (N.getOpcode() == ISD::SETCC) {
630 LHS = N.getOperand(0);
631 RHS = N.getOperand(1);
632 CC = N.getOperand(2);
636 if (N.getOpcode() != ISD::SELECT_CC ||
637 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
638 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
641 LHS = N.getOperand(0);
642 RHS = N.getOperand(1);
643 CC = N.getOperand(4);
647 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
648 // one use. If this is true, it allows the users to invert the operation for
649 // free when it is profitable to do so.
650 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
652 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
657 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
658 /// elements are all the same constant or undefined.
659 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
660 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
665 unsigned SplatBitSize;
667 EVT EltVT = N->getValueType(0).getVectorElementType();
668 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
670 EltVT.getSizeInBits() >= SplatBitSize);
673 // \brief Returns the SDNode if it is a constant BuildVector or constant.
674 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
675 if (isa<ConstantSDNode>(N))
677 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
678 if(BV && BV->isConstant())
683 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
685 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
686 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
689 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
690 BitVector UndefElements;
691 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
693 // BuildVectors can truncate their operands. Ignore that case here.
694 // FIXME: We blindly ignore splats which include undef which is overly
696 if (CN && UndefElements.none() &&
697 CN->getValueType(0) == N.getValueType().getScalarType())
704 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
706 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
707 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
710 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
711 BitVector UndefElements;
712 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
714 // BuildVectors can truncate their operands. Ignore that case here.
715 // FIXME: We blindly ignore splats which include undef which is overly
717 if (CN && UndefElements.none() &&
718 CN->getValueType(0) == N.getValueType().getScalarType())
725 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
726 SDValue N0, SDValue N1) {
727 EVT VT = N0.getValueType();
728 if (N0.getOpcode() == Opc) {
729 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
730 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
731 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
732 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
733 if (!OpNode.getNode())
735 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
737 if (N0.hasOneUse()) {
738 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
740 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
741 if (!OpNode.getNode())
743 AddToWorklist(OpNode.getNode());
744 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
749 if (N1.getOpcode() == Opc) {
750 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
751 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
752 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
753 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
754 if (!OpNode.getNode())
756 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
758 if (N1.hasOneUse()) {
759 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
761 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
762 if (!OpNode.getNode())
764 AddToWorklist(OpNode.getNode());
765 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
773 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
775 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
777 DEBUG(dbgs() << "\nReplacing.1 ";
779 dbgs() << "\nWith: ";
780 To[0].getNode()->dump(&DAG);
781 dbgs() << " and " << NumTo-1 << " other values\n";
782 for (unsigned i = 0, e = NumTo; i != e; ++i)
783 assert((!To[i].getNode() ||
784 N->getValueType(i) == To[i].getValueType()) &&
785 "Cannot combine value to value of different type!"));
786 WorklistRemover DeadNodes(*this);
787 DAG.ReplaceAllUsesWith(N, To);
789 // Push the new nodes and any users onto the worklist
790 for (unsigned i = 0, e = NumTo; i != e; ++i) {
791 if (To[i].getNode()) {
792 AddToWorklist(To[i].getNode());
793 AddUsersToWorklist(To[i].getNode());
798 // Finally, if the node is now dead, remove it from the graph. The node
799 // may not be dead if the replacement process recursively simplified to
800 // something else needing this node.
802 deleteAndRecombine(N);
803 return SDValue(N, 0);
807 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
808 // Replace all uses. If any nodes become isomorphic to other nodes and
809 // are deleted, make sure to remove them from our worklist.
810 WorklistRemover DeadNodes(*this);
811 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
813 // Push the new node and any (possibly new) users onto the worklist.
814 AddToWorklist(TLO.New.getNode());
815 AddUsersToWorklist(TLO.New.getNode());
817 // Finally, if the node is now dead, remove it from the graph. The node
818 // may not be dead if the replacement process recursively simplified to
819 // something else needing this node.
820 if (TLO.Old.getNode()->use_empty())
821 deleteAndRecombine(TLO.Old.getNode());
824 /// SimplifyDemandedBits - Check the specified integer node value to see if
825 /// it can be simplified or if things it uses can be simplified by bit
826 /// propagation. If so, return true.
827 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
828 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
829 APInt KnownZero, KnownOne;
830 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
834 AddToWorklist(Op.getNode());
836 // Replace the old value with the new one.
838 DEBUG(dbgs() << "\nReplacing.2 ";
839 TLO.Old.getNode()->dump(&DAG);
840 dbgs() << "\nWith: ";
841 TLO.New.getNode()->dump(&DAG);
844 CommitTargetLoweringOpt(TLO);
848 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
850 EVT VT = Load->getValueType(0);
851 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
853 DEBUG(dbgs() << "\nReplacing.9 ";
855 dbgs() << "\nWith: ";
856 Trunc.getNode()->dump(&DAG);
858 WorklistRemover DeadNodes(*this);
859 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
860 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
861 deleteAndRecombine(Load);
862 AddToWorklist(Trunc.getNode());
865 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
868 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
869 EVT MemVT = LD->getMemoryVT();
870 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
871 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
873 : LD->getExtensionType();
875 return DAG.getExtLoad(ExtType, dl, PVT,
876 LD->getChain(), LD->getBasePtr(),
877 MemVT, LD->getMemOperand());
880 unsigned Opc = Op.getOpcode();
883 case ISD::AssertSext:
884 return DAG.getNode(ISD::AssertSext, dl, PVT,
885 SExtPromoteOperand(Op.getOperand(0), PVT),
887 case ISD::AssertZext:
888 return DAG.getNode(ISD::AssertZext, dl, PVT,
889 ZExtPromoteOperand(Op.getOperand(0), PVT),
891 case ISD::Constant: {
893 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
894 return DAG.getNode(ExtOpc, dl, PVT, Op);
898 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
900 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
903 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
904 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
906 EVT OldVT = Op.getValueType();
908 bool Replace = false;
909 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
910 if (!NewOp.getNode())
912 AddToWorklist(NewOp.getNode());
915 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
916 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
917 DAG.getValueType(OldVT));
920 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
921 EVT OldVT = Op.getValueType();
923 bool Replace = false;
924 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
925 if (!NewOp.getNode())
927 AddToWorklist(NewOp.getNode());
930 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
931 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
934 /// PromoteIntBinOp - Promote the specified integer binary operation if the
935 /// target indicates it is beneficial. e.g. On x86, it's usually better to
936 /// promote i16 operations to i32 since i16 instructions are longer.
937 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
938 if (!LegalOperations)
941 EVT VT = Op.getValueType();
942 if (VT.isVector() || !VT.isInteger())
945 // If operation type is 'undesirable', e.g. i16 on x86, consider
947 unsigned Opc = Op.getOpcode();
948 if (TLI.isTypeDesirableForOp(Opc, VT))
952 // Consult target whether it is a good idea to promote this operation and
953 // what's the right type to promote it to.
954 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
955 assert(PVT != VT && "Don't know what type to promote to!");
957 bool Replace0 = false;
958 SDValue N0 = Op.getOperand(0);
959 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
963 bool Replace1 = false;
964 SDValue N1 = Op.getOperand(1);
969 NN1 = PromoteOperand(N1, PVT, Replace1);
974 AddToWorklist(NN0.getNode());
976 AddToWorklist(NN1.getNode());
979 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
981 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
983 DEBUG(dbgs() << "\nPromoting ";
984 Op.getNode()->dump(&DAG));
986 return DAG.getNode(ISD::TRUNCATE, dl, VT,
987 DAG.getNode(Opc, dl, PVT, NN0, NN1));
992 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
993 /// target indicates it is beneficial. e.g. On x86, it's usually better to
994 /// promote i16 operations to i32 since i16 instructions are longer.
995 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
996 if (!LegalOperations)
999 EVT VT = Op.getValueType();
1000 if (VT.isVector() || !VT.isInteger())
1003 // If operation type is 'undesirable', e.g. i16 on x86, consider
1005 unsigned Opc = Op.getOpcode();
1006 if (TLI.isTypeDesirableForOp(Opc, VT))
1010 // Consult target whether it is a good idea to promote this operation and
1011 // what's the right type to promote it to.
1012 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1013 assert(PVT != VT && "Don't know what type to promote to!");
1015 bool Replace = false;
1016 SDValue N0 = Op.getOperand(0);
1017 if (Opc == ISD::SRA)
1018 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1019 else if (Opc == ISD::SRL)
1020 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1022 N0 = PromoteOperand(N0, PVT, Replace);
1026 AddToWorklist(N0.getNode());
1028 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1030 DEBUG(dbgs() << "\nPromoting ";
1031 Op.getNode()->dump(&DAG));
1033 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1034 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1039 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1040 if (!LegalOperations)
1043 EVT VT = Op.getValueType();
1044 if (VT.isVector() || !VT.isInteger())
1047 // If operation type is 'undesirable', e.g. i16 on x86, consider
1049 unsigned Opc = Op.getOpcode();
1050 if (TLI.isTypeDesirableForOp(Opc, VT))
1054 // Consult target whether it is a good idea to promote this operation and
1055 // what's the right type to promote it to.
1056 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1057 assert(PVT != VT && "Don't know what type to promote to!");
1058 // fold (aext (aext x)) -> (aext x)
1059 // fold (aext (zext x)) -> (zext x)
1060 // fold (aext (sext x)) -> (sext x)
1061 DEBUG(dbgs() << "\nPromoting ";
1062 Op.getNode()->dump(&DAG));
1063 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1068 bool DAGCombiner::PromoteLoad(SDValue Op) {
1069 if (!LegalOperations)
1072 EVT VT = Op.getValueType();
1073 if (VT.isVector() || !VT.isInteger())
1076 // If operation type is 'undesirable', e.g. i16 on x86, consider
1078 unsigned Opc = Op.getOpcode();
1079 if (TLI.isTypeDesirableForOp(Opc, VT))
1083 // Consult target whether it is a good idea to promote this operation and
1084 // what's the right type to promote it to.
1085 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1086 assert(PVT != VT && "Don't know what type to promote to!");
1089 SDNode *N = Op.getNode();
1090 LoadSDNode *LD = cast<LoadSDNode>(N);
1091 EVT MemVT = LD->getMemoryVT();
1092 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1093 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1095 : LD->getExtensionType();
1096 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1097 LD->getChain(), LD->getBasePtr(),
1098 MemVT, LD->getMemOperand());
1099 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1101 DEBUG(dbgs() << "\nPromoting ";
1104 Result.getNode()->dump(&DAG);
1106 WorklistRemover DeadNodes(*this);
1107 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1108 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1109 deleteAndRecombine(N);
1110 AddToWorklist(Result.getNode());
1116 /// \brief Recursively delete a node which has no uses and any operands for
1117 /// which it is the only use.
1119 /// Note that this both deletes the nodes and removes them from the worklist.
1120 /// It also adds any nodes who have had a user deleted to the worklist as they
1121 /// may now have only one use and subject to other combines.
1122 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1123 if (!N->use_empty())
1126 SmallSetVector<SDNode *, 16> Nodes;
1129 N = Nodes.pop_back_val();
1133 if (N->use_empty()) {
1134 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1135 Nodes.insert(N->getOperand(i).getNode());
1137 removeFromWorklist(N);
1142 } while (!Nodes.empty());
1146 //===----------------------------------------------------------------------===//
1147 // Main DAG Combiner implementation
1148 //===----------------------------------------------------------------------===//
1150 void DAGCombiner::Run(CombineLevel AtLevel) {
1151 // set the instance variables, so that the various visit routines may use it.
1153 LegalOperations = Level >= AfterLegalizeVectorOps;
1154 LegalTypes = Level >= AfterLegalizeTypes;
1156 // Add all the dag nodes to the worklist.
1157 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1158 E = DAG.allnodes_end(); I != E; ++I)
1161 // Create a dummy node (which is not added to allnodes), that adds a reference
1162 // to the root node, preventing it from being deleted, and tracking any
1163 // changes of the root.
1164 HandleSDNode Dummy(DAG.getRoot());
1166 // while the worklist isn't empty, find a node and
1167 // try and combine it.
1168 while (!WorklistMap.empty()) {
1170 // The Worklist holds the SDNodes in order, but it may contain null entries.
1172 N = Worklist.pop_back_val();
1175 bool GoodWorklistEntry = WorklistMap.erase(N);
1176 (void)GoodWorklistEntry;
1177 assert(GoodWorklistEntry &&
1178 "Found a worklist entry without a corresponding map entry!");
1180 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1181 // N is deleted from the DAG, since they too may now be dead or may have a
1182 // reduced number of uses, allowing other xforms.
1183 if (recursivelyDeleteUnusedNodes(N))
1186 WorklistRemover DeadNodes(*this);
1188 // If this combine is running after legalizing the DAG, re-legalize any
1189 // nodes pulled off the worklist.
1190 if (Level == AfterLegalizeDAG) {
1191 SmallSetVector<SDNode *, 16> UpdatedNodes;
1192 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1194 for (SDNode *LN : UpdatedNodes) {
1196 AddUsersToWorklist(LN);
1202 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1204 // Add any operands of the new node which have not yet been combined to the
1205 // worklist as well. Because the worklist uniques things already, this
1206 // won't repeatedly process the same operand.
1207 CombinedNodes.insert(N);
1208 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1209 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1210 AddToWorklist(N->getOperand(i).getNode());
1212 SDValue RV = combine(N);
1219 // If we get back the same node we passed in, rather than a new node or
1220 // zero, we know that the node must have defined multiple values and
1221 // CombineTo was used. Since CombineTo takes care of the worklist
1222 // mechanics for us, we have no work to do in this case.
1223 if (RV.getNode() == N)
1226 assert(N->getOpcode() != ISD::DELETED_NODE &&
1227 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1228 "Node was deleted but visit returned new node!");
1230 DEBUG(dbgs() << " ... into: ";
1231 RV.getNode()->dump(&DAG));
1233 // Transfer debug value.
1234 DAG.TransferDbgValues(SDValue(N, 0), RV);
1235 if (N->getNumValues() == RV.getNode()->getNumValues())
1236 DAG.ReplaceAllUsesWith(N, RV.getNode());
1238 assert(N->getValueType(0) == RV.getValueType() &&
1239 N->getNumValues() == 1 && "Type mismatch");
1241 DAG.ReplaceAllUsesWith(N, &OpV);
1244 // Push the new node and any users onto the worklist
1245 AddToWorklist(RV.getNode());
1246 AddUsersToWorklist(RV.getNode());
1248 // Finally, if the node is now dead, remove it from the graph. The node
1249 // may not be dead if the replacement process recursively simplified to
1250 // something else needing this node. This will also take care of adding any
1251 // operands which have lost a user to the worklist.
1252 recursivelyDeleteUnusedNodes(N);
1255 // If the root changed (e.g. it was a dead load, update the root).
1256 DAG.setRoot(Dummy.getValue());
1257 DAG.RemoveDeadNodes();
1260 SDValue DAGCombiner::visit(SDNode *N) {
1261 switch (N->getOpcode()) {
1263 case ISD::TokenFactor: return visitTokenFactor(N);
1264 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1265 case ISD::ADD: return visitADD(N);
1266 case ISD::SUB: return visitSUB(N);
1267 case ISD::ADDC: return visitADDC(N);
1268 case ISD::SUBC: return visitSUBC(N);
1269 case ISD::ADDE: return visitADDE(N);
1270 case ISD::SUBE: return visitSUBE(N);
1271 case ISD::MUL: return visitMUL(N);
1272 case ISD::SDIV: return visitSDIV(N);
1273 case ISD::UDIV: return visitUDIV(N);
1274 case ISD::SREM: return visitSREM(N);
1275 case ISD::UREM: return visitUREM(N);
1276 case ISD::MULHU: return visitMULHU(N);
1277 case ISD::MULHS: return visitMULHS(N);
1278 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1279 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1280 case ISD::SMULO: return visitSMULO(N);
1281 case ISD::UMULO: return visitUMULO(N);
1282 case ISD::SDIVREM: return visitSDIVREM(N);
1283 case ISD::UDIVREM: return visitUDIVREM(N);
1284 case ISD::AND: return visitAND(N);
1285 case ISD::OR: return visitOR(N);
1286 case ISD::XOR: return visitXOR(N);
1287 case ISD::SHL: return visitSHL(N);
1288 case ISD::SRA: return visitSRA(N);
1289 case ISD::SRL: return visitSRL(N);
1291 case ISD::ROTL: return visitRotate(N);
1292 case ISD::CTLZ: return visitCTLZ(N);
1293 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1294 case ISD::CTTZ: return visitCTTZ(N);
1295 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1296 case ISD::CTPOP: return visitCTPOP(N);
1297 case ISD::SELECT: return visitSELECT(N);
1298 case ISD::VSELECT: return visitVSELECT(N);
1299 case ISD::SELECT_CC: return visitSELECT_CC(N);
1300 case ISD::SETCC: return visitSETCC(N);
1301 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1302 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1303 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1304 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1305 case ISD::TRUNCATE: return visitTRUNCATE(N);
1306 case ISD::BITCAST: return visitBITCAST(N);
1307 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1308 case ISD::FADD: return visitFADD(N);
1309 case ISD::FSUB: return visitFSUB(N);
1310 case ISD::FMUL: return visitFMUL(N);
1311 case ISD::FMA: return visitFMA(N);
1312 case ISD::FDIV: return visitFDIV(N);
1313 case ISD::FREM: return visitFREM(N);
1314 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1315 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1316 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1317 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1318 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1319 case ISD::FP_ROUND: return visitFP_ROUND(N);
1320 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1321 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1322 case ISD::FNEG: return visitFNEG(N);
1323 case ISD::FABS: return visitFABS(N);
1324 case ISD::FFLOOR: return visitFFLOOR(N);
1325 case ISD::FCEIL: return visitFCEIL(N);
1326 case ISD::FTRUNC: return visitFTRUNC(N);
1327 case ISD::BRCOND: return visitBRCOND(N);
1328 case ISD::BR_CC: return visitBR_CC(N);
1329 case ISD::LOAD: return visitLOAD(N);
1330 case ISD::STORE: return visitSTORE(N);
1331 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1332 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1333 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1334 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1335 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1336 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1337 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1342 SDValue DAGCombiner::combine(SDNode *N) {
1343 SDValue RV = visit(N);
1345 // If nothing happened, try a target-specific DAG combine.
1346 if (!RV.getNode()) {
1347 assert(N->getOpcode() != ISD::DELETED_NODE &&
1348 "Node was deleted but visit returned NULL!");
1350 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1351 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1353 // Expose the DAG combiner to the target combiner impls.
1354 TargetLowering::DAGCombinerInfo
1355 DagCombineInfo(DAG, Level, false, this);
1357 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1361 // If nothing happened still, try promoting the operation.
1362 if (!RV.getNode()) {
1363 switch (N->getOpcode()) {
1371 RV = PromoteIntBinOp(SDValue(N, 0));
1376 RV = PromoteIntShiftOp(SDValue(N, 0));
1378 case ISD::SIGN_EXTEND:
1379 case ISD::ZERO_EXTEND:
1380 case ISD::ANY_EXTEND:
1381 RV = PromoteExtend(SDValue(N, 0));
1384 if (PromoteLoad(SDValue(N, 0)))
1390 // If N is a commutative binary node, try commuting it to enable more
1392 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1393 N->getNumValues() == 1) {
1394 SDValue N0 = N->getOperand(0);
1395 SDValue N1 = N->getOperand(1);
1397 // Constant operands are canonicalized to RHS.
1398 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1399 SDValue Ops[] = {N1, N0};
1401 if (const BinaryWithFlagsSDNode *BinNode =
1402 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1403 CSENode = DAG.getNodeIfExists(
1404 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1405 BinNode->hasNoSignedWrap(), BinNode->isExact());
1407 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1410 return SDValue(CSENode, 0);
1417 /// getInputChainForNode - Given a node, return its input chain if it has one,
1418 /// otherwise return a null sd operand.
1419 static SDValue getInputChainForNode(SDNode *N) {
1420 if (unsigned NumOps = N->getNumOperands()) {
1421 if (N->getOperand(0).getValueType() == MVT::Other)
1422 return N->getOperand(0);
1423 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1424 return N->getOperand(NumOps-1);
1425 for (unsigned i = 1; i < NumOps-1; ++i)
1426 if (N->getOperand(i).getValueType() == MVT::Other)
1427 return N->getOperand(i);
1432 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1433 // If N has two operands, where one has an input chain equal to the other,
1434 // the 'other' chain is redundant.
1435 if (N->getNumOperands() == 2) {
1436 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1437 return N->getOperand(0);
1438 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1439 return N->getOperand(1);
1442 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1443 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1444 SmallPtrSet<SDNode*, 16> SeenOps;
1445 bool Changed = false; // If we should replace this token factor.
1447 // Start out with this token factor.
1450 // Iterate through token factors. The TFs grows when new token factors are
1452 for (unsigned i = 0; i < TFs.size(); ++i) {
1453 SDNode *TF = TFs[i];
1455 // Check each of the operands.
1456 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1457 SDValue Op = TF->getOperand(i);
1459 switch (Op.getOpcode()) {
1460 case ISD::EntryToken:
1461 // Entry tokens don't need to be added to the list. They are
1466 case ISD::TokenFactor:
1467 if (Op.hasOneUse() &&
1468 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1469 // Queue up for processing.
1470 TFs.push_back(Op.getNode());
1471 // Clean up in case the token factor is removed.
1472 AddToWorklist(Op.getNode());
1479 // Only add if it isn't already in the list.
1480 if (SeenOps.insert(Op.getNode()))
1491 // If we've change things around then replace token factor.
1494 // The entry token is the only possible outcome.
1495 Result = DAG.getEntryNode();
1497 // New and improved token factor.
1498 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1501 // Don't add users to work list.
1502 return CombineTo(N, Result, false);
1508 /// MERGE_VALUES can always be eliminated.
1509 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1510 WorklistRemover DeadNodes(*this);
1511 // Replacing results may cause a different MERGE_VALUES to suddenly
1512 // be CSE'd with N, and carry its uses with it. Iterate until no
1513 // uses remain, to ensure that the node can be safely deleted.
1514 // First add the users of this node to the work list so that they
1515 // can be tried again once they have new operands.
1516 AddUsersToWorklist(N);
1518 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1519 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1520 } while (!N->use_empty());
1521 deleteAndRecombine(N);
1522 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1526 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1527 SelectionDAG &DAG) {
1528 EVT VT = N0.getValueType();
1529 SDValue N00 = N0.getOperand(0);
1530 SDValue N01 = N0.getOperand(1);
1531 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1533 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1534 isa<ConstantSDNode>(N00.getOperand(1))) {
1535 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1536 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1537 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1538 N00.getOperand(0), N01),
1539 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1540 N00.getOperand(1), N01));
1541 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1547 SDValue DAGCombiner::visitADD(SDNode *N) {
1548 SDValue N0 = N->getOperand(0);
1549 SDValue N1 = N->getOperand(1);
1550 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1551 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1552 EVT VT = N0.getValueType();
1555 if (VT.isVector()) {
1556 SDValue FoldedVOp = SimplifyVBinOp(N);
1557 if (FoldedVOp.getNode()) return FoldedVOp;
1559 // fold (add x, 0) -> x, vector edition
1560 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1562 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1566 // fold (add x, undef) -> undef
1567 if (N0.getOpcode() == ISD::UNDEF)
1569 if (N1.getOpcode() == ISD::UNDEF)
1571 // fold (add c1, c2) -> c1+c2
1573 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1574 // canonicalize constant to RHS
1576 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1577 // fold (add x, 0) -> x
1578 if (N1C && N1C->isNullValue())
1580 // fold (add Sym, c) -> Sym+c
1581 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1582 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1583 GA->getOpcode() == ISD::GlobalAddress)
1584 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1586 (uint64_t)N1C->getSExtValue());
1587 // fold ((c1-A)+c2) -> (c1+c2)-A
1588 if (N1C && N0.getOpcode() == ISD::SUB)
1589 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1590 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1591 DAG.getConstant(N1C->getAPIntValue()+
1592 N0C->getAPIntValue(), VT),
1595 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1598 // fold ((0-A) + B) -> B-A
1599 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1600 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1601 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1602 // fold (A + (0-B)) -> A-B
1603 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1604 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1605 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1606 // fold (A+(B-A)) -> B
1607 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1608 return N1.getOperand(0);
1609 // fold ((B-A)+A) -> B
1610 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1611 return N0.getOperand(0);
1612 // fold (A+(B-(A+C))) to (B-C)
1613 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1614 N0 == N1.getOperand(1).getOperand(0))
1615 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1616 N1.getOperand(1).getOperand(1));
1617 // fold (A+(B-(C+A))) to (B-C)
1618 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1619 N0 == N1.getOperand(1).getOperand(1))
1620 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1621 N1.getOperand(1).getOperand(0));
1622 // fold (A+((B-A)+or-C)) to (B+or-C)
1623 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1624 N1.getOperand(0).getOpcode() == ISD::SUB &&
1625 N0 == N1.getOperand(0).getOperand(1))
1626 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1627 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1629 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1630 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1631 SDValue N00 = N0.getOperand(0);
1632 SDValue N01 = N0.getOperand(1);
1633 SDValue N10 = N1.getOperand(0);
1634 SDValue N11 = N1.getOperand(1);
1636 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1637 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1638 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1639 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1642 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1643 return SDValue(N, 0);
1645 // fold (a+b) -> (a|b) iff a and b share no bits.
1646 if (VT.isInteger() && !VT.isVector()) {
1647 APInt LHSZero, LHSOne;
1648 APInt RHSZero, RHSOne;
1649 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1651 if (LHSZero.getBoolValue()) {
1652 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1654 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1655 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1656 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1657 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1658 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1663 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1664 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1665 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1666 if (Result.getNode()) return Result;
1668 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1669 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1670 if (Result.getNode()) return Result;
1673 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1674 if (N1.getOpcode() == ISD::SHL &&
1675 N1.getOperand(0).getOpcode() == ISD::SUB)
1676 if (ConstantSDNode *C =
1677 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1678 if (C->getAPIntValue() == 0)
1679 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1680 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1681 N1.getOperand(0).getOperand(1),
1683 if (N0.getOpcode() == ISD::SHL &&
1684 N0.getOperand(0).getOpcode() == ISD::SUB)
1685 if (ConstantSDNode *C =
1686 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1687 if (C->getAPIntValue() == 0)
1688 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1689 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1690 N0.getOperand(0).getOperand(1),
1693 if (N1.getOpcode() == ISD::AND) {
1694 SDValue AndOp0 = N1.getOperand(0);
1695 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1696 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1697 unsigned DestBits = VT.getScalarType().getSizeInBits();
1699 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1700 // and similar xforms where the inner op is either ~0 or 0.
1701 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1703 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1707 // add (sext i1), X -> sub X, (zext i1)
1708 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1709 N0.getOperand(0).getValueType() == MVT::i1 &&
1710 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1712 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1713 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1719 SDValue DAGCombiner::visitADDC(SDNode *N) {
1720 SDValue N0 = N->getOperand(0);
1721 SDValue N1 = N->getOperand(1);
1722 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1723 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1724 EVT VT = N0.getValueType();
1726 // If the flag result is dead, turn this into an ADD.
1727 if (!N->hasAnyUseOfValue(1))
1728 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1729 DAG.getNode(ISD::CARRY_FALSE,
1730 SDLoc(N), MVT::Glue));
1732 // canonicalize constant to RHS.
1734 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1736 // fold (addc x, 0) -> x + no carry out
1737 if (N1C && N1C->isNullValue())
1738 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1739 SDLoc(N), MVT::Glue));
1741 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1742 APInt LHSZero, LHSOne;
1743 APInt RHSZero, RHSOne;
1744 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1746 if (LHSZero.getBoolValue()) {
1747 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1749 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1750 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1751 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1752 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1753 DAG.getNode(ISD::CARRY_FALSE,
1754 SDLoc(N), MVT::Glue));
1760 SDValue DAGCombiner::visitADDE(SDNode *N) {
1761 SDValue N0 = N->getOperand(0);
1762 SDValue N1 = N->getOperand(1);
1763 SDValue CarryIn = N->getOperand(2);
1764 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1765 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1767 // canonicalize constant to RHS
1769 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1772 // fold (adde x, y, false) -> (addc x, y)
1773 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1774 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1779 // Since it may not be valid to emit a fold to zero for vector initializers
1780 // check if we can before folding.
1781 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1783 bool LegalOperations, bool LegalTypes) {
1785 return DAG.getConstant(0, VT);
1786 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1787 return DAG.getConstant(0, VT);
1791 SDValue DAGCombiner::visitSUB(SDNode *N) {
1792 SDValue N0 = N->getOperand(0);
1793 SDValue N1 = N->getOperand(1);
1794 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1795 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1796 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1797 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1798 EVT VT = N0.getValueType();
1801 if (VT.isVector()) {
1802 SDValue FoldedVOp = SimplifyVBinOp(N);
1803 if (FoldedVOp.getNode()) return FoldedVOp;
1805 // fold (sub x, 0) -> x, vector edition
1806 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1810 // fold (sub x, x) -> 0
1811 // FIXME: Refactor this and xor and other similar operations together.
1813 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1814 // fold (sub c1, c2) -> c1-c2
1816 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1817 // fold (sub x, c) -> (add x, -c)
1819 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1820 DAG.getConstant(-N1C->getAPIntValue(), VT));
1821 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1822 if (N0C && N0C->isAllOnesValue())
1823 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1824 // fold A-(A-B) -> B
1825 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1826 return N1.getOperand(1);
1827 // fold (A+B)-A -> B
1828 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1829 return N0.getOperand(1);
1830 // fold (A+B)-B -> A
1831 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1832 return N0.getOperand(0);
1833 // fold C2-(A+C1) -> (C2-C1)-A
1834 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1835 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1837 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1840 // fold ((A+(B+or-C))-B) -> A+or-C
1841 if (N0.getOpcode() == ISD::ADD &&
1842 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1843 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1844 N0.getOperand(1).getOperand(0) == N1)
1845 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1846 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1847 // fold ((A+(C+B))-B) -> A+C
1848 if (N0.getOpcode() == ISD::ADD &&
1849 N0.getOperand(1).getOpcode() == ISD::ADD &&
1850 N0.getOperand(1).getOperand(1) == N1)
1851 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1852 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1853 // fold ((A-(B-C))-C) -> A-B
1854 if (N0.getOpcode() == ISD::SUB &&
1855 N0.getOperand(1).getOpcode() == ISD::SUB &&
1856 N0.getOperand(1).getOperand(1) == N1)
1857 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1858 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1860 // If either operand of a sub is undef, the result is undef
1861 if (N0.getOpcode() == ISD::UNDEF)
1863 if (N1.getOpcode() == ISD::UNDEF)
1866 // If the relocation model supports it, consider symbol offsets.
1867 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1868 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1869 // fold (sub Sym, c) -> Sym-c
1870 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1871 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1873 (uint64_t)N1C->getSExtValue());
1874 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1875 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1876 if (GA->getGlobal() == GB->getGlobal())
1877 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1884 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1885 SDValue N0 = N->getOperand(0);
1886 SDValue N1 = N->getOperand(1);
1887 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1888 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1889 EVT VT = N0.getValueType();
1891 // If the flag result is dead, turn this into an SUB.
1892 if (!N->hasAnyUseOfValue(1))
1893 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1894 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1897 // fold (subc x, x) -> 0 + no borrow
1899 return CombineTo(N, DAG.getConstant(0, VT),
1900 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1903 // fold (subc x, 0) -> x + no borrow
1904 if (N1C && N1C->isNullValue())
1905 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1908 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1909 if (N0C && N0C->isAllOnesValue())
1910 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1911 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1917 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1918 SDValue N0 = N->getOperand(0);
1919 SDValue N1 = N->getOperand(1);
1920 SDValue CarryIn = N->getOperand(2);
1922 // fold (sube x, y, false) -> (subc x, y)
1923 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1924 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1929 SDValue DAGCombiner::visitMUL(SDNode *N) {
1930 SDValue N0 = N->getOperand(0);
1931 SDValue N1 = N->getOperand(1);
1932 EVT VT = N0.getValueType();
1934 // fold (mul x, undef) -> 0
1935 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1936 return DAG.getConstant(0, VT);
1938 bool N0IsConst = false;
1939 bool N1IsConst = false;
1940 APInt ConstValue0, ConstValue1;
1942 if (VT.isVector()) {
1943 SDValue FoldedVOp = SimplifyVBinOp(N);
1944 if (FoldedVOp.getNode()) return FoldedVOp;
1946 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1947 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1949 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1950 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1952 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1953 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1957 // fold (mul c1, c2) -> c1*c2
1958 if (N0IsConst && N1IsConst)
1959 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1961 // canonicalize constant to RHS
1962 if (N0IsConst && !N1IsConst)
1963 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1964 // fold (mul x, 0) -> 0
1965 if (N1IsConst && ConstValue1 == 0)
1967 // We require a splat of the entire scalar bit width for non-contiguous
1970 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1971 // fold (mul x, 1) -> x
1972 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1974 // fold (mul x, -1) -> 0-x
1975 if (N1IsConst && ConstValue1.isAllOnesValue())
1976 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1977 DAG.getConstant(0, VT), N0);
1978 // fold (mul x, (1 << c)) -> x << c
1979 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1980 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1981 DAG.getConstant(ConstValue1.logBase2(),
1982 getShiftAmountTy(N0.getValueType())));
1983 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1984 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1985 unsigned Log2Val = (-ConstValue1).logBase2();
1986 // FIXME: If the input is something that is easily negated (e.g. a
1987 // single-use add), we should put the negate there.
1988 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1989 DAG.getConstant(0, VT),
1990 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1991 DAG.getConstant(Log2Val,
1992 getShiftAmountTy(N0.getValueType()))));
1996 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1997 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1998 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1999 isa<ConstantSDNode>(N0.getOperand(1)))) {
2000 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2001 N1, N0.getOperand(1));
2002 AddToWorklist(C3.getNode());
2003 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2004 N0.getOperand(0), C3);
2007 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2010 SDValue Sh(nullptr,0), Y(nullptr,0);
2011 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2012 if (N0.getOpcode() == ISD::SHL &&
2013 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2014 isa<ConstantSDNode>(N0.getOperand(1))) &&
2015 N0.getNode()->hasOneUse()) {
2017 } else if (N1.getOpcode() == ISD::SHL &&
2018 isa<ConstantSDNode>(N1.getOperand(1)) &&
2019 N1.getNode()->hasOneUse()) {
2024 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2025 Sh.getOperand(0), Y);
2026 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2027 Mul, Sh.getOperand(1));
2031 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2032 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2033 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2034 isa<ConstantSDNode>(N0.getOperand(1))))
2035 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2036 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2037 N0.getOperand(0), N1),
2038 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2039 N0.getOperand(1), N1));
2042 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2049 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2050 SDValue N0 = N->getOperand(0);
2051 SDValue N1 = N->getOperand(1);
2052 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2053 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2054 EVT VT = N->getValueType(0);
2057 if (VT.isVector()) {
2058 SDValue FoldedVOp = SimplifyVBinOp(N);
2059 if (FoldedVOp.getNode()) return FoldedVOp;
2062 // fold (sdiv c1, c2) -> c1/c2
2063 if (N0C && N1C && !N1C->isNullValue())
2064 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2065 // fold (sdiv X, 1) -> X
2066 if (N1C && N1C->getAPIntValue() == 1LL)
2068 // fold (sdiv X, -1) -> 0-X
2069 if (N1C && N1C->isAllOnesValue())
2070 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2071 DAG.getConstant(0, VT), N0);
2072 // If we know the sign bits of both operands are zero, strength reduce to a
2073 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2074 if (!VT.isVector()) {
2075 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2076 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2080 // fold (sdiv X, pow2) -> simple ops after legalize
2081 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2082 (-N1C->getAPIntValue()).isPowerOf2())) {
2083 // If dividing by powers of two is cheap, then don't perform the following
2085 if (TLI.isPow2DivCheap())
2088 // Target-specific implementation of sdiv x, pow2.
2089 SDValue Res = BuildSDIVPow2(N);
2093 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2095 // Splat the sign bit into the register
2097 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2098 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2099 getShiftAmountTy(N0.getValueType())));
2100 AddToWorklist(SGN.getNode());
2102 // Add (N0 < 0) ? abs2 - 1 : 0;
2104 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2105 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2106 getShiftAmountTy(SGN.getValueType())));
2107 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2108 AddToWorklist(SRL.getNode());
2109 AddToWorklist(ADD.getNode()); // Divide by pow2
2110 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2111 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2113 // If we're dividing by a positive value, we're done. Otherwise, we must
2114 // negate the result.
2115 if (N1C->getAPIntValue().isNonNegative())
2118 AddToWorklist(SRA.getNode());
2119 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2122 // if integer divide is expensive and we satisfy the requirements, emit an
2123 // alternate sequence.
2124 if (N1C && !TLI.isIntDivCheap()) {
2125 SDValue Op = BuildSDIV(N);
2126 if (Op.getNode()) return Op;
2130 if (N0.getOpcode() == ISD::UNDEF)
2131 return DAG.getConstant(0, VT);
2132 // X / undef -> undef
2133 if (N1.getOpcode() == ISD::UNDEF)
2139 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2140 SDValue N0 = N->getOperand(0);
2141 SDValue N1 = N->getOperand(1);
2142 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2143 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2144 EVT VT = N->getValueType(0);
2147 if (VT.isVector()) {
2148 SDValue FoldedVOp = SimplifyVBinOp(N);
2149 if (FoldedVOp.getNode()) return FoldedVOp;
2152 // fold (udiv c1, c2) -> c1/c2
2153 if (N0C && N1C && !N1C->isNullValue())
2154 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2155 // fold (udiv x, (1 << c)) -> x >>u c
2156 if (N1C && N1C->getAPIntValue().isPowerOf2())
2157 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2158 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2159 getShiftAmountTy(N0.getValueType())));
2160 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2161 if (N1.getOpcode() == ISD::SHL) {
2162 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2163 if (SHC->getAPIntValue().isPowerOf2()) {
2164 EVT ADDVT = N1.getOperand(1).getValueType();
2165 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2167 DAG.getConstant(SHC->getAPIntValue()
2170 AddToWorklist(Add.getNode());
2171 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2175 // fold (udiv x, c) -> alternate
2176 if (N1C && !TLI.isIntDivCheap()) {
2177 SDValue Op = BuildUDIV(N);
2178 if (Op.getNode()) return Op;
2182 if (N0.getOpcode() == ISD::UNDEF)
2183 return DAG.getConstant(0, VT);
2184 // X / undef -> undef
2185 if (N1.getOpcode() == ISD::UNDEF)
2191 SDValue DAGCombiner::visitSREM(SDNode *N) {
2192 SDValue N0 = N->getOperand(0);
2193 SDValue N1 = N->getOperand(1);
2194 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2195 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2196 EVT VT = N->getValueType(0);
2198 // fold (srem c1, c2) -> c1%c2
2199 if (N0C && N1C && !N1C->isNullValue())
2200 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2201 // If we know the sign bits of both operands are zero, strength reduce to a
2202 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2203 if (!VT.isVector()) {
2204 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2205 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2208 // If X/C can be simplified by the division-by-constant logic, lower
2209 // X%C to the equivalent of X-X/C*C.
2210 if (N1C && !N1C->isNullValue()) {
2211 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2212 AddToWorklist(Div.getNode());
2213 SDValue OptimizedDiv = combine(Div.getNode());
2214 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2215 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2217 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2218 AddToWorklist(Mul.getNode());
2224 if (N0.getOpcode() == ISD::UNDEF)
2225 return DAG.getConstant(0, VT);
2226 // X % undef -> undef
2227 if (N1.getOpcode() == ISD::UNDEF)
2233 SDValue DAGCombiner::visitUREM(SDNode *N) {
2234 SDValue N0 = N->getOperand(0);
2235 SDValue N1 = N->getOperand(1);
2236 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2237 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2238 EVT VT = N->getValueType(0);
2240 // fold (urem c1, c2) -> c1%c2
2241 if (N0C && N1C && !N1C->isNullValue())
2242 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2243 // fold (urem x, pow2) -> (and x, pow2-1)
2244 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2245 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2246 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2247 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2248 if (N1.getOpcode() == ISD::SHL) {
2249 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2250 if (SHC->getAPIntValue().isPowerOf2()) {
2252 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2253 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2255 AddToWorklist(Add.getNode());
2256 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2261 // If X/C can be simplified by the division-by-constant logic, lower
2262 // X%C to the equivalent of X-X/C*C.
2263 if (N1C && !N1C->isNullValue()) {
2264 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2265 AddToWorklist(Div.getNode());
2266 SDValue OptimizedDiv = combine(Div.getNode());
2267 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2268 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2270 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2271 AddToWorklist(Mul.getNode());
2277 if (N0.getOpcode() == ISD::UNDEF)
2278 return DAG.getConstant(0, VT);
2279 // X % undef -> undef
2280 if (N1.getOpcode() == ISD::UNDEF)
2286 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2287 SDValue N0 = N->getOperand(0);
2288 SDValue N1 = N->getOperand(1);
2289 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2290 EVT VT = N->getValueType(0);
2293 // fold (mulhs x, 0) -> 0
2294 if (N1C && N1C->isNullValue())
2296 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2297 if (N1C && N1C->getAPIntValue() == 1)
2298 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2299 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2300 getShiftAmountTy(N0.getValueType())));
2301 // fold (mulhs x, undef) -> 0
2302 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2303 return DAG.getConstant(0, VT);
2305 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2307 if (VT.isSimple() && !VT.isVector()) {
2308 MVT Simple = VT.getSimpleVT();
2309 unsigned SimpleSize = Simple.getSizeInBits();
2310 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2311 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2312 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2313 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2314 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2315 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2316 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2317 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2324 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2325 SDValue N0 = N->getOperand(0);
2326 SDValue N1 = N->getOperand(1);
2327 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2328 EVT VT = N->getValueType(0);
2331 // fold (mulhu x, 0) -> 0
2332 if (N1C && N1C->isNullValue())
2334 // fold (mulhu x, 1) -> 0
2335 if (N1C && N1C->getAPIntValue() == 1)
2336 return DAG.getConstant(0, N0.getValueType());
2337 // fold (mulhu x, undef) -> 0
2338 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2339 return DAG.getConstant(0, VT);
2341 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2343 if (VT.isSimple() && !VT.isVector()) {
2344 MVT Simple = VT.getSimpleVT();
2345 unsigned SimpleSize = Simple.getSizeInBits();
2346 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2347 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2348 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2349 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2350 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2351 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2352 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2353 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2360 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2361 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2362 /// that are being performed. Return true if a simplification was made.
2364 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2366 // If the high half is not needed, just compute the low half.
2367 bool HiExists = N->hasAnyUseOfValue(1);
2369 (!LegalOperations ||
2370 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2371 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2372 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2373 return CombineTo(N, Res, Res);
2376 // If the low half is not needed, just compute the high half.
2377 bool LoExists = N->hasAnyUseOfValue(0);
2379 (!LegalOperations ||
2380 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2381 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2382 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2383 return CombineTo(N, Res, Res);
2386 // If both halves are used, return as it is.
2387 if (LoExists && HiExists)
2390 // If the two computed results can be simplified separately, separate them.
2392 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2393 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2394 AddToWorklist(Lo.getNode());
2395 SDValue LoOpt = combine(Lo.getNode());
2396 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2397 (!LegalOperations ||
2398 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2399 return CombineTo(N, LoOpt, LoOpt);
2403 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2404 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2405 AddToWorklist(Hi.getNode());
2406 SDValue HiOpt = combine(Hi.getNode());
2407 if (HiOpt.getNode() && HiOpt != Hi &&
2408 (!LegalOperations ||
2409 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2410 return CombineTo(N, HiOpt, HiOpt);
2416 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2417 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2418 if (Res.getNode()) return Res;
2420 EVT VT = N->getValueType(0);
2423 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2425 if (VT.isSimple() && !VT.isVector()) {
2426 MVT Simple = VT.getSimpleVT();
2427 unsigned SimpleSize = Simple.getSizeInBits();
2428 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2429 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2430 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2431 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2432 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2433 // Compute the high part as N1.
2434 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2435 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2436 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2437 // Compute the low part as N0.
2438 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2439 return CombineTo(N, Lo, Hi);
2446 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2447 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2448 if (Res.getNode()) return Res;
2450 EVT VT = N->getValueType(0);
2453 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2455 if (VT.isSimple() && !VT.isVector()) {
2456 MVT Simple = VT.getSimpleVT();
2457 unsigned SimpleSize = Simple.getSizeInBits();
2458 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2459 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2460 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2461 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2462 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2463 // Compute the high part as N1.
2464 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2465 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2466 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2467 // Compute the low part as N0.
2468 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2469 return CombineTo(N, Lo, Hi);
2476 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2477 // (smulo x, 2) -> (saddo x, x)
2478 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2479 if (C2->getAPIntValue() == 2)
2480 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2481 N->getOperand(0), N->getOperand(0));
2486 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2487 // (umulo x, 2) -> (uaddo x, x)
2488 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2489 if (C2->getAPIntValue() == 2)
2490 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2491 N->getOperand(0), N->getOperand(0));
2496 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2497 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2498 if (Res.getNode()) return Res;
2503 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2504 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2505 if (Res.getNode()) return Res;
2510 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2511 /// two operands of the same opcode, try to simplify it.
2512 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2513 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2514 EVT VT = N0.getValueType();
2515 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2517 // Bail early if none of these transforms apply.
2518 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2520 // For each of OP in AND/OR/XOR:
2521 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2522 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2523 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2524 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2526 // do not sink logical op inside of a vector extend, since it may combine
2528 EVT Op0VT = N0.getOperand(0).getValueType();
2529 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2530 N0.getOpcode() == ISD::SIGN_EXTEND ||
2531 // Avoid infinite looping with PromoteIntBinOp.
2532 (N0.getOpcode() == ISD::ANY_EXTEND &&
2533 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2534 (N0.getOpcode() == ISD::TRUNCATE &&
2535 (!TLI.isZExtFree(VT, Op0VT) ||
2536 !TLI.isTruncateFree(Op0VT, VT)) &&
2537 TLI.isTypeLegal(Op0VT))) &&
2539 Op0VT == N1.getOperand(0).getValueType() &&
2540 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2541 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2542 N0.getOperand(0).getValueType(),
2543 N0.getOperand(0), N1.getOperand(0));
2544 AddToWorklist(ORNode.getNode());
2545 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2548 // For each of OP in SHL/SRL/SRA/AND...
2549 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2550 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2551 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2552 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2553 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2554 N0.getOperand(1) == N1.getOperand(1)) {
2555 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2556 N0.getOperand(0).getValueType(),
2557 N0.getOperand(0), N1.getOperand(0));
2558 AddToWorklist(ORNode.getNode());
2559 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2560 ORNode, N0.getOperand(1));
2563 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2564 // Only perform this optimization after type legalization and before
2565 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2566 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2567 // we don't want to undo this promotion.
2568 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2570 if ((N0.getOpcode() == ISD::BITCAST ||
2571 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2572 Level == AfterLegalizeTypes) {
2573 SDValue In0 = N0.getOperand(0);
2574 SDValue In1 = N1.getOperand(0);
2575 EVT In0Ty = In0.getValueType();
2576 EVT In1Ty = In1.getValueType();
2578 // If both incoming values are integers, and the original types are the
2580 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2581 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2582 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2583 AddToWorklist(Op.getNode());
2588 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2589 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2590 // If both shuffles use the same mask, and both shuffle within a single
2591 // vector, then it is worthwhile to move the swizzle after the operation.
2592 // The type-legalizer generates this pattern when loading illegal
2593 // vector types from memory. In many cases this allows additional shuffle
2595 // There are other cases where moving the shuffle after the xor/and/or
2596 // is profitable even if shuffles don't perform a swizzle.
2597 // If both shuffles use the same mask, and both shuffles have the same first
2598 // or second operand, then it might still be profitable to move the shuffle
2599 // after the xor/and/or operation.
2600 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2601 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2602 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2604 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2605 "Inputs to shuffles are not the same type");
2607 // Check that both shuffles use the same mask. The masks are known to be of
2608 // the same length because the result vector type is the same.
2609 // Check also that shuffles have only one use to avoid introducing extra
2611 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2612 SVN0->getMask().equals(SVN1->getMask())) {
2613 SDValue ShOp = N0->getOperand(1);
2615 // Don't try to fold this node if it requires introducing a
2616 // build vector of all zeros that might be illegal at this stage.
2617 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2619 ShOp = DAG.getConstant(0, VT);
2624 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2625 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2626 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2627 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2628 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2629 N0->getOperand(0), N1->getOperand(0));
2630 AddToWorklist(NewNode.getNode());
2631 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2632 &SVN0->getMask()[0]);
2635 // Don't try to fold this node if it requires introducing a
2636 // build vector of all zeros that might be illegal at this stage.
2637 ShOp = N0->getOperand(0);
2638 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2640 ShOp = DAG.getConstant(0, VT);
2645 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2646 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2647 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2648 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2649 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2650 N0->getOperand(1), N1->getOperand(1));
2651 AddToWorklist(NewNode.getNode());
2652 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2653 &SVN0->getMask()[0]);
2661 SDValue DAGCombiner::visitAND(SDNode *N) {
2662 SDValue N0 = N->getOperand(0);
2663 SDValue N1 = N->getOperand(1);
2664 SDValue LL, LR, RL, RR, CC0, CC1;
2665 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2666 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2667 EVT VT = N1.getValueType();
2668 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2671 if (VT.isVector()) {
2672 SDValue FoldedVOp = SimplifyVBinOp(N);
2673 if (FoldedVOp.getNode()) return FoldedVOp;
2675 // fold (and x, 0) -> 0, vector edition
2676 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2678 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2681 // fold (and x, -1) -> x, vector edition
2682 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2684 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2688 // fold (and x, undef) -> 0
2689 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2690 return DAG.getConstant(0, VT);
2691 // fold (and c1, c2) -> c1&c2
2693 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2694 // canonicalize constant to RHS
2696 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2697 // fold (and x, -1) -> x
2698 if (N1C && N1C->isAllOnesValue())
2700 // if (and x, c) is known to be zero, return 0
2701 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2702 APInt::getAllOnesValue(BitWidth)))
2703 return DAG.getConstant(0, VT);
2705 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2708 // fold (and (or x, C), D) -> D if (C & D) == D
2709 if (N1C && N0.getOpcode() == ISD::OR)
2710 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2711 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2713 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2714 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2715 SDValue N0Op0 = N0.getOperand(0);
2716 APInt Mask = ~N1C->getAPIntValue();
2717 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2718 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2719 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2720 N0.getValueType(), N0Op0);
2722 // Replace uses of the AND with uses of the Zero extend node.
2725 // We actually want to replace all uses of the any_extend with the
2726 // zero_extend, to avoid duplicating things. This will later cause this
2727 // AND to be folded.
2728 CombineTo(N0.getNode(), Zext);
2729 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2732 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2733 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2734 // already be zero by virtue of the width of the base type of the load.
2736 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2738 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2739 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2740 N0.getOpcode() == ISD::LOAD) {
2741 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2742 N0 : N0.getOperand(0) );
2744 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2745 // This can be a pure constant or a vector splat, in which case we treat the
2746 // vector as a scalar and use the splat value.
2747 APInt Constant = APInt::getNullValue(1);
2748 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2749 Constant = C->getAPIntValue();
2750 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2751 APInt SplatValue, SplatUndef;
2752 unsigned SplatBitSize;
2754 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2755 SplatBitSize, HasAnyUndefs);
2757 // Undef bits can contribute to a possible optimisation if set, so
2759 SplatValue |= SplatUndef;
2761 // The splat value may be something like "0x00FFFFFF", which means 0 for
2762 // the first vector value and FF for the rest, repeating. We need a mask
2763 // that will apply equally to all members of the vector, so AND all the
2764 // lanes of the constant together.
2765 EVT VT = Vector->getValueType(0);
2766 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2768 // If the splat value has been compressed to a bitlength lower
2769 // than the size of the vector lane, we need to re-expand it to
2771 if (BitWidth > SplatBitSize)
2772 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2773 SplatBitSize < BitWidth;
2774 SplatBitSize = SplatBitSize * 2)
2775 SplatValue |= SplatValue.shl(SplatBitSize);
2777 Constant = APInt::getAllOnesValue(BitWidth);
2778 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2779 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2783 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2784 // actually legal and isn't going to get expanded, else this is a false
2786 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2787 Load->getMemoryVT());
2789 // Resize the constant to the same size as the original memory access before
2790 // extension. If it is still the AllOnesValue then this AND is completely
2793 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2796 switch (Load->getExtensionType()) {
2797 default: B = false; break;
2798 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2800 case ISD::NON_EXTLOAD: B = true; break;
2803 if (B && Constant.isAllOnesValue()) {
2804 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2805 // preserve semantics once we get rid of the AND.
2806 SDValue NewLoad(Load, 0);
2807 if (Load->getExtensionType() == ISD::EXTLOAD) {
2808 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2809 Load->getValueType(0), SDLoc(Load),
2810 Load->getChain(), Load->getBasePtr(),
2811 Load->getOffset(), Load->getMemoryVT(),
2812 Load->getMemOperand());
2813 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2814 if (Load->getNumValues() == 3) {
2815 // PRE/POST_INC loads have 3 values.
2816 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2817 NewLoad.getValue(2) };
2818 CombineTo(Load, To, 3, true);
2820 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2824 // Fold the AND away, taking care not to fold to the old load node if we
2826 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2828 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2831 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2832 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2833 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2834 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2836 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2837 LL.getValueType().isInteger()) {
2838 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2839 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2840 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2841 LR.getValueType(), LL, RL);
2842 AddToWorklist(ORNode.getNode());
2843 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2845 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2846 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2847 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2848 LR.getValueType(), LL, RL);
2849 AddToWorklist(ANDNode.getNode());
2850 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2852 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2853 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2854 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2855 LR.getValueType(), LL, RL);
2856 AddToWorklist(ORNode.getNode());
2857 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2860 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2861 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2862 Op0 == Op1 && LL.getValueType().isInteger() &&
2863 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2864 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2865 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2866 cast<ConstantSDNode>(RR)->isNullValue()))) {
2867 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2868 LL, DAG.getConstant(1, LL.getValueType()));
2869 AddToWorklist(ADDNode.getNode());
2870 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2871 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2873 // canonicalize equivalent to ll == rl
2874 if (LL == RR && LR == RL) {
2875 Op1 = ISD::getSetCCSwappedOperands(Op1);
2878 if (LL == RL && LR == RR) {
2879 bool isInteger = LL.getValueType().isInteger();
2880 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2881 if (Result != ISD::SETCC_INVALID &&
2882 (!LegalOperations ||
2883 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2884 TLI.isOperationLegal(ISD::SETCC,
2885 getSetCCResultType(N0.getSimpleValueType())))))
2886 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2891 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2892 if (N0.getOpcode() == N1.getOpcode()) {
2893 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2894 if (Tmp.getNode()) return Tmp;
2897 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2898 // fold (and (sra)) -> (and (srl)) when possible.
2899 if (!VT.isVector() &&
2900 SimplifyDemandedBits(SDValue(N, 0)))
2901 return SDValue(N, 0);
2903 // fold (zext_inreg (extload x)) -> (zextload x)
2904 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2905 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2906 EVT MemVT = LN0->getMemoryVT();
2907 // If we zero all the possible extended bits, then we can turn this into
2908 // a zextload if we are running before legalize or the operation is legal.
2909 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2910 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2911 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2912 ((!LegalOperations && !LN0->isVolatile()) ||
2913 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2914 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2915 LN0->getChain(), LN0->getBasePtr(),
2916 MemVT, LN0->getMemOperand());
2918 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2919 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2922 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2923 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2925 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2926 EVT MemVT = LN0->getMemoryVT();
2927 // If we zero all the possible extended bits, then we can turn this into
2928 // a zextload if we are running before legalize or the operation is legal.
2929 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2930 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2931 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2932 ((!LegalOperations && !LN0->isVolatile()) ||
2933 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2934 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2935 LN0->getChain(), LN0->getBasePtr(),
2936 MemVT, LN0->getMemOperand());
2938 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2939 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2943 // fold (and (load x), 255) -> (zextload x, i8)
2944 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2945 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2946 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2947 (N0.getOpcode() == ISD::ANY_EXTEND &&
2948 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2949 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2950 LoadSDNode *LN0 = HasAnyExt
2951 ? cast<LoadSDNode>(N0.getOperand(0))
2952 : cast<LoadSDNode>(N0);
2953 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2954 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2955 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2956 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2957 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2958 EVT LoadedVT = LN0->getMemoryVT();
2960 if (ExtVT == LoadedVT &&
2961 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2962 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2965 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2966 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2967 LN0->getMemOperand());
2969 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2970 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2973 // Do not change the width of a volatile load.
2974 // Do not generate loads of non-round integer types since these can
2975 // be expensive (and would be wrong if the type is not byte sized).
2976 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2977 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2978 EVT PtrType = LN0->getOperand(1).getValueType();
2980 unsigned Alignment = LN0->getAlignment();
2981 SDValue NewPtr = LN0->getBasePtr();
2983 // For big endian targets, we need to add an offset to the pointer
2984 // to load the correct bytes. For little endian systems, we merely
2985 // need to read fewer bytes from the same pointer.
2986 if (TLI.isBigEndian()) {
2987 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2988 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2989 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2990 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2991 NewPtr, DAG.getConstant(PtrOff, PtrType));
2992 Alignment = MinAlign(Alignment, PtrOff);
2995 AddToWorklist(NewPtr.getNode());
2997 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2999 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3000 LN0->getChain(), NewPtr,
3001 LN0->getPointerInfo(),
3002 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3003 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3005 CombineTo(LN0, Load, Load.getValue(1));
3006 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3012 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3013 VT.getSizeInBits() <= 64) {
3014 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3015 APInt ADDC = ADDI->getAPIntValue();
3016 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3017 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3018 // immediate for an add, but it is legal if its top c2 bits are set,
3019 // transform the ADD so the immediate doesn't need to be materialized
3021 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3022 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3023 SRLI->getZExtValue());
3024 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3026 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3028 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3029 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3030 CombineTo(N0.getNode(), NewAdd);
3031 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3039 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3040 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3041 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3042 N0.getOperand(1), false);
3043 if (BSwap.getNode())
3050 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
3052 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3053 bool DemandHighBits) {
3054 if (!LegalOperations)
3057 EVT VT = N->getValueType(0);
3058 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3060 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3063 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3064 bool LookPassAnd0 = false;
3065 bool LookPassAnd1 = false;
3066 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3068 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3070 if (N0.getOpcode() == ISD::AND) {
3071 if (!N0.getNode()->hasOneUse())
3073 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3074 if (!N01C || N01C->getZExtValue() != 0xFF00)
3076 N0 = N0.getOperand(0);
3077 LookPassAnd0 = true;
3080 if (N1.getOpcode() == ISD::AND) {
3081 if (!N1.getNode()->hasOneUse())
3083 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3084 if (!N11C || N11C->getZExtValue() != 0xFF)
3086 N1 = N1.getOperand(0);
3087 LookPassAnd1 = true;
3090 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3092 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3094 if (!N0.getNode()->hasOneUse() ||
3095 !N1.getNode()->hasOneUse())
3098 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3099 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3102 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3105 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3106 SDValue N00 = N0->getOperand(0);
3107 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3108 if (!N00.getNode()->hasOneUse())
3110 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3111 if (!N001C || N001C->getZExtValue() != 0xFF)
3113 N00 = N00.getOperand(0);
3114 LookPassAnd0 = true;
3117 SDValue N10 = N1->getOperand(0);
3118 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3119 if (!N10.getNode()->hasOneUse())
3121 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3122 if (!N101C || N101C->getZExtValue() != 0xFF00)
3124 N10 = N10.getOperand(0);
3125 LookPassAnd1 = true;
3131 // Make sure everything beyond the low halfword gets set to zero since the SRL
3132 // 16 will clear the top bits.
3133 unsigned OpSizeInBits = VT.getSizeInBits();
3134 if (DemandHighBits && OpSizeInBits > 16) {
3135 // If the left-shift isn't masked out then the only way this is a bswap is
3136 // if all bits beyond the low 8 are 0. In that case the entire pattern
3137 // reduces to a left shift anyway: leave it for other parts of the combiner.
3141 // However, if the right shift isn't masked out then it might be because
3142 // it's not needed. See if we can spot that too.
3143 if (!LookPassAnd1 &&
3144 !DAG.MaskedValueIsZero(
3145 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3149 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3150 if (OpSizeInBits > 16)
3151 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3152 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3156 /// isBSwapHWordElement - Return true if the specified node is an element
3157 /// that makes up a 32-bit packed halfword byteswap. i.e.
3158 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3159 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3160 if (!N.getNode()->hasOneUse())
3163 unsigned Opc = N.getOpcode();
3164 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3167 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3172 switch (N1C->getZExtValue()) {
3175 case 0xFF: Num = 0; break;
3176 case 0xFF00: Num = 1; break;
3177 case 0xFF0000: Num = 2; break;
3178 case 0xFF000000: Num = 3; break;
3181 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3182 SDValue N0 = N.getOperand(0);
3183 if (Opc == ISD::AND) {
3184 if (Num == 0 || Num == 2) {
3186 // (x >> 8) & 0xff0000
3187 if (N0.getOpcode() != ISD::SRL)
3189 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3190 if (!C || C->getZExtValue() != 8)
3193 // (x << 8) & 0xff00
3194 // (x << 8) & 0xff000000
3195 if (N0.getOpcode() != ISD::SHL)
3197 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3198 if (!C || C->getZExtValue() != 8)
3201 } else if (Opc == ISD::SHL) {
3203 // (x & 0xff0000) << 8
3204 if (Num != 0 && Num != 2)
3206 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3207 if (!C || C->getZExtValue() != 8)
3209 } else { // Opc == ISD::SRL
3210 // (x & 0xff00) >> 8
3211 // (x & 0xff000000) >> 8
3212 if (Num != 1 && Num != 3)
3214 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3215 if (!C || C->getZExtValue() != 8)
3222 Parts[Num] = N0.getOperand(0).getNode();
3226 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3227 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3228 /// => (rotl (bswap x), 16)
3229 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3230 if (!LegalOperations)
3233 EVT VT = N->getValueType(0);
3236 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3239 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3241 // (or (or (and), (and)), (or (and), (and)))
3242 // (or (or (or (and), (and)), (and)), (and))
3243 if (N0.getOpcode() != ISD::OR)
3245 SDValue N00 = N0.getOperand(0);
3246 SDValue N01 = N0.getOperand(1);
3248 if (N1.getOpcode() == ISD::OR &&
3249 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3250 // (or (or (and), (and)), (or (and), (and)))
3251 SDValue N000 = N00.getOperand(0);
3252 if (!isBSwapHWordElement(N000, Parts))
3255 SDValue N001 = N00.getOperand(1);
3256 if (!isBSwapHWordElement(N001, Parts))
3258 SDValue N010 = N01.getOperand(0);
3259 if (!isBSwapHWordElement(N010, Parts))
3261 SDValue N011 = N01.getOperand(1);
3262 if (!isBSwapHWordElement(N011, Parts))
3265 // (or (or (or (and), (and)), (and)), (and))
3266 if (!isBSwapHWordElement(N1, Parts))
3268 if (!isBSwapHWordElement(N01, Parts))
3270 if (N00.getOpcode() != ISD::OR)
3272 SDValue N000 = N00.getOperand(0);
3273 if (!isBSwapHWordElement(N000, Parts))
3275 SDValue N001 = N00.getOperand(1);
3276 if (!isBSwapHWordElement(N001, Parts))
3280 // Make sure the parts are all coming from the same node.
3281 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3284 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3285 SDValue(Parts[0],0));
3287 // Result of the bswap should be rotated by 16. If it's not legal, then
3288 // do (x << 16) | (x >> 16).
3289 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3290 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3291 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3292 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3293 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3294 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3295 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3296 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3299 SDValue DAGCombiner::visitOR(SDNode *N) {
3300 SDValue N0 = N->getOperand(0);
3301 SDValue N1 = N->getOperand(1);
3302 SDValue LL, LR, RL, RR, CC0, CC1;
3303 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3304 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3305 EVT VT = N1.getValueType();
3308 if (VT.isVector()) {
3309 SDValue FoldedVOp = SimplifyVBinOp(N);
3310 if (FoldedVOp.getNode()) return FoldedVOp;
3312 // fold (or x, 0) -> x, vector edition
3313 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3315 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3318 // fold (or x, -1) -> -1, vector edition
3319 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3321 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3324 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3325 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3326 // Do this only if the resulting shuffle is legal.
3327 if (isa<ShuffleVectorSDNode>(N0) &&
3328 isa<ShuffleVectorSDNode>(N1) &&
3329 // Avoid folding a node with illegal type.
3330 TLI.isTypeLegal(VT) &&
3331 N0->getOperand(1) == N1->getOperand(1) &&
3332 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3333 bool CanFold = true;
3334 unsigned NumElts = VT.getVectorNumElements();
3335 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3336 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3337 // We construct two shuffle masks:
3338 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3339 // and N1 as the second operand.
3340 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3341 // and N0 as the second operand.
3342 // We do this because OR is commutable and therefore there might be
3343 // two ways to fold this node into a shuffle.
3344 SmallVector<int,4> Mask1;
3345 SmallVector<int,4> Mask2;
3347 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3348 int M0 = SV0->getMaskElt(i);
3349 int M1 = SV1->getMaskElt(i);
3351 // Both shuffle indexes are undef. Propagate Undef.
3352 if (M0 < 0 && M1 < 0) {
3353 Mask1.push_back(M0);
3354 Mask2.push_back(M0);
3358 if (M0 < 0 || M1 < 0 ||
3359 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3360 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3365 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3366 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3370 // Fold this sequence only if the resulting shuffle is 'legal'.
3371 if (TLI.isShuffleMaskLegal(Mask1, VT))
3372 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3373 N1->getOperand(0), &Mask1[0]);
3374 if (TLI.isShuffleMaskLegal(Mask2, VT))
3375 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3376 N0->getOperand(0), &Mask2[0]);
3381 // fold (or x, undef) -> -1
3382 if (!LegalOperations &&
3383 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3384 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3385 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3387 // fold (or c1, c2) -> c1|c2
3389 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3390 // canonicalize constant to RHS
3392 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3393 // fold (or x, 0) -> x
3394 if (N1C && N1C->isNullValue())
3396 // fold (or x, -1) -> -1
3397 if (N1C && N1C->isAllOnesValue())
3399 // fold (or x, c) -> c iff (x & ~c) == 0
3400 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3403 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3404 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3405 if (BSwap.getNode())
3407 BSwap = MatchBSwapHWordLow(N, N0, N1);
3408 if (BSwap.getNode())
3412 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3415 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3416 // iff (c1 & c2) == 0.
3417 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3418 isa<ConstantSDNode>(N0.getOperand(1))) {
3419 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3420 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3421 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3424 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3425 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3426 N0.getOperand(0), N1), COR);
3429 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3430 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3431 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3432 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3434 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3435 LL.getValueType().isInteger()) {
3436 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3437 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3438 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3439 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3440 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3441 LR.getValueType(), LL, RL);
3442 AddToWorklist(ORNode.getNode());
3443 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3445 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3446 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3447 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3448 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3449 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3450 LR.getValueType(), LL, RL);
3451 AddToWorklist(ANDNode.getNode());
3452 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3455 // canonicalize equivalent to ll == rl
3456 if (LL == RR && LR == RL) {
3457 Op1 = ISD::getSetCCSwappedOperands(Op1);
3460 if (LL == RL && LR == RR) {
3461 bool isInteger = LL.getValueType().isInteger();
3462 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3463 if (Result != ISD::SETCC_INVALID &&
3464 (!LegalOperations ||
3465 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3466 TLI.isOperationLegal(ISD::SETCC,
3467 getSetCCResultType(N0.getValueType())))))
3468 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3473 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3474 if (N0.getOpcode() == N1.getOpcode()) {
3475 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3476 if (Tmp.getNode()) return Tmp;
3479 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3480 if (N0.getOpcode() == ISD::AND &&
3481 N1.getOpcode() == ISD::AND &&
3482 N0.getOperand(1).getOpcode() == ISD::Constant &&
3483 N1.getOperand(1).getOpcode() == ISD::Constant &&
3484 // Don't increase # computations.
3485 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3486 // We can only do this xform if we know that bits from X that are set in C2
3487 // but not in C1 are already zero. Likewise for Y.
3488 const APInt &LHSMask =
3489 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3490 const APInt &RHSMask =
3491 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3493 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3494 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3495 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3496 N0.getOperand(0), N1.getOperand(0));
3497 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3498 DAG.getConstant(LHSMask | RHSMask, VT));
3502 // See if this is some rotate idiom.
3503 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3504 return SDValue(Rot, 0);
3506 // Simplify the operands using demanded-bits information.
3507 if (!VT.isVector() &&
3508 SimplifyDemandedBits(SDValue(N, 0)))
3509 return SDValue(N, 0);
3514 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3515 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3516 if (Op.getOpcode() == ISD::AND) {
3517 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3518 Mask = Op.getOperand(1);
3519 Op = Op.getOperand(0);
3525 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3533 // Return true if we can prove that, whenever Neg and Pos are both in the
3534 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3535 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3537 // (or (shift1 X, Neg), (shift2 X, Pos))
3539 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3540 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3541 // to consider shift amounts with defined behavior.
3542 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3543 // If OpSize is a power of 2 then:
3545 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3546 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3548 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3549 // for the stronger condition:
3551 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3553 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3554 // we can just replace Neg with Neg' for the rest of the function.
3556 // In other cases we check for the even stronger condition:
3558 // Neg == OpSize - Pos [B]
3560 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3561 // behavior if Pos == 0 (and consequently Neg == OpSize).
3563 // We could actually use [A] whenever OpSize is a power of 2, but the
3564 // only extra cases that it would match are those uninteresting ones
3565 // where Neg and Pos are never in range at the same time. E.g. for
3566 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3567 // as well as (sub 32, Pos), but:
3569 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3571 // always invokes undefined behavior for 32-bit X.
3573 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3574 unsigned MaskLoBits = 0;
3575 if (Neg.getOpcode() == ISD::AND &&
3576 isPowerOf2_64(OpSize) &&
3577 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3578 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3579 Neg = Neg.getOperand(0);
3580 MaskLoBits = Log2_64(OpSize);
3583 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3584 if (Neg.getOpcode() != ISD::SUB)
3586 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3589 SDValue NegOp1 = Neg.getOperand(1);
3591 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3592 // Pos'. The truncation is redundant for the purpose of the equality.
3594 Pos.getOpcode() == ISD::AND &&
3595 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3596 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3597 Pos = Pos.getOperand(0);
3599 // The condition we need is now:
3601 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3603 // If NegOp1 == Pos then we need:
3605 // OpSize & Mask == NegC & Mask
3607 // (because "x & Mask" is a truncation and distributes through subtraction).
3610 Width = NegC->getAPIntValue();
3611 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3612 // Then the condition we want to prove becomes:
3614 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3616 // which, again because "x & Mask" is a truncation, becomes:
3618 // NegC & Mask == (OpSize - PosC) & Mask
3619 // OpSize & Mask == (NegC + PosC) & Mask
3620 else if (Pos.getOpcode() == ISD::ADD &&
3621 Pos.getOperand(0) == NegOp1 &&
3622 Pos.getOperand(1).getOpcode() == ISD::Constant)
3623 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3624 NegC->getAPIntValue());
3628 // Now we just need to check that OpSize & Mask == Width & Mask.
3630 // Opsize & Mask is 0 since Mask is Opsize - 1.
3631 return Width.getLoBits(MaskLoBits) == 0;
3632 return Width == OpSize;
3635 // A subroutine of MatchRotate used once we have found an OR of two opposite
3636 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3637 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3638 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3639 // Neg with outer conversions stripped away.
3640 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3641 SDValue Neg, SDValue InnerPos,
3642 SDValue InnerNeg, unsigned PosOpcode,
3643 unsigned NegOpcode, SDLoc DL) {
3644 // fold (or (shl x, (*ext y)),
3645 // (srl x, (*ext (sub 32, y)))) ->
3646 // (rotl x, y) or (rotr x, (sub 32, y))
3648 // fold (or (shl x, (*ext (sub 32, y))),
3649 // (srl x, (*ext y))) ->
3650 // (rotr x, y) or (rotl x, (sub 32, y))
3651 EVT VT = Shifted.getValueType();
3652 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3653 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3654 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3655 HasPos ? Pos : Neg).getNode();
3661 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3662 // idioms for rotate, and if the target supports rotation instructions, generate
3664 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3665 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3666 EVT VT = LHS.getValueType();
3667 if (!TLI.isTypeLegal(VT)) return nullptr;
3669 // The target must have at least one rotate flavor.
3670 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3671 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3672 if (!HasROTL && !HasROTR) return nullptr;
3674 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3675 SDValue LHSShift; // The shift.
3676 SDValue LHSMask; // AND value if any.
3677 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3678 return nullptr; // Not part of a rotate.
3680 SDValue RHSShift; // The shift.
3681 SDValue RHSMask; // AND value if any.
3682 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3683 return nullptr; // Not part of a rotate.
3685 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3686 return nullptr; // Not shifting the same value.
3688 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3689 return nullptr; // Shifts must disagree.
3691 // Canonicalize shl to left side in a shl/srl pair.
3692 if (RHSShift.getOpcode() == ISD::SHL) {
3693 std::swap(LHS, RHS);
3694 std::swap(LHSShift, RHSShift);
3695 std::swap(LHSMask , RHSMask );
3698 unsigned OpSizeInBits = VT.getSizeInBits();
3699 SDValue LHSShiftArg = LHSShift.getOperand(0);
3700 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3701 SDValue RHSShiftArg = RHSShift.getOperand(0);
3702 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3704 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3705 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3706 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3707 RHSShiftAmt.getOpcode() == ISD::Constant) {
3708 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3709 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3710 if ((LShVal + RShVal) != OpSizeInBits)
3713 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3714 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3716 // If there is an AND of either shifted operand, apply it to the result.
3717 if (LHSMask.getNode() || RHSMask.getNode()) {
3718 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3720 if (LHSMask.getNode()) {
3721 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3722 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3724 if (RHSMask.getNode()) {
3725 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3726 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3729 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3732 return Rot.getNode();
3735 // If there is a mask here, and we have a variable shift, we can't be sure
3736 // that we're masking out the right stuff.
3737 if (LHSMask.getNode() || RHSMask.getNode())
3740 // If the shift amount is sign/zext/any-extended just peel it off.
3741 SDValue LExtOp0 = LHSShiftAmt;
3742 SDValue RExtOp0 = RHSShiftAmt;
3743 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3744 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3745 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3746 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3747 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3748 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3749 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3750 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3751 LExtOp0 = LHSShiftAmt.getOperand(0);
3752 RExtOp0 = RHSShiftAmt.getOperand(0);
3755 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3756 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3760 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3761 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3768 SDValue DAGCombiner::visitXOR(SDNode *N) {
3769 SDValue N0 = N->getOperand(0);
3770 SDValue N1 = N->getOperand(1);
3771 SDValue LHS, RHS, CC;
3772 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3773 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3774 EVT VT = N0.getValueType();
3777 if (VT.isVector()) {
3778 SDValue FoldedVOp = SimplifyVBinOp(N);
3779 if (FoldedVOp.getNode()) return FoldedVOp;
3781 // fold (xor x, 0) -> x, vector edition
3782 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3784 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3788 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3789 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3790 return DAG.getConstant(0, VT);
3791 // fold (xor x, undef) -> undef
3792 if (N0.getOpcode() == ISD::UNDEF)
3794 if (N1.getOpcode() == ISD::UNDEF)
3796 // fold (xor c1, c2) -> c1^c2
3798 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3799 // canonicalize constant to RHS
3801 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3802 // fold (xor x, 0) -> x
3803 if (N1C && N1C->isNullValue())
3806 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3810 // fold !(x cc y) -> (x !cc y)
3811 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3812 bool isInt = LHS.getValueType().isInteger();
3813 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3816 if (!LegalOperations ||
3817 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3818 switch (N0.getOpcode()) {
3820 llvm_unreachable("Unhandled SetCC Equivalent!");
3822 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3823 case ISD::SELECT_CC:
3824 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3825 N0.getOperand(3), NotCC);
3830 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3831 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3832 N0.getNode()->hasOneUse() &&
3833 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3834 SDValue V = N0.getOperand(0);
3835 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3836 DAG.getConstant(1, V.getValueType()));
3837 AddToWorklist(V.getNode());
3838 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3841 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3842 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3843 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3844 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3845 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3846 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3847 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3848 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3849 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3850 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3853 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3854 if (N1C && N1C->isAllOnesValue() &&
3855 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3856 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3857 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3858 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3859 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3860 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3861 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3862 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3865 // fold (xor (and x, y), y) -> (and (not x), y)
3866 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3867 N0->getOperand(1) == N1) {
3868 SDValue X = N0->getOperand(0);
3869 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3870 AddToWorklist(NotX.getNode());
3871 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3873 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3874 if (N1C && N0.getOpcode() == ISD::XOR) {
3875 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3876 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3878 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3879 DAG.getConstant(N1C->getAPIntValue() ^
3880 N00C->getAPIntValue(), VT));
3882 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3883 DAG.getConstant(N1C->getAPIntValue() ^
3884 N01C->getAPIntValue(), VT));
3886 // fold (xor x, x) -> 0
3888 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3890 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3891 if (N0.getOpcode() == N1.getOpcode()) {
3892 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3893 if (Tmp.getNode()) return Tmp;
3896 // Simplify the expression using non-local knowledge.
3897 if (!VT.isVector() &&
3898 SimplifyDemandedBits(SDValue(N, 0)))
3899 return SDValue(N, 0);
3904 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3905 /// the shift amount is a constant.
3906 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3907 // We can't and shouldn't fold opaque constants.
3908 if (Amt->isOpaque())
3911 SDNode *LHS = N->getOperand(0).getNode();
3912 if (!LHS->hasOneUse()) return SDValue();
3914 // We want to pull some binops through shifts, so that we have (and (shift))
3915 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3916 // thing happens with address calculations, so it's important to canonicalize
3918 bool HighBitSet = false; // Can we transform this if the high bit is set?
3920 switch (LHS->getOpcode()) {
3921 default: return SDValue();
3924 HighBitSet = false; // We can only transform sra if the high bit is clear.
3927 HighBitSet = true; // We can only transform sra if the high bit is set.
3930 if (N->getOpcode() != ISD::SHL)
3931 return SDValue(); // only shl(add) not sr[al](add).
3932 HighBitSet = false; // We can only transform sra if the high bit is clear.
3936 // We require the RHS of the binop to be a constant and not opaque as well.
3937 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3938 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3940 // FIXME: disable this unless the input to the binop is a shift by a constant.
3941 // If it is not a shift, it pessimizes some common cases like:
3943 // void foo(int *X, int i) { X[i & 1235] = 1; }
3944 // int bar(int *X, int i) { return X[i & 255]; }
3945 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3946 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3947 BinOpLHSVal->getOpcode() != ISD::SRA &&
3948 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3949 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3952 EVT VT = N->getValueType(0);
3954 // If this is a signed shift right, and the high bit is modified by the
3955 // logical operation, do not perform the transformation. The highBitSet
3956 // boolean indicates the value of the high bit of the constant which would
3957 // cause it to be modified for this operation.
3958 if (N->getOpcode() == ISD::SRA) {
3959 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3960 if (BinOpRHSSignSet != HighBitSet)
3964 if (!TLI.isDesirableToCommuteWithShift(LHS))
3967 // Fold the constants, shifting the binop RHS by the shift amount.
3968 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3970 LHS->getOperand(1), N->getOperand(1));
3971 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3973 // Create the new shift.
3974 SDValue NewShift = DAG.getNode(N->getOpcode(),
3975 SDLoc(LHS->getOperand(0)),
3976 VT, LHS->getOperand(0), N->getOperand(1));
3978 // Create the new binop.
3979 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3982 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3983 assert(N->getOpcode() == ISD::TRUNCATE);
3984 assert(N->getOperand(0).getOpcode() == ISD::AND);
3986 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3987 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3988 SDValue N01 = N->getOperand(0).getOperand(1);
3990 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3991 EVT TruncVT = N->getValueType(0);
3992 SDValue N00 = N->getOperand(0).getOperand(0);
3993 APInt TruncC = N01C->getAPIntValue();
3994 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3996 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3997 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3998 DAG.getConstant(TruncC, TruncVT));
4005 SDValue DAGCombiner::visitRotate(SDNode *N) {
4006 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4007 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4008 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4009 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4010 if (NewOp1.getNode())
4011 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4012 N->getOperand(0), NewOp1);
4017 SDValue DAGCombiner::visitSHL(SDNode *N) {
4018 SDValue N0 = N->getOperand(0);
4019 SDValue N1 = N->getOperand(1);
4020 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4021 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4022 EVT VT = N0.getValueType();
4023 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4026 if (VT.isVector()) {
4027 SDValue FoldedVOp = SimplifyVBinOp(N);
4028 if (FoldedVOp.getNode()) return FoldedVOp;
4030 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4031 // If setcc produces all-one true value then:
4032 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4033 if (N1CV && N1CV->isConstant()) {
4034 if (N0.getOpcode() == ISD::AND) {
4035 SDValue N00 = N0->getOperand(0);
4036 SDValue N01 = N0->getOperand(1);
4037 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4039 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4040 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4041 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4042 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4044 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4047 N1C = isConstOrConstSplat(N1);
4052 // fold (shl c1, c2) -> c1<<c2
4054 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4055 // fold (shl 0, x) -> 0
4056 if (N0C && N0C->isNullValue())
4058 // fold (shl x, c >= size(x)) -> undef
4059 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4060 return DAG.getUNDEF(VT);
4061 // fold (shl x, 0) -> x
4062 if (N1C && N1C->isNullValue())
4064 // fold (shl undef, x) -> 0
4065 if (N0.getOpcode() == ISD::UNDEF)
4066 return DAG.getConstant(0, VT);
4067 // if (shl x, c) is known to be zero, return 0
4068 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4069 APInt::getAllOnesValue(OpSizeInBits)))
4070 return DAG.getConstant(0, VT);
4071 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4072 if (N1.getOpcode() == ISD::TRUNCATE &&
4073 N1.getOperand(0).getOpcode() == ISD::AND) {
4074 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4075 if (NewOp1.getNode())
4076 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4079 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4080 return SDValue(N, 0);
4082 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4083 if (N1C && N0.getOpcode() == ISD::SHL) {
4084 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4085 uint64_t c1 = N0C1->getZExtValue();
4086 uint64_t c2 = N1C->getZExtValue();
4087 if (c1 + c2 >= OpSizeInBits)
4088 return DAG.getConstant(0, VT);
4089 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4090 DAG.getConstant(c1 + c2, N1.getValueType()));
4094 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4095 // For this to be valid, the second form must not preserve any of the bits
4096 // that are shifted out by the inner shift in the first form. This means
4097 // the outer shift size must be >= the number of bits added by the ext.
4098 // As a corollary, we don't care what kind of ext it is.
4099 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4100 N0.getOpcode() == ISD::ANY_EXTEND ||
4101 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4102 N0.getOperand(0).getOpcode() == ISD::SHL) {
4103 SDValue N0Op0 = N0.getOperand(0);
4104 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4105 uint64_t c1 = N0Op0C1->getZExtValue();
4106 uint64_t c2 = N1C->getZExtValue();
4107 EVT InnerShiftVT = N0Op0.getValueType();
4108 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4109 if (c2 >= OpSizeInBits - InnerShiftSize) {
4110 if (c1 + c2 >= OpSizeInBits)
4111 return DAG.getConstant(0, VT);
4112 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4113 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4114 N0Op0->getOperand(0)),
4115 DAG.getConstant(c1 + c2, N1.getValueType()));
4120 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4121 // Only fold this if the inner zext has no other uses to avoid increasing
4122 // the total number of instructions.
4123 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4124 N0.getOperand(0).getOpcode() == ISD::SRL) {
4125 SDValue N0Op0 = N0.getOperand(0);
4126 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4127 uint64_t c1 = N0Op0C1->getZExtValue();
4128 if (c1 < VT.getScalarSizeInBits()) {
4129 uint64_t c2 = N1C->getZExtValue();
4131 SDValue NewOp0 = N0.getOperand(0);
4132 EVT CountVT = NewOp0.getOperand(1).getValueType();
4133 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4134 NewOp0, DAG.getConstant(c2, CountVT));
4135 AddToWorklist(NewSHL.getNode());
4136 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4142 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4143 // (and (srl x, (sub c1, c2), MASK)
4144 // Only fold this if the inner shift has no other uses -- if it does, folding
4145 // this will increase the total number of instructions.
4146 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4147 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4148 uint64_t c1 = N0C1->getZExtValue();
4149 if (c1 < OpSizeInBits) {
4150 uint64_t c2 = N1C->getZExtValue();
4151 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4154 Mask = Mask.shl(c2 - c1);
4155 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4156 DAG.getConstant(c2 - c1, N1.getValueType()));
4158 Mask = Mask.lshr(c1 - c2);
4159 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4160 DAG.getConstant(c1 - c2, N1.getValueType()));
4162 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4163 DAG.getConstant(Mask, VT));
4167 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4168 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4169 unsigned BitSize = VT.getScalarSizeInBits();
4170 SDValue HiBitsMask =
4171 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4172 BitSize - N1C->getZExtValue()), VT);
4173 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4178 SDValue NewSHL = visitShiftByConstant(N, N1C);
4179 if (NewSHL.getNode())
4186 SDValue DAGCombiner::visitSRA(SDNode *N) {
4187 SDValue N0 = N->getOperand(0);
4188 SDValue N1 = N->getOperand(1);
4189 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4190 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4191 EVT VT = N0.getValueType();
4192 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4195 if (VT.isVector()) {
4196 SDValue FoldedVOp = SimplifyVBinOp(N);
4197 if (FoldedVOp.getNode()) return FoldedVOp;
4199 N1C = isConstOrConstSplat(N1);
4202 // fold (sra c1, c2) -> (sra c1, c2)
4204 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4205 // fold (sra 0, x) -> 0
4206 if (N0C && N0C->isNullValue())
4208 // fold (sra -1, x) -> -1
4209 if (N0C && N0C->isAllOnesValue())
4211 // fold (sra x, (setge c, size(x))) -> undef
4212 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4213 return DAG.getUNDEF(VT);
4214 // fold (sra x, 0) -> x
4215 if (N1C && N1C->isNullValue())
4217 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4219 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4220 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4221 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4223 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4224 ExtVT, VT.getVectorNumElements());
4225 if ((!LegalOperations ||
4226 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4227 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4228 N0.getOperand(0), DAG.getValueType(ExtVT));
4231 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4232 if (N1C && N0.getOpcode() == ISD::SRA) {
4233 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4234 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4235 if (Sum >= OpSizeInBits)
4236 Sum = OpSizeInBits - 1;
4237 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4238 DAG.getConstant(Sum, N1.getValueType()));
4242 // fold (sra (shl X, m), (sub result_size, n))
4243 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4244 // result_size - n != m.
4245 // If truncate is free for the target sext(shl) is likely to result in better
4247 if (N0.getOpcode() == ISD::SHL && N1C) {
4248 // Get the two constanst of the shifts, CN0 = m, CN = n.
4249 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4251 LLVMContext &Ctx = *DAG.getContext();
4252 // Determine what the truncate's result bitsize and type would be.
4253 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4256 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4258 // Determine the residual right-shift amount.
4259 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4261 // If the shift is not a no-op (in which case this should be just a sign
4262 // extend already), the truncated to type is legal, sign_extend is legal
4263 // on that type, and the truncate to that type is both legal and free,
4264 // perform the transform.
4265 if ((ShiftAmt > 0) &&
4266 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4267 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4268 TLI.isTruncateFree(VT, TruncVT)) {
4270 SDValue Amt = DAG.getConstant(ShiftAmt,
4271 getShiftAmountTy(N0.getOperand(0).getValueType()));
4272 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4273 N0.getOperand(0), Amt);
4274 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4276 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4277 N->getValueType(0), Trunc);
4282 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4283 if (N1.getOpcode() == ISD::TRUNCATE &&
4284 N1.getOperand(0).getOpcode() == ISD::AND) {
4285 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4286 if (NewOp1.getNode())
4287 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4290 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4291 // if c1 is equal to the number of bits the trunc removes
4292 if (N0.getOpcode() == ISD::TRUNCATE &&
4293 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4294 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4295 N0.getOperand(0).hasOneUse() &&
4296 N0.getOperand(0).getOperand(1).hasOneUse() &&
4298 SDValue N0Op0 = N0.getOperand(0);
4299 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4300 unsigned LargeShiftVal = LargeShift->getZExtValue();
4301 EVT LargeVT = N0Op0.getValueType();
4303 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4305 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4306 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4307 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4308 N0Op0.getOperand(0), Amt);
4309 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4314 // Simplify, based on bits shifted out of the LHS.
4315 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4316 return SDValue(N, 0);
4319 // If the sign bit is known to be zero, switch this to a SRL.
4320 if (DAG.SignBitIsZero(N0))
4321 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4324 SDValue NewSRA = visitShiftByConstant(N, N1C);
4325 if (NewSRA.getNode())
4332 SDValue DAGCombiner::visitSRL(SDNode *N) {
4333 SDValue N0 = N->getOperand(0);
4334 SDValue N1 = N->getOperand(1);
4335 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4336 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4337 EVT VT = N0.getValueType();
4338 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4341 if (VT.isVector()) {
4342 SDValue FoldedVOp = SimplifyVBinOp(N);
4343 if (FoldedVOp.getNode()) return FoldedVOp;
4345 N1C = isConstOrConstSplat(N1);
4348 // fold (srl c1, c2) -> c1 >>u c2
4350 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4351 // fold (srl 0, x) -> 0
4352 if (N0C && N0C->isNullValue())
4354 // fold (srl x, c >= size(x)) -> undef
4355 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4356 return DAG.getUNDEF(VT);
4357 // fold (srl x, 0) -> x
4358 if (N1C && N1C->isNullValue())
4360 // if (srl x, c) is known to be zero, return 0
4361 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4362 APInt::getAllOnesValue(OpSizeInBits)))
4363 return DAG.getConstant(0, VT);
4365 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4366 if (N1C && N0.getOpcode() == ISD::SRL) {
4367 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4368 uint64_t c1 = N01C->getZExtValue();
4369 uint64_t c2 = N1C->getZExtValue();
4370 if (c1 + c2 >= OpSizeInBits)
4371 return DAG.getConstant(0, VT);
4372 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4373 DAG.getConstant(c1 + c2, N1.getValueType()));
4377 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4378 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4379 N0.getOperand(0).getOpcode() == ISD::SRL &&
4380 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4382 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4383 uint64_t c2 = N1C->getZExtValue();
4384 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4385 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4386 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4387 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4388 if (c1 + OpSizeInBits == InnerShiftSize) {
4389 if (c1 + c2 >= InnerShiftSize)
4390 return DAG.getConstant(0, VT);
4391 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4392 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4393 N0.getOperand(0)->getOperand(0),
4394 DAG.getConstant(c1 + c2, ShiftCountVT)));
4398 // fold (srl (shl x, c), c) -> (and x, cst2)
4399 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4400 unsigned BitSize = N0.getScalarValueSizeInBits();
4401 if (BitSize <= 64) {
4402 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4403 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4404 DAG.getConstant(~0ULL >> ShAmt, VT));
4408 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4409 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4410 // Shifting in all undef bits?
4411 EVT SmallVT = N0.getOperand(0).getValueType();
4412 unsigned BitSize = SmallVT.getScalarSizeInBits();
4413 if (N1C->getZExtValue() >= BitSize)
4414 return DAG.getUNDEF(VT);
4416 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4417 uint64_t ShiftAmt = N1C->getZExtValue();
4418 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4420 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4421 AddToWorklist(SmallShift.getNode());
4422 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4423 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4424 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4425 DAG.getConstant(Mask, VT));
4429 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4430 // bit, which is unmodified by sra.
4431 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4432 if (N0.getOpcode() == ISD::SRA)
4433 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4436 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4437 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4438 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4439 APInt KnownZero, KnownOne;
4440 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4442 // If any of the input bits are KnownOne, then the input couldn't be all
4443 // zeros, thus the result of the srl will always be zero.
4444 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4446 // If all of the bits input the to ctlz node are known to be zero, then
4447 // the result of the ctlz is "32" and the result of the shift is one.
4448 APInt UnknownBits = ~KnownZero;
4449 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4451 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4452 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4453 // Okay, we know that only that the single bit specified by UnknownBits
4454 // could be set on input to the CTLZ node. If this bit is set, the SRL
4455 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4456 // to an SRL/XOR pair, which is likely to simplify more.
4457 unsigned ShAmt = UnknownBits.countTrailingZeros();
4458 SDValue Op = N0.getOperand(0);
4461 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4462 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4463 AddToWorklist(Op.getNode());
4466 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4467 Op, DAG.getConstant(1, VT));
4471 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4472 if (N1.getOpcode() == ISD::TRUNCATE &&
4473 N1.getOperand(0).getOpcode() == ISD::AND) {
4474 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4475 if (NewOp1.getNode())
4476 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4479 // fold operands of srl based on knowledge that the low bits are not
4481 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4482 return SDValue(N, 0);
4485 SDValue NewSRL = visitShiftByConstant(N, N1C);
4486 if (NewSRL.getNode())
4490 // Attempt to convert a srl of a load into a narrower zero-extending load.
4491 SDValue NarrowLoad = ReduceLoadWidth(N);
4492 if (NarrowLoad.getNode())
4495 // Here is a common situation. We want to optimize:
4498 // %b = and i32 %a, 2
4499 // %c = srl i32 %b, 1
4500 // brcond i32 %c ...
4506 // %c = setcc eq %b, 0
4509 // However when after the source operand of SRL is optimized into AND, the SRL
4510 // itself may not be optimized further. Look for it and add the BRCOND into
4512 if (N->hasOneUse()) {
4513 SDNode *Use = *N->use_begin();
4514 if (Use->getOpcode() == ISD::BRCOND)
4516 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4517 // Also look pass the truncate.
4518 Use = *Use->use_begin();
4519 if (Use->getOpcode() == ISD::BRCOND)
4527 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4528 SDValue N0 = N->getOperand(0);
4529 EVT VT = N->getValueType(0);
4531 // fold (ctlz c1) -> c2
4532 if (isa<ConstantSDNode>(N0))
4533 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4537 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4538 SDValue N0 = N->getOperand(0);
4539 EVT VT = N->getValueType(0);
4541 // fold (ctlz_zero_undef c1) -> c2
4542 if (isa<ConstantSDNode>(N0))
4543 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4547 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4548 SDValue N0 = N->getOperand(0);
4549 EVT VT = N->getValueType(0);
4551 // fold (cttz c1) -> c2
4552 if (isa<ConstantSDNode>(N0))
4553 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4557 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4558 SDValue N0 = N->getOperand(0);
4559 EVT VT = N->getValueType(0);
4561 // fold (cttz_zero_undef c1) -> c2
4562 if (isa<ConstantSDNode>(N0))
4563 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4567 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4568 SDValue N0 = N->getOperand(0);
4569 EVT VT = N->getValueType(0);
4571 // fold (ctpop c1) -> c2
4572 if (isa<ConstantSDNode>(N0))
4573 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4577 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4578 SDValue N0 = N->getOperand(0);
4579 SDValue N1 = N->getOperand(1);
4580 SDValue N2 = N->getOperand(2);
4581 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4582 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4583 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4584 EVT VT = N->getValueType(0);
4585 EVT VT0 = N0.getValueType();
4587 // fold (select C, X, X) -> X
4590 // fold (select true, X, Y) -> X
4591 if (N0C && !N0C->isNullValue())
4593 // fold (select false, X, Y) -> Y
4594 if (N0C && N0C->isNullValue())
4596 // fold (select C, 1, X) -> (or C, X)
4597 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4598 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4599 // fold (select C, 0, 1) -> (xor C, 1)
4600 // We can't do this reliably if integer based booleans have different contents
4601 // to floating point based booleans. This is because we can't tell whether we
4602 // have an integer-based boolean or a floating-point-based boolean unless we
4603 // can find the SETCC that produced it and inspect its operands. This is
4604 // fairly easy if C is the SETCC node, but it can potentially be
4605 // undiscoverable (or not reasonably discoverable). For example, it could be
4606 // in another basic block or it could require searching a complicated
4608 if (VT.isInteger() &&
4609 (VT0 == MVT::i1 || (VT0.isInteger() &&
4610 TLI.getBooleanContents(false, false) ==
4611 TLI.getBooleanContents(false, true) &&
4612 TLI.getBooleanContents(false, false) ==
4613 TargetLowering::ZeroOrOneBooleanContent)) &&
4614 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4617 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4618 N0, DAG.getConstant(1, VT0));
4619 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4620 N0, DAG.getConstant(1, VT0));
4621 AddToWorklist(XORNode.getNode());
4623 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4624 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4626 // fold (select C, 0, X) -> (and (not C), X)
4627 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4628 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4629 AddToWorklist(NOTNode.getNode());
4630 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4632 // fold (select C, X, 1) -> (or (not C), X)
4633 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4634 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4635 AddToWorklist(NOTNode.getNode());
4636 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4638 // fold (select C, X, 0) -> (and C, X)
4639 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4640 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4641 // fold (select X, X, Y) -> (or X, Y)
4642 // fold (select X, 1, Y) -> (or X, Y)
4643 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4644 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4645 // fold (select X, Y, X) -> (and X, Y)
4646 // fold (select X, Y, 0) -> (and X, Y)
4647 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4648 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4650 // If we can fold this based on the true/false value, do so.
4651 if (SimplifySelectOps(N, N1, N2))
4652 return SDValue(N, 0); // Don't revisit N.
4654 // fold selects based on a setcc into other things, such as min/max/abs
4655 if (N0.getOpcode() == ISD::SETCC) {
4656 if ((!LegalOperations &&
4657 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4658 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4659 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4660 N0.getOperand(0), N0.getOperand(1),
4661 N1, N2, N0.getOperand(2));
4662 return SimplifySelect(SDLoc(N), N0, N1, N2);
4669 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4672 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4674 // Split the inputs.
4675 SDValue Lo, Hi, LL, LH, RL, RH;
4676 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4677 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4679 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4680 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4682 return std::make_pair(Lo, Hi);
4685 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4686 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4687 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4689 SDValue Cond = N->getOperand(0);
4690 SDValue LHS = N->getOperand(1);
4691 SDValue RHS = N->getOperand(2);
4692 EVT VT = N->getValueType(0);
4693 int NumElems = VT.getVectorNumElements();
4694 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4695 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4696 Cond.getOpcode() == ISD::BUILD_VECTOR);
4698 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4699 // binary ones here.
4700 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4703 // We're sure we have an even number of elements due to the
4704 // concat_vectors we have as arguments to vselect.
4705 // Skip BV elements until we find one that's not an UNDEF
4706 // After we find an UNDEF element, keep looping until we get to half the
4707 // length of the BV and see if all the non-undef nodes are the same.
4708 ConstantSDNode *BottomHalf = nullptr;
4709 for (int i = 0; i < NumElems / 2; ++i) {
4710 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4713 if (BottomHalf == nullptr)
4714 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4715 else if (Cond->getOperand(i).getNode() != BottomHalf)
4719 // Do the same for the second half of the BuildVector
4720 ConstantSDNode *TopHalf = nullptr;
4721 for (int i = NumElems / 2; i < NumElems; ++i) {
4722 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4725 if (TopHalf == nullptr)
4726 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4727 else if (Cond->getOperand(i).getNode() != TopHalf)
4731 assert(TopHalf && BottomHalf &&
4732 "One half of the selector was all UNDEFs and the other was all the "
4733 "same value. This should have been addressed before this function.");
4735 ISD::CONCAT_VECTORS, dl, VT,
4736 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4737 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4740 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4741 SDValue N0 = N->getOperand(0);
4742 SDValue N1 = N->getOperand(1);
4743 SDValue N2 = N->getOperand(2);
4746 // Canonicalize integer abs.
4747 // vselect (setg[te] X, 0), X, -X ->
4748 // vselect (setgt X, -1), X, -X ->
4749 // vselect (setl[te] X, 0), -X, X ->
4750 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4751 if (N0.getOpcode() == ISD::SETCC) {
4752 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4753 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4755 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4757 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4758 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4759 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4760 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4761 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4762 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4763 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4766 EVT VT = LHS.getValueType();
4767 SDValue Shift = DAG.getNode(
4768 ISD::SRA, DL, VT, LHS,
4769 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4770 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4771 AddToWorklist(Shift.getNode());
4772 AddToWorklist(Add.getNode());
4773 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4777 // If the VSELECT result requires splitting and the mask is provided by a
4778 // SETCC, then split both nodes and its operands before legalization. This
4779 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4780 // and enables future optimizations (e.g. min/max pattern matching on X86).
4781 if (N0.getOpcode() == ISD::SETCC) {
4782 EVT VT = N->getValueType(0);
4784 // Check if any splitting is required.
4785 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4786 TargetLowering::TypeSplitVector)
4789 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4790 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4791 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4792 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4794 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4795 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4797 // Add the new VSELECT nodes to the work list in case they need to be split
4799 AddToWorklist(Lo.getNode());
4800 AddToWorklist(Hi.getNode());
4802 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4805 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4806 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4808 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4809 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4812 // The ConvertSelectToConcatVector function is assuming both the above
4813 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4815 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4816 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4817 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4818 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4826 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4827 SDValue N0 = N->getOperand(0);
4828 SDValue N1 = N->getOperand(1);
4829 SDValue N2 = N->getOperand(2);
4830 SDValue N3 = N->getOperand(3);
4831 SDValue N4 = N->getOperand(4);
4832 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4834 // fold select_cc lhs, rhs, x, x, cc -> x
4838 // Determine if the condition we're dealing with is constant
4839 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4840 N0, N1, CC, SDLoc(N), false);
4841 if (SCC.getNode()) {
4842 AddToWorklist(SCC.getNode());
4844 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4845 if (!SCCC->isNullValue())
4846 return N2; // cond always true -> true val
4848 return N3; // cond always false -> false val
4851 // Fold to a simpler select_cc
4852 if (SCC.getOpcode() == ISD::SETCC)
4853 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4854 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4858 // If we can fold this based on the true/false value, do so.
4859 if (SimplifySelectOps(N, N2, N3))
4860 return SDValue(N, 0); // Don't revisit N.
4862 // fold select_cc into other things, such as min/max/abs
4863 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4866 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4867 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4868 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4872 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4873 // dag node into a ConstantSDNode or a build_vector of constants.
4874 // This function is called by the DAGCombiner when visiting sext/zext/aext
4875 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4876 // Vector extends are not folded if operations are legal; this is to
4877 // avoid introducing illegal build_vector dag nodes.
4878 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4879 SelectionDAG &DAG, bool LegalTypes,
4880 bool LegalOperations) {
4881 unsigned Opcode = N->getOpcode();
4882 SDValue N0 = N->getOperand(0);
4883 EVT VT = N->getValueType(0);
4885 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4886 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4888 // fold (sext c1) -> c1
4889 // fold (zext c1) -> c1
4890 // fold (aext c1) -> c1
4891 if (isa<ConstantSDNode>(N0))
4892 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4894 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4895 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4896 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4897 EVT SVT = VT.getScalarType();
4898 if (!(VT.isVector() &&
4899 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4900 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4903 // We can fold this node into a build_vector.
4904 unsigned VTBits = SVT.getSizeInBits();
4905 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4906 unsigned ShAmt = VTBits - EVTBits;
4907 SmallVector<SDValue, 8> Elts;
4908 unsigned NumElts = N0->getNumOperands();
4911 for (unsigned i=0; i != NumElts; ++i) {
4912 SDValue Op = N0->getOperand(i);
4913 if (Op->getOpcode() == ISD::UNDEF) {
4914 Elts.push_back(DAG.getUNDEF(SVT));
4918 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4919 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4920 if (Opcode == ISD::SIGN_EXTEND)
4921 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4924 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4928 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4931 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4932 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4933 // transformation. Returns true if extension are possible and the above
4934 // mentioned transformation is profitable.
4935 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4937 SmallVectorImpl<SDNode *> &ExtendNodes,
4938 const TargetLowering &TLI) {
4939 bool HasCopyToRegUses = false;
4940 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4941 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4942 UE = N0.getNode()->use_end();
4947 if (UI.getUse().getResNo() != N0.getResNo())
4949 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4950 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4951 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4952 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4953 // Sign bits will be lost after a zext.
4956 for (unsigned i = 0; i != 2; ++i) {
4957 SDValue UseOp = User->getOperand(i);
4960 if (!isa<ConstantSDNode>(UseOp))
4965 ExtendNodes.push_back(User);
4968 // If truncates aren't free and there are users we can't
4969 // extend, it isn't worthwhile.
4972 // Remember if this value is live-out.
4973 if (User->getOpcode() == ISD::CopyToReg)
4974 HasCopyToRegUses = true;
4977 if (HasCopyToRegUses) {
4978 bool BothLiveOut = false;
4979 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4981 SDUse &Use = UI.getUse();
4982 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4988 // Both unextended and extended values are live out. There had better be
4989 // a good reason for the transformation.
4990 return ExtendNodes.size();
4995 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4996 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4997 ISD::NodeType ExtType) {
4998 // Extend SetCC uses if necessary.
4999 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5000 SDNode *SetCC = SetCCs[i];
5001 SmallVector<SDValue, 4> Ops;
5003 for (unsigned j = 0; j != 2; ++j) {
5004 SDValue SOp = SetCC->getOperand(j);
5006 Ops.push_back(ExtLoad);
5008 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5011 Ops.push_back(SetCC->getOperand(2));
5012 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5016 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5017 SDValue N0 = N->getOperand(0);
5018 EVT VT = N->getValueType(0);
5020 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5022 return SDValue(Res, 0);
5024 // fold (sext (sext x)) -> (sext x)
5025 // fold (sext (aext x)) -> (sext x)
5026 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5027 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5030 if (N0.getOpcode() == ISD::TRUNCATE) {
5031 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5032 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5033 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5034 if (NarrowLoad.getNode()) {
5035 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5036 if (NarrowLoad.getNode() != N0.getNode()) {
5037 CombineTo(N0.getNode(), NarrowLoad);
5038 // CombineTo deleted the truncate, if needed, but not what's under it.
5041 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5044 // See if the value being truncated is already sign extended. If so, just
5045 // eliminate the trunc/sext pair.
5046 SDValue Op = N0.getOperand(0);
5047 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5048 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5049 unsigned DestBits = VT.getScalarType().getSizeInBits();
5050 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5052 if (OpBits == DestBits) {
5053 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5054 // bits, it is already ready.
5055 if (NumSignBits > DestBits-MidBits)
5057 } else if (OpBits < DestBits) {
5058 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5059 // bits, just sext from i32.
5060 if (NumSignBits > OpBits-MidBits)
5061 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5063 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5064 // bits, just truncate to i32.
5065 if (NumSignBits > OpBits-MidBits)
5066 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5069 // fold (sext (truncate x)) -> (sextinreg x).
5070 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5071 N0.getValueType())) {
5072 if (OpBits < DestBits)
5073 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5074 else if (OpBits > DestBits)
5075 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5076 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5077 DAG.getValueType(N0.getValueType()));
5081 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5082 // None of the supported targets knows how to perform load and sign extend
5083 // on vectors in one instruction. We only perform this transformation on
5085 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5086 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5087 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5088 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5089 bool DoXform = true;
5090 SmallVector<SDNode*, 4> SetCCs;
5091 if (!N0.hasOneUse())
5092 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5094 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5095 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5097 LN0->getBasePtr(), N0.getValueType(),
5098 LN0->getMemOperand());
5099 CombineTo(N, ExtLoad);
5100 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5101 N0.getValueType(), ExtLoad);
5102 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5103 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5105 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5109 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5110 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5111 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5112 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5113 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5114 EVT MemVT = LN0->getMemoryVT();
5115 if ((!LegalOperations && !LN0->isVolatile()) ||
5116 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5117 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5119 LN0->getBasePtr(), MemVT,
5120 LN0->getMemOperand());
5121 CombineTo(N, ExtLoad);
5122 CombineTo(N0.getNode(),
5123 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5124 N0.getValueType(), ExtLoad),
5125 ExtLoad.getValue(1));
5126 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5130 // fold (sext (and/or/xor (load x), cst)) ->
5131 // (and/or/xor (sextload x), (sext cst))
5132 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5133 N0.getOpcode() == ISD::XOR) &&
5134 isa<LoadSDNode>(N0.getOperand(0)) &&
5135 N0.getOperand(1).getOpcode() == ISD::Constant &&
5136 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5137 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5138 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5139 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5140 bool DoXform = true;
5141 SmallVector<SDNode*, 4> SetCCs;
5142 if (!N0.hasOneUse())
5143 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5146 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5147 LN0->getChain(), LN0->getBasePtr(),
5149 LN0->getMemOperand());
5150 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5151 Mask = Mask.sext(VT.getSizeInBits());
5152 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5153 ExtLoad, DAG.getConstant(Mask, VT));
5154 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5155 SDLoc(N0.getOperand(0)),
5156 N0.getOperand(0).getValueType(), ExtLoad);
5158 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5159 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5161 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5166 if (N0.getOpcode() == ISD::SETCC) {
5167 EVT N0VT = N0.getOperand(0).getValueType();
5168 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5169 // Only do this before legalize for now.
5170 if (VT.isVector() && !LegalOperations &&
5171 TLI.getBooleanContents(N0VT) ==
5172 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5173 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5174 // of the same size as the compared operands. Only optimize sext(setcc())
5175 // if this is the case.
5176 EVT SVT = getSetCCResultType(N0VT);
5178 // We know that the # elements of the results is the same as the
5179 // # elements of the compare (and the # elements of the compare result
5180 // for that matter). Check to see that they are the same size. If so,
5181 // we know that the element size of the sext'd result matches the
5182 // element size of the compare operands.
5183 if (VT.getSizeInBits() == SVT.getSizeInBits())
5184 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5186 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5188 // If the desired elements are smaller or larger than the source
5189 // elements we can use a matching integer vector type and then
5190 // truncate/sign extend
5191 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5192 if (SVT == MatchingVectorType) {
5193 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5194 N0.getOperand(0), N0.getOperand(1),
5195 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5196 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5200 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5201 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5203 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5205 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5206 NegOne, DAG.getConstant(0, VT),
5207 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5208 if (SCC.getNode()) return SCC;
5210 if (!VT.isVector()) {
5211 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5212 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5214 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5215 SDValue SetCC = DAG.getSetCC(DL,
5217 N0.getOperand(0), N0.getOperand(1), CC);
5218 EVT SelectVT = getSetCCResultType(VT);
5219 return DAG.getSelect(DL, VT,
5220 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5221 NegOne, DAG.getConstant(0, VT));
5227 // fold (sext x) -> (zext x) if the sign bit is known zero.
5228 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5229 DAG.SignBitIsZero(N0))
5230 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5235 // isTruncateOf - If N is a truncate of some other value, return true, record
5236 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5237 // This function computes KnownZero to avoid a duplicated call to
5238 // computeKnownBits in the caller.
5239 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5242 if (N->getOpcode() == ISD::TRUNCATE) {
5243 Op = N->getOperand(0);
5244 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5248 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5249 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5252 SDValue Op0 = N->getOperand(0);
5253 SDValue Op1 = N->getOperand(1);
5254 assert(Op0.getValueType() == Op1.getValueType());
5256 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5257 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5258 if (COp0 && COp0->isNullValue())
5260 else if (COp1 && COp1->isNullValue())
5265 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5267 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5273 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5274 SDValue N0 = N->getOperand(0);
5275 EVT VT = N->getValueType(0);
5277 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5279 return SDValue(Res, 0);
5281 // fold (zext (zext x)) -> (zext x)
5282 // fold (zext (aext x)) -> (zext x)
5283 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5284 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5287 // fold (zext (truncate x)) -> (zext x) or
5288 // (zext (truncate x)) -> (truncate x)
5289 // This is valid when the truncated bits of x are already zero.
5290 // FIXME: We should extend this to work for vectors too.
5293 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5294 APInt TruncatedBits =
5295 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5296 APInt(Op.getValueSizeInBits(), 0) :
5297 APInt::getBitsSet(Op.getValueSizeInBits(),
5298 N0.getValueSizeInBits(),
5299 std::min(Op.getValueSizeInBits(),
5300 VT.getSizeInBits()));
5301 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5302 if (VT.bitsGT(Op.getValueType()))
5303 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5304 if (VT.bitsLT(Op.getValueType()))
5305 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5311 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5312 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5313 if (N0.getOpcode() == ISD::TRUNCATE) {
5314 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5315 if (NarrowLoad.getNode()) {
5316 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5317 if (NarrowLoad.getNode() != N0.getNode()) {
5318 CombineTo(N0.getNode(), NarrowLoad);
5319 // CombineTo deleted the truncate, if needed, but not what's under it.
5322 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5326 // fold (zext (truncate x)) -> (and x, mask)
5327 if (N0.getOpcode() == ISD::TRUNCATE &&
5328 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5330 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5331 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5332 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5333 if (NarrowLoad.getNode()) {
5334 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5335 if (NarrowLoad.getNode() != N0.getNode()) {
5336 CombineTo(N0.getNode(), NarrowLoad);
5337 // CombineTo deleted the truncate, if needed, but not what's under it.
5340 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5343 SDValue Op = N0.getOperand(0);
5344 if (Op.getValueType().bitsLT(VT)) {
5345 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5346 AddToWorklist(Op.getNode());
5347 } else if (Op.getValueType().bitsGT(VT)) {
5348 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5349 AddToWorklist(Op.getNode());
5351 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5352 N0.getValueType().getScalarType());
5355 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5356 // if either of the casts is not free.
5357 if (N0.getOpcode() == ISD::AND &&
5358 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5359 N0.getOperand(1).getOpcode() == ISD::Constant &&
5360 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5361 N0.getValueType()) ||
5362 !TLI.isZExtFree(N0.getValueType(), VT))) {
5363 SDValue X = N0.getOperand(0).getOperand(0);
5364 if (X.getValueType().bitsLT(VT)) {
5365 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5366 } else if (X.getValueType().bitsGT(VT)) {
5367 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5369 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5370 Mask = Mask.zext(VT.getSizeInBits());
5371 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5372 X, DAG.getConstant(Mask, VT));
5375 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5376 // None of the supported targets knows how to perform load and vector_zext
5377 // on vectors in one instruction. We only perform this transformation on
5379 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5380 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5381 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5382 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5383 bool DoXform = true;
5384 SmallVector<SDNode*, 4> SetCCs;
5385 if (!N0.hasOneUse())
5386 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5388 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5389 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5391 LN0->getBasePtr(), N0.getValueType(),
5392 LN0->getMemOperand());
5393 CombineTo(N, ExtLoad);
5394 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5395 N0.getValueType(), ExtLoad);
5396 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5398 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5400 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5404 // fold (zext (and/or/xor (load x), cst)) ->
5405 // (and/or/xor (zextload x), (zext cst))
5406 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5407 N0.getOpcode() == ISD::XOR) &&
5408 isa<LoadSDNode>(N0.getOperand(0)) &&
5409 N0.getOperand(1).getOpcode() == ISD::Constant &&
5410 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5411 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5412 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5413 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5414 bool DoXform = true;
5415 SmallVector<SDNode*, 4> SetCCs;
5416 if (!N0.hasOneUse())
5417 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5420 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5421 LN0->getChain(), LN0->getBasePtr(),
5423 LN0->getMemOperand());
5424 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5425 Mask = Mask.zext(VT.getSizeInBits());
5426 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5427 ExtLoad, DAG.getConstant(Mask, VT));
5428 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5429 SDLoc(N0.getOperand(0)),
5430 N0.getOperand(0).getValueType(), ExtLoad);
5432 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5433 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5435 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5440 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5441 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5442 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5443 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5444 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5445 EVT MemVT = LN0->getMemoryVT();
5446 if ((!LegalOperations && !LN0->isVolatile()) ||
5447 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5448 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5450 LN0->getBasePtr(), MemVT,
5451 LN0->getMemOperand());
5452 CombineTo(N, ExtLoad);
5453 CombineTo(N0.getNode(),
5454 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5456 ExtLoad.getValue(1));
5457 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5461 if (N0.getOpcode() == ISD::SETCC) {
5462 if (!LegalOperations && VT.isVector() &&
5463 N0.getValueType().getVectorElementType() == MVT::i1) {
5464 EVT N0VT = N0.getOperand(0).getValueType();
5465 if (getSetCCResultType(N0VT) == N0.getValueType())
5468 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5469 // Only do this before legalize for now.
5470 EVT EltVT = VT.getVectorElementType();
5471 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5472 DAG.getConstant(1, EltVT));
5473 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5474 // We know that the # elements of the results is the same as the
5475 // # elements of the compare (and the # elements of the compare result
5476 // for that matter). Check to see that they are the same size. If so,
5477 // we know that the element size of the sext'd result matches the
5478 // element size of the compare operands.
5479 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5480 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5482 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5483 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5486 // If the desired elements are smaller or larger than the source
5487 // elements we can use a matching integer vector type and then
5488 // truncate/sign extend
5489 EVT MatchingElementType =
5490 EVT::getIntegerVT(*DAG.getContext(),
5491 N0VT.getScalarType().getSizeInBits());
5492 EVT MatchingVectorType =
5493 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5494 N0VT.getVectorNumElements());
5496 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5498 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5499 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5500 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5501 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5504 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5506 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5507 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5508 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5509 if (SCC.getNode()) return SCC;
5512 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5513 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5514 isa<ConstantSDNode>(N0.getOperand(1)) &&
5515 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5517 SDValue ShAmt = N0.getOperand(1);
5518 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5519 if (N0.getOpcode() == ISD::SHL) {
5520 SDValue InnerZExt = N0.getOperand(0);
5521 // If the original shl may be shifting out bits, do not perform this
5523 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5524 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5525 if (ShAmtVal > KnownZeroBits)
5531 // Ensure that the shift amount is wide enough for the shifted value.
5532 if (VT.getSizeInBits() >= 256)
5533 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5535 return DAG.getNode(N0.getOpcode(), DL, VT,
5536 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5543 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5544 SDValue N0 = N->getOperand(0);
5545 EVT VT = N->getValueType(0);
5547 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5549 return SDValue(Res, 0);
5551 // fold (aext (aext x)) -> (aext x)
5552 // fold (aext (zext x)) -> (zext x)
5553 // fold (aext (sext x)) -> (sext x)
5554 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5555 N0.getOpcode() == ISD::ZERO_EXTEND ||
5556 N0.getOpcode() == ISD::SIGN_EXTEND)
5557 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5559 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5560 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5561 if (N0.getOpcode() == ISD::TRUNCATE) {
5562 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5563 if (NarrowLoad.getNode()) {
5564 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5565 if (NarrowLoad.getNode() != N0.getNode()) {
5566 CombineTo(N0.getNode(), NarrowLoad);
5567 // CombineTo deleted the truncate, if needed, but not what's under it.
5570 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5574 // fold (aext (truncate x))
5575 if (N0.getOpcode() == ISD::TRUNCATE) {
5576 SDValue TruncOp = N0.getOperand(0);
5577 if (TruncOp.getValueType() == VT)
5578 return TruncOp; // x iff x size == zext size.
5579 if (TruncOp.getValueType().bitsGT(VT))
5580 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5581 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5584 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5585 // if the trunc is not free.
5586 if (N0.getOpcode() == ISD::AND &&
5587 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5588 N0.getOperand(1).getOpcode() == ISD::Constant &&
5589 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5590 N0.getValueType())) {
5591 SDValue X = N0.getOperand(0).getOperand(0);
5592 if (X.getValueType().bitsLT(VT)) {
5593 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5594 } else if (X.getValueType().bitsGT(VT)) {
5595 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5597 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5598 Mask = Mask.zext(VT.getSizeInBits());
5599 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5600 X, DAG.getConstant(Mask, VT));
5603 // fold (aext (load x)) -> (aext (truncate (extload x)))
5604 // None of the supported targets knows how to perform load and any_ext
5605 // on vectors in one instruction. We only perform this transformation on
5607 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5608 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5609 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5610 bool DoXform = true;
5611 SmallVector<SDNode*, 4> SetCCs;
5612 if (!N0.hasOneUse())
5613 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5615 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5616 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5618 LN0->getBasePtr(), N0.getValueType(),
5619 LN0->getMemOperand());
5620 CombineTo(N, ExtLoad);
5621 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5622 N0.getValueType(), ExtLoad);
5623 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5624 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5626 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5630 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5631 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5632 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5633 if (N0.getOpcode() == ISD::LOAD &&
5634 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5636 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5637 ISD::LoadExtType ExtType = LN0->getExtensionType();
5638 EVT MemVT = LN0->getMemoryVT();
5639 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5640 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5641 VT, LN0->getChain(), LN0->getBasePtr(),
5642 MemVT, LN0->getMemOperand());
5643 CombineTo(N, ExtLoad);
5644 CombineTo(N0.getNode(),
5645 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5646 N0.getValueType(), ExtLoad),
5647 ExtLoad.getValue(1));
5648 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5652 if (N0.getOpcode() == ISD::SETCC) {
5654 // aext(setcc) -> vsetcc
5655 // aext(setcc) -> truncate(vsetcc)
5656 // aext(setcc) -> aext(vsetcc)
5657 // Only do this before legalize for now.
5658 if (VT.isVector() && !LegalOperations) {
5659 EVT N0VT = N0.getOperand(0).getValueType();
5660 // We know that the # elements of the results is the same as the
5661 // # elements of the compare (and the # elements of the compare result
5662 // for that matter). Check to see that they are the same size. If so,
5663 // we know that the element size of the sext'd result matches the
5664 // element size of the compare operands.
5665 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5666 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5668 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5669 // If the desired elements are smaller or larger than the source
5670 // elements we can use a matching integer vector type and then
5671 // truncate/any extend
5673 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5675 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5677 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5678 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5682 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5684 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5685 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5686 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5694 /// GetDemandedBits - See if the specified operand can be simplified with the
5695 /// knowledge that only the bits specified by Mask are used. If so, return the
5696 /// simpler operand, otherwise return a null SDValue.
5697 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5698 switch (V.getOpcode()) {
5700 case ISD::Constant: {
5701 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5702 assert(CV && "Const value should be ConstSDNode.");
5703 const APInt &CVal = CV->getAPIntValue();
5704 APInt NewVal = CVal & Mask;
5706 return DAG.getConstant(NewVal, V.getValueType());
5711 // If the LHS or RHS don't contribute bits to the or, drop them.
5712 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5713 return V.getOperand(1);
5714 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5715 return V.getOperand(0);
5718 // Only look at single-use SRLs.
5719 if (!V.getNode()->hasOneUse())
5721 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5722 // See if we can recursively simplify the LHS.
5723 unsigned Amt = RHSC->getZExtValue();
5725 // Watch out for shift count overflow though.
5726 if (Amt >= Mask.getBitWidth()) break;
5727 APInt NewMask = Mask << Amt;
5728 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5729 if (SimplifyLHS.getNode())
5730 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5731 SimplifyLHS, V.getOperand(1));
5737 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5738 /// bits and then truncated to a narrower type and where N is a multiple
5739 /// of number of bits of the narrower type, transform it to a narrower load
5740 /// from address + N / num of bits of new type. If the result is to be
5741 /// extended, also fold the extension to form a extending load.
5742 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5743 unsigned Opc = N->getOpcode();
5745 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5746 SDValue N0 = N->getOperand(0);
5747 EVT VT = N->getValueType(0);
5750 // This transformation isn't valid for vector loads.
5754 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5756 if (Opc == ISD::SIGN_EXTEND_INREG) {
5757 ExtType = ISD::SEXTLOAD;
5758 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5759 } else if (Opc == ISD::SRL) {
5760 // Another special-case: SRL is basically zero-extending a narrower value.
5761 ExtType = ISD::ZEXTLOAD;
5763 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5764 if (!N01) return SDValue();
5765 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5766 VT.getSizeInBits() - N01->getZExtValue());
5768 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5771 unsigned EVTBits = ExtVT.getSizeInBits();
5773 // Do not generate loads of non-round integer types since these can
5774 // be expensive (and would be wrong if the type is not byte sized).
5775 if (!ExtVT.isRound())
5779 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5780 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5781 ShAmt = N01->getZExtValue();
5782 // Is the shift amount a multiple of size of VT?
5783 if ((ShAmt & (EVTBits-1)) == 0) {
5784 N0 = N0.getOperand(0);
5785 // Is the load width a multiple of size of VT?
5786 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5790 // At this point, we must have a load or else we can't do the transform.
5791 if (!isa<LoadSDNode>(N0)) return SDValue();
5793 // Because a SRL must be assumed to *need* to zero-extend the high bits
5794 // (as opposed to anyext the high bits), we can't combine the zextload
5795 // lowering of SRL and an sextload.
5796 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5799 // If the shift amount is larger than the input type then we're not
5800 // accessing any of the loaded bytes. If the load was a zextload/extload
5801 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5802 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5807 // If the load is shifted left (and the result isn't shifted back right),
5808 // we can fold the truncate through the shift.
5809 unsigned ShLeftAmt = 0;
5810 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5811 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5812 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5813 ShLeftAmt = N01->getZExtValue();
5814 N0 = N0.getOperand(0);
5818 // If we haven't found a load, we can't narrow it. Don't transform one with
5819 // multiple uses, this would require adding a new load.
5820 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5823 // Don't change the width of a volatile load.
5824 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5825 if (LN0->isVolatile())
5828 // Verify that we are actually reducing a load width here.
5829 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5832 // For the transform to be legal, the load must produce only two values
5833 // (the value loaded and the chain). Don't transform a pre-increment
5834 // load, for example, which produces an extra value. Otherwise the
5835 // transformation is not equivalent, and the downstream logic to replace
5836 // uses gets things wrong.
5837 if (LN0->getNumValues() > 2)
5840 // If the load that we're shrinking is an extload and we're not just
5841 // discarding the extension we can't simply shrink the load. Bail.
5842 // TODO: It would be possible to merge the extensions in some cases.
5843 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5844 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5847 EVT PtrType = N0.getOperand(1).getValueType();
5849 if (PtrType == MVT::Untyped || PtrType.isExtended())
5850 // It's not possible to generate a constant of extended or untyped type.
5853 // For big endian targets, we need to adjust the offset to the pointer to
5854 // load the correct bytes.
5855 if (TLI.isBigEndian()) {
5856 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5857 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5858 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5861 uint64_t PtrOff = ShAmt / 8;
5862 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5863 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5864 PtrType, LN0->getBasePtr(),
5865 DAG.getConstant(PtrOff, PtrType));
5866 AddToWorklist(NewPtr.getNode());
5869 if (ExtType == ISD::NON_EXTLOAD)
5870 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5871 LN0->getPointerInfo().getWithOffset(PtrOff),
5872 LN0->isVolatile(), LN0->isNonTemporal(),
5873 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5875 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5876 LN0->getPointerInfo().getWithOffset(PtrOff),
5877 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5878 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5880 // Replace the old load's chain with the new load's chain.
5881 WorklistRemover DeadNodes(*this);
5882 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5884 // Shift the result left, if we've swallowed a left shift.
5885 SDValue Result = Load;
5886 if (ShLeftAmt != 0) {
5887 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5888 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5890 // If the shift amount is as large as the result size (but, presumably,
5891 // no larger than the source) then the useful bits of the result are
5892 // zero; we can't simply return the shortened shift, because the result
5893 // of that operation is undefined.
5894 if (ShLeftAmt >= VT.getSizeInBits())
5895 Result = DAG.getConstant(0, VT);
5897 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5898 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5901 // Return the new loaded value.
5905 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5906 SDValue N0 = N->getOperand(0);
5907 SDValue N1 = N->getOperand(1);
5908 EVT VT = N->getValueType(0);
5909 EVT EVT = cast<VTSDNode>(N1)->getVT();
5910 unsigned VTBits = VT.getScalarType().getSizeInBits();
5911 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5913 // fold (sext_in_reg c1) -> c1
5914 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5915 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5917 // If the input is already sign extended, just drop the extension.
5918 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5921 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5922 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5923 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5924 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5925 N0.getOperand(0), N1);
5927 // fold (sext_in_reg (sext x)) -> (sext x)
5928 // fold (sext_in_reg (aext x)) -> (sext x)
5929 // if x is small enough.
5930 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5931 SDValue N00 = N0.getOperand(0);
5932 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5933 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5934 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5937 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5938 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5939 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5941 // fold operands of sext_in_reg based on knowledge that the top bits are not
5943 if (SimplifyDemandedBits(SDValue(N, 0)))
5944 return SDValue(N, 0);
5946 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5947 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5948 SDValue NarrowLoad = ReduceLoadWidth(N);
5949 if (NarrowLoad.getNode())
5952 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5953 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5954 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5955 if (N0.getOpcode() == ISD::SRL) {
5956 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5957 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5958 // We can turn this into an SRA iff the input to the SRL is already sign
5960 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5961 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5962 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5963 N0.getOperand(0), N0.getOperand(1));
5967 // fold (sext_inreg (extload x)) -> (sextload x)
5968 if (ISD::isEXTLoad(N0.getNode()) &&
5969 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5970 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5971 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5972 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5973 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5974 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5976 LN0->getBasePtr(), EVT,
5977 LN0->getMemOperand());
5978 CombineTo(N, ExtLoad);
5979 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5980 AddToWorklist(ExtLoad.getNode());
5981 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5983 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5984 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5986 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5987 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5988 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5989 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5990 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5992 LN0->getBasePtr(), EVT,
5993 LN0->getMemOperand());
5994 CombineTo(N, ExtLoad);
5995 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5996 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5999 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6000 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6001 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6002 N0.getOperand(1), false);
6003 if (BSwap.getNode())
6004 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6008 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6009 // into a build_vector.
6010 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6011 SmallVector<SDValue, 8> Elts;
6012 unsigned NumElts = N0->getNumOperands();
6013 unsigned ShAmt = VTBits - EVTBits;
6015 for (unsigned i = 0; i != NumElts; ++i) {
6016 SDValue Op = N0->getOperand(i);
6017 if (Op->getOpcode() == ISD::UNDEF) {
6022 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6023 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6024 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6025 Op.getValueType()));
6028 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6034 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6035 SDValue N0 = N->getOperand(0);
6036 EVT VT = N->getValueType(0);
6037 bool isLE = TLI.isLittleEndian();
6040 if (N0.getValueType() == N->getValueType(0))
6042 // fold (truncate c1) -> c1
6043 if (isa<ConstantSDNode>(N0))
6044 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6045 // fold (truncate (truncate x)) -> (truncate x)
6046 if (N0.getOpcode() == ISD::TRUNCATE)
6047 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6048 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6049 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6050 N0.getOpcode() == ISD::SIGN_EXTEND ||
6051 N0.getOpcode() == ISD::ANY_EXTEND) {
6052 if (N0.getOperand(0).getValueType().bitsLT(VT))
6053 // if the source is smaller than the dest, we still need an extend
6054 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6056 if (N0.getOperand(0).getValueType().bitsGT(VT))
6057 // if the source is larger than the dest, than we just need the truncate
6058 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6059 // if the source and dest are the same type, we can drop both the extend
6060 // and the truncate.
6061 return N0.getOperand(0);
6064 // Fold extract-and-trunc into a narrow extract. For example:
6065 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6066 // i32 y = TRUNCATE(i64 x)
6068 // v16i8 b = BITCAST (v2i64 val)
6069 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6071 // Note: We only run this optimization after type legalization (which often
6072 // creates this pattern) and before operation legalization after which
6073 // we need to be more careful about the vector instructions that we generate.
6074 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6075 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6077 EVT VecTy = N0.getOperand(0).getValueType();
6078 EVT ExTy = N0.getValueType();
6079 EVT TrTy = N->getValueType(0);
6081 unsigned NumElem = VecTy.getVectorNumElements();
6082 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6084 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6085 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6087 SDValue EltNo = N0->getOperand(1);
6088 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6089 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6090 EVT IndexTy = TLI.getVectorIdxTy();
6091 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6093 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6094 NVT, N0.getOperand(0));
6096 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6098 DAG.getConstant(Index, IndexTy));
6102 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6103 if (N0.getOpcode() == ISD::SELECT) {
6104 EVT SrcVT = N0.getValueType();
6105 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6106 TLI.isTruncateFree(SrcVT, VT)) {
6108 SDValue Cond = N0.getOperand(0);
6109 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6110 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6111 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6115 // Fold a series of buildvector, bitcast, and truncate if possible.
6117 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6118 // (2xi32 (buildvector x, y)).
6119 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6120 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6121 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6122 N0.getOperand(0).hasOneUse()) {
6124 SDValue BuildVect = N0.getOperand(0);
6125 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6126 EVT TruncVecEltTy = VT.getVectorElementType();
6128 // Check that the element types match.
6129 if (BuildVectEltTy == TruncVecEltTy) {
6130 // Now we only need to compute the offset of the truncated elements.
6131 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6132 unsigned TruncVecNumElts = VT.getVectorNumElements();
6133 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6135 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6136 "Invalid number of elements");
6138 SmallVector<SDValue, 8> Opnds;
6139 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6140 Opnds.push_back(BuildVect.getOperand(i));
6142 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6146 // See if we can simplify the input to this truncate through knowledge that
6147 // only the low bits are being used.
6148 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6149 // Currently we only perform this optimization on scalars because vectors
6150 // may have different active low bits.
6151 if (!VT.isVector()) {
6153 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6154 VT.getSizeInBits()));
6155 if (Shorter.getNode())
6156 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6158 // fold (truncate (load x)) -> (smaller load x)
6159 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6160 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6161 SDValue Reduced = ReduceLoadWidth(N);
6162 if (Reduced.getNode())
6164 // Handle the case where the load remains an extending load even
6165 // after truncation.
6166 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6167 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6168 if (!LN0->isVolatile() &&
6169 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6170 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6171 VT, LN0->getChain(), LN0->getBasePtr(),
6173 LN0->getMemOperand());
6174 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6179 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6180 // where ... are all 'undef'.
6181 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6182 SmallVector<EVT, 8> VTs;
6185 unsigned NumDefs = 0;
6187 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6188 SDValue X = N0.getOperand(i);
6189 if (X.getOpcode() != ISD::UNDEF) {
6194 // Stop if more than one members are non-undef.
6197 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6198 VT.getVectorElementType(),
6199 X.getValueType().getVectorNumElements()));
6203 return DAG.getUNDEF(VT);
6206 assert(V.getNode() && "The single defined operand is empty!");
6207 SmallVector<SDValue, 8> Opnds;
6208 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6210 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6213 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6214 AddToWorklist(NV.getNode());
6215 Opnds.push_back(NV);
6217 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6221 // Simplify the operands using demanded-bits information.
6222 if (!VT.isVector() &&
6223 SimplifyDemandedBits(SDValue(N, 0)))
6224 return SDValue(N, 0);
6229 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6230 SDValue Elt = N->getOperand(i);
6231 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6232 return Elt.getNode();
6233 return Elt.getOperand(Elt.getResNo()).getNode();
6236 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6237 /// if load locations are consecutive.
6238 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6239 assert(N->getOpcode() == ISD::BUILD_PAIR);
6241 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6242 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6243 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6244 LD1->getAddressSpace() != LD2->getAddressSpace())
6246 EVT LD1VT = LD1->getValueType(0);
6248 if (ISD::isNON_EXTLoad(LD2) &&
6250 // If both are volatile this would reduce the number of volatile loads.
6251 // If one is volatile it might be ok, but play conservative and bail out.
6252 !LD1->isVolatile() &&
6253 !LD2->isVolatile() &&
6254 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6255 unsigned Align = LD1->getAlignment();
6256 unsigned NewAlign = TLI.getDataLayout()->
6257 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6259 if (NewAlign <= Align &&
6260 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6261 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6262 LD1->getBasePtr(), LD1->getPointerInfo(),
6263 false, false, false, Align);
6269 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6270 SDValue N0 = N->getOperand(0);
6271 EVT VT = N->getValueType(0);
6273 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6274 // Only do this before legalize, since afterward the target may be depending
6275 // on the bitconvert.
6276 // First check to see if this is all constant.
6278 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6280 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6282 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6283 assert(!DestEltVT.isVector() &&
6284 "Element type of vector ValueType must not be vector!");
6286 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6289 // If the input is a constant, let getNode fold it.
6290 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6291 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6292 if (Res.getNode() != N) {
6293 if (!LegalOperations ||
6294 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6297 // Folding it resulted in an illegal node, and it's too late to
6298 // do that. Clean up the old node and forego the transformation.
6299 // Ideally this won't happen very often, because instcombine
6300 // and the earlier dagcombine runs (where illegal nodes are
6301 // permitted) should have folded most of them already.
6302 deleteAndRecombine(Res.getNode());
6306 // (conv (conv x, t1), t2) -> (conv x, t2)
6307 if (N0.getOpcode() == ISD::BITCAST)
6308 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6311 // fold (conv (load x)) -> (load (conv*)x)
6312 // If the resultant load doesn't need a higher alignment than the original!
6313 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6314 // Do not change the width of a volatile load.
6315 !cast<LoadSDNode>(N0)->isVolatile() &&
6316 // Do not remove the cast if the types differ in endian layout.
6317 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6318 TLI.hasBigEndianPartOrdering(VT) &&
6319 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6320 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6321 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6322 unsigned Align = TLI.getDataLayout()->
6323 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6324 unsigned OrigAlign = LN0->getAlignment();
6326 if (Align <= OrigAlign) {
6327 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6328 LN0->getBasePtr(), LN0->getPointerInfo(),
6329 LN0->isVolatile(), LN0->isNonTemporal(),
6330 LN0->isInvariant(), OrigAlign,
6332 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6337 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6338 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6339 // This often reduces constant pool loads.
6340 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6341 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6342 N0.getNode()->hasOneUse() && VT.isInteger() &&
6343 !VT.isVector() && !N0.getValueType().isVector()) {
6344 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6346 AddToWorklist(NewConv.getNode());
6348 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6349 if (N0.getOpcode() == ISD::FNEG)
6350 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6351 NewConv, DAG.getConstant(SignBit, VT));
6352 assert(N0.getOpcode() == ISD::FABS);
6353 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6354 NewConv, DAG.getConstant(~SignBit, VT));
6357 // fold (bitconvert (fcopysign cst, x)) ->
6358 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6359 // Note that we don't handle (copysign x, cst) because this can always be
6360 // folded to an fneg or fabs.
6361 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6362 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6363 VT.isInteger() && !VT.isVector()) {
6364 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6365 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6366 if (isTypeLegal(IntXVT)) {
6367 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6368 IntXVT, N0.getOperand(1));
6369 AddToWorklist(X.getNode());
6371 // If X has a different width than the result/lhs, sext it or truncate it.
6372 unsigned VTWidth = VT.getSizeInBits();
6373 if (OrigXWidth < VTWidth) {
6374 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6375 AddToWorklist(X.getNode());
6376 } else if (OrigXWidth > VTWidth) {
6377 // To get the sign bit in the right place, we have to shift it right
6378 // before truncating.
6379 X = DAG.getNode(ISD::SRL, SDLoc(X),
6380 X.getValueType(), X,
6381 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6382 AddToWorklist(X.getNode());
6383 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6384 AddToWorklist(X.getNode());
6387 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6388 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6389 X, DAG.getConstant(SignBit, VT));
6390 AddToWorklist(X.getNode());
6392 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6393 VT, N0.getOperand(0));
6394 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6395 Cst, DAG.getConstant(~SignBit, VT));
6396 AddToWorklist(Cst.getNode());
6398 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6402 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6403 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6404 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6405 if (CombineLD.getNode())
6412 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6413 EVT VT = N->getValueType(0);
6414 return CombineConsecutiveLoads(N, VT);
6417 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6418 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6419 /// destination element value type.
6420 SDValue DAGCombiner::
6421 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6422 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6424 // If this is already the right type, we're done.
6425 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6427 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6428 unsigned DstBitSize = DstEltVT.getSizeInBits();
6430 // If this is a conversion of N elements of one type to N elements of another
6431 // type, convert each element. This handles FP<->INT cases.
6432 if (SrcBitSize == DstBitSize) {
6433 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6434 BV->getValueType(0).getVectorNumElements());
6436 // Due to the FP element handling below calling this routine recursively,
6437 // we can end up with a scalar-to-vector node here.
6438 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6439 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6440 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6441 DstEltVT, BV->getOperand(0)));
6443 SmallVector<SDValue, 8> Ops;
6444 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6445 SDValue Op = BV->getOperand(i);
6446 // If the vector element type is not legal, the BUILD_VECTOR operands
6447 // are promoted and implicitly truncated. Make that explicit here.
6448 if (Op.getValueType() != SrcEltVT)
6449 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6450 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6452 AddToWorklist(Ops.back().getNode());
6454 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6457 // Otherwise, we're growing or shrinking the elements. To avoid having to
6458 // handle annoying details of growing/shrinking FP values, we convert them to
6460 if (SrcEltVT.isFloatingPoint()) {
6461 // Convert the input float vector to a int vector where the elements are the
6463 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6464 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6465 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6469 // Now we know the input is an integer vector. If the output is a FP type,
6470 // convert to integer first, then to FP of the right size.
6471 if (DstEltVT.isFloatingPoint()) {
6472 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6473 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6474 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6476 // Next, convert to FP elements of the same size.
6477 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6480 // Okay, we know the src/dst types are both integers of differing types.
6481 // Handling growing first.
6482 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6483 if (SrcBitSize < DstBitSize) {
6484 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6486 SmallVector<SDValue, 8> Ops;
6487 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6488 i += NumInputsPerOutput) {
6489 bool isLE = TLI.isLittleEndian();
6490 APInt NewBits = APInt(DstBitSize, 0);
6491 bool EltIsUndef = true;
6492 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6493 // Shift the previously computed bits over.
6494 NewBits <<= SrcBitSize;
6495 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6496 if (Op.getOpcode() == ISD::UNDEF) continue;
6499 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6500 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6504 Ops.push_back(DAG.getUNDEF(DstEltVT));
6506 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6509 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6510 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6513 // Finally, this must be the case where we are shrinking elements: each input
6514 // turns into multiple outputs.
6515 bool isS2V = ISD::isScalarToVector(BV);
6516 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6517 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6518 NumOutputsPerInput*BV->getNumOperands());
6519 SmallVector<SDValue, 8> Ops;
6521 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6522 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6523 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6524 Ops.push_back(DAG.getUNDEF(DstEltVT));
6528 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6529 getAPIntValue().zextOrTrunc(SrcBitSize);
6531 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6532 APInt ThisVal = OpVal.trunc(DstBitSize);
6533 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6534 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6535 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6536 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6538 OpVal = OpVal.lshr(DstBitSize);
6541 // For big endian targets, swap the order of the pieces of each element.
6542 if (TLI.isBigEndian())
6543 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6546 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6549 SDValue DAGCombiner::visitFADD(SDNode *N) {
6550 SDValue N0 = N->getOperand(0);
6551 SDValue N1 = N->getOperand(1);
6552 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6553 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6554 EVT VT = N->getValueType(0);
6557 if (VT.isVector()) {
6558 SDValue FoldedVOp = SimplifyVBinOp(N);
6559 if (FoldedVOp.getNode()) return FoldedVOp;
6562 // fold (fadd c1, c2) -> c1 + c2
6564 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6565 // canonicalize constant to RHS
6566 if (N0CFP && !N1CFP)
6567 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6568 // fold (fadd A, 0) -> A
6569 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6570 N1CFP->getValueAPF().isZero())
6572 // fold (fadd A, (fneg B)) -> (fsub A, B)
6573 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6574 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6575 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6576 GetNegatedExpression(N1, DAG, LegalOperations));
6577 // fold (fadd (fneg A), B) -> (fsub B, A)
6578 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6579 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6580 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6581 GetNegatedExpression(N0, DAG, LegalOperations));
6583 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6584 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6585 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6586 isa<ConstantFPSDNode>(N0.getOperand(1)))
6587 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6588 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6589 N0.getOperand(1), N1));
6591 // No FP constant should be created after legalization as Instruction
6592 // Selection pass has hard time in dealing with FP constant.
6594 // We don't need test this condition for transformation like following, as
6595 // the DAG being transformed implies it is legal to take FP constant as
6598 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6600 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6602 // If allow, fold (fadd (fneg x), x) -> 0.0
6603 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6604 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6605 return DAG.getConstantFP(0.0, VT);
6607 // If allow, fold (fadd x, (fneg x)) -> 0.0
6608 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6609 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6610 return DAG.getConstantFP(0.0, VT);
6612 // In unsafe math mode, we can fold chains of FADD's of the same value
6613 // into multiplications. This transform is not safe in general because
6614 // we are reducing the number of rounding steps.
6615 if (DAG.getTarget().Options.UnsafeFPMath &&
6616 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6618 if (N0.getOpcode() == ISD::FMUL) {
6619 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6620 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6622 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6623 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6624 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6626 DAG.getConstantFP(1.0, VT));
6627 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6631 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6632 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6633 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6635 DAG.getConstantFP(1.0, VT));
6636 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6640 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6641 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6642 N1.getOperand(0) == N1.getOperand(1) &&
6643 N0.getOperand(1) == N1.getOperand(0)) {
6644 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6646 DAG.getConstantFP(2.0, VT));
6647 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6648 N0.getOperand(1), NewCFP);
6651 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6652 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6653 N1.getOperand(0) == N1.getOperand(1) &&
6654 N0.getOperand(0) == N1.getOperand(0)) {
6655 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6657 DAG.getConstantFP(2.0, VT));
6658 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6659 N0.getOperand(0), NewCFP);
6663 if (N1.getOpcode() == ISD::FMUL) {
6664 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6665 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6667 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6668 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6669 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6671 DAG.getConstantFP(1.0, VT));
6672 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6676 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6677 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6678 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6680 DAG.getConstantFP(1.0, VT));
6681 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6686 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6687 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6688 N0.getOperand(0) == N0.getOperand(1) &&
6689 N1.getOperand(1) == N0.getOperand(0)) {
6690 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6692 DAG.getConstantFP(2.0, VT));
6693 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6694 N1.getOperand(1), NewCFP);
6697 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6698 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6699 N0.getOperand(0) == N0.getOperand(1) &&
6700 N1.getOperand(0) == N0.getOperand(0)) {
6701 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6703 DAG.getConstantFP(2.0, VT));
6704 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6705 N1.getOperand(0), NewCFP);
6709 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6710 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6711 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6712 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6713 (N0.getOperand(0) == N1))
6714 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6715 N1, DAG.getConstantFP(3.0, VT));
6718 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6719 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6720 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6721 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6722 N1.getOperand(0) == N0)
6723 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6724 N0, DAG.getConstantFP(3.0, VT));
6727 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6728 if (AllowNewFpConst &&
6729 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6730 N0.getOperand(0) == N0.getOperand(1) &&
6731 N1.getOperand(0) == N1.getOperand(1) &&
6732 N0.getOperand(0) == N1.getOperand(0))
6733 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6735 DAG.getConstantFP(4.0, VT));
6738 // FADD -> FMA combines:
6739 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6740 DAG.getTarget().Options.UnsafeFPMath) &&
6743 ->getTargetLowering()
6744 ->isFMAFasterThanFMulAndFAdd(VT) &&
6745 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6747 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6748 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6749 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6750 N0.getOperand(0), N0.getOperand(1), N1);
6752 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6753 // Note: Commutes FADD operands.
6754 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6755 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6756 N1.getOperand(0), N1.getOperand(1), N0);
6762 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6763 SDValue N0 = N->getOperand(0);
6764 SDValue N1 = N->getOperand(1);
6765 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6766 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6767 EVT VT = N->getValueType(0);
6771 if (VT.isVector()) {
6772 SDValue FoldedVOp = SimplifyVBinOp(N);
6773 if (FoldedVOp.getNode()) return FoldedVOp;
6776 // fold (fsub c1, c2) -> c1-c2
6778 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6779 // fold (fsub A, 0) -> A
6780 if (DAG.getTarget().Options.UnsafeFPMath &&
6781 N1CFP && N1CFP->getValueAPF().isZero())
6783 // fold (fsub 0, B) -> -B
6784 if (DAG.getTarget().Options.UnsafeFPMath &&
6785 N0CFP && N0CFP->getValueAPF().isZero()) {
6786 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6787 return GetNegatedExpression(N1, DAG, LegalOperations);
6788 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6789 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6791 // fold (fsub A, (fneg B)) -> (fadd A, B)
6792 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6793 return DAG.getNode(ISD::FADD, dl, VT, N0,
6794 GetNegatedExpression(N1, DAG, LegalOperations));
6796 // If 'unsafe math' is enabled, fold
6797 // (fsub x, x) -> 0.0 &
6798 // (fsub x, (fadd x, y)) -> (fneg y) &
6799 // (fsub x, (fadd y, x)) -> (fneg y)
6800 if (DAG.getTarget().Options.UnsafeFPMath) {
6802 return DAG.getConstantFP(0.0f, VT);
6804 if (N1.getOpcode() == ISD::FADD) {
6805 SDValue N10 = N1->getOperand(0);
6806 SDValue N11 = N1->getOperand(1);
6808 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6809 &DAG.getTarget().Options))
6810 return GetNegatedExpression(N11, DAG, LegalOperations);
6812 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6813 &DAG.getTarget().Options))
6814 return GetNegatedExpression(N10, DAG, LegalOperations);
6818 // FSUB -> FMA combines:
6819 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6820 DAG.getTarget().Options.UnsafeFPMath) &&
6823 ->getTargetLowering()
6824 ->isFMAFasterThanFMulAndFAdd(VT) &&
6825 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6827 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6828 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6829 return DAG.getNode(ISD::FMA, dl, VT,
6830 N0.getOperand(0), N0.getOperand(1),
6831 DAG.getNode(ISD::FNEG, dl, VT, N1));
6833 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6834 // Note: Commutes FSUB operands.
6835 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6836 return DAG.getNode(ISD::FMA, dl, VT,
6837 DAG.getNode(ISD::FNEG, dl, VT,
6839 N1.getOperand(1), N0);
6841 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6842 if (N0.getOpcode() == ISD::FNEG &&
6843 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6844 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6845 SDValue N00 = N0.getOperand(0).getOperand(0);
6846 SDValue N01 = N0.getOperand(0).getOperand(1);
6847 return DAG.getNode(ISD::FMA, dl, VT,
6848 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6849 DAG.getNode(ISD::FNEG, dl, VT, N1));
6856 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6857 SDValue N0 = N->getOperand(0);
6858 SDValue N1 = N->getOperand(1);
6859 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6860 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6861 EVT VT = N->getValueType(0);
6862 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6865 if (VT.isVector()) {
6866 SDValue FoldedVOp = SimplifyVBinOp(N);
6867 if (FoldedVOp.getNode()) return FoldedVOp;
6870 // fold (fmul c1, c2) -> c1*c2
6872 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6873 // canonicalize constant to RHS
6874 if (N0CFP && !N1CFP)
6875 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6876 // fold (fmul A, 0) -> 0
6877 if (DAG.getTarget().Options.UnsafeFPMath &&
6878 N1CFP && N1CFP->getValueAPF().isZero())
6880 // fold (fmul A, 1.0) -> A
6881 if (N1CFP && N1CFP->isExactlyValue(1.0))
6884 // fold (fmul X, 2.0) -> (fadd X, X)
6885 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6886 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6887 // fold (fmul X, -1.0) -> (fneg X)
6888 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6889 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6890 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6892 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6893 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6894 &DAG.getTarget().Options)) {
6895 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6896 &DAG.getTarget().Options)) {
6897 // Both can be negated for free, check to see if at least one is cheaper
6899 if (LHSNeg == 2 || RHSNeg == 2)
6900 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6901 GetNegatedExpression(N0, DAG, LegalOperations),
6902 GetNegatedExpression(N1, DAG, LegalOperations));
6906 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6907 if (DAG.getTarget().Options.UnsafeFPMath &&
6908 N1CFP && N0.getOpcode() == ISD::FMUL &&
6909 N0.getNode()->hasOneUse() && isConstOrConstSplatFP(N0.getOperand(1))) {
6910 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6911 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6912 N0.getOperand(1), N1));
6918 SDValue DAGCombiner::visitFMA(SDNode *N) {
6919 SDValue N0 = N->getOperand(0);
6920 SDValue N1 = N->getOperand(1);
6921 SDValue N2 = N->getOperand(2);
6922 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6923 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6924 EVT VT = N->getValueType(0);
6928 // Constant fold FMA.
6929 if (isa<ConstantFPSDNode>(N0) &&
6930 isa<ConstantFPSDNode>(N1) &&
6931 isa<ConstantFPSDNode>(N2)) {
6932 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6935 if (DAG.getTarget().Options.UnsafeFPMath) {
6936 if (N0CFP && N0CFP->isZero())
6938 if (N1CFP && N1CFP->isZero())
6941 if (N0CFP && N0CFP->isExactlyValue(1.0))
6942 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6943 if (N1CFP && N1CFP->isExactlyValue(1.0))
6944 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6946 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6947 if (N0CFP && !N1CFP)
6948 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6950 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6951 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6952 N2.getOpcode() == ISD::FMUL &&
6953 N0 == N2.getOperand(0) &&
6954 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6955 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6956 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6960 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6961 if (DAG.getTarget().Options.UnsafeFPMath &&
6962 N0.getOpcode() == ISD::FMUL && N1CFP &&
6963 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6964 return DAG.getNode(ISD::FMA, dl, VT,
6966 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6970 // (fma x, 1, y) -> (fadd x, y)
6971 // (fma x, -1, y) -> (fadd (fneg x), y)
6973 if (N1CFP->isExactlyValue(1.0))
6974 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6976 if (N1CFP->isExactlyValue(-1.0) &&
6977 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6978 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6979 AddToWorklist(RHSNeg.getNode());
6980 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6984 // (fma x, c, x) -> (fmul x, (c+1))
6985 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6986 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6987 DAG.getNode(ISD::FADD, dl, VT,
6988 N1, DAG.getConstantFP(1.0, VT)));
6990 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6991 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6992 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6993 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6994 DAG.getNode(ISD::FADD, dl, VT,
6995 N1, DAG.getConstantFP(-1.0, VT)));
7001 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7002 SDValue N0 = N->getOperand(0);
7003 SDValue N1 = N->getOperand(1);
7004 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7005 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7006 EVT VT = N->getValueType(0);
7007 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7010 if (VT.isVector()) {
7011 SDValue FoldedVOp = SimplifyVBinOp(N);
7012 if (FoldedVOp.getNode()) return FoldedVOp;
7015 // fold (fdiv c1, c2) -> c1/c2
7017 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7019 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7020 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
7021 // Compute the reciprocal 1.0 / c2.
7022 APFloat N1APF = N1CFP->getValueAPF();
7023 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7024 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7025 // Only do the transform if the reciprocal is a legal fp immediate that
7026 // isn't too nasty (eg NaN, denormal, ...).
7027 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7028 (!LegalOperations ||
7029 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7030 // backend)... we should handle this gracefully after Legalize.
7031 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7032 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7033 TLI.isFPImmLegal(Recip, VT)))
7034 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7035 DAG.getConstantFP(Recip, VT));
7038 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7039 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
7040 &DAG.getTarget().Options)) {
7041 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
7042 &DAG.getTarget().Options)) {
7043 // Both can be negated for free, check to see if at least one is cheaper
7045 if (LHSNeg == 2 || RHSNeg == 2)
7046 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7047 GetNegatedExpression(N0, DAG, LegalOperations),
7048 GetNegatedExpression(N1, DAG, LegalOperations));
7055 SDValue DAGCombiner::visitFREM(SDNode *N) {
7056 SDValue N0 = N->getOperand(0);
7057 SDValue N1 = N->getOperand(1);
7058 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7059 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7060 EVT VT = N->getValueType(0);
7062 // fold (frem c1, c2) -> fmod(c1,c2)
7064 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7069 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7070 SDValue N0 = N->getOperand(0);
7071 SDValue N1 = N->getOperand(1);
7072 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7073 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7074 EVT VT = N->getValueType(0);
7076 if (N0CFP && N1CFP) // Constant fold
7077 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7080 const APFloat& V = N1CFP->getValueAPF();
7081 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7082 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7083 if (!V.isNegative()) {
7084 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7085 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7087 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7088 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7089 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7093 // copysign(fabs(x), y) -> copysign(x, y)
7094 // copysign(fneg(x), y) -> copysign(x, y)
7095 // copysign(copysign(x,z), y) -> copysign(x, y)
7096 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7097 N0.getOpcode() == ISD::FCOPYSIGN)
7098 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7099 N0.getOperand(0), N1);
7101 // copysign(x, abs(y)) -> abs(x)
7102 if (N1.getOpcode() == ISD::FABS)
7103 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7105 // copysign(x, copysign(y,z)) -> copysign(x, z)
7106 if (N1.getOpcode() == ISD::FCOPYSIGN)
7107 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7108 N0, N1.getOperand(1));
7110 // copysign(x, fp_extend(y)) -> copysign(x, y)
7111 // copysign(x, fp_round(y)) -> copysign(x, y)
7112 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7113 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7114 N0, N1.getOperand(0));
7119 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7120 SDValue N0 = N->getOperand(0);
7121 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7122 EVT VT = N->getValueType(0);
7123 EVT OpVT = N0.getValueType();
7125 // fold (sint_to_fp c1) -> c1fp
7127 // ...but only if the target supports immediate floating-point values
7128 (!LegalOperations ||
7129 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7130 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7132 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7133 // but UINT_TO_FP is legal on this target, try to convert.
7134 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7135 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7136 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7137 if (DAG.SignBitIsZero(N0))
7138 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7141 // The next optimizations are desirable only if SELECT_CC can be lowered.
7142 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7143 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7144 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7146 (!LegalOperations ||
7147 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7149 { N0.getOperand(0), N0.getOperand(1),
7150 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7152 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7155 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7156 // (select_cc x, y, 1.0, 0.0,, cc)
7157 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7158 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7159 (!LegalOperations ||
7160 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7162 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7163 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7164 N0.getOperand(0).getOperand(2) };
7165 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7172 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7173 SDValue N0 = N->getOperand(0);
7174 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7175 EVT VT = N->getValueType(0);
7176 EVT OpVT = N0.getValueType();
7178 // fold (uint_to_fp c1) -> c1fp
7180 // ...but only if the target supports immediate floating-point values
7181 (!LegalOperations ||
7182 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7183 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7185 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7186 // but SINT_TO_FP is legal on this target, try to convert.
7187 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7188 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7189 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7190 if (DAG.SignBitIsZero(N0))
7191 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7194 // The next optimizations are desirable only if SELECT_CC can be lowered.
7195 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7196 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7198 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7199 (!LegalOperations ||
7200 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7202 { N0.getOperand(0), N0.getOperand(1),
7203 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7205 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7212 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7213 SDValue N0 = N->getOperand(0);
7214 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7215 EVT VT = N->getValueType(0);
7217 // fold (fp_to_sint c1fp) -> c1
7219 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7224 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7225 SDValue N0 = N->getOperand(0);
7226 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7227 EVT VT = N->getValueType(0);
7229 // fold (fp_to_uint c1fp) -> c1
7231 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7236 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7237 SDValue N0 = N->getOperand(0);
7238 SDValue N1 = N->getOperand(1);
7239 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7240 EVT VT = N->getValueType(0);
7242 // fold (fp_round c1fp) -> c1fp
7244 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7246 // fold (fp_round (fp_extend x)) -> x
7247 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7248 return N0.getOperand(0);
7250 // fold (fp_round (fp_round x)) -> (fp_round x)
7251 if (N0.getOpcode() == ISD::FP_ROUND) {
7252 // This is a value preserving truncation if both round's are.
7253 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7254 N0.getNode()->getConstantOperandVal(1) == 1;
7255 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7256 DAG.getIntPtrConstant(IsTrunc));
7259 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7260 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7261 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7262 N0.getOperand(0), N1);
7263 AddToWorklist(Tmp.getNode());
7264 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7265 Tmp, N0.getOperand(1));
7271 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7272 SDValue N0 = N->getOperand(0);
7273 EVT VT = N->getValueType(0);
7274 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7275 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7277 // fold (fp_round_inreg c1fp) -> c1fp
7278 if (N0CFP && isTypeLegal(EVT)) {
7279 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7280 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7286 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7287 SDValue N0 = N->getOperand(0);
7288 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7289 EVT VT = N->getValueType(0);
7291 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7292 if (N->hasOneUse() &&
7293 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7296 // fold (fp_extend c1fp) -> c1fp
7298 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7300 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7302 if (N0.getOpcode() == ISD::FP_ROUND
7303 && N0.getNode()->getConstantOperandVal(1) == 1) {
7304 SDValue In = N0.getOperand(0);
7305 if (In.getValueType() == VT) return In;
7306 if (VT.bitsLT(In.getValueType()))
7307 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7308 In, N0.getOperand(1));
7309 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7312 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7313 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7314 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7315 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7316 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7318 LN0->getBasePtr(), N0.getValueType(),
7319 LN0->getMemOperand());
7320 CombineTo(N, ExtLoad);
7321 CombineTo(N0.getNode(),
7322 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7323 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7324 ExtLoad.getValue(1));
7325 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7331 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7332 SDValue N0 = N->getOperand(0);
7333 EVT VT = N->getValueType(0);
7335 // Constant fold FNEG.
7336 if (isa<ConstantFPSDNode>(N0))
7337 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7339 if (VT.isVector()) {
7340 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7341 if (FoldedVOp.getNode()) return FoldedVOp;
7344 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7345 &DAG.getTarget().Options))
7346 return GetNegatedExpression(N0, DAG, LegalOperations);
7348 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7349 // constant pool values.
7350 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7351 N0.getNode()->hasOneUse()) {
7352 SDValue Int = N0.getOperand(0);
7353 EVT IntVT = Int.getValueType();
7354 if (IntVT.isInteger() && !IntVT.isVector()) {
7356 if (N0.getValueType().isVector()) {
7357 // For a vector, get a mask such as 0x80... per scalar element
7359 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7360 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7362 // For a scalar, just generate 0x80...
7363 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7365 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7366 DAG.getConstant(SignMask, IntVT));
7367 AddToWorklist(Int.getNode());
7368 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7372 // (fneg (fmul c, x)) -> (fmul -c, x)
7373 if (N0.getOpcode() == ISD::FMUL) {
7374 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7376 APFloat CVal = CFP1->getValueAPF();
7378 if (Level >= AfterLegalizeDAG &&
7379 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7380 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7382 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7383 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7390 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7391 SDValue N0 = N->getOperand(0);
7392 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7393 EVT VT = N->getValueType(0);
7395 // fold (fceil c1) -> fceil(c1)
7397 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7402 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7403 SDValue N0 = N->getOperand(0);
7404 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7405 EVT VT = N->getValueType(0);
7407 // fold (ftrunc c1) -> ftrunc(c1)
7409 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7414 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7415 SDValue N0 = N->getOperand(0);
7416 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7417 EVT VT = N->getValueType(0);
7419 // fold (ffloor c1) -> ffloor(c1)
7421 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7426 SDValue DAGCombiner::visitFABS(SDNode *N) {
7427 SDValue N0 = N->getOperand(0);
7428 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7429 EVT VT = N->getValueType(0);
7431 if (VT.isVector()) {
7432 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7433 if (FoldedVOp.getNode()) return FoldedVOp;
7436 // fold (fabs c1) -> fabs(c1)
7438 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7439 // fold (fabs (fabs x)) -> (fabs x)
7440 if (N0.getOpcode() == ISD::FABS)
7441 return N->getOperand(0);
7442 // fold (fabs (fneg x)) -> (fabs x)
7443 // fold (fabs (fcopysign x, y)) -> (fabs x)
7444 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7445 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7447 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7448 // constant pool values.
7449 if (!TLI.isFAbsFree(VT) &&
7450 N0.getOpcode() == ISD::BITCAST &&
7451 N0.getNode()->hasOneUse()) {
7452 SDValue Int = N0.getOperand(0);
7453 EVT IntVT = Int.getValueType();
7454 if (IntVT.isInteger() && !IntVT.isVector()) {
7456 if (N0.getValueType().isVector()) {
7457 // For a vector, get a mask such as 0x7f... per scalar element
7459 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7460 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7462 // For a scalar, just generate 0x7f...
7463 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7465 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7466 DAG.getConstant(SignMask, IntVT));
7467 AddToWorklist(Int.getNode());
7468 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7475 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7476 SDValue Chain = N->getOperand(0);
7477 SDValue N1 = N->getOperand(1);
7478 SDValue N2 = N->getOperand(2);
7480 // If N is a constant we could fold this into a fallthrough or unconditional
7481 // branch. However that doesn't happen very often in normal code, because
7482 // Instcombine/SimplifyCFG should have handled the available opportunities.
7483 // If we did this folding here, it would be necessary to update the
7484 // MachineBasicBlock CFG, which is awkward.
7486 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7488 if (N1.getOpcode() == ISD::SETCC &&
7489 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7490 N1.getOperand(0).getValueType())) {
7491 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7492 Chain, N1.getOperand(2),
7493 N1.getOperand(0), N1.getOperand(1), N2);
7496 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7497 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7498 (N1.getOperand(0).hasOneUse() &&
7499 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7500 SDNode *Trunc = nullptr;
7501 if (N1.getOpcode() == ISD::TRUNCATE) {
7502 // Look pass the truncate.
7503 Trunc = N1.getNode();
7504 N1 = N1.getOperand(0);
7507 // Match this pattern so that we can generate simpler code:
7510 // %b = and i32 %a, 2
7511 // %c = srl i32 %b, 1
7512 // brcond i32 %c ...
7517 // %b = and i32 %a, 2
7518 // %c = setcc eq %b, 0
7521 // This applies only when the AND constant value has one bit set and the
7522 // SRL constant is equal to the log2 of the AND constant. The back-end is
7523 // smart enough to convert the result into a TEST/JMP sequence.
7524 SDValue Op0 = N1.getOperand(0);
7525 SDValue Op1 = N1.getOperand(1);
7527 if (Op0.getOpcode() == ISD::AND &&
7528 Op1.getOpcode() == ISD::Constant) {
7529 SDValue AndOp1 = Op0.getOperand(1);
7531 if (AndOp1.getOpcode() == ISD::Constant) {
7532 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7534 if (AndConst.isPowerOf2() &&
7535 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7537 DAG.getSetCC(SDLoc(N),
7538 getSetCCResultType(Op0.getValueType()),
7539 Op0, DAG.getConstant(0, Op0.getValueType()),
7542 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7543 MVT::Other, Chain, SetCC, N2);
7544 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7545 // will convert it back to (X & C1) >> C2.
7546 CombineTo(N, NewBRCond, false);
7547 // Truncate is dead.
7549 deleteAndRecombine(Trunc);
7550 // Replace the uses of SRL with SETCC
7551 WorklistRemover DeadNodes(*this);
7552 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7553 deleteAndRecombine(N1.getNode());
7554 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7560 // Restore N1 if the above transformation doesn't match.
7561 N1 = N->getOperand(1);
7564 // Transform br(xor(x, y)) -> br(x != y)
7565 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7566 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7567 SDNode *TheXor = N1.getNode();
7568 SDValue Op0 = TheXor->getOperand(0);
7569 SDValue Op1 = TheXor->getOperand(1);
7570 if (Op0.getOpcode() == Op1.getOpcode()) {
7571 // Avoid missing important xor optimizations.
7572 SDValue Tmp = visitXOR(TheXor);
7573 if (Tmp.getNode()) {
7574 if (Tmp.getNode() != TheXor) {
7575 DEBUG(dbgs() << "\nReplacing.8 ";
7577 dbgs() << "\nWith: ";
7578 Tmp.getNode()->dump(&DAG);
7580 WorklistRemover DeadNodes(*this);
7581 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7582 deleteAndRecombine(TheXor);
7583 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7584 MVT::Other, Chain, Tmp, N2);
7587 // visitXOR has changed XOR's operands or replaced the XOR completely,
7589 return SDValue(N, 0);
7593 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7595 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7596 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7597 Op0.getOpcode() == ISD::XOR) {
7598 TheXor = Op0.getNode();
7602 EVT SetCCVT = N1.getValueType();
7604 SetCCVT = getSetCCResultType(SetCCVT);
7605 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7608 Equal ? ISD::SETEQ : ISD::SETNE);
7609 // Replace the uses of XOR with SETCC
7610 WorklistRemover DeadNodes(*this);
7611 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7612 deleteAndRecombine(N1.getNode());
7613 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7614 MVT::Other, Chain, SetCC, N2);
7621 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7623 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7624 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7625 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7627 // If N is a constant we could fold this into a fallthrough or unconditional
7628 // branch. However that doesn't happen very often in normal code, because
7629 // Instcombine/SimplifyCFG should have handled the available opportunities.
7630 // If we did this folding here, it would be necessary to update the
7631 // MachineBasicBlock CFG, which is awkward.
7633 // Use SimplifySetCC to simplify SETCC's.
7634 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7635 CondLHS, CondRHS, CC->get(), SDLoc(N),
7637 if (Simp.getNode()) AddToWorklist(Simp.getNode());
7639 // fold to a simpler setcc
7640 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7641 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7642 N->getOperand(0), Simp.getOperand(2),
7643 Simp.getOperand(0), Simp.getOperand(1),
7649 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7650 /// uses N as its base pointer and that N may be folded in the load / store
7651 /// addressing mode.
7652 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7654 const TargetLowering &TLI) {
7656 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7657 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7659 VT = Use->getValueType(0);
7660 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7661 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7663 VT = ST->getValue().getValueType();
7667 TargetLowering::AddrMode AM;
7668 if (N->getOpcode() == ISD::ADD) {
7669 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7672 AM.BaseOffs = Offset->getSExtValue();
7676 } else if (N->getOpcode() == ISD::SUB) {
7677 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7680 AM.BaseOffs = -Offset->getSExtValue();
7687 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7690 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7691 /// pre-indexed load / store when the base pointer is an add or subtract
7692 /// and it has other uses besides the load / store. After the
7693 /// transformation, the new indexed load / store has effectively folded
7694 /// the add / subtract in and all of its other uses are redirected to the
7695 /// new load / store.
7696 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7697 if (Level < AfterLegalizeDAG)
7703 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7704 if (LD->isIndexed())
7706 VT = LD->getMemoryVT();
7707 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7708 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7710 Ptr = LD->getBasePtr();
7711 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7712 if (ST->isIndexed())
7714 VT = ST->getMemoryVT();
7715 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7716 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7718 Ptr = ST->getBasePtr();
7724 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7725 // out. There is no reason to make this a preinc/predec.
7726 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7727 Ptr.getNode()->hasOneUse())
7730 // Ask the target to do addressing mode selection.
7733 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7734 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7737 // Backends without true r+i pre-indexed forms may need to pass a
7738 // constant base with a variable offset so that constant coercion
7739 // will work with the patterns in canonical form.
7740 bool Swapped = false;
7741 if (isa<ConstantSDNode>(BasePtr)) {
7742 std::swap(BasePtr, Offset);
7746 // Don't create a indexed load / store with zero offset.
7747 if (isa<ConstantSDNode>(Offset) &&
7748 cast<ConstantSDNode>(Offset)->isNullValue())
7751 // Try turning it into a pre-indexed load / store except when:
7752 // 1) The new base ptr is a frame index.
7753 // 2) If N is a store and the new base ptr is either the same as or is a
7754 // predecessor of the value being stored.
7755 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7756 // that would create a cycle.
7757 // 4) All uses are load / store ops that use it as old base ptr.
7759 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7760 // (plus the implicit offset) to a register to preinc anyway.
7761 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7766 SDValue Val = cast<StoreSDNode>(N)->getValue();
7767 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7771 // If the offset is a constant, there may be other adds of constants that
7772 // can be folded with this one. We should do this to avoid having to keep
7773 // a copy of the original base pointer.
7774 SmallVector<SDNode *, 16> OtherUses;
7775 if (isa<ConstantSDNode>(Offset))
7776 for (SDNode *Use : BasePtr.getNode()->uses()) {
7777 if (Use == Ptr.getNode())
7780 if (Use->isPredecessorOf(N))
7783 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7788 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7789 if (Op1.getNode() == BasePtr.getNode())
7790 std::swap(Op0, Op1);
7791 assert(Op0.getNode() == BasePtr.getNode() &&
7792 "Use of ADD/SUB but not an operand");
7794 if (!isa<ConstantSDNode>(Op1)) {
7799 // FIXME: In some cases, we can be smarter about this.
7800 if (Op1.getValueType() != Offset.getValueType()) {
7805 OtherUses.push_back(Use);
7809 std::swap(BasePtr, Offset);
7811 // Now check for #3 and #4.
7812 bool RealUse = false;
7814 // Caches for hasPredecessorHelper
7815 SmallPtrSet<const SDNode *, 32> Visited;
7816 SmallVector<const SDNode *, 16> Worklist;
7818 for (SDNode *Use : Ptr.getNode()->uses()) {
7821 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7824 // If Ptr may be folded in addressing mode of other use, then it's
7825 // not profitable to do this transformation.
7826 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7835 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7836 BasePtr, Offset, AM);
7838 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7839 BasePtr, Offset, AM);
7842 DEBUG(dbgs() << "\nReplacing.4 ";
7844 dbgs() << "\nWith: ";
7845 Result.getNode()->dump(&DAG);
7847 WorklistRemover DeadNodes(*this);
7849 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7850 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7852 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7855 // Finally, since the node is now dead, remove it from the graph.
7856 deleteAndRecombine(N);
7859 std::swap(BasePtr, Offset);
7861 // Replace other uses of BasePtr that can be updated to use Ptr
7862 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7863 unsigned OffsetIdx = 1;
7864 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7866 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7867 BasePtr.getNode() && "Expected BasePtr operand");
7869 // We need to replace ptr0 in the following expression:
7870 // x0 * offset0 + y0 * ptr0 = t0
7872 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7874 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7875 // indexed load/store and the expresion that needs to be re-written.
7877 // Therefore, we have:
7878 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7880 ConstantSDNode *CN =
7881 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7883 APInt Offset0 = CN->getAPIntValue();
7884 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7886 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7887 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7888 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7889 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7891 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7893 APInt CNV = Offset0;
7894 if (X0 < 0) CNV = -CNV;
7895 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7896 else CNV = CNV - Offset1;
7898 // We can now generate the new expression.
7899 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7900 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7902 SDValue NewUse = DAG.getNode(Opcode,
7903 SDLoc(OtherUses[i]),
7904 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7905 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7906 deleteAndRecombine(OtherUses[i]);
7909 // Replace the uses of Ptr with uses of the updated base value.
7910 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7911 deleteAndRecombine(Ptr.getNode());
7916 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7917 /// add / sub of the base pointer node into a post-indexed load / store.
7918 /// The transformation folded the add / subtract into the new indexed
7919 /// load / store effectively and all of its uses are redirected to the
7920 /// new load / store.
7921 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7922 if (Level < AfterLegalizeDAG)
7928 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7929 if (LD->isIndexed())
7931 VT = LD->getMemoryVT();
7932 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7933 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7935 Ptr = LD->getBasePtr();
7936 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7937 if (ST->isIndexed())
7939 VT = ST->getMemoryVT();
7940 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7941 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7943 Ptr = ST->getBasePtr();
7949 if (Ptr.getNode()->hasOneUse())
7952 for (SDNode *Op : Ptr.getNode()->uses()) {
7954 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7959 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7960 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7961 // Don't create a indexed load / store with zero offset.
7962 if (isa<ConstantSDNode>(Offset) &&
7963 cast<ConstantSDNode>(Offset)->isNullValue())
7966 // Try turning it into a post-indexed load / store except when
7967 // 1) All uses are load / store ops that use it as base ptr (and
7968 // it may be folded as addressing mmode).
7969 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7970 // nor a successor of N. Otherwise, if Op is folded that would
7973 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7977 bool TryNext = false;
7978 for (SDNode *Use : BasePtr.getNode()->uses()) {
7979 if (Use == Ptr.getNode())
7982 // If all the uses are load / store addresses, then don't do the
7984 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7985 bool RealUse = false;
7986 for (SDNode *UseUse : Use->uses()) {
7987 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8002 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8003 SDValue Result = isLoad
8004 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8005 BasePtr, Offset, AM)
8006 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8007 BasePtr, Offset, AM);
8010 DEBUG(dbgs() << "\nReplacing.5 ";
8012 dbgs() << "\nWith: ";
8013 Result.getNode()->dump(&DAG);
8015 WorklistRemover DeadNodes(*this);
8017 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8018 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8020 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8023 // Finally, since the node is now dead, remove it from the graph.
8024 deleteAndRecombine(N);
8026 // Replace the uses of Use with uses of the updated base value.
8027 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8028 Result.getValue(isLoad ? 1 : 0));
8029 deleteAndRecombine(Op);
8038 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8039 LoadSDNode *LD = cast<LoadSDNode>(N);
8040 SDValue Chain = LD->getChain();
8041 SDValue Ptr = LD->getBasePtr();
8043 // If load is not volatile and there are no uses of the loaded value (and
8044 // the updated indexed value in case of indexed loads), change uses of the
8045 // chain value into uses of the chain input (i.e. delete the dead load).
8046 if (!LD->isVolatile()) {
8047 if (N->getValueType(1) == MVT::Other) {
8049 if (!N->hasAnyUseOfValue(0)) {
8050 // It's not safe to use the two value CombineTo variant here. e.g.
8051 // v1, chain2 = load chain1, loc
8052 // v2, chain3 = load chain2, loc
8054 // Now we replace use of chain2 with chain1. This makes the second load
8055 // isomorphic to the one we are deleting, and thus makes this load live.
8056 DEBUG(dbgs() << "\nReplacing.6 ";
8058 dbgs() << "\nWith chain: ";
8059 Chain.getNode()->dump(&DAG);
8061 WorklistRemover DeadNodes(*this);
8062 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8065 deleteAndRecombine(N);
8067 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8071 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8072 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
8073 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8074 DEBUG(dbgs() << "\nReplacing.7 ";
8076 dbgs() << "\nWith: ";
8077 Undef.getNode()->dump(&DAG);
8078 dbgs() << " and 2 other values\n");
8079 WorklistRemover DeadNodes(*this);
8080 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8081 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8082 DAG.getUNDEF(N->getValueType(1)));
8083 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8084 deleteAndRecombine(N);
8085 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8090 // If this load is directly stored, replace the load value with the stored
8092 // TODO: Handle store large -> read small portion.
8093 // TODO: Handle TRUNCSTORE/LOADEXT
8094 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8095 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8096 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8097 if (PrevST->getBasePtr() == Ptr &&
8098 PrevST->getValue().getValueType() == N->getValueType(0))
8099 return CombineTo(N, Chain.getOperand(1), Chain);
8103 // Try to infer better alignment information than the load already has.
8104 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8105 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8106 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8108 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8109 LD->getValueType(0),
8110 Chain, Ptr, LD->getPointerInfo(),
8112 LD->isVolatile(), LD->isNonTemporal(),
8113 LD->isInvariant(), Align, LD->getAAInfo());
8114 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8119 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8120 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8122 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8123 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8126 if (UseAA && LD->isUnindexed()) {
8127 // Walk up chain skipping non-aliasing memory nodes.
8128 SDValue BetterChain = FindBetterChain(N, Chain);
8130 // If there is a better chain.
8131 if (Chain != BetterChain) {
8134 // Replace the chain to void dependency.
8135 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8136 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8137 BetterChain, Ptr, LD->getMemOperand());
8139 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8140 LD->getValueType(0),
8141 BetterChain, Ptr, LD->getMemoryVT(),
8142 LD->getMemOperand());
8145 // Create token factor to keep old chain connected.
8146 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8147 MVT::Other, Chain, ReplLoad.getValue(1));
8149 // Make sure the new and old chains are cleaned up.
8150 AddToWorklist(Token.getNode());
8152 // Replace uses with load result and token factor. Don't add users
8154 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8158 // Try transforming N to an indexed load.
8159 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8160 return SDValue(N, 0);
8162 // Try to slice up N to more direct loads if the slices are mapped to
8163 // different register banks or pairing can take place.
8165 return SDValue(N, 0);
8171 /// \brief Helper structure used to slice a load in smaller loads.
8172 /// Basically a slice is obtained from the following sequence:
8173 /// Origin = load Ty1, Base
8174 /// Shift = srl Ty1 Origin, CstTy Amount
8175 /// Inst = trunc Shift to Ty2
8177 /// Then, it will be rewriten into:
8178 /// Slice = load SliceTy, Base + SliceOffset
8179 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8181 /// SliceTy is deduced from the number of bits that are actually used to
8183 struct LoadedSlice {
8184 /// \brief Helper structure used to compute the cost of a slice.
8186 /// Are we optimizing for code size.
8191 unsigned CrossRegisterBanksCopies;
8195 Cost(bool ForCodeSize = false)
8196 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8197 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8199 /// \brief Get the cost of one isolated slice.
8200 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8201 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8202 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8203 EVT TruncType = LS.Inst->getValueType(0);
8204 EVT LoadedType = LS.getLoadedType();
8205 if (TruncType != LoadedType &&
8206 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8210 /// \brief Account for slicing gain in the current cost.
8211 /// Slicing provide a few gains like removing a shift or a
8212 /// truncate. This method allows to grow the cost of the original
8213 /// load with the gain from this slice.
8214 void addSliceGain(const LoadedSlice &LS) {
8215 // Each slice saves a truncate.
8216 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8217 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8218 LS.Inst->getOperand(0).getValueType()))
8220 // If there is a shift amount, this slice gets rid of it.
8223 // If this slice can merge a cross register bank copy, account for it.
8224 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8225 ++CrossRegisterBanksCopies;
8228 Cost &operator+=(const Cost &RHS) {
8230 Truncates += RHS.Truncates;
8231 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8237 bool operator==(const Cost &RHS) const {
8238 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8239 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8240 ZExts == RHS.ZExts && Shift == RHS.Shift;
8243 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8245 bool operator<(const Cost &RHS) const {
8246 // Assume cross register banks copies are as expensive as loads.
8247 // FIXME: Do we want some more target hooks?
8248 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8249 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8250 // Unless we are optimizing for code size, consider the
8251 // expensive operation first.
8252 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8253 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8254 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8255 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8258 bool operator>(const Cost &RHS) const { return RHS < *this; }
8260 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8262 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8264 // The last instruction that represent the slice. This should be a
8265 // truncate instruction.
8267 // The original load instruction.
8269 // The right shift amount in bits from the original load.
8271 // The DAG from which Origin came from.
8272 // This is used to get some contextual information about legal types, etc.
8275 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8276 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8277 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8279 LoadedSlice(const LoadedSlice &LS)
8280 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8282 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8283 /// \return Result is \p BitWidth and has used bits set to 1 and
8284 /// not used bits set to 0.
8285 APInt getUsedBits() const {
8286 // Reproduce the trunc(lshr) sequence:
8287 // - Start from the truncated value.
8288 // - Zero extend to the desired bit width.
8290 assert(Origin && "No original load to compare against.");
8291 unsigned BitWidth = Origin->getValueSizeInBits(0);
8292 assert(Inst && "This slice is not bound to an instruction");
8293 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8294 "Extracted slice is bigger than the whole type!");
8295 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8296 UsedBits.setAllBits();
8297 UsedBits = UsedBits.zext(BitWidth);
8302 /// \brief Get the size of the slice to be loaded in bytes.
8303 unsigned getLoadedSize() const {
8304 unsigned SliceSize = getUsedBits().countPopulation();
8305 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8306 return SliceSize / 8;
8309 /// \brief Get the type that will be loaded for this slice.
8310 /// Note: This may not be the final type for the slice.
8311 EVT getLoadedType() const {
8312 assert(DAG && "Missing context");
8313 LLVMContext &Ctxt = *DAG->getContext();
8314 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8317 /// \brief Get the alignment of the load used for this slice.
8318 unsigned getAlignment() const {
8319 unsigned Alignment = Origin->getAlignment();
8320 unsigned Offset = getOffsetFromBase();
8322 Alignment = MinAlign(Alignment, Alignment + Offset);
8326 /// \brief Check if this slice can be rewritten with legal operations.
8327 bool isLegal() const {
8328 // An invalid slice is not legal.
8329 if (!Origin || !Inst || !DAG)
8332 // Offsets are for indexed load only, we do not handle that.
8333 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8336 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8338 // Check that the type is legal.
8339 EVT SliceType = getLoadedType();
8340 if (!TLI.isTypeLegal(SliceType))
8343 // Check that the load is legal for this type.
8344 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8347 // Check that the offset can be computed.
8348 // 1. Check its type.
8349 EVT PtrType = Origin->getBasePtr().getValueType();
8350 if (PtrType == MVT::Untyped || PtrType.isExtended())
8353 // 2. Check that it fits in the immediate.
8354 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8357 // 3. Check that the computation is legal.
8358 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8361 // Check that the zext is legal if it needs one.
8362 EVT TruncateType = Inst->getValueType(0);
8363 if (TruncateType != SliceType &&
8364 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8370 /// \brief Get the offset in bytes of this slice in the original chunk of
8372 /// \pre DAG != nullptr.
8373 uint64_t getOffsetFromBase() const {
8374 assert(DAG && "Missing context.");
8376 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8377 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8378 uint64_t Offset = Shift / 8;
8379 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8380 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8381 "The size of the original loaded type is not a multiple of a"
8383 // If Offset is bigger than TySizeInBytes, it means we are loading all
8384 // zeros. This should have been optimized before in the process.
8385 assert(TySizeInBytes > Offset &&
8386 "Invalid shift amount for given loaded size");
8388 Offset = TySizeInBytes - Offset - getLoadedSize();
8392 /// \brief Generate the sequence of instructions to load the slice
8393 /// represented by this object and redirect the uses of this slice to
8394 /// this new sequence of instructions.
8395 /// \pre this->Inst && this->Origin are valid Instructions and this
8396 /// object passed the legal check: LoadedSlice::isLegal returned true.
8397 /// \return The last instruction of the sequence used to load the slice.
8398 SDValue loadSlice() const {
8399 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8400 const SDValue &OldBaseAddr = Origin->getBasePtr();
8401 SDValue BaseAddr = OldBaseAddr;
8402 // Get the offset in that chunk of bytes w.r.t. the endianess.
8403 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8404 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8406 // BaseAddr = BaseAddr + Offset.
8407 EVT ArithType = BaseAddr.getValueType();
8408 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8409 DAG->getConstant(Offset, ArithType));
8412 // Create the type of the loaded slice according to its size.
8413 EVT SliceType = getLoadedType();
8415 // Create the load for the slice.
8416 SDValue LastInst = DAG->getLoad(
8417 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8418 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8419 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8420 // If the final type is not the same as the loaded type, this means that
8421 // we have to pad with zero. Create a zero extend for that.
8422 EVT FinalType = Inst->getValueType(0);
8423 if (SliceType != FinalType)
8425 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8429 /// \brief Check if this slice can be merged with an expensive cross register
8430 /// bank copy. E.g.,
8432 /// f = bitcast i32 i to float
8433 bool canMergeExpensiveCrossRegisterBankCopy() const {
8434 if (!Inst || !Inst->hasOneUse())
8436 SDNode *Use = *Inst->use_begin();
8437 if (Use->getOpcode() != ISD::BITCAST)
8439 assert(DAG && "Missing context");
8440 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8441 EVT ResVT = Use->getValueType(0);
8442 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8443 const TargetRegisterClass *ArgRC =
8444 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8445 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8448 // At this point, we know that we perform a cross-register-bank copy.
8449 // Check if it is expensive.
8450 const TargetRegisterInfo *TRI =
8451 TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8452 // Assume bitcasts are cheap, unless both register classes do not
8453 // explicitly share a common sub class.
8454 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8457 // Check if it will be merged with the load.
8458 // 1. Check the alignment constraint.
8459 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8460 ResVT.getTypeForEVT(*DAG->getContext()));
8462 if (RequiredAlignment > getAlignment())
8465 // 2. Check that the load is a legal operation for that type.
8466 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8469 // 3. Check that we do not have a zext in the way.
8470 if (Inst->getValueType(0) != getLoadedType())
8478 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8479 /// \p UsedBits looks like 0..0 1..1 0..0.
8480 static bool areUsedBitsDense(const APInt &UsedBits) {
8481 // If all the bits are one, this is dense!
8482 if (UsedBits.isAllOnesValue())
8485 // Get rid of the unused bits on the right.
8486 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8487 // Get rid of the unused bits on the left.
8488 if (NarrowedUsedBits.countLeadingZeros())
8489 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8490 // Check that the chunk of bits is completely used.
8491 return NarrowedUsedBits.isAllOnesValue();
8494 /// \brief Check whether or not \p First and \p Second are next to each other
8495 /// in memory. This means that there is no hole between the bits loaded
8496 /// by \p First and the bits loaded by \p Second.
8497 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8498 const LoadedSlice &Second) {
8499 assert(First.Origin == Second.Origin && First.Origin &&
8500 "Unable to match different memory origins.");
8501 APInt UsedBits = First.getUsedBits();
8502 assert((UsedBits & Second.getUsedBits()) == 0 &&
8503 "Slices are not supposed to overlap.");
8504 UsedBits |= Second.getUsedBits();
8505 return areUsedBitsDense(UsedBits);
8508 /// \brief Adjust the \p GlobalLSCost according to the target
8509 /// paring capabilities and the layout of the slices.
8510 /// \pre \p GlobalLSCost should account for at least as many loads as
8511 /// there is in the slices in \p LoadedSlices.
8512 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8513 LoadedSlice::Cost &GlobalLSCost) {
8514 unsigned NumberOfSlices = LoadedSlices.size();
8515 // If there is less than 2 elements, no pairing is possible.
8516 if (NumberOfSlices < 2)
8519 // Sort the slices so that elements that are likely to be next to each
8520 // other in memory are next to each other in the list.
8521 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8522 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8523 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8524 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8526 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8527 // First (resp. Second) is the first (resp. Second) potentially candidate
8528 // to be placed in a paired load.
8529 const LoadedSlice *First = nullptr;
8530 const LoadedSlice *Second = nullptr;
8531 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8532 // Set the beginning of the pair.
8535 Second = &LoadedSlices[CurrSlice];
8537 // If First is NULL, it means we start a new pair.
8538 // Get to the next slice.
8542 EVT LoadedType = First->getLoadedType();
8544 // If the types of the slices are different, we cannot pair them.
8545 if (LoadedType != Second->getLoadedType())
8548 // Check if the target supplies paired loads for this type.
8549 unsigned RequiredAlignment = 0;
8550 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8551 // move to the next pair, this type is hopeless.
8555 // Check if we meet the alignment requirement.
8556 if (RequiredAlignment > First->getAlignment())
8559 // Check that both loads are next to each other in memory.
8560 if (!areSlicesNextToEachOther(*First, *Second))
8563 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8564 --GlobalLSCost.Loads;
8565 // Move to the next pair.
8570 /// \brief Check the profitability of all involved LoadedSlice.
8571 /// Currently, it is considered profitable if there is exactly two
8572 /// involved slices (1) which are (2) next to each other in memory, and
8573 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8575 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8576 /// the elements themselves.
8578 /// FIXME: When the cost model will be mature enough, we can relax
8579 /// constraints (1) and (2).
8580 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8581 const APInt &UsedBits, bool ForCodeSize) {
8582 unsigned NumberOfSlices = LoadedSlices.size();
8583 if (StressLoadSlicing)
8584 return NumberOfSlices > 1;
8587 if (NumberOfSlices != 2)
8591 if (!areUsedBitsDense(UsedBits))
8595 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8596 // The original code has one big load.
8598 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8599 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8600 // Accumulate the cost of all the slices.
8601 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8602 GlobalSlicingCost += SliceCost;
8604 // Account as cost in the original configuration the gain obtained
8605 // with the current slices.
8606 OrigCost.addSliceGain(LS);
8609 // If the target supports paired load, adjust the cost accordingly.
8610 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8611 return OrigCost > GlobalSlicingCost;
8614 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8615 /// operations, split it in the various pieces being extracted.
8617 /// This sort of thing is introduced by SROA.
8618 /// This slicing takes care not to insert overlapping loads.
8619 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8620 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8621 if (Level < AfterLegalizeDAG)
8624 LoadSDNode *LD = cast<LoadSDNode>(N);
8625 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8626 !LD->getValueType(0).isInteger())
8629 // Keep track of already used bits to detect overlapping values.
8630 // In that case, we will just abort the transformation.
8631 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8633 SmallVector<LoadedSlice, 4> LoadedSlices;
8635 // Check if this load is used as several smaller chunks of bits.
8636 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8637 // of computation for each trunc.
8638 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8639 UI != UIEnd; ++UI) {
8640 // Skip the uses of the chain.
8641 if (UI.getUse().getResNo() != 0)
8647 // Check if this is a trunc(lshr).
8648 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8649 isa<ConstantSDNode>(User->getOperand(1))) {
8650 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8651 User = *User->use_begin();
8654 // At this point, User is a Truncate, iff we encountered, trunc or
8656 if (User->getOpcode() != ISD::TRUNCATE)
8659 // The width of the type must be a power of 2 and greater than 8-bits.
8660 // Otherwise the load cannot be represented in LLVM IR.
8661 // Moreover, if we shifted with a non-8-bits multiple, the slice
8662 // will be across several bytes. We do not support that.
8663 unsigned Width = User->getValueSizeInBits(0);
8664 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8667 // Build the slice for this chain of computations.
8668 LoadedSlice LS(User, LD, Shift, &DAG);
8669 APInt CurrentUsedBits = LS.getUsedBits();
8671 // Check if this slice overlaps with another.
8672 if ((CurrentUsedBits & UsedBits) != 0)
8674 // Update the bits used globally.
8675 UsedBits |= CurrentUsedBits;
8677 // Check if the new slice would be legal.
8681 // Record the slice.
8682 LoadedSlices.push_back(LS);
8685 // Abort slicing if it does not seem to be profitable.
8686 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8691 // Rewrite each chain to use an independent load.
8692 // By construction, each chain can be represented by a unique load.
8694 // Prepare the argument for the new token factor for all the slices.
8695 SmallVector<SDValue, 8> ArgChains;
8696 for (SmallVectorImpl<LoadedSlice>::const_iterator
8697 LSIt = LoadedSlices.begin(),
8698 LSItEnd = LoadedSlices.end();
8699 LSIt != LSItEnd; ++LSIt) {
8700 SDValue SliceInst = LSIt->loadSlice();
8701 CombineTo(LSIt->Inst, SliceInst, true);
8702 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8703 SliceInst = SliceInst.getOperand(0);
8704 assert(SliceInst->getOpcode() == ISD::LOAD &&
8705 "It takes more than a zext to get to the loaded slice!!");
8706 ArgChains.push_back(SliceInst.getValue(1));
8709 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8711 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8715 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8716 /// load is having specific bytes cleared out. If so, return the byte size
8717 /// being masked out and the shift amount.
8718 static std::pair<unsigned, unsigned>
8719 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8720 std::pair<unsigned, unsigned> Result(0, 0);
8722 // Check for the structure we're looking for.
8723 if (V->getOpcode() != ISD::AND ||
8724 !isa<ConstantSDNode>(V->getOperand(1)) ||
8725 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8728 // Check the chain and pointer.
8729 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8730 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8732 // The store should be chained directly to the load or be an operand of a
8734 if (LD == Chain.getNode())
8736 else if (Chain->getOpcode() != ISD::TokenFactor)
8737 return Result; // Fail.
8740 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8741 if (Chain->getOperand(i).getNode() == LD) {
8745 if (!isOk) return Result;
8748 // This only handles simple types.
8749 if (V.getValueType() != MVT::i16 &&
8750 V.getValueType() != MVT::i32 &&
8751 V.getValueType() != MVT::i64)
8754 // Check the constant mask. Invert it so that the bits being masked out are
8755 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8756 // follow the sign bit for uniformity.
8757 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8758 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8759 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8760 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8761 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8762 if (NotMaskLZ == 64) return Result; // All zero mask.
8764 // See if we have a continuous run of bits. If so, we have 0*1+0*
8765 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8768 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8769 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8770 NotMaskLZ -= 64-V.getValueSizeInBits();
8772 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8773 switch (MaskedBytes) {
8777 default: return Result; // All one mask, or 5-byte mask.
8780 // Verify that the first bit starts at a multiple of mask so that the access
8781 // is aligned the same as the access width.
8782 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8784 Result.first = MaskedBytes;
8785 Result.second = NotMaskTZ/8;
8790 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8791 /// provides a value as specified by MaskInfo. If so, replace the specified
8792 /// store with a narrower store of truncated IVal.
8794 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8795 SDValue IVal, StoreSDNode *St,
8797 unsigned NumBytes = MaskInfo.first;
8798 unsigned ByteShift = MaskInfo.second;
8799 SelectionDAG &DAG = DC->getDAG();
8801 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8802 // that uses this. If not, this is not a replacement.
8803 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8804 ByteShift*8, (ByteShift+NumBytes)*8);
8805 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8807 // Check that it is legal on the target to do this. It is legal if the new
8808 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8810 MVT VT = MVT::getIntegerVT(NumBytes*8);
8811 if (!DC->isTypeLegal(VT))
8814 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8815 // shifted by ByteShift and truncated down to NumBytes.
8817 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8818 DAG.getConstant(ByteShift*8,
8819 DC->getShiftAmountTy(IVal.getValueType())));
8821 // Figure out the offset for the store and the alignment of the access.
8823 unsigned NewAlign = St->getAlignment();
8825 if (DAG.getTargetLoweringInfo().isLittleEndian())
8826 StOffset = ByteShift;
8828 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8830 SDValue Ptr = St->getBasePtr();
8832 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8833 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8834 NewAlign = MinAlign(NewAlign, StOffset);
8837 // Truncate down to the new size.
8838 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8841 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8842 St->getPointerInfo().getWithOffset(StOffset),
8843 false, false, NewAlign).getNode();
8847 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8848 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8849 /// of the loaded bits, try narrowing the load and store if it would end up
8850 /// being a win for performance or code size.
8851 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8852 StoreSDNode *ST = cast<StoreSDNode>(N);
8853 if (ST->isVolatile())
8856 SDValue Chain = ST->getChain();
8857 SDValue Value = ST->getValue();
8858 SDValue Ptr = ST->getBasePtr();
8859 EVT VT = Value.getValueType();
8861 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8864 unsigned Opc = Value.getOpcode();
8866 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8867 // is a byte mask indicating a consecutive number of bytes, check to see if
8868 // Y is known to provide just those bytes. If so, we try to replace the
8869 // load + replace + store sequence with a single (narrower) store, which makes
8871 if (Opc == ISD::OR) {
8872 std::pair<unsigned, unsigned> MaskedLoad;
8873 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8874 if (MaskedLoad.first)
8875 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8876 Value.getOperand(1), ST,this))
8877 return SDValue(NewST, 0);
8879 // Or is commutative, so try swapping X and Y.
8880 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8881 if (MaskedLoad.first)
8882 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8883 Value.getOperand(0), ST,this))
8884 return SDValue(NewST, 0);
8887 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8888 Value.getOperand(1).getOpcode() != ISD::Constant)
8891 SDValue N0 = Value.getOperand(0);
8892 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8893 Chain == SDValue(N0.getNode(), 1)) {
8894 LoadSDNode *LD = cast<LoadSDNode>(N0);
8895 if (LD->getBasePtr() != Ptr ||
8896 LD->getPointerInfo().getAddrSpace() !=
8897 ST->getPointerInfo().getAddrSpace())
8900 // Find the type to narrow it the load / op / store to.
8901 SDValue N1 = Value.getOperand(1);
8902 unsigned BitWidth = N1.getValueSizeInBits();
8903 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8904 if (Opc == ISD::AND)
8905 Imm ^= APInt::getAllOnesValue(BitWidth);
8906 if (Imm == 0 || Imm.isAllOnesValue())
8908 unsigned ShAmt = Imm.countTrailingZeros();
8909 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8910 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8911 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8912 while (NewBW < BitWidth &&
8913 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8914 TLI.isNarrowingProfitable(VT, NewVT))) {
8915 NewBW = NextPowerOf2(NewBW);
8916 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8918 if (NewBW >= BitWidth)
8921 // If the lsb changed does not start at the type bitwidth boundary,
8922 // start at the previous one.
8924 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8925 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8926 std::min(BitWidth, ShAmt + NewBW));
8927 if ((Imm & Mask) == Imm) {
8928 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8929 if (Opc == ISD::AND)
8930 NewImm ^= APInt::getAllOnesValue(NewBW);
8931 uint64_t PtrOff = ShAmt / 8;
8932 // For big endian targets, we need to adjust the offset to the pointer to
8933 // load the correct bytes.
8934 if (TLI.isBigEndian())
8935 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8937 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8938 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8939 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8942 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8943 Ptr.getValueType(), Ptr,
8944 DAG.getConstant(PtrOff, Ptr.getValueType()));
8945 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8946 LD->getChain(), NewPtr,
8947 LD->getPointerInfo().getWithOffset(PtrOff),
8948 LD->isVolatile(), LD->isNonTemporal(),
8949 LD->isInvariant(), NewAlign,
8951 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8952 DAG.getConstant(NewImm, NewVT));
8953 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8955 ST->getPointerInfo().getWithOffset(PtrOff),
8956 false, false, NewAlign);
8958 AddToWorklist(NewPtr.getNode());
8959 AddToWorklist(NewLD.getNode());
8960 AddToWorklist(NewVal.getNode());
8961 WorklistRemover DeadNodes(*this);
8962 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8971 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8972 /// if the load value isn't used by any other operations, then consider
8973 /// transforming the pair to integer load / store operations if the target
8974 /// deems the transformation profitable.
8975 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8976 StoreSDNode *ST = cast<StoreSDNode>(N);
8977 SDValue Chain = ST->getChain();
8978 SDValue Value = ST->getValue();
8979 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8980 Value.hasOneUse() &&
8981 Chain == SDValue(Value.getNode(), 1)) {
8982 LoadSDNode *LD = cast<LoadSDNode>(Value);
8983 EVT VT = LD->getMemoryVT();
8984 if (!VT.isFloatingPoint() ||
8985 VT != ST->getMemoryVT() ||
8986 LD->isNonTemporal() ||
8987 ST->isNonTemporal() ||
8988 LD->getPointerInfo().getAddrSpace() != 0 ||
8989 ST->getPointerInfo().getAddrSpace() != 0)
8992 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8993 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8994 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8995 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8996 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8999 unsigned LDAlign = LD->getAlignment();
9000 unsigned STAlign = ST->getAlignment();
9001 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9002 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9003 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9006 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9007 LD->getChain(), LD->getBasePtr(),
9008 LD->getPointerInfo(),
9009 false, false, false, LDAlign);
9011 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9012 NewLD, ST->getBasePtr(),
9013 ST->getPointerInfo(),
9014 false, false, STAlign);
9016 AddToWorklist(NewLD.getNode());
9017 AddToWorklist(NewST.getNode());
9018 WorklistRemover DeadNodes(*this);
9019 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9027 /// Helper struct to parse and store a memory address as base + index + offset.
9028 /// We ignore sign extensions when it is safe to do so.
9029 /// The following two expressions are not equivalent. To differentiate we need
9030 /// to store whether there was a sign extension involved in the index
9032 /// (load (i64 add (i64 copyfromreg %c)
9033 /// (i64 signextend (add (i8 load %index)
9037 /// (load (i64 add (i64 copyfromreg %c)
9038 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9040 struct BaseIndexOffset {
9044 bool IsIndexSignExt;
9046 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9048 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9049 bool IsIndexSignExt) :
9050 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9052 bool equalBaseIndex(const BaseIndexOffset &Other) {
9053 return Other.Base == Base && Other.Index == Index &&
9054 Other.IsIndexSignExt == IsIndexSignExt;
9057 /// Parses tree in Ptr for base, index, offset addresses.
9058 static BaseIndexOffset match(SDValue Ptr) {
9059 bool IsIndexSignExt = false;
9061 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9062 // instruction, then it could be just the BASE or everything else we don't
9063 // know how to handle. Just use Ptr as BASE and give up.
9064 if (Ptr->getOpcode() != ISD::ADD)
9065 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9067 // We know that we have at least an ADD instruction. Try to pattern match
9068 // the simple case of BASE + OFFSET.
9069 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9070 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9071 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9075 // Inside a loop the current BASE pointer is calculated using an ADD and a
9076 // MUL instruction. In this case Ptr is the actual BASE pointer.
9077 // (i64 add (i64 %array_ptr)
9078 // (i64 mul (i64 %induction_var)
9079 // (i64 %element_size)))
9080 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9081 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9083 // Look at Base + Index + Offset cases.
9084 SDValue Base = Ptr->getOperand(0);
9085 SDValue IndexOffset = Ptr->getOperand(1);
9087 // Skip signextends.
9088 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9089 IndexOffset = IndexOffset->getOperand(0);
9090 IsIndexSignExt = true;
9093 // Either the case of Base + Index (no offset) or something else.
9094 if (IndexOffset->getOpcode() != ISD::ADD)
9095 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9097 // Now we have the case of Base + Index + offset.
9098 SDValue Index = IndexOffset->getOperand(0);
9099 SDValue Offset = IndexOffset->getOperand(1);
9101 if (!isa<ConstantSDNode>(Offset))
9102 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9104 // Ignore signextends.
9105 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9106 Index = Index->getOperand(0);
9107 IsIndexSignExt = true;
9108 } else IsIndexSignExt = false;
9110 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9111 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9115 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9116 /// is located in a sequence of memory operations connected by a chain.
9118 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9119 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9120 // Ptr to the mem node.
9121 LSBaseSDNode *MemNode;
9122 // Offset from the base ptr.
9123 int64_t OffsetFromBase;
9124 // What is the sequence number of this mem node.
9125 // Lowest mem operand in the DAG starts at zero.
9126 unsigned SequenceNum;
9129 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9130 EVT MemVT = St->getMemoryVT();
9131 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9132 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9133 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9135 // Don't merge vectors into wider inputs.
9136 if (MemVT.isVector() || !MemVT.isSimple())
9139 // Perform an early exit check. Do not bother looking at stored values that
9140 // are not constants or loads.
9141 SDValue StoredVal = St->getValue();
9142 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9143 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9147 // Only look at ends of store sequences.
9148 SDValue Chain = SDValue(St, 0);
9149 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9152 // This holds the base pointer, index, and the offset in bytes from the base
9154 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9156 // We must have a base and an offset.
9157 if (!BasePtr.Base.getNode())
9160 // Do not handle stores to undef base pointers.
9161 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9164 // Save the LoadSDNodes that we find in the chain.
9165 // We need to make sure that these nodes do not interfere with
9166 // any of the store nodes.
9167 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9169 // Save the StoreSDNodes that we find in the chain.
9170 SmallVector<MemOpLink, 8> StoreNodes;
9172 // Walk up the chain and look for nodes with offsets from the same
9173 // base pointer. Stop when reaching an instruction with a different kind
9174 // or instruction which has a different base pointer.
9176 StoreSDNode *Index = St;
9178 // If the chain has more than one use, then we can't reorder the mem ops.
9179 if (Index != St && !SDValue(Index, 0)->hasOneUse())
9182 // Find the base pointer and offset for this memory node.
9183 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9185 // Check that the base pointer is the same as the original one.
9186 if (!Ptr.equalBaseIndex(BasePtr))
9189 // Check that the alignment is the same.
9190 if (Index->getAlignment() != St->getAlignment())
9193 // The memory operands must not be volatile.
9194 if (Index->isVolatile() || Index->isIndexed())
9198 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9199 if (St->isTruncatingStore())
9202 // The stored memory type must be the same.
9203 if (Index->getMemoryVT() != MemVT)
9206 // We do not allow unaligned stores because we want to prevent overriding
9208 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9211 // We found a potential memory operand to merge.
9212 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9214 // Find the next memory operand in the chain. If the next operand in the
9215 // chain is a store then move up and continue the scan with the next
9216 // memory operand. If the next operand is a load save it and use alias
9217 // information to check if it interferes with anything.
9218 SDNode *NextInChain = Index->getChain().getNode();
9220 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9221 // We found a store node. Use it for the next iteration.
9224 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9225 if (Ldn->isVolatile()) {
9230 // Save the load node for later. Continue the scan.
9231 AliasLoadNodes.push_back(Ldn);
9232 NextInChain = Ldn->getChain().getNode();
9241 // Check if there is anything to merge.
9242 if (StoreNodes.size() < 2)
9245 // Sort the memory operands according to their distance from the base pointer.
9246 std::sort(StoreNodes.begin(), StoreNodes.end(),
9247 [](MemOpLink LHS, MemOpLink RHS) {
9248 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9249 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9250 LHS.SequenceNum > RHS.SequenceNum);
9253 // Scan the memory operations on the chain and find the first non-consecutive
9254 // store memory address.
9255 unsigned LastConsecutiveStore = 0;
9256 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9257 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9259 // Check that the addresses are consecutive starting from the second
9260 // element in the list of stores.
9262 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9263 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9268 // Check if this store interferes with any of the loads that we found.
9269 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9270 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9274 // We found a load that alias with this store. Stop the sequence.
9278 // Mark this node as useful.
9279 LastConsecutiveStore = i;
9282 // The node with the lowest store address.
9283 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9285 // Store the constants into memory as one consecutive store.
9287 unsigned LastLegalType = 0;
9288 unsigned LastLegalVectorType = 0;
9289 bool NonZero = false;
9290 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9291 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9292 SDValue StoredVal = St->getValue();
9294 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9295 NonZero |= !C->isNullValue();
9296 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9297 NonZero |= !C->getConstantFPValue()->isNullValue();
9303 // Find a legal type for the constant store.
9304 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9305 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9306 if (TLI.isTypeLegal(StoreTy))
9307 LastLegalType = i+1;
9308 // Or check whether a truncstore is legal.
9309 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9310 TargetLowering::TypePromoteInteger) {
9311 EVT LegalizedStoredValueTy =
9312 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9313 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9314 LastLegalType = i+1;
9317 // Find a legal type for the vector store.
9318 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9319 if (TLI.isTypeLegal(Ty))
9320 LastLegalVectorType = i + 1;
9323 // We only use vectors if the constant is known to be zero and the
9324 // function is not marked with the noimplicitfloat attribute.
9325 if (NonZero || NoVectors)
9326 LastLegalVectorType = 0;
9328 // Check if we found a legal integer type to store.
9329 if (LastLegalType == 0 && LastLegalVectorType == 0)
9332 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9333 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9335 // Make sure we have something to merge.
9339 unsigned EarliestNodeUsed = 0;
9340 for (unsigned i=0; i < NumElem; ++i) {
9341 // Find a chain for the new wide-store operand. Notice that some
9342 // of the store nodes that we found may not be selected for inclusion
9343 // in the wide store. The chain we use needs to be the chain of the
9344 // earliest store node which is *used* and replaced by the wide store.
9345 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9346 EarliestNodeUsed = i;
9349 // The earliest Node in the DAG.
9350 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9351 SDLoc DL(StoreNodes[0].MemNode);
9355 // Find a legal type for the vector store.
9356 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9357 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9358 StoredVal = DAG.getConstant(0, Ty);
9360 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9361 APInt StoreInt(StoreBW, 0);
9363 // Construct a single integer constant which is made of the smaller
9365 bool IsLE = TLI.isLittleEndian();
9366 for (unsigned i = 0; i < NumElem ; ++i) {
9367 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9368 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9369 SDValue Val = St->getValue();
9370 StoreInt<<=ElementSizeBytes*8;
9371 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9372 StoreInt|=C->getAPIntValue().zext(StoreBW);
9373 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9374 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9376 assert(false && "Invalid constant element type");
9380 // Create the new Load and Store operations.
9381 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9382 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9385 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9386 FirstInChain->getBasePtr(),
9387 FirstInChain->getPointerInfo(),
9389 FirstInChain->getAlignment());
9391 // Replace the first store with the new store
9392 CombineTo(EarliestOp, NewStore);
9393 // Erase all other stores.
9394 for (unsigned i = 0; i < NumElem ; ++i) {
9395 if (StoreNodes[i].MemNode == EarliestOp)
9397 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9398 // ReplaceAllUsesWith will replace all uses that existed when it was
9399 // called, but graph optimizations may cause new ones to appear. For
9400 // example, the case in pr14333 looks like
9402 // St's chain -> St -> another store -> X
9404 // And the only difference from St to the other store is the chain.
9405 // When we change it's chain to be St's chain they become identical,
9406 // get CSEed and the net result is that X is now a use of St.
9407 // Since we know that St is redundant, just iterate.
9408 while (!St->use_empty())
9409 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9410 deleteAndRecombine(St);
9416 // Below we handle the case of multiple consecutive stores that
9417 // come from multiple consecutive loads. We merge them into a single
9418 // wide load and a single wide store.
9420 // Look for load nodes which are used by the stored values.
9421 SmallVector<MemOpLink, 8> LoadNodes;
9423 // Find acceptable loads. Loads need to have the same chain (token factor),
9424 // must not be zext, volatile, indexed, and they must be consecutive.
9425 BaseIndexOffset LdBasePtr;
9426 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9427 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9428 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9431 // Loads must only have one use.
9432 if (!Ld->hasNUsesOfValue(1, 0))
9435 // Check that the alignment is the same as the stores.
9436 if (Ld->getAlignment() != St->getAlignment())
9439 // The memory operands must not be volatile.
9440 if (Ld->isVolatile() || Ld->isIndexed())
9443 // We do not accept ext loads.
9444 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9447 // The stored memory type must be the same.
9448 if (Ld->getMemoryVT() != MemVT)
9451 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9452 // If this is not the first ptr that we check.
9453 if (LdBasePtr.Base.getNode()) {
9454 // The base ptr must be the same.
9455 if (!LdPtr.equalBaseIndex(LdBasePtr))
9458 // Check that all other base pointers are the same as this one.
9462 // We found a potential memory operand to merge.
9463 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9466 if (LoadNodes.size() < 2)
9469 // If we have load/store pair instructions and we only have two values,
9471 unsigned RequiredAlignment;
9472 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9473 St->getAlignment() >= RequiredAlignment)
9476 // Scan the memory operations on the chain and find the first non-consecutive
9477 // load memory address. These variables hold the index in the store node
9479 unsigned LastConsecutiveLoad = 0;
9480 // This variable refers to the size and not index in the array.
9481 unsigned LastLegalVectorType = 0;
9482 unsigned LastLegalIntegerType = 0;
9483 StartAddress = LoadNodes[0].OffsetFromBase;
9484 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9485 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9486 // All loads much share the same chain.
9487 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9490 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9491 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9493 LastConsecutiveLoad = i;
9495 // Find a legal type for the vector store.
9496 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9497 if (TLI.isTypeLegal(StoreTy))
9498 LastLegalVectorType = i + 1;
9500 // Find a legal type for the integer store.
9501 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9502 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9503 if (TLI.isTypeLegal(StoreTy))
9504 LastLegalIntegerType = i + 1;
9505 // Or check whether a truncstore and extload is legal.
9506 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9507 TargetLowering::TypePromoteInteger) {
9508 EVT LegalizedStoredValueTy =
9509 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9510 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9511 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9512 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9513 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9514 LastLegalIntegerType = i+1;
9518 // Only use vector types if the vector type is larger than the integer type.
9519 // If they are the same, use integers.
9520 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9521 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9523 // We add +1 here because the LastXXX variables refer to location while
9524 // the NumElem refers to array/index size.
9525 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9526 NumElem = std::min(LastLegalType, NumElem);
9531 // The earliest Node in the DAG.
9532 unsigned EarliestNodeUsed = 0;
9533 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9534 for (unsigned i=1; i<NumElem; ++i) {
9535 // Find a chain for the new wide-store operand. Notice that some
9536 // of the store nodes that we found may not be selected for inclusion
9537 // in the wide store. The chain we use needs to be the chain of the
9538 // earliest store node which is *used* and replaced by the wide store.
9539 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9540 EarliestNodeUsed = i;
9543 // Find if it is better to use vectors or integers to load and store
9547 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9549 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9550 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9553 SDLoc LoadDL(LoadNodes[0].MemNode);
9554 SDLoc StoreDL(StoreNodes[0].MemNode);
9556 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9557 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9558 FirstLoad->getChain(),
9559 FirstLoad->getBasePtr(),
9560 FirstLoad->getPointerInfo(),
9561 false, false, false,
9562 FirstLoad->getAlignment());
9564 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9565 FirstInChain->getBasePtr(),
9566 FirstInChain->getPointerInfo(), false, false,
9567 FirstInChain->getAlignment());
9569 // Replace one of the loads with the new load.
9570 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9571 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9572 SDValue(NewLoad.getNode(), 1));
9574 // Remove the rest of the load chains.
9575 for (unsigned i = 1; i < NumElem ; ++i) {
9576 // Replace all chain users of the old load nodes with the chain of the new
9578 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9579 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9582 // Replace the first store with the new store.
9583 CombineTo(EarliestOp, NewStore);
9584 // Erase all other stores.
9585 for (unsigned i = 0; i < NumElem ; ++i) {
9586 // Remove all Store nodes.
9587 if (StoreNodes[i].MemNode == EarliestOp)
9589 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9590 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9591 deleteAndRecombine(St);
9597 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9598 StoreSDNode *ST = cast<StoreSDNode>(N);
9599 SDValue Chain = ST->getChain();
9600 SDValue Value = ST->getValue();
9601 SDValue Ptr = ST->getBasePtr();
9603 // If this is a store of a bit convert, store the input value if the
9604 // resultant store does not need a higher alignment than the original.
9605 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9606 ST->isUnindexed()) {
9607 unsigned OrigAlign = ST->getAlignment();
9608 EVT SVT = Value.getOperand(0).getValueType();
9609 unsigned Align = TLI.getDataLayout()->
9610 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9611 if (Align <= OrigAlign &&
9612 ((!LegalOperations && !ST->isVolatile()) ||
9613 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9614 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9615 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9616 ST->isNonTemporal(), OrigAlign,
9620 // Turn 'store undef, Ptr' -> nothing.
9621 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9624 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9625 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9626 // NOTE: If the original store is volatile, this transform must not increase
9627 // the number of stores. For example, on x86-32 an f64 can be stored in one
9628 // processor operation but an i64 (which is not legal) requires two. So the
9629 // transform should not be done in this case.
9630 if (Value.getOpcode() != ISD::TargetConstantFP) {
9632 switch (CFP->getSimpleValueType(0).SimpleTy) {
9633 default: llvm_unreachable("Unknown FP type");
9634 case MVT::f16: // We don't do this for these yet.
9640 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9641 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9642 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9643 bitcastToAPInt().getZExtValue(), MVT::i32);
9644 return DAG.getStore(Chain, SDLoc(N), Tmp,
9645 Ptr, ST->getMemOperand());
9649 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9650 !ST->isVolatile()) ||
9651 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9652 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9653 getZExtValue(), MVT::i64);
9654 return DAG.getStore(Chain, SDLoc(N), Tmp,
9655 Ptr, ST->getMemOperand());
9658 if (!ST->isVolatile() &&
9659 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9660 // Many FP stores are not made apparent until after legalize, e.g. for
9661 // argument passing. Since this is so common, custom legalize the
9662 // 64-bit integer store into two 32-bit stores.
9663 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9664 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9665 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9666 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9668 unsigned Alignment = ST->getAlignment();
9669 bool isVolatile = ST->isVolatile();
9670 bool isNonTemporal = ST->isNonTemporal();
9671 AAMDNodes AAInfo = ST->getAAInfo();
9673 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9674 Ptr, ST->getPointerInfo(),
9675 isVolatile, isNonTemporal,
9676 ST->getAlignment(), AAInfo);
9677 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9678 DAG.getConstant(4, Ptr.getValueType()));
9679 Alignment = MinAlign(Alignment, 4U);
9680 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9681 Ptr, ST->getPointerInfo().getWithOffset(4),
9682 isVolatile, isNonTemporal,
9684 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9693 // Try to infer better alignment information than the store already has.
9694 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9695 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9696 if (Align > ST->getAlignment())
9697 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9698 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9699 ST->isVolatile(), ST->isNonTemporal(), Align,
9704 // Try transforming a pair floating point load / store ops to integer
9705 // load / store ops.
9706 SDValue NewST = TransformFPLoadStorePair(N);
9707 if (NewST.getNode())
9710 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9711 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9713 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9714 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9717 if (UseAA && ST->isUnindexed()) {
9718 // Walk up chain skipping non-aliasing memory nodes.
9719 SDValue BetterChain = FindBetterChain(N, Chain);
9721 // If there is a better chain.
9722 if (Chain != BetterChain) {
9725 // Replace the chain to avoid dependency.
9726 if (ST->isTruncatingStore()) {
9727 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9728 ST->getMemoryVT(), ST->getMemOperand());
9730 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9731 ST->getMemOperand());
9734 // Create token to keep both nodes around.
9735 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9736 MVT::Other, Chain, ReplStore);
9738 // Make sure the new and old chains are cleaned up.
9739 AddToWorklist(Token.getNode());
9741 // Don't add users to work list.
9742 return CombineTo(N, Token, false);
9746 // Try transforming N to an indexed store.
9747 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9748 return SDValue(N, 0);
9750 // FIXME: is there such a thing as a truncating indexed store?
9751 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9752 Value.getValueType().isInteger()) {
9753 // See if we can simplify the input to this truncstore with knowledge that
9754 // only the low bits are being used. For example:
9755 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9757 GetDemandedBits(Value,
9758 APInt::getLowBitsSet(
9759 Value.getValueType().getScalarType().getSizeInBits(),
9760 ST->getMemoryVT().getScalarType().getSizeInBits()));
9761 AddToWorklist(Value.getNode());
9762 if (Shorter.getNode())
9763 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9764 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9766 // Otherwise, see if we can simplify the operation with
9767 // SimplifyDemandedBits, which only works if the value has a single use.
9768 if (SimplifyDemandedBits(Value,
9769 APInt::getLowBitsSet(
9770 Value.getValueType().getScalarType().getSizeInBits(),
9771 ST->getMemoryVT().getScalarType().getSizeInBits())))
9772 return SDValue(N, 0);
9775 // If this is a load followed by a store to the same location, then the store
9777 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9778 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9779 ST->isUnindexed() && !ST->isVolatile() &&
9780 // There can't be any side effects between the load and store, such as
9782 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9783 // The store is dead, remove it.
9788 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9789 // truncating store. We can do this even if this is already a truncstore.
9790 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9791 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9792 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9793 ST->getMemoryVT())) {
9794 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9795 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9798 // Only perform this optimization before the types are legal, because we
9799 // don't want to perform this optimization on every DAGCombine invocation.
9801 bool EverChanged = false;
9804 // There can be multiple store sequences on the same chain.
9805 // Keep trying to merge store sequences until we are unable to do so
9806 // or until we merge the last store on the chain.
9807 bool Changed = MergeConsecutiveStores(ST);
9808 EverChanged |= Changed;
9809 if (!Changed) break;
9810 } while (ST->getOpcode() != ISD::DELETED_NODE);
9813 return SDValue(N, 0);
9816 return ReduceLoadOpStoreWidth(N);
9819 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9820 SDValue InVec = N->getOperand(0);
9821 SDValue InVal = N->getOperand(1);
9822 SDValue EltNo = N->getOperand(2);
9825 // If the inserted element is an UNDEF, just use the input vector.
9826 if (InVal.getOpcode() == ISD::UNDEF)
9829 EVT VT = InVec.getValueType();
9831 // If we can't generate a legal BUILD_VECTOR, exit
9832 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9835 // Check that we know which element is being inserted
9836 if (!isa<ConstantSDNode>(EltNo))
9838 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9840 // Canonicalize insert_vector_elt dag nodes.
9842 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9843 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9845 // Do this only if the child insert_vector node has one use; also
9846 // do this only if indices are both constants and Idx1 < Idx0.
9847 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9848 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9850 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9851 if (Elt < OtherElt) {
9853 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9854 InVec.getOperand(0), InVal, EltNo);
9855 AddToWorklist(NewOp.getNode());
9856 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9857 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9861 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9862 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9864 SmallVector<SDValue, 8> Ops;
9865 // Do not combine these two vectors if the output vector will not replace
9866 // the input vector.
9867 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9868 Ops.append(InVec.getNode()->op_begin(),
9869 InVec.getNode()->op_end());
9870 } else if (InVec.getOpcode() == ISD::UNDEF) {
9871 unsigned NElts = VT.getVectorNumElements();
9872 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9877 // Insert the element
9878 if (Elt < Ops.size()) {
9879 // All the operands of BUILD_VECTOR must have the same type;
9880 // we enforce that here.
9881 EVT OpVT = Ops[0].getValueType();
9882 if (InVal.getValueType() != OpVT)
9883 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9884 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9885 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9889 // Return the new vector
9890 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9893 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9894 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9895 EVT ResultVT = EVE->getValueType(0);
9896 EVT VecEltVT = InVecVT.getVectorElementType();
9897 unsigned Align = OriginalLoad->getAlignment();
9898 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9899 VecEltVT.getTypeForEVT(*DAG.getContext()));
9901 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9906 SDValue NewPtr = OriginalLoad->getBasePtr();
9908 EVT PtrType = NewPtr.getValueType();
9909 MachinePointerInfo MPI;
9910 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9911 int Elt = ConstEltNo->getZExtValue();
9912 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9913 if (TLI.isBigEndian())
9914 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9915 Offset = DAG.getConstant(PtrOff, PtrType);
9916 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9918 Offset = DAG.getNode(
9919 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9920 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9921 if (TLI.isBigEndian())
9922 Offset = DAG.getNode(
9923 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9924 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9925 MPI = OriginalLoad->getPointerInfo();
9927 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9929 // The replacement we need to do here is a little tricky: we need to
9930 // replace an extractelement of a load with a load.
9931 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9932 // Note that this replacement assumes that the extractvalue is the only
9933 // use of the load; that's okay because we don't want to perform this
9934 // transformation in other cases anyway.
9937 if (ResultVT.bitsGT(VecEltVT)) {
9938 // If the result type of vextract is wider than the load, then issue an
9939 // extending load instead.
9940 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9943 Load = DAG.getExtLoad(
9944 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9945 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9946 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9947 Chain = Load.getValue(1);
9950 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9951 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9952 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9953 Chain = Load.getValue(1);
9954 if (ResultVT.bitsLT(VecEltVT))
9955 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9957 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9959 WorklistRemover DeadNodes(*this);
9960 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9961 SDValue To[] = { Load, Chain };
9962 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9963 // Since we're explicitly calling ReplaceAllUses, add the new node to the
9964 // worklist explicitly as well.
9965 AddToWorklist(Load.getNode());
9966 AddUsersToWorklist(Load.getNode()); // Add users too
9967 // Make sure to revisit this node to clean it up; it will usually be dead.
9970 return SDValue(EVE, 0);
9973 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9974 // (vextract (scalar_to_vector val, 0) -> val
9975 SDValue InVec = N->getOperand(0);
9976 EVT VT = InVec.getValueType();
9977 EVT NVT = N->getValueType(0);
9979 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9980 // Check if the result type doesn't match the inserted element type. A
9981 // SCALAR_TO_VECTOR may truncate the inserted element and the
9982 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9983 SDValue InOp = InVec.getOperand(0);
9984 if (InOp.getValueType() != NVT) {
9985 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9986 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9991 SDValue EltNo = N->getOperand(1);
9992 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9994 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9995 // We only perform this optimization before the op legalization phase because
9996 // we may introduce new vector instructions which are not backed by TD
9997 // patterns. For example on AVX, extracting elements from a wide vector
9998 // without using extract_subvector. However, if we can find an underlying
9999 // scalar value, then we can always use that.
10000 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10002 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10003 int NumElem = VT.getVectorNumElements();
10004 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10005 // Find the new index to extract from.
10006 int OrigElt = SVOp->getMaskElt(Elt);
10008 // Extracting an undef index is undef.
10010 return DAG.getUNDEF(NVT);
10012 // Select the right vector half to extract from.
10014 if (OrigElt < NumElem) {
10015 SVInVec = InVec->getOperand(0);
10017 SVInVec = InVec->getOperand(1);
10018 OrigElt -= NumElem;
10021 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10022 SDValue InOp = SVInVec.getOperand(OrigElt);
10023 if (InOp.getValueType() != NVT) {
10024 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10025 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10031 // FIXME: We should handle recursing on other vector shuffles and
10032 // scalar_to_vector here as well.
10034 if (!LegalOperations) {
10035 EVT IndexTy = TLI.getVectorIdxTy();
10036 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10037 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10041 bool BCNumEltsChanged = false;
10042 EVT ExtVT = VT.getVectorElementType();
10045 // If the result of load has to be truncated, then it's not necessarily
10047 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10050 if (InVec.getOpcode() == ISD::BITCAST) {
10051 // Don't duplicate a load with other uses.
10052 if (!InVec.hasOneUse())
10055 EVT BCVT = InVec.getOperand(0).getValueType();
10056 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10058 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10059 BCNumEltsChanged = true;
10060 InVec = InVec.getOperand(0);
10061 ExtVT = BCVT.getVectorElementType();
10064 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10065 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10066 ISD::isNormalLoad(InVec.getNode()) &&
10067 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10068 SDValue Index = N->getOperand(1);
10069 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10070 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10074 // Perform only after legalization to ensure build_vector / vector_shuffle
10075 // optimizations have already been done.
10076 if (!LegalOperations) return SDValue();
10078 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10079 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10080 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10083 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10085 LoadSDNode *LN0 = nullptr;
10086 const ShuffleVectorSDNode *SVN = nullptr;
10087 if (ISD::isNormalLoad(InVec.getNode())) {
10088 LN0 = cast<LoadSDNode>(InVec);
10089 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10090 InVec.getOperand(0).getValueType() == ExtVT &&
10091 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10092 // Don't duplicate a load with other uses.
10093 if (!InVec.hasOneUse())
10096 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10097 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10098 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10100 // (load $addr+1*size)
10102 // Don't duplicate a load with other uses.
10103 if (!InVec.hasOneUse())
10106 // If the bit convert changed the number of elements, it is unsafe
10107 // to examine the mask.
10108 if (BCNumEltsChanged)
10111 // Select the input vector, guarding against out of range extract vector.
10112 unsigned NumElems = VT.getVectorNumElements();
10113 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10114 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10116 if (InVec.getOpcode() == ISD::BITCAST) {
10117 // Don't duplicate a load with other uses.
10118 if (!InVec.hasOneUse())
10121 InVec = InVec.getOperand(0);
10123 if (ISD::isNormalLoad(InVec.getNode())) {
10124 LN0 = cast<LoadSDNode>(InVec);
10125 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10126 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10130 // Make sure we found a non-volatile load and the extractelement is
10132 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10135 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10137 return DAG.getUNDEF(LVT);
10139 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10145 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10146 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10147 // We perform this optimization post type-legalization because
10148 // the type-legalizer often scalarizes integer-promoted vectors.
10149 // Performing this optimization before may create bit-casts which
10150 // will be type-legalized to complex code sequences.
10151 // We perform this optimization only before the operation legalizer because we
10152 // may introduce illegal operations.
10153 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10156 unsigned NumInScalars = N->getNumOperands();
10158 EVT VT = N->getValueType(0);
10160 // Check to see if this is a BUILD_VECTOR of a bunch of values
10161 // which come from any_extend or zero_extend nodes. If so, we can create
10162 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10163 // optimizations. We do not handle sign-extend because we can't fill the sign
10165 EVT SourceType = MVT::Other;
10166 bool AllAnyExt = true;
10168 for (unsigned i = 0; i != NumInScalars; ++i) {
10169 SDValue In = N->getOperand(i);
10170 // Ignore undef inputs.
10171 if (In.getOpcode() == ISD::UNDEF) continue;
10173 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10174 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10176 // Abort if the element is not an extension.
10177 if (!ZeroExt && !AnyExt) {
10178 SourceType = MVT::Other;
10182 // The input is a ZeroExt or AnyExt. Check the original type.
10183 EVT InTy = In.getOperand(0).getValueType();
10185 // Check that all of the widened source types are the same.
10186 if (SourceType == MVT::Other)
10189 else if (InTy != SourceType) {
10190 // Multiple income types. Abort.
10191 SourceType = MVT::Other;
10195 // Check if all of the extends are ANY_EXTENDs.
10196 AllAnyExt &= AnyExt;
10199 // In order to have valid types, all of the inputs must be extended from the
10200 // same source type and all of the inputs must be any or zero extend.
10201 // Scalar sizes must be a power of two.
10202 EVT OutScalarTy = VT.getScalarType();
10203 bool ValidTypes = SourceType != MVT::Other &&
10204 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10205 isPowerOf2_32(SourceType.getSizeInBits());
10207 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10208 // turn into a single shuffle instruction.
10212 bool isLE = TLI.isLittleEndian();
10213 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10214 assert(ElemRatio > 1 && "Invalid element size ratio");
10215 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10216 DAG.getConstant(0, SourceType);
10218 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10219 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10221 // Populate the new build_vector
10222 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10223 SDValue Cast = N->getOperand(i);
10224 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10225 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10226 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10228 if (Cast.getOpcode() == ISD::UNDEF)
10229 In = DAG.getUNDEF(SourceType);
10231 In = Cast->getOperand(0);
10232 unsigned Index = isLE ? (i * ElemRatio) :
10233 (i * ElemRatio + (ElemRatio - 1));
10235 assert(Index < Ops.size() && "Invalid index");
10239 // The type of the new BUILD_VECTOR node.
10240 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10241 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10242 "Invalid vector size");
10243 // Check if the new vector type is legal.
10244 if (!isTypeLegal(VecVT)) return SDValue();
10246 // Make the new BUILD_VECTOR.
10247 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10249 // The new BUILD_VECTOR node has the potential to be further optimized.
10250 AddToWorklist(BV.getNode());
10251 // Bitcast to the desired type.
10252 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10255 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10256 EVT VT = N->getValueType(0);
10258 unsigned NumInScalars = N->getNumOperands();
10261 EVT SrcVT = MVT::Other;
10262 unsigned Opcode = ISD::DELETED_NODE;
10263 unsigned NumDefs = 0;
10265 for (unsigned i = 0; i != NumInScalars; ++i) {
10266 SDValue In = N->getOperand(i);
10267 unsigned Opc = In.getOpcode();
10269 if (Opc == ISD::UNDEF)
10272 // If all scalar values are floats and converted from integers.
10273 if (Opcode == ISD::DELETED_NODE &&
10274 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10281 EVT InVT = In.getOperand(0).getValueType();
10283 // If all scalar values are typed differently, bail out. It's chosen to
10284 // simplify BUILD_VECTOR of integer types.
10285 if (SrcVT == MVT::Other)
10292 // If the vector has just one element defined, it's not worth to fold it into
10293 // a vectorized one.
10297 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10298 && "Should only handle conversion from integer to float.");
10299 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10301 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10303 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10306 SmallVector<SDValue, 8> Opnds;
10307 for (unsigned i = 0; i != NumInScalars; ++i) {
10308 SDValue In = N->getOperand(i);
10310 if (In.getOpcode() == ISD::UNDEF)
10311 Opnds.push_back(DAG.getUNDEF(SrcVT));
10313 Opnds.push_back(In.getOperand(0));
10315 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10316 AddToWorklist(BV.getNode());
10318 return DAG.getNode(Opcode, dl, VT, BV);
10321 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10322 unsigned NumInScalars = N->getNumOperands();
10324 EVT VT = N->getValueType(0);
10326 // A vector built entirely of undefs is undef.
10327 if (ISD::allOperandsUndef(N))
10328 return DAG.getUNDEF(VT);
10330 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10334 V = reduceBuildVecConvertToConvertBuildVec(N);
10338 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10339 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10340 // at most two distinct vectors, turn this into a shuffle node.
10342 // May only combine to shuffle after legalize if shuffle is legal.
10343 if (LegalOperations &&
10344 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10347 SDValue VecIn1, VecIn2;
10348 for (unsigned i = 0; i != NumInScalars; ++i) {
10349 // Ignore undef inputs.
10350 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10352 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10353 // constant index, bail out.
10354 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10355 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10356 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10360 // We allow up to two distinct input vectors.
10361 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10362 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10365 if (!VecIn1.getNode()) {
10366 VecIn1 = ExtractedFromVec;
10367 } else if (!VecIn2.getNode()) {
10368 VecIn2 = ExtractedFromVec;
10370 // Too many inputs.
10371 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10376 // If everything is good, we can make a shuffle operation.
10377 if (VecIn1.getNode()) {
10378 SmallVector<int, 8> Mask;
10379 for (unsigned i = 0; i != NumInScalars; ++i) {
10380 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10381 Mask.push_back(-1);
10385 // If extracting from the first vector, just use the index directly.
10386 SDValue Extract = N->getOperand(i);
10387 SDValue ExtVal = Extract.getOperand(1);
10388 if (Extract.getOperand(0) == VecIn1) {
10389 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10390 if (ExtIndex > VT.getVectorNumElements())
10393 Mask.push_back(ExtIndex);
10397 // Otherwise, use InIdx + VecSize
10398 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10399 Mask.push_back(Idx+NumInScalars);
10402 // We can't generate a shuffle node with mismatched input and output types.
10403 // Attempt to transform a single input vector to the correct type.
10404 if ((VT != VecIn1.getValueType())) {
10405 // We don't support shuffeling between TWO values of different types.
10406 if (VecIn2.getNode())
10409 // We only support widening of vectors which are half the size of the
10410 // output registers. For example XMM->YMM widening on X86 with AVX.
10411 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10414 // If the input vector type has a different base type to the output
10415 // vector type, bail out.
10416 if (VecIn1.getValueType().getVectorElementType() !=
10417 VT.getVectorElementType())
10420 // Widen the input vector by adding undef values.
10421 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10422 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10425 // If VecIn2 is unused then change it to undef.
10426 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10428 // Check that we were able to transform all incoming values to the same
10430 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10431 VecIn1.getValueType() != VT)
10434 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10435 if (!isTypeLegal(VT))
10438 // Return the new VECTOR_SHUFFLE node.
10442 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10448 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10449 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10450 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10451 // inputs come from at most two distinct vectors, turn this into a shuffle
10454 // If we only have one input vector, we don't need to do any concatenation.
10455 if (N->getNumOperands() == 1)
10456 return N->getOperand(0);
10458 // Check if all of the operands are undefs.
10459 EVT VT = N->getValueType(0);
10460 if (ISD::allOperandsUndef(N))
10461 return DAG.getUNDEF(VT);
10463 // Optimize concat_vectors where one of the vectors is undef.
10464 if (N->getNumOperands() == 2 &&
10465 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10466 SDValue In = N->getOperand(0);
10467 assert(In.getValueType().isVector() && "Must concat vectors");
10469 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10470 if (In->getOpcode() == ISD::BITCAST &&
10471 !In->getOperand(0)->getValueType(0).isVector()) {
10472 SDValue Scalar = In->getOperand(0);
10473 EVT SclTy = Scalar->getValueType(0);
10475 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10478 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10479 VT.getSizeInBits() / SclTy.getSizeInBits());
10480 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10483 SDLoc dl = SDLoc(N);
10484 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10485 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10489 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10490 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10491 if (N->getNumOperands() == 2 &&
10492 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10493 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10494 EVT VT = N->getValueType(0);
10495 SDValue N0 = N->getOperand(0);
10496 SDValue N1 = N->getOperand(1);
10497 SmallVector<SDValue, 8> Opnds;
10498 unsigned BuildVecNumElts = N0.getNumOperands();
10500 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10501 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10502 if (SclTy0.isFloatingPoint()) {
10503 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10504 Opnds.push_back(N0.getOperand(i));
10505 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10506 Opnds.push_back(N1.getOperand(i));
10508 // If BUILD_VECTOR are from built from integer, they may have different
10509 // operand types. Get the smaller type and truncate all operands to it.
10510 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10511 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10512 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10513 N0.getOperand(i)));
10514 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10515 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10516 N1.getOperand(i)));
10519 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10522 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10523 // nodes often generate nop CONCAT_VECTOR nodes.
10524 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10525 // place the incoming vectors at the exact same location.
10526 SDValue SingleSource = SDValue();
10527 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10529 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10530 SDValue Op = N->getOperand(i);
10532 if (Op.getOpcode() == ISD::UNDEF)
10535 // Check if this is the identity extract:
10536 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10539 // Find the single incoming vector for the extract_subvector.
10540 if (SingleSource.getNode()) {
10541 if (Op.getOperand(0) != SingleSource)
10544 SingleSource = Op.getOperand(0);
10546 // Check the source type is the same as the type of the result.
10547 // If not, this concat may extend the vector, so we can not
10548 // optimize it away.
10549 if (SingleSource.getValueType() != N->getValueType(0))
10553 unsigned IdentityIndex = i * PartNumElem;
10554 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10555 // The extract index must be constant.
10559 // Check that we are reading from the identity index.
10560 if (CS->getZExtValue() != IdentityIndex)
10564 if (SingleSource.getNode())
10565 return SingleSource;
10570 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10571 EVT NVT = N->getValueType(0);
10572 SDValue V = N->getOperand(0);
10574 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10576 // (extract_subvec (concat V1, V2, ...), i)
10579 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10581 if (V->getOperand(0).getValueType() != NVT)
10583 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10584 unsigned NumElems = NVT.getVectorNumElements();
10585 assert((Idx % NumElems) == 0 &&
10586 "IDX in concat is not a multiple of the result vector length.");
10587 return V->getOperand(Idx / NumElems);
10591 if (V->getOpcode() == ISD::BITCAST)
10592 V = V.getOperand(0);
10594 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10596 // Handle only simple case where vector being inserted and vector
10597 // being extracted are of same type, and are half size of larger vectors.
10598 EVT BigVT = V->getOperand(0).getValueType();
10599 EVT SmallVT = V->getOperand(1).getValueType();
10600 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10603 // Only handle cases where both indexes are constants with the same type.
10604 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10605 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10607 if (InsIdx && ExtIdx &&
10608 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10609 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10611 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10613 // indices are equal or bit offsets are equal => V1
10614 // otherwise => (extract_subvec V1, ExtIdx)
10615 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10616 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10617 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10618 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10619 DAG.getNode(ISD::BITCAST, dl,
10620 N->getOperand(0).getValueType(),
10621 V->getOperand(0)), N->getOperand(1));
10628 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10629 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10630 EVT VT = N->getValueType(0);
10631 unsigned NumElts = VT.getVectorNumElements();
10633 SDValue N0 = N->getOperand(0);
10634 SDValue N1 = N->getOperand(1);
10635 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10637 SmallVector<SDValue, 4> Ops;
10638 EVT ConcatVT = N0.getOperand(0).getValueType();
10639 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10640 unsigned NumConcats = NumElts / NumElemsPerConcat;
10642 // Look at every vector that's inserted. We're looking for exact
10643 // subvector-sized copies from a concatenated vector
10644 for (unsigned I = 0; I != NumConcats; ++I) {
10645 // Make sure we're dealing with a copy.
10646 unsigned Begin = I * NumElemsPerConcat;
10647 bool AllUndef = true, NoUndef = true;
10648 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10649 if (SVN->getMaskElt(J) >= 0)
10656 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10659 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10660 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10663 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10664 if (FirstElt < N0.getNumOperands())
10665 Ops.push_back(N0.getOperand(FirstElt));
10667 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10669 } else if (AllUndef) {
10670 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10671 } else { // Mixed with general masks and undefs, can't do optimization.
10676 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10679 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10680 EVT VT = N->getValueType(0);
10681 unsigned NumElts = VT.getVectorNumElements();
10683 SDValue N0 = N->getOperand(0);
10684 SDValue N1 = N->getOperand(1);
10686 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10688 // Canonicalize shuffle undef, undef -> undef
10689 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10690 return DAG.getUNDEF(VT);
10692 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10694 // Canonicalize shuffle v, v -> v, undef
10696 SmallVector<int, 8> NewMask;
10697 for (unsigned i = 0; i != NumElts; ++i) {
10698 int Idx = SVN->getMaskElt(i);
10699 if (Idx >= (int)NumElts) Idx -= NumElts;
10700 NewMask.push_back(Idx);
10702 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10706 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10707 if (N0.getOpcode() == ISD::UNDEF) {
10708 SmallVector<int, 8> NewMask;
10709 for (unsigned i = 0; i != NumElts; ++i) {
10710 int Idx = SVN->getMaskElt(i);
10712 if (Idx >= (int)NumElts)
10715 Idx = -1; // remove reference to lhs
10717 NewMask.push_back(Idx);
10719 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10723 // Remove references to rhs if it is undef
10724 if (N1.getOpcode() == ISD::UNDEF) {
10725 bool Changed = false;
10726 SmallVector<int, 8> NewMask;
10727 for (unsigned i = 0; i != NumElts; ++i) {
10728 int Idx = SVN->getMaskElt(i);
10729 if (Idx >= (int)NumElts) {
10733 NewMask.push_back(Idx);
10736 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10739 // If it is a splat, check if the argument vector is another splat or a
10740 // build_vector with all scalar elements the same.
10741 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10742 SDNode *V = N0.getNode();
10744 // If this is a bit convert that changes the element type of the vector but
10745 // not the number of vector elements, look through it. Be careful not to
10746 // look though conversions that change things like v4f32 to v2f64.
10747 if (V->getOpcode() == ISD::BITCAST) {
10748 SDValue ConvInput = V->getOperand(0);
10749 if (ConvInput.getValueType().isVector() &&
10750 ConvInput.getValueType().getVectorNumElements() == NumElts)
10751 V = ConvInput.getNode();
10754 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10755 assert(V->getNumOperands() == NumElts &&
10756 "BUILD_VECTOR has wrong number of operands");
10758 bool AllSame = true;
10759 for (unsigned i = 0; i != NumElts; ++i) {
10760 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10761 Base = V->getOperand(i);
10765 // Splat of <u, u, u, u>, return <u, u, u, u>
10766 if (!Base.getNode())
10768 for (unsigned i = 0; i != NumElts; ++i) {
10769 if (V->getOperand(i) != Base) {
10774 // Splat of <x, x, x, x>, return <x, x, x, x>
10780 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10781 Level < AfterLegalizeVectorOps &&
10782 (N1.getOpcode() == ISD::UNDEF ||
10783 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10784 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10785 SDValue V = partitionShuffleOfConcats(N, DAG);
10791 // If this shuffle node is simply a swizzle of another shuffle node,
10792 // then try to simplify it.
10793 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10794 N1.getOpcode() == ISD::UNDEF) {
10796 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10798 // The incoming shuffle must be of the same type as the result of the
10799 // current shuffle.
10800 assert(OtherSV->getOperand(0).getValueType() == VT &&
10801 "Shuffle types don't match");
10803 SmallVector<int, 4> Mask;
10804 // Compute the combined shuffle mask.
10805 for (unsigned i = 0; i != NumElts; ++i) {
10806 int Idx = SVN->getMaskElt(i);
10807 assert(Idx < (int)NumElts && "Index references undef operand");
10808 // Next, this index comes from the first value, which is the incoming
10809 // shuffle. Adopt the incoming index.
10811 Idx = OtherSV->getMaskElt(Idx);
10812 Mask.push_back(Idx);
10815 // Check if all indices in Mask are Undef. In case, propagate Undef.
10816 bool isUndefMask = true;
10817 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10818 isUndefMask &= Mask[i] < 0;
10821 return DAG.getUNDEF(VT);
10823 bool CommuteOperands = false;
10824 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10825 // To be valid, the combine shuffle mask should only reference elements
10826 // from one of the two vectors in input to the inner shufflevector.
10827 bool IsValidMask = true;
10828 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10829 // See if the combined mask only reference undefs or elements coming
10830 // from the first shufflevector operand.
10831 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10833 if (!IsValidMask) {
10834 IsValidMask = true;
10835 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10836 // Check that all the elements come from the second shuffle operand.
10837 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10838 CommuteOperands = IsValidMask;
10841 // Early exit if the combined shuffle mask is not valid.
10846 // See if this pair of shuffles can be safely folded according to either
10847 // of the following rules:
10848 // shuffle(shuffle(x, y), undef) -> x
10849 // shuffle(shuffle(x, undef), undef) -> x
10850 // shuffle(shuffle(x, y), undef) -> y
10851 bool IsIdentityMask = true;
10852 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10853 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10858 // The combined shuffle must map each index to itself.
10859 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10862 if (IsIdentityMask) {
10863 if (CommuteOperands)
10864 // optimize shuffle(shuffle(x, y), undef) -> y.
10865 return OtherSV->getOperand(1);
10867 // optimize shuffle(shuffle(x, undef), undef) -> x
10868 // optimize shuffle(shuffle(x, y), undef) -> x
10869 return OtherSV->getOperand(0);
10872 // It may still be beneficial to combine the two shuffles if the
10873 // resulting shuffle is legal.
10874 if (TLI.isTypeLegal(VT)) {
10875 if (!CommuteOperands) {
10876 if (TLI.isShuffleMaskLegal(Mask, VT))
10877 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10878 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10879 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10882 // Compute the commuted shuffle mask.
10883 for (unsigned i = 0; i != NumElts; ++i) {
10887 else if (idx < (int)NumElts)
10888 Mask[i] = idx + NumElts;
10890 Mask[i] = idx - NumElts;
10893 if (TLI.isShuffleMaskLegal(Mask, VT))
10894 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10895 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10901 // Canonicalize shuffles according to rules:
10902 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10903 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10904 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10905 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10906 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10907 TLI.isTypeLegal(VT)) {
10908 // The incoming shuffle must be of the same type as the result of the
10909 // current shuffle.
10910 assert(N1->getOperand(0).getValueType() == VT &&
10911 "Shuffle types don't match");
10913 SDValue SV0 = N1->getOperand(0);
10914 SDValue SV1 = N1->getOperand(1);
10915 bool HasSameOp0 = N0 == SV0;
10916 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10917 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10918 // Commute the operands of this shuffle so that next rule
10920 return DAG.getCommutedVectorShuffle(*SVN);
10923 // Try to fold according to rules:
10924 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10925 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10926 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10927 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10928 // Don't try to fold shuffles with illegal type.
10929 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10930 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10931 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10933 // The incoming shuffle must be of the same type as the result of the
10934 // current shuffle.
10935 assert(OtherSV->getOperand(0).getValueType() == VT &&
10936 "Shuffle types don't match");
10938 SDValue SV0 = OtherSV->getOperand(0);
10939 SDValue SV1 = OtherSV->getOperand(1);
10940 bool HasSameOp0 = N1 == SV0;
10941 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10942 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10946 SmallVector<int, 4> Mask;
10947 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10948 // operand, and SV1 as the second operand.
10949 for (unsigned i = 0; i != NumElts; ++i) {
10950 int Idx = SVN->getMaskElt(i);
10952 // Propagate Undef.
10953 Mask.push_back(Idx);
10957 if (Idx < (int)NumElts) {
10958 Idx = OtherSV->getMaskElt(Idx);
10959 if (IsSV1Undef && Idx >= (int) NumElts)
10960 Idx = -1; // Propagate Undef.
10962 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10964 Mask.push_back(Idx);
10967 // Check if all indices in Mask are Undef. In case, propagate Undef.
10968 bool isUndefMask = true;
10969 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10970 isUndefMask &= Mask[i] < 0;
10973 return DAG.getUNDEF(VT);
10975 // Avoid introducing shuffles with illegal mask.
10976 if (TLI.isShuffleMaskLegal(Mask, VT)) {
10978 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10979 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10980 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10981 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10988 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10989 SDValue N0 = N->getOperand(0);
10990 SDValue N2 = N->getOperand(2);
10992 // If the input vector is a concatenation, and the insert replaces
10993 // one of the halves, we can optimize into a single concat_vectors.
10994 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10995 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10996 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10997 EVT VT = N->getValueType(0);
10999 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11000 // (concat_vectors Z, Y)
11002 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11003 N->getOperand(1), N0.getOperand(1));
11005 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11006 // (concat_vectors X, Z)
11007 if (InsIdx == VT.getVectorNumElements()/2)
11008 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11009 N0.getOperand(0), N->getOperand(1));
11015 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
11016 /// an AND to a vector_shuffle with the destination vector and a zero vector.
11017 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11018 /// vector_shuffle V, Zero, <0, 4, 2, 4>
11019 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11020 EVT VT = N->getValueType(0);
11022 SDValue LHS = N->getOperand(0);
11023 SDValue RHS = N->getOperand(1);
11024 if (N->getOpcode() == ISD::AND) {
11025 if (RHS.getOpcode() == ISD::BITCAST)
11026 RHS = RHS.getOperand(0);
11027 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11028 SmallVector<int, 8> Indices;
11029 unsigned NumElts = RHS.getNumOperands();
11030 for (unsigned i = 0; i != NumElts; ++i) {
11031 SDValue Elt = RHS.getOperand(i);
11032 if (!isa<ConstantSDNode>(Elt))
11035 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11036 Indices.push_back(i);
11037 else if (cast<ConstantSDNode>(Elt)->isNullValue())
11038 Indices.push_back(NumElts);
11043 // Let's see if the target supports this vector_shuffle.
11044 EVT RVT = RHS.getValueType();
11045 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11048 // Return the new VECTOR_SHUFFLE node.
11049 EVT EltVT = RVT.getVectorElementType();
11050 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11051 DAG.getConstant(0, EltVT));
11052 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11053 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11054 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11055 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11062 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
11063 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11064 assert(N->getValueType(0).isVector() &&
11065 "SimplifyVBinOp only works on vectors!");
11067 SDValue LHS = N->getOperand(0);
11068 SDValue RHS = N->getOperand(1);
11069 SDValue Shuffle = XformToShuffleWithZero(N);
11070 if (Shuffle.getNode()) return Shuffle;
11072 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11074 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11075 RHS.getOpcode() == ISD::BUILD_VECTOR) {
11076 // Check if both vectors are constants. If not bail out.
11077 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11078 cast<BuildVectorSDNode>(RHS)->isConstant()))
11081 SmallVector<SDValue, 8> Ops;
11082 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11083 SDValue LHSOp = LHS.getOperand(i);
11084 SDValue RHSOp = RHS.getOperand(i);
11086 // Can't fold divide by zero.
11087 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11088 N->getOpcode() == ISD::FDIV) {
11089 if ((RHSOp.getOpcode() == ISD::Constant &&
11090 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11091 (RHSOp.getOpcode() == ISD::ConstantFP &&
11092 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11096 EVT VT = LHSOp.getValueType();
11097 EVT RVT = RHSOp.getValueType();
11099 // Integer BUILD_VECTOR operands may have types larger than the element
11100 // size (e.g., when the element type is not legal). Prior to type
11101 // legalization, the types may not match between the two BUILD_VECTORS.
11102 // Truncate one of the operands to make them match.
11103 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11104 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11106 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11110 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11112 if (FoldOp.getOpcode() != ISD::UNDEF &&
11113 FoldOp.getOpcode() != ISD::Constant &&
11114 FoldOp.getOpcode() != ISD::ConstantFP)
11116 Ops.push_back(FoldOp);
11117 AddToWorklist(FoldOp.getNode());
11120 if (Ops.size() == LHS.getNumOperands())
11121 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11124 // Type legalization might introduce new shuffles in the DAG.
11125 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11126 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11127 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11128 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11129 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11130 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11131 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11132 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11134 if (SVN0->getMask().equals(SVN1->getMask())) {
11135 EVT VT = N->getValueType(0);
11136 SDValue UndefVector = LHS.getOperand(1);
11137 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11138 LHS.getOperand(0), RHS.getOperand(0));
11139 AddUsersToWorklist(N);
11140 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11141 &SVN0->getMask()[0]);
11148 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11149 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11150 assert(N->getValueType(0).isVector() &&
11151 "SimplifyVUnaryOp only works on vectors!");
11153 SDValue N0 = N->getOperand(0);
11155 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11158 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11159 SmallVector<SDValue, 8> Ops;
11160 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11161 SDValue Op = N0.getOperand(i);
11162 if (Op.getOpcode() != ISD::UNDEF &&
11163 Op.getOpcode() != ISD::ConstantFP)
11165 EVT EltVT = Op.getValueType();
11166 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11167 if (FoldOp.getOpcode() != ISD::UNDEF &&
11168 FoldOp.getOpcode() != ISD::ConstantFP)
11170 Ops.push_back(FoldOp);
11171 AddToWorklist(FoldOp.getNode());
11174 if (Ops.size() != N0.getNumOperands())
11177 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11180 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11181 SDValue N1, SDValue N2){
11182 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11184 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11185 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11187 // If we got a simplified select_cc node back from SimplifySelectCC, then
11188 // break it down into a new SETCC node, and a new SELECT node, and then return
11189 // the SELECT node, since we were called with a SELECT node.
11190 if (SCC.getNode()) {
11191 // Check to see if we got a select_cc back (to turn into setcc/select).
11192 // Otherwise, just return whatever node we got back, like fabs.
11193 if (SCC.getOpcode() == ISD::SELECT_CC) {
11194 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11196 SCC.getOperand(0), SCC.getOperand(1),
11197 SCC.getOperand(4));
11198 AddToWorklist(SETCC.getNode());
11199 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11200 SCC.getOperand(2), SCC.getOperand(3));
11208 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11209 /// are the two values being selected between, see if we can simplify the
11210 /// select. Callers of this should assume that TheSelect is deleted if this
11211 /// returns true. As such, they should return the appropriate thing (e.g. the
11212 /// node) back to the top-level of the DAG combiner loop to avoid it being
11214 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11217 // Cannot simplify select with vector condition
11218 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11220 // If this is a select from two identical things, try to pull the operation
11221 // through the select.
11222 if (LHS.getOpcode() != RHS.getOpcode() ||
11223 !LHS.hasOneUse() || !RHS.hasOneUse())
11226 // If this is a load and the token chain is identical, replace the select
11227 // of two loads with a load through a select of the address to load from.
11228 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11229 // constants have been dropped into the constant pool.
11230 if (LHS.getOpcode() == ISD::LOAD) {
11231 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11232 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11234 // Token chains must be identical.
11235 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11236 // Do not let this transformation reduce the number of volatile loads.
11237 LLD->isVolatile() || RLD->isVolatile() ||
11238 // If this is an EXTLOAD, the VT's must match.
11239 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11240 // If this is an EXTLOAD, the kind of extension must match.
11241 (LLD->getExtensionType() != RLD->getExtensionType() &&
11242 // The only exception is if one of the extensions is anyext.
11243 LLD->getExtensionType() != ISD::EXTLOAD &&
11244 RLD->getExtensionType() != ISD::EXTLOAD) ||
11245 // FIXME: this discards src value information. This is
11246 // over-conservative. It would be beneficial to be able to remember
11247 // both potential memory locations. Since we are discarding
11248 // src value info, don't do the transformation if the memory
11249 // locations are not in the default address space.
11250 LLD->getPointerInfo().getAddrSpace() != 0 ||
11251 RLD->getPointerInfo().getAddrSpace() != 0 ||
11252 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11253 LLD->getBasePtr().getValueType()))
11256 // Check that the select condition doesn't reach either load. If so,
11257 // folding this will induce a cycle into the DAG. If not, this is safe to
11258 // xform, so create a select of the addresses.
11260 if (TheSelect->getOpcode() == ISD::SELECT) {
11261 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11262 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11263 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11265 // The loads must not depend on one another.
11266 if (LLD->isPredecessorOf(RLD) ||
11267 RLD->isPredecessorOf(LLD))
11269 Addr = DAG.getSelect(SDLoc(TheSelect),
11270 LLD->getBasePtr().getValueType(),
11271 TheSelect->getOperand(0), LLD->getBasePtr(),
11272 RLD->getBasePtr());
11273 } else { // Otherwise SELECT_CC
11274 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11275 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11277 if ((LLD->hasAnyUseOfValue(1) &&
11278 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11279 (RLD->hasAnyUseOfValue(1) &&
11280 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11283 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11284 LLD->getBasePtr().getValueType(),
11285 TheSelect->getOperand(0),
11286 TheSelect->getOperand(1),
11287 LLD->getBasePtr(), RLD->getBasePtr(),
11288 TheSelect->getOperand(4));
11292 // It is safe to replace the two loads if they have different alignments,
11293 // but the new load must be the minimum (most restrictive) alignment of the
11295 bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11296 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11297 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11298 Load = DAG.getLoad(TheSelect->getValueType(0),
11300 // FIXME: Discards pointer and AA info.
11301 LLD->getChain(), Addr, MachinePointerInfo(),
11302 LLD->isVolatile(), LLD->isNonTemporal(),
11303 isInvariant, Alignment);
11305 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11306 RLD->getExtensionType() : LLD->getExtensionType(),
11308 TheSelect->getValueType(0),
11309 // FIXME: Discards pointer and AA info.
11310 LLD->getChain(), Addr, MachinePointerInfo(),
11311 LLD->getMemoryVT(), LLD->isVolatile(),
11312 LLD->isNonTemporal(), isInvariant, Alignment);
11315 // Users of the select now use the result of the load.
11316 CombineTo(TheSelect, Load);
11318 // Users of the old loads now use the new load's chain. We know the
11319 // old-load value is dead now.
11320 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11321 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11328 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11329 /// where 'cond' is the comparison specified by CC.
11330 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11331 SDValue N2, SDValue N3,
11332 ISD::CondCode CC, bool NotExtCompare) {
11333 // (x ? y : y) -> y.
11334 if (N2 == N3) return N2;
11336 EVT VT = N2.getValueType();
11337 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11338 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11339 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11341 // Determine if the condition we're dealing with is constant
11342 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11343 N0, N1, CC, DL, false);
11344 if (SCC.getNode()) AddToWorklist(SCC.getNode());
11345 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11347 // fold select_cc true, x, y -> x
11348 if (SCCC && !SCCC->isNullValue())
11350 // fold select_cc false, x, y -> y
11351 if (SCCC && SCCC->isNullValue())
11354 // Check to see if we can simplify the select into an fabs node
11355 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11356 // Allow either -0.0 or 0.0
11357 if (CFP->getValueAPF().isZero()) {
11358 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11359 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11360 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11361 N2 == N3.getOperand(0))
11362 return DAG.getNode(ISD::FABS, DL, VT, N0);
11364 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11365 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11366 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11367 N2.getOperand(0) == N3)
11368 return DAG.getNode(ISD::FABS, DL, VT, N3);
11372 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11373 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11374 // in it. This is a win when the constant is not otherwise available because
11375 // it replaces two constant pool loads with one. We only do this if the FP
11376 // type is known to be legal, because if it isn't, then we are before legalize
11377 // types an we want the other legalization to happen first (e.g. to avoid
11378 // messing with soft float) and if the ConstantFP is not legal, because if
11379 // it is legal, we may not need to store the FP constant in a constant pool.
11380 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11381 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11382 if (TLI.isTypeLegal(N2.getValueType()) &&
11383 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11384 TargetLowering::Legal &&
11385 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11386 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11387 // If both constants have multiple uses, then we won't need to do an
11388 // extra load, they are likely around in registers for other users.
11389 (TV->hasOneUse() || FV->hasOneUse())) {
11390 Constant *Elts[] = {
11391 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11392 const_cast<ConstantFP*>(TV->getConstantFPValue())
11394 Type *FPTy = Elts[0]->getType();
11395 const DataLayout &TD = *TLI.getDataLayout();
11397 // Create a ConstantArray of the two constants.
11398 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11399 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11400 TD.getPrefTypeAlignment(FPTy));
11401 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11403 // Get the offsets to the 0 and 1 element of the array so that we can
11404 // select between them.
11405 SDValue Zero = DAG.getIntPtrConstant(0);
11406 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11407 SDValue One = DAG.getIntPtrConstant(EltSize);
11409 SDValue Cond = DAG.getSetCC(DL,
11410 getSetCCResultType(N0.getValueType()),
11412 AddToWorklist(Cond.getNode());
11413 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11415 AddToWorklist(CstOffset.getNode());
11416 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11418 AddToWorklist(CPIdx.getNode());
11419 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11420 MachinePointerInfo::getConstantPool(), false,
11421 false, false, Alignment);
11426 // Check to see if we can perform the "gzip trick", transforming
11427 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11428 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11429 (N1C->isNullValue() || // (a < 0) ? b : 0
11430 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11431 EVT XType = N0.getValueType();
11432 EVT AType = N2.getValueType();
11433 if (XType.bitsGE(AType)) {
11434 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11435 // single-bit constant.
11436 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11437 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11438 ShCtV = XType.getSizeInBits()-ShCtV-1;
11439 SDValue ShCt = DAG.getConstant(ShCtV,
11440 getShiftAmountTy(N0.getValueType()));
11441 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11443 AddToWorklist(Shift.getNode());
11445 if (XType.bitsGT(AType)) {
11446 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11447 AddToWorklist(Shift.getNode());
11450 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11453 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11455 DAG.getConstant(XType.getSizeInBits()-1,
11456 getShiftAmountTy(N0.getValueType())));
11457 AddToWorklist(Shift.getNode());
11459 if (XType.bitsGT(AType)) {
11460 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11461 AddToWorklist(Shift.getNode());
11464 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11468 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11469 // where y is has a single bit set.
11470 // A plaintext description would be, we can turn the SELECT_CC into an AND
11471 // when the condition can be materialized as an all-ones register. Any
11472 // single bit-test can be materialized as an all-ones register with
11473 // shift-left and shift-right-arith.
11474 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11475 N0->getValueType(0) == VT &&
11476 N1C && N1C->isNullValue() &&
11477 N2C && N2C->isNullValue()) {
11478 SDValue AndLHS = N0->getOperand(0);
11479 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11480 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11481 // Shift the tested bit over the sign bit.
11482 APInt AndMask = ConstAndRHS->getAPIntValue();
11484 DAG.getConstant(AndMask.countLeadingZeros(),
11485 getShiftAmountTy(AndLHS.getValueType()));
11486 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11488 // Now arithmetic right shift it all the way over, so the result is either
11489 // all-ones, or zero.
11491 DAG.getConstant(AndMask.getBitWidth()-1,
11492 getShiftAmountTy(Shl.getValueType()));
11493 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11495 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11499 // fold select C, 16, 0 -> shl C, 4
11500 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11501 TLI.getBooleanContents(N0.getValueType()) ==
11502 TargetLowering::ZeroOrOneBooleanContent) {
11504 // If the caller doesn't want us to simplify this into a zext of a compare,
11506 if (NotExtCompare && N2C->getAPIntValue() == 1)
11509 // Get a SetCC of the condition
11510 // NOTE: Don't create a SETCC if it's not legal on this target.
11511 if (!LegalOperations ||
11512 TLI.isOperationLegal(ISD::SETCC,
11513 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11515 // cast from setcc result type to select result type
11517 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11519 if (N2.getValueType().bitsLT(SCC.getValueType()))
11520 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11521 N2.getValueType());
11523 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11524 N2.getValueType(), SCC);
11526 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11527 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11528 N2.getValueType(), SCC);
11531 AddToWorklist(SCC.getNode());
11532 AddToWorklist(Temp.getNode());
11534 if (N2C->getAPIntValue() == 1)
11537 // shl setcc result by log2 n2c
11538 return DAG.getNode(
11539 ISD::SHL, DL, N2.getValueType(), Temp,
11540 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11541 getShiftAmountTy(Temp.getValueType())));
11545 // Check to see if this is the equivalent of setcc
11546 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11547 // otherwise, go ahead with the folds.
11548 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11549 EVT XType = N0.getValueType();
11550 if (!LegalOperations ||
11551 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11552 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11553 if (Res.getValueType() != VT)
11554 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11558 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11559 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11560 (!LegalOperations ||
11561 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11562 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11563 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11564 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11565 getShiftAmountTy(Ctlz.getValueType())));
11567 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11568 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11569 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11570 XType, DAG.getConstant(0, XType), N0);
11571 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11572 return DAG.getNode(ISD::SRL, DL, XType,
11573 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11574 DAG.getConstant(XType.getSizeInBits()-1,
11575 getShiftAmountTy(XType)));
11577 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11578 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11579 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11580 DAG.getConstant(XType.getSizeInBits()-1,
11581 getShiftAmountTy(N0.getValueType())));
11582 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11586 // Check to see if this is an integer abs.
11587 // select_cc setg[te] X, 0, X, -X ->
11588 // select_cc setgt X, -1, X, -X ->
11589 // select_cc setl[te] X, 0, -X, X ->
11590 // select_cc setlt X, 1, -X, X ->
11591 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11593 ConstantSDNode *SubC = nullptr;
11594 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11595 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11596 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11597 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11598 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11599 (N1C->isOne() && CC == ISD::SETLT)) &&
11600 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11601 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11603 EVT XType = N0.getValueType();
11604 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11605 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11607 DAG.getConstant(XType.getSizeInBits()-1,
11608 getShiftAmountTy(N0.getValueType())));
11609 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11611 AddToWorklist(Shift.getNode());
11612 AddToWorklist(Add.getNode());
11613 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11620 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11621 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11622 SDValue N1, ISD::CondCode Cond,
11623 SDLoc DL, bool foldBooleans) {
11624 TargetLowering::DAGCombinerInfo
11625 DagCombineInfo(DAG, Level, false, this);
11626 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11629 /// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11630 /// a DAG expression to select that will generate the same value by multiplying
11631 /// by a magic number. See:
11632 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11633 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11634 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11638 // Avoid division by zero.
11639 if (!C->getAPIntValue())
11642 std::vector<SDNode*> Built;
11644 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11646 for (SDNode *N : Built)
11651 /// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11652 /// power of 2, return a DAG expression to select that will generate the same
11653 /// value by right shifting.
11654 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11655 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11659 // Avoid division by zero.
11660 if (!C->getAPIntValue())
11663 std::vector<SDNode *> Built;
11664 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11666 for (SDNode *N : Built)
11671 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11672 /// return a DAG expression to select that will generate the same value by
11673 /// multiplying by a magic number. See:
11674 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11675 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11676 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11680 // Avoid division by zero.
11681 if (!C->getAPIntValue())
11684 std::vector<SDNode*> Built;
11686 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11688 for (SDNode *N : Built)
11693 /// FindBaseOffset - Return true if base is a frame index, which is known not
11694 // to alias with anything but itself. Provides base object and offset as
11696 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11697 const GlobalValue *&GV, const void *&CV) {
11698 // Assume it is a primitive operation.
11699 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11701 // If it's an adding a simple constant then integrate the offset.
11702 if (Base.getOpcode() == ISD::ADD) {
11703 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11704 Base = Base.getOperand(0);
11705 Offset += C->getZExtValue();
11709 // Return the underlying GlobalValue, and update the Offset. Return false
11710 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11711 // by multiple nodes with different offsets.
11712 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11713 GV = G->getGlobal();
11714 Offset += G->getOffset();
11718 // Return the underlying Constant value, and update the Offset. Return false
11719 // for ConstantSDNodes since the same constant pool entry may be represented
11720 // by multiple nodes with different offsets.
11721 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11722 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11723 : (const void *)C->getConstVal();
11724 Offset += C->getOffset();
11727 // If it's any of the following then it can't alias with anything but itself.
11728 return isa<FrameIndexSDNode>(Base);
11731 /// isAlias - Return true if there is any possibility that the two addresses
11733 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11734 // If they are the same then they must be aliases.
11735 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11737 // If they are both volatile then they cannot be reordered.
11738 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11740 // Gather base node and offset information.
11741 SDValue Base1, Base2;
11742 int64_t Offset1, Offset2;
11743 const GlobalValue *GV1, *GV2;
11744 const void *CV1, *CV2;
11745 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11746 Base1, Offset1, GV1, CV1);
11747 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11748 Base2, Offset2, GV2, CV2);
11750 // If they have a same base address then check to see if they overlap.
11751 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11752 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11753 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11755 // It is possible for different frame indices to alias each other, mostly
11756 // when tail call optimization reuses return address slots for arguments.
11757 // To catch this case, look up the actual index of frame indices to compute
11758 // the real alias relationship.
11759 if (isFrameIndex1 && isFrameIndex2) {
11760 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11761 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11762 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11763 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11764 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11767 // Otherwise, if we know what the bases are, and they aren't identical, then
11768 // we know they cannot alias.
11769 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11772 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11773 // compared to the size and offset of the access, we may be able to prove they
11774 // do not alias. This check is conservative for now to catch cases created by
11775 // splitting vector types.
11776 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11777 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11778 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11779 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11780 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11781 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11782 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11784 // There is no overlap between these relatively aligned accesses of similar
11785 // size, return no alias.
11786 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11787 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11791 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11792 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11794 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11795 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11799 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11800 // Use alias analysis information.
11801 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11802 Op1->getSrcValueOffset());
11803 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11804 Op0->getSrcValueOffset() - MinOffset;
11805 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11806 Op1->getSrcValueOffset() - MinOffset;
11807 AliasAnalysis::AliasResult AAResult =
11808 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11810 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11811 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11813 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11814 if (AAResult == AliasAnalysis::NoAlias)
11818 // Otherwise we have to assume they alias.
11822 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11823 /// looking for aliasing nodes and adding them to the Aliases vector.
11824 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11825 SmallVectorImpl<SDValue> &Aliases) {
11826 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11827 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11829 // Get alias information for node.
11830 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11833 Chains.push_back(OriginalChain);
11834 unsigned Depth = 0;
11836 // Look at each chain and determine if it is an alias. If so, add it to the
11837 // aliases list. If not, then continue up the chain looking for the next
11839 while (!Chains.empty()) {
11840 SDValue Chain = Chains.back();
11843 // For TokenFactor nodes, look at each operand and only continue up the
11844 // chain until we find two aliases. If we've seen two aliases, assume we'll
11845 // find more and revert to original chain since the xform is unlikely to be
11848 // FIXME: The depth check could be made to return the last non-aliasing
11849 // chain we found before we hit a tokenfactor rather than the original
11851 if (Depth > 6 || Aliases.size() == 2) {
11853 Aliases.push_back(OriginalChain);
11857 // Don't bother if we've been before.
11858 if (!Visited.insert(Chain.getNode()))
11861 switch (Chain.getOpcode()) {
11862 case ISD::EntryToken:
11863 // Entry token is ideal chain operand, but handled in FindBetterChain.
11868 // Get alias information for Chain.
11869 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11870 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11872 // If chain is alias then stop here.
11873 if (!(IsLoad && IsOpLoad) &&
11874 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11875 Aliases.push_back(Chain);
11877 // Look further up the chain.
11878 Chains.push_back(Chain.getOperand(0));
11884 case ISD::TokenFactor:
11885 // We have to check each of the operands of the token factor for "small"
11886 // token factors, so we queue them up. Adding the operands to the queue
11887 // (stack) in reverse order maintains the original order and increases the
11888 // likelihood that getNode will find a matching token factor (CSE.)
11889 if (Chain.getNumOperands() > 16) {
11890 Aliases.push_back(Chain);
11893 for (unsigned n = Chain.getNumOperands(); n;)
11894 Chains.push_back(Chain.getOperand(--n));
11899 // For all other instructions we will just have to take what we can get.
11900 Aliases.push_back(Chain);
11905 // We need to be careful here to also search for aliases through the
11906 // value operand of a store, etc. Consider the following situation:
11908 // L1 = load Token1, %52
11909 // S1 = store Token1, L1, %51
11910 // L2 = load Token1, %52+8
11911 // S2 = store Token1, L2, %51+8
11912 // Token2 = Token(S1, S2)
11913 // L3 = load Token2, %53
11914 // S3 = store Token2, L3, %52
11915 // L4 = load Token2, %53+8
11916 // S4 = store Token2, L4, %52+8
11917 // If we search for aliases of S3 (which loads address %52), and we look
11918 // only through the chain, then we'll miss the trivial dependence on L1
11919 // (which also loads from %52). We then might change all loads and
11920 // stores to use Token1 as their chain operand, which could result in
11921 // copying %53 into %52 before copying %52 into %51 (which should
11924 // The problem is, however, that searching for such data dependencies
11925 // can become expensive, and the cost is not directly related to the
11926 // chain depth. Instead, we'll rule out such configurations here by
11927 // insisting that we've visited all chain users (except for users
11928 // of the original chain, which is not necessary). When doing this,
11929 // we need to look through nodes we don't care about (otherwise, things
11930 // like register copies will interfere with trivial cases).
11932 SmallVector<const SDNode *, 16> Worklist;
11933 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11934 IE = Visited.end(); I != IE; ++I)
11935 if (*I != OriginalChain.getNode())
11936 Worklist.push_back(*I);
11938 while (!Worklist.empty()) {
11939 const SDNode *M = Worklist.pop_back_val();
11941 // We have already visited M, and want to make sure we've visited any uses
11942 // of M that we care about. For uses that we've not visisted, and don't
11943 // care about, queue them to the worklist.
11945 for (SDNode::use_iterator UI = M->use_begin(),
11946 UIE = M->use_end(); UI != UIE; ++UI)
11947 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11948 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11949 // We've not visited this use, and we care about it (it could have an
11950 // ordering dependency with the original node).
11952 Aliases.push_back(OriginalChain);
11956 // We've not visited this use, but we don't care about it. Mark it as
11957 // visited and enqueue it to the worklist.
11958 Worklist.push_back(*UI);
11963 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11964 /// for a better chain (aliasing node.)
11965 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11966 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11968 // Accumulate all the aliases to this node.
11969 GatherAllAliases(N, OldChain, Aliases);
11971 // If no operands then chain to entry token.
11972 if (Aliases.size() == 0)
11973 return DAG.getEntryNode();
11975 // If a single operand then chain to it. We don't need to revisit it.
11976 if (Aliases.size() == 1)
11979 // Construct a custom tailored token factor.
11980 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11983 // SelectionDAG::Combine - This is the entry point for the file.
11985 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11986 CodeGenOpt::Level OptLevel) {
11987 /// run - This is the main entry point to this class.
11989 DAGCombiner(*this, AA, OptLevel).Run(Level);