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/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.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 "
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 /// \brief Worklist of all of the nodes that need to be simplified.
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
104 /// \brief Mapping from an SDNode to its position on the worklist.
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
111 /// \brief Set of nodes which have been combined (at least once).
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
117 // AA - Used for DAG load/store alias analysis.
120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
122 void AddUsersToWorklist(SDNode *N) {
123 for (SDNode *Node : N->uses())
127 /// Call the node-specific routine that folds each particular type of node.
128 SDValue visit(SDNode *N);
131 /// Add to the worklist making sure its instance is at the back (next to be
133 void AddToWorklist(SDNode *N) {
134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
143 /// 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 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// 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 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190 bool SliceUpLoad(SDNode *N);
192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue PromoteIntBinOp(SDValue Op);
207 SDValue PromoteIntShiftOp(SDValue Op);
208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213 ISD::NodeType ExtType);
215 /// Call the node-specific routine that knows how to fold each
216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
218 SDValue combine(SDNode *N);
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
232 SDValue visitSUBC(SDNode *N);
233 SDValue visitADDE(SDNode *N);
234 SDValue visitSUBE(SDNode *N);
235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
249 SDValue visitOR(SDNode *N);
250 SDValue visitXOR(SDNode *N);
251 SDValue SimplifyVBinOp(SDNode *N);
252 SDValue SimplifyVUnaryOp(SDNode *N);
253 SDValue visitSHL(SDNode *N);
254 SDValue visitSRA(SDNode *N);
255 SDValue visitSRL(SDNode *N);
256 SDValue visitRotate(SDNode *N);
257 SDValue visitCTLZ(SDNode *N);
258 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
259 SDValue visitCTTZ(SDNode *N);
260 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
261 SDValue visitCTPOP(SDNode *N);
262 SDValue visitSELECT(SDNode *N);
263 SDValue visitVSELECT(SDNode *N);
264 SDValue visitSELECT_CC(SDNode *N);
265 SDValue visitSETCC(SDNode *N);
266 SDValue visitSIGN_EXTEND(SDNode *N);
267 SDValue visitZERO_EXTEND(SDNode *N);
268 SDValue visitANY_EXTEND(SDNode *N);
269 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270 SDValue visitTRUNCATE(SDNode *N);
271 SDValue visitBITCAST(SDNode *N);
272 SDValue visitBUILD_PAIR(SDNode *N);
273 SDValue visitFADD(SDNode *N);
274 SDValue visitFSUB(SDNode *N);
275 SDValue visitFMUL(SDNode *N);
276 SDValue visitFMA(SDNode *N);
277 SDValue visitFDIV(SDNode *N);
278 SDValue visitFREM(SDNode *N);
279 SDValue visitFSQRT(SDNode *N);
280 SDValue visitFCOPYSIGN(SDNode *N);
281 SDValue visitSINT_TO_FP(SDNode *N);
282 SDValue visitUINT_TO_FP(SDNode *N);
283 SDValue visitFP_TO_SINT(SDNode *N);
284 SDValue visitFP_TO_UINT(SDNode *N);
285 SDValue visitFP_ROUND(SDNode *N);
286 SDValue visitFP_ROUND_INREG(SDNode *N);
287 SDValue visitFP_EXTEND(SDNode *N);
288 SDValue visitFNEG(SDNode *N);
289 SDValue visitFABS(SDNode *N);
290 SDValue visitFCEIL(SDNode *N);
291 SDValue visitFTRUNC(SDNode *N);
292 SDValue visitFFLOOR(SDNode *N);
293 SDValue visitFMINNUM(SDNode *N);
294 SDValue visitFMAXNUM(SDNode *N);
295 SDValue visitBRCOND(SDNode *N);
296 SDValue visitBR_CC(SDNode *N);
297 SDValue visitLOAD(SDNode *N);
298 SDValue visitSTORE(SDNode *N);
299 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
300 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
301 SDValue visitBUILD_VECTOR(SDNode *N);
302 SDValue visitCONCAT_VECTORS(SDNode *N);
303 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
304 SDValue visitVECTOR_SHUFFLE(SDNode *N);
305 SDValue visitINSERT_SUBVECTOR(SDNode *N);
306 SDValue visitMLOAD(SDNode *N);
307 SDValue visitMSTORE(SDNode *N);
309 SDValue XformToShuffleWithZero(SDNode *N);
310 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
312 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
314 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
315 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
316 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
317 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
318 SDValue N3, ISD::CondCode CC,
319 bool NotExtCompare = false);
320 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
321 SDLoc DL, bool foldBooleans = true);
323 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
325 bool isOneUseSetCC(SDValue N) const;
327 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
329 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
330 SDValue CombineExtLoad(SDNode *N);
331 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
332 SDValue BuildSDIV(SDNode *N);
333 SDValue BuildSDIVPow2(SDNode *N);
334 SDValue BuildUDIV(SDNode *N);
335 SDValue BuildReciprocalEstimate(SDValue Op);
336 SDValue BuildRsqrtEstimate(SDValue Op);
337 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
338 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
339 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
340 bool DemandHighBits = true);
341 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
342 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
343 SDValue InnerPos, SDValue InnerNeg,
344 unsigned PosOpcode, unsigned NegOpcode,
346 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
347 SDValue ReduceLoadWidth(SDNode *N);
348 SDValue ReduceLoadOpStoreWidth(SDNode *N);
349 SDValue TransformFPLoadStorePair(SDNode *N);
350 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
351 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
353 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
355 /// Walk up chain skipping non-aliasing memory nodes,
356 /// looking for aliasing nodes and adding them to the Aliases vector.
357 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
358 SmallVectorImpl<SDValue> &Aliases);
360 /// Return true if there is any possibility that the two addresses overlap.
361 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
363 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
364 /// chain (aliasing node.)
365 SDValue FindBetterChain(SDNode *N, SDValue Chain);
367 /// Holds a pointer to an LSBaseSDNode as well as information on where it
368 /// is located in a sequence of memory operations connected by a chain.
370 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
371 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
372 // Ptr to the mem node.
373 LSBaseSDNode *MemNode;
374 // Offset from the base ptr.
375 int64_t OffsetFromBase;
376 // What is the sequence number of this mem node.
377 // Lowest mem operand in the DAG starts at zero.
378 unsigned SequenceNum;
381 /// This is a helper function for MergeConsecutiveStores. When the source
382 /// elements of the consecutive stores are all constants or all extracted
383 /// vector elements, try to merge them into one larger store.
384 /// \return True if a merged store was created.
385 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
386 EVT MemVT, unsigned NumElem,
387 bool IsConstantSrc, bool UseVector);
389 /// Merge consecutive store operations into a wide store.
390 /// This optimization uses wide integers or vectors when possible.
391 /// \return True if some memory operations were changed.
392 bool MergeConsecutiveStores(StoreSDNode *N);
394 /// \brief Try to transform a truncation where C is a constant:
395 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
397 /// \p N needs to be a truncation and its first operand an AND. Other
398 /// requirements are checked by the function (e.g. that trunc is
399 /// single-use) and if missed an empty SDValue is returned.
400 SDValue distributeTruncateThroughAnd(SDNode *N);
403 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
404 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
405 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
406 AttributeSet FnAttrs =
407 DAG.getMachineFunction().getFunction()->getAttributes();
409 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
410 Attribute::OptimizeForSize) ||
411 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
414 /// Runs the dag combiner on all nodes in the work list
415 void Run(CombineLevel AtLevel);
417 SelectionDAG &getDAG() const { return DAG; }
419 /// Returns a type large enough to hold any valid shift amount - before type
420 /// legalization these can be huge.
421 EVT getShiftAmountTy(EVT LHSTy) {
422 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
423 if (LHSTy.isVector())
425 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
426 : TLI.getPointerTy();
429 /// This method returns true if we are running before type legalization or
430 /// if the specified VT is legal.
431 bool isTypeLegal(const EVT &VT) {
432 if (!LegalTypes) return true;
433 return TLI.isTypeLegal(VT);
436 /// Convenience wrapper around TargetLowering::getSetCCResultType
437 EVT getSetCCResultType(EVT VT) const {
438 return TLI.getSetCCResultType(*DAG.getContext(), VT);
445 /// This class is a DAGUpdateListener that removes any deleted
446 /// nodes from the worklist.
447 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
450 explicit WorklistRemover(DAGCombiner &dc)
451 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
453 void NodeDeleted(SDNode *N, SDNode *E) override {
454 DC.removeFromWorklist(N);
459 //===----------------------------------------------------------------------===//
460 // TargetLowering::DAGCombinerInfo implementation
461 //===----------------------------------------------------------------------===//
463 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
464 ((DAGCombiner*)DC)->AddToWorklist(N);
467 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
468 ((DAGCombiner*)DC)->removeFromWorklist(N);
471 SDValue TargetLowering::DAGCombinerInfo::
472 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
473 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
476 SDValue TargetLowering::DAGCombinerInfo::
477 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
478 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
482 SDValue TargetLowering::DAGCombinerInfo::
483 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
484 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
487 void TargetLowering::DAGCombinerInfo::
488 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
489 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
492 //===----------------------------------------------------------------------===//
494 //===----------------------------------------------------------------------===//
496 void DAGCombiner::deleteAndRecombine(SDNode *N) {
497 removeFromWorklist(N);
499 // If the operands of this node are only used by the node, they will now be
500 // dead. Make sure to re-visit them and recursively delete dead nodes.
501 for (const SDValue &Op : N->ops())
502 // For an operand generating multiple values, one of the values may
503 // become dead allowing further simplification (e.g. split index
504 // arithmetic from an indexed load).
505 if (Op->hasOneUse() || Op->getNumValues() > 1)
506 AddToWorklist(Op.getNode());
511 /// Return 1 if we can compute the negated form of the specified expression for
512 /// the same cost as the expression itself, or 2 if we can compute the negated
513 /// form more cheaply than the expression itself.
514 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
515 const TargetLowering &TLI,
516 const TargetOptions *Options,
517 unsigned Depth = 0) {
518 // fneg is removable even if it has multiple uses.
519 if (Op.getOpcode() == ISD::FNEG) return 2;
521 // Don't allow anything with multiple uses.
522 if (!Op.hasOneUse()) return 0;
524 // Don't recurse exponentially.
525 if (Depth > 6) return 0;
527 switch (Op.getOpcode()) {
528 default: return false;
529 case ISD::ConstantFP:
530 // Don't invert constant FP values after legalize. The negated constant
531 // isn't necessarily legal.
532 return LegalOperations ? 0 : 1;
534 // FIXME: determine better conditions for this xform.
535 if (!Options->UnsafeFPMath) return 0;
537 // After operation legalization, it might not be legal to create new FSUBs.
538 if (LegalOperations &&
539 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
542 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
543 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
546 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
547 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
550 // We can't turn -(A-B) into B-A when we honor signed zeros.
551 if (!Options->UnsafeFPMath) return 0;
553 // fold (fneg (fsub A, B)) -> (fsub B, A)
558 if (Options->HonorSignDependentRoundingFPMath()) return 0;
560 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
561 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
565 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
571 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
576 /// If isNegatibleForFree returns true, return the newly negated expression.
577 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
578 bool LegalOperations, unsigned Depth = 0) {
579 const TargetOptions &Options = DAG.getTarget().Options;
580 // fneg is removable even if it has multiple uses.
581 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
583 // Don't allow anything with multiple uses.
584 assert(Op.hasOneUse() && "Unknown reuse!");
586 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
587 switch (Op.getOpcode()) {
588 default: llvm_unreachable("Unknown code");
589 case ISD::ConstantFP: {
590 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
592 return DAG.getConstantFP(V, Op.getValueType());
595 // FIXME: determine better conditions for this xform.
596 assert(Options.UnsafeFPMath);
598 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
599 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
600 DAG.getTargetLoweringInfo(), &Options, Depth+1))
601 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
602 GetNegatedExpression(Op.getOperand(0), DAG,
603 LegalOperations, Depth+1),
605 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
606 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
607 GetNegatedExpression(Op.getOperand(1), DAG,
608 LegalOperations, Depth+1),
611 // We can't turn -(A-B) into B-A when we honor signed zeros.
612 assert(Options.UnsafeFPMath);
614 // fold (fneg (fsub 0, B)) -> B
615 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
616 if (N0CFP->getValueAPF().isZero())
617 return Op.getOperand(1);
619 // fold (fneg (fsub A, B)) -> (fsub B, A)
620 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
621 Op.getOperand(1), Op.getOperand(0));
625 assert(!Options.HonorSignDependentRoundingFPMath());
627 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
628 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
629 DAG.getTargetLoweringInfo(), &Options, Depth+1))
630 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
631 GetNegatedExpression(Op.getOperand(0), DAG,
632 LegalOperations, Depth+1),
635 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
636 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
638 GetNegatedExpression(Op.getOperand(1), DAG,
639 LegalOperations, Depth+1));
643 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
644 GetNegatedExpression(Op.getOperand(0), DAG,
645 LegalOperations, Depth+1));
647 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
648 GetNegatedExpression(Op.getOperand(0), DAG,
649 LegalOperations, Depth+1),
654 // Return true if this node is a setcc, or is a select_cc
655 // that selects between the target values used for true and false, making it
656 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
657 // the appropriate nodes based on the type of node we are checking. This
658 // simplifies life a bit for the callers.
659 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
661 if (N.getOpcode() == ISD::SETCC) {
662 LHS = N.getOperand(0);
663 RHS = N.getOperand(1);
664 CC = N.getOperand(2);
668 if (N.getOpcode() != ISD::SELECT_CC ||
669 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
670 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
673 if (TLI.getBooleanContents(N.getValueType()) ==
674 TargetLowering::UndefinedBooleanContent)
677 LHS = N.getOperand(0);
678 RHS = N.getOperand(1);
679 CC = N.getOperand(4);
683 /// Return true if this is a SetCC-equivalent operation with only one use.
684 /// If this is true, it allows the users to invert the operation for free when
685 /// it is profitable to do so.
686 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
688 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
693 /// Returns true if N is a BUILD_VECTOR node whose
694 /// elements are all the same constant or undefined.
695 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
696 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
701 unsigned SplatBitSize;
703 EVT EltVT = N->getValueType(0).getVectorElementType();
704 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
706 EltVT.getSizeInBits() >= SplatBitSize);
709 // \brief Returns the SDNode if it is a constant BuildVector or constant.
710 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
711 if (isa<ConstantSDNode>(N))
713 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
714 if (BV && BV->isConstant())
719 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
721 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
722 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
725 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
726 BitVector UndefElements;
727 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
729 // BuildVectors can truncate their operands. Ignore that case here.
730 // FIXME: We blindly ignore splats which include undef which is overly
732 if (CN && UndefElements.none() &&
733 CN->getValueType(0) == N.getValueType().getScalarType())
740 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
742 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
743 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
746 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
747 BitVector UndefElements;
748 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
750 if (CN && UndefElements.none())
757 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
758 SDValue N0, SDValue N1) {
759 EVT VT = N0.getValueType();
760 if (N0.getOpcode() == Opc) {
761 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
762 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
763 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
764 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
765 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
768 if (N0.hasOneUse()) {
769 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
771 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
772 if (!OpNode.getNode())
774 AddToWorklist(OpNode.getNode());
775 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
780 if (N1.getOpcode() == Opc) {
781 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
782 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
783 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
784 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
785 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
788 if (N1.hasOneUse()) {
789 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
791 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
792 if (!OpNode.getNode())
794 AddToWorklist(OpNode.getNode());
795 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
803 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
805 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
807 DEBUG(dbgs() << "\nReplacing.1 ";
809 dbgs() << "\nWith: ";
810 To[0].getNode()->dump(&DAG);
811 dbgs() << " and " << NumTo-1 << " other values\n");
812 for (unsigned i = 0, e = NumTo; i != e; ++i)
813 assert((!To[i].getNode() ||
814 N->getValueType(i) == To[i].getValueType()) &&
815 "Cannot combine value to value of different type!");
817 WorklistRemover DeadNodes(*this);
818 DAG.ReplaceAllUsesWith(N, To);
820 // Push the new nodes and any users onto the worklist
821 for (unsigned i = 0, e = NumTo; i != e; ++i) {
822 if (To[i].getNode()) {
823 AddToWorklist(To[i].getNode());
824 AddUsersToWorklist(To[i].getNode());
829 // Finally, if the node is now dead, remove it from the graph. The node
830 // may not be dead if the replacement process recursively simplified to
831 // something else needing this node.
833 deleteAndRecombine(N);
834 return SDValue(N, 0);
838 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
839 // Replace all uses. If any nodes become isomorphic to other nodes and
840 // are deleted, make sure to remove them from our worklist.
841 WorklistRemover DeadNodes(*this);
842 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
844 // Push the new node and any (possibly new) users onto the worklist.
845 AddToWorklist(TLO.New.getNode());
846 AddUsersToWorklist(TLO.New.getNode());
848 // Finally, if the node is now dead, remove it from the graph. The node
849 // may not be dead if the replacement process recursively simplified to
850 // something else needing this node.
851 if (TLO.Old.getNode()->use_empty())
852 deleteAndRecombine(TLO.Old.getNode());
855 /// Check the specified integer node value to see if it can be simplified or if
856 /// things it uses can be simplified by bit propagation. If so, return true.
857 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
858 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
859 APInt KnownZero, KnownOne;
860 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
864 AddToWorklist(Op.getNode());
866 // Replace the old value with the new one.
868 DEBUG(dbgs() << "\nReplacing.2 ";
869 TLO.Old.getNode()->dump(&DAG);
870 dbgs() << "\nWith: ";
871 TLO.New.getNode()->dump(&DAG);
874 CommitTargetLoweringOpt(TLO);
878 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
880 EVT VT = Load->getValueType(0);
881 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
883 DEBUG(dbgs() << "\nReplacing.9 ";
885 dbgs() << "\nWith: ";
886 Trunc.getNode()->dump(&DAG);
888 WorklistRemover DeadNodes(*this);
889 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
890 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
891 deleteAndRecombine(Load);
892 AddToWorklist(Trunc.getNode());
895 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
898 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
899 EVT MemVT = LD->getMemoryVT();
900 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
901 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
903 : LD->getExtensionType();
905 return DAG.getExtLoad(ExtType, dl, PVT,
906 LD->getChain(), LD->getBasePtr(),
907 MemVT, LD->getMemOperand());
910 unsigned Opc = Op.getOpcode();
913 case ISD::AssertSext:
914 return DAG.getNode(ISD::AssertSext, dl, PVT,
915 SExtPromoteOperand(Op.getOperand(0), PVT),
917 case ISD::AssertZext:
918 return DAG.getNode(ISD::AssertZext, dl, PVT,
919 ZExtPromoteOperand(Op.getOperand(0), PVT),
921 case ISD::Constant: {
923 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
924 return DAG.getNode(ExtOpc, dl, PVT, Op);
928 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
930 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
933 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
934 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
936 EVT OldVT = Op.getValueType();
938 bool Replace = false;
939 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
940 if (!NewOp.getNode())
942 AddToWorklist(NewOp.getNode());
945 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
946 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
947 DAG.getValueType(OldVT));
950 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
951 EVT OldVT = Op.getValueType();
953 bool Replace = false;
954 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
955 if (!NewOp.getNode())
957 AddToWorklist(NewOp.getNode());
960 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
961 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
964 /// Promote the specified integer binary operation if the target indicates it is
965 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
966 /// i32 since i16 instructions are longer.
967 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
968 if (!LegalOperations)
971 EVT VT = Op.getValueType();
972 if (VT.isVector() || !VT.isInteger())
975 // If operation type is 'undesirable', e.g. i16 on x86, consider
977 unsigned Opc = Op.getOpcode();
978 if (TLI.isTypeDesirableForOp(Opc, VT))
982 // Consult target whether it is a good idea to promote this operation and
983 // what's the right type to promote it to.
984 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
985 assert(PVT != VT && "Don't know what type to promote to!");
987 bool Replace0 = false;
988 SDValue N0 = Op.getOperand(0);
989 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
993 bool Replace1 = false;
994 SDValue N1 = Op.getOperand(1);
999 NN1 = PromoteOperand(N1, PVT, Replace1);
1004 AddToWorklist(NN0.getNode());
1006 AddToWorklist(NN1.getNode());
1009 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1011 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1013 DEBUG(dbgs() << "\nPromoting ";
1014 Op.getNode()->dump(&DAG));
1016 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1017 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1022 /// Promote the specified integer shift operation if the target indicates it is
1023 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1024 /// i32 since i16 instructions are longer.
1025 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1026 if (!LegalOperations)
1029 EVT VT = Op.getValueType();
1030 if (VT.isVector() || !VT.isInteger())
1033 // If operation type is 'undesirable', e.g. i16 on x86, consider
1035 unsigned Opc = Op.getOpcode();
1036 if (TLI.isTypeDesirableForOp(Opc, VT))
1040 // Consult target whether it is a good idea to promote this operation and
1041 // what's the right type to promote it to.
1042 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1043 assert(PVT != VT && "Don't know what type to promote to!");
1045 bool Replace = false;
1046 SDValue N0 = Op.getOperand(0);
1047 if (Opc == ISD::SRA)
1048 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1049 else if (Opc == ISD::SRL)
1050 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1052 N0 = PromoteOperand(N0, PVT, Replace);
1056 AddToWorklist(N0.getNode());
1058 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1060 DEBUG(dbgs() << "\nPromoting ";
1061 Op.getNode()->dump(&DAG));
1063 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1064 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1069 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1070 if (!LegalOperations)
1073 EVT VT = Op.getValueType();
1074 if (VT.isVector() || !VT.isInteger())
1077 // If operation type is 'undesirable', e.g. i16 on x86, consider
1079 unsigned Opc = Op.getOpcode();
1080 if (TLI.isTypeDesirableForOp(Opc, VT))
1084 // Consult target whether it is a good idea to promote this operation and
1085 // what's the right type to promote it to.
1086 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1087 assert(PVT != VT && "Don't know what type to promote to!");
1088 // fold (aext (aext x)) -> (aext x)
1089 // fold (aext (zext x)) -> (zext x)
1090 // fold (aext (sext x)) -> (sext x)
1091 DEBUG(dbgs() << "\nPromoting ";
1092 Op.getNode()->dump(&DAG));
1093 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1098 bool DAGCombiner::PromoteLoad(SDValue Op) {
1099 if (!LegalOperations)
1102 EVT VT = Op.getValueType();
1103 if (VT.isVector() || !VT.isInteger())
1106 // If operation type is 'undesirable', e.g. i16 on x86, consider
1108 unsigned Opc = Op.getOpcode();
1109 if (TLI.isTypeDesirableForOp(Opc, VT))
1113 // Consult target whether it is a good idea to promote this operation and
1114 // what's the right type to promote it to.
1115 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1116 assert(PVT != VT && "Don't know what type to promote to!");
1119 SDNode *N = Op.getNode();
1120 LoadSDNode *LD = cast<LoadSDNode>(N);
1121 EVT MemVT = LD->getMemoryVT();
1122 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1123 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1125 : LD->getExtensionType();
1126 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1127 LD->getChain(), LD->getBasePtr(),
1128 MemVT, LD->getMemOperand());
1129 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1131 DEBUG(dbgs() << "\nPromoting ";
1134 Result.getNode()->dump(&DAG);
1136 WorklistRemover DeadNodes(*this);
1137 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1138 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1139 deleteAndRecombine(N);
1140 AddToWorklist(Result.getNode());
1146 /// \brief Recursively delete a node which has no uses and any operands for
1147 /// which it is the only use.
1149 /// Note that this both deletes the nodes and removes them from the worklist.
1150 /// It also adds any nodes who have had a user deleted to the worklist as they
1151 /// may now have only one use and subject to other combines.
1152 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1153 if (!N->use_empty())
1156 SmallSetVector<SDNode *, 16> Nodes;
1159 N = Nodes.pop_back_val();
1163 if (N->use_empty()) {
1164 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1165 Nodes.insert(N->getOperand(i).getNode());
1167 removeFromWorklist(N);
1172 } while (!Nodes.empty());
1176 //===----------------------------------------------------------------------===//
1177 // Main DAG Combiner implementation
1178 //===----------------------------------------------------------------------===//
1180 void DAGCombiner::Run(CombineLevel AtLevel) {
1181 // set the instance variables, so that the various visit routines may use it.
1183 LegalOperations = Level >= AfterLegalizeVectorOps;
1184 LegalTypes = Level >= AfterLegalizeTypes;
1186 // Early exit if this basic block is in an optnone function.
1187 AttributeSet FnAttrs =
1188 DAG.getMachineFunction().getFunction()->getAttributes();
1189 if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1190 Attribute::OptimizeNone))
1193 // Add all the dag nodes to the worklist.
1194 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1195 E = DAG.allnodes_end(); I != E; ++I)
1198 // Create a dummy node (which is not added to allnodes), that adds a reference
1199 // to the root node, preventing it from being deleted, and tracking any
1200 // changes of the root.
1201 HandleSDNode Dummy(DAG.getRoot());
1203 // while the worklist isn't empty, find a node and
1204 // try and combine it.
1205 while (!WorklistMap.empty()) {
1207 // The Worklist holds the SDNodes in order, but it may contain null entries.
1209 N = Worklist.pop_back_val();
1212 bool GoodWorklistEntry = WorklistMap.erase(N);
1213 (void)GoodWorklistEntry;
1214 assert(GoodWorklistEntry &&
1215 "Found a worklist entry without a corresponding map entry!");
1217 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1218 // N is deleted from the DAG, since they too may now be dead or may have a
1219 // reduced number of uses, allowing other xforms.
1220 if (recursivelyDeleteUnusedNodes(N))
1223 WorklistRemover DeadNodes(*this);
1225 // If this combine is running after legalizing the DAG, re-legalize any
1226 // nodes pulled off the worklist.
1227 if (Level == AfterLegalizeDAG) {
1228 SmallSetVector<SDNode *, 16> UpdatedNodes;
1229 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1231 for (SDNode *LN : UpdatedNodes) {
1233 AddUsersToWorklist(LN);
1239 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1241 // Add any operands of the new node which have not yet been combined to the
1242 // worklist as well. Because the worklist uniques things already, this
1243 // won't repeatedly process the same operand.
1244 CombinedNodes.insert(N);
1245 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1246 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1247 AddToWorklist(N->getOperand(i).getNode());
1249 SDValue RV = combine(N);
1256 // If we get back the same node we passed in, rather than a new node or
1257 // zero, we know that the node must have defined multiple values and
1258 // CombineTo was used. Since CombineTo takes care of the worklist
1259 // mechanics for us, we have no work to do in this case.
1260 if (RV.getNode() == N)
1263 assert(N->getOpcode() != ISD::DELETED_NODE &&
1264 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1265 "Node was deleted but visit returned new node!");
1267 DEBUG(dbgs() << " ... into: ";
1268 RV.getNode()->dump(&DAG));
1270 // Transfer debug value.
1271 DAG.TransferDbgValues(SDValue(N, 0), RV);
1272 if (N->getNumValues() == RV.getNode()->getNumValues())
1273 DAG.ReplaceAllUsesWith(N, RV.getNode());
1275 assert(N->getValueType(0) == RV.getValueType() &&
1276 N->getNumValues() == 1 && "Type mismatch");
1278 DAG.ReplaceAllUsesWith(N, &OpV);
1281 // Push the new node and any users onto the worklist
1282 AddToWorklist(RV.getNode());
1283 AddUsersToWorklist(RV.getNode());
1285 // Finally, if the node is now dead, remove it from the graph. The node
1286 // may not be dead if the replacement process recursively simplified to
1287 // something else needing this node. This will also take care of adding any
1288 // operands which have lost a user to the worklist.
1289 recursivelyDeleteUnusedNodes(N);
1292 // If the root changed (e.g. it was a dead load, update the root).
1293 DAG.setRoot(Dummy.getValue());
1294 DAG.RemoveDeadNodes();
1297 SDValue DAGCombiner::visit(SDNode *N) {
1298 switch (N->getOpcode()) {
1300 case ISD::TokenFactor: return visitTokenFactor(N);
1301 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1302 case ISD::ADD: return visitADD(N);
1303 case ISD::SUB: return visitSUB(N);
1304 case ISD::ADDC: return visitADDC(N);
1305 case ISD::SUBC: return visitSUBC(N);
1306 case ISD::ADDE: return visitADDE(N);
1307 case ISD::SUBE: return visitSUBE(N);
1308 case ISD::MUL: return visitMUL(N);
1309 case ISD::SDIV: return visitSDIV(N);
1310 case ISD::UDIV: return visitUDIV(N);
1311 case ISD::SREM: return visitSREM(N);
1312 case ISD::UREM: return visitUREM(N);
1313 case ISD::MULHU: return visitMULHU(N);
1314 case ISD::MULHS: return visitMULHS(N);
1315 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1316 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1317 case ISD::SMULO: return visitSMULO(N);
1318 case ISD::UMULO: return visitUMULO(N);
1319 case ISD::SDIVREM: return visitSDIVREM(N);
1320 case ISD::UDIVREM: return visitUDIVREM(N);
1321 case ISD::AND: return visitAND(N);
1322 case ISD::OR: return visitOR(N);
1323 case ISD::XOR: return visitXOR(N);
1324 case ISD::SHL: return visitSHL(N);
1325 case ISD::SRA: return visitSRA(N);
1326 case ISD::SRL: return visitSRL(N);
1328 case ISD::ROTL: return visitRotate(N);
1329 case ISD::CTLZ: return visitCTLZ(N);
1330 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1331 case ISD::CTTZ: return visitCTTZ(N);
1332 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1333 case ISD::CTPOP: return visitCTPOP(N);
1334 case ISD::SELECT: return visitSELECT(N);
1335 case ISD::VSELECT: return visitVSELECT(N);
1336 case ISD::SELECT_CC: return visitSELECT_CC(N);
1337 case ISD::SETCC: return visitSETCC(N);
1338 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1339 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1340 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1341 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1342 case ISD::TRUNCATE: return visitTRUNCATE(N);
1343 case ISD::BITCAST: return visitBITCAST(N);
1344 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1345 case ISD::FADD: return visitFADD(N);
1346 case ISD::FSUB: return visitFSUB(N);
1347 case ISD::FMUL: return visitFMUL(N);
1348 case ISD::FMA: return visitFMA(N);
1349 case ISD::FDIV: return visitFDIV(N);
1350 case ISD::FREM: return visitFREM(N);
1351 case ISD::FSQRT: return visitFSQRT(N);
1352 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1353 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1354 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1355 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1356 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1357 case ISD::FP_ROUND: return visitFP_ROUND(N);
1358 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1359 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1360 case ISD::FNEG: return visitFNEG(N);
1361 case ISD::FABS: return visitFABS(N);
1362 case ISD::FFLOOR: return visitFFLOOR(N);
1363 case ISD::FMINNUM: return visitFMINNUM(N);
1364 case ISD::FMAXNUM: return visitFMAXNUM(N);
1365 case ISD::FCEIL: return visitFCEIL(N);
1366 case ISD::FTRUNC: return visitFTRUNC(N);
1367 case ISD::BRCOND: return visitBRCOND(N);
1368 case ISD::BR_CC: return visitBR_CC(N);
1369 case ISD::LOAD: return visitLOAD(N);
1370 case ISD::STORE: return visitSTORE(N);
1371 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1372 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1373 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1374 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1375 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1376 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1377 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1378 case ISD::MLOAD: return visitMLOAD(N);
1379 case ISD::MSTORE: return visitMSTORE(N);
1384 SDValue DAGCombiner::combine(SDNode *N) {
1385 SDValue RV = visit(N);
1387 // If nothing happened, try a target-specific DAG combine.
1388 if (!RV.getNode()) {
1389 assert(N->getOpcode() != ISD::DELETED_NODE &&
1390 "Node was deleted but visit returned NULL!");
1392 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1393 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1395 // Expose the DAG combiner to the target combiner impls.
1396 TargetLowering::DAGCombinerInfo
1397 DagCombineInfo(DAG, Level, false, this);
1399 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1403 // If nothing happened still, try promoting the operation.
1404 if (!RV.getNode()) {
1405 switch (N->getOpcode()) {
1413 RV = PromoteIntBinOp(SDValue(N, 0));
1418 RV = PromoteIntShiftOp(SDValue(N, 0));
1420 case ISD::SIGN_EXTEND:
1421 case ISD::ZERO_EXTEND:
1422 case ISD::ANY_EXTEND:
1423 RV = PromoteExtend(SDValue(N, 0));
1426 if (PromoteLoad(SDValue(N, 0)))
1432 // If N is a commutative binary node, try commuting it to enable more
1434 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1435 N->getNumValues() == 1) {
1436 SDValue N0 = N->getOperand(0);
1437 SDValue N1 = N->getOperand(1);
1439 // Constant operands are canonicalized to RHS.
1440 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1441 SDValue Ops[] = {N1, N0};
1443 if (const BinaryWithFlagsSDNode *BinNode =
1444 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1445 CSENode = DAG.getNodeIfExists(
1446 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1447 BinNode->hasNoSignedWrap(), BinNode->isExact());
1449 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1452 return SDValue(CSENode, 0);
1459 /// Given a node, return its input chain if it has one, otherwise return a null
1461 static SDValue getInputChainForNode(SDNode *N) {
1462 if (unsigned NumOps = N->getNumOperands()) {
1463 if (N->getOperand(0).getValueType() == MVT::Other)
1464 return N->getOperand(0);
1465 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1466 return N->getOperand(NumOps-1);
1467 for (unsigned i = 1; i < NumOps-1; ++i)
1468 if (N->getOperand(i).getValueType() == MVT::Other)
1469 return N->getOperand(i);
1474 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1475 // If N has two operands, where one has an input chain equal to the other,
1476 // the 'other' chain is redundant.
1477 if (N->getNumOperands() == 2) {
1478 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1479 return N->getOperand(0);
1480 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1481 return N->getOperand(1);
1484 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1485 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1486 SmallPtrSet<SDNode*, 16> SeenOps;
1487 bool Changed = false; // If we should replace this token factor.
1489 // Start out with this token factor.
1492 // Iterate through token factors. The TFs grows when new token factors are
1494 for (unsigned i = 0; i < TFs.size(); ++i) {
1495 SDNode *TF = TFs[i];
1497 // Check each of the operands.
1498 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1499 SDValue Op = TF->getOperand(i);
1501 switch (Op.getOpcode()) {
1502 case ISD::EntryToken:
1503 // Entry tokens don't need to be added to the list. They are
1508 case ISD::TokenFactor:
1509 if (Op.hasOneUse() &&
1510 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1511 // Queue up for processing.
1512 TFs.push_back(Op.getNode());
1513 // Clean up in case the token factor is removed.
1514 AddToWorklist(Op.getNode());
1521 // Only add if it isn't already in the list.
1522 if (SeenOps.insert(Op.getNode()).second)
1533 // If we've changed things around then replace token factor.
1536 // The entry token is the only possible outcome.
1537 Result = DAG.getEntryNode();
1539 // New and improved token factor.
1540 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1543 // Add users to worklist if AA is enabled, since it may introduce
1544 // a lot of new chained token factors while removing memory deps.
1545 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1546 : DAG.getSubtarget().useAA();
1547 return CombineTo(N, Result, UseAA /*add to worklist*/);
1553 /// MERGE_VALUES can always be eliminated.
1554 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1555 WorklistRemover DeadNodes(*this);
1556 // Replacing results may cause a different MERGE_VALUES to suddenly
1557 // be CSE'd with N, and carry its uses with it. Iterate until no
1558 // uses remain, to ensure that the node can be safely deleted.
1559 // First add the users of this node to the work list so that they
1560 // can be tried again once they have new operands.
1561 AddUsersToWorklist(N);
1563 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1564 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1565 } while (!N->use_empty());
1566 deleteAndRecombine(N);
1567 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1570 SDValue DAGCombiner::visitADD(SDNode *N) {
1571 SDValue N0 = N->getOperand(0);
1572 SDValue N1 = N->getOperand(1);
1573 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1574 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1575 EVT VT = N0.getValueType();
1578 if (VT.isVector()) {
1579 SDValue FoldedVOp = SimplifyVBinOp(N);
1580 if (FoldedVOp.getNode()) return FoldedVOp;
1582 // fold (add x, 0) -> x, vector edition
1583 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1585 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1589 // fold (add x, undef) -> undef
1590 if (N0.getOpcode() == ISD::UNDEF)
1592 if (N1.getOpcode() == ISD::UNDEF)
1594 // fold (add c1, c2) -> c1+c2
1596 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1597 // canonicalize constant to RHS
1599 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1600 // fold (add x, 0) -> x
1601 if (N1C && N1C->isNullValue())
1603 // fold (add Sym, c) -> Sym+c
1604 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1605 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1606 GA->getOpcode() == ISD::GlobalAddress)
1607 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1609 (uint64_t)N1C->getSExtValue());
1610 // fold ((c1-A)+c2) -> (c1+c2)-A
1611 if (N1C && N0.getOpcode() == ISD::SUB)
1612 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1613 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1614 DAG.getConstant(N1C->getAPIntValue()+
1615 N0C->getAPIntValue(), VT),
1618 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1621 // fold ((0-A) + B) -> B-A
1622 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1623 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1624 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1625 // fold (A + (0-B)) -> A-B
1626 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1627 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1628 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1629 // fold (A+(B-A)) -> B
1630 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1631 return N1.getOperand(0);
1632 // fold ((B-A)+A) -> B
1633 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1634 return N0.getOperand(0);
1635 // fold (A+(B-(A+C))) to (B-C)
1636 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1637 N0 == N1.getOperand(1).getOperand(0))
1638 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1639 N1.getOperand(1).getOperand(1));
1640 // fold (A+(B-(C+A))) to (B-C)
1641 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1642 N0 == N1.getOperand(1).getOperand(1))
1643 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1644 N1.getOperand(1).getOperand(0));
1645 // fold (A+((B-A)+or-C)) to (B+or-C)
1646 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1647 N1.getOperand(0).getOpcode() == ISD::SUB &&
1648 N0 == N1.getOperand(0).getOperand(1))
1649 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1650 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1652 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1653 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1654 SDValue N00 = N0.getOperand(0);
1655 SDValue N01 = N0.getOperand(1);
1656 SDValue N10 = N1.getOperand(0);
1657 SDValue N11 = N1.getOperand(1);
1659 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1660 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1661 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1662 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1665 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1666 return SDValue(N, 0);
1668 // fold (a+b) -> (a|b) iff a and b share no bits.
1669 if (VT.isInteger() && !VT.isVector()) {
1670 APInt LHSZero, LHSOne;
1671 APInt RHSZero, RHSOne;
1672 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1674 if (LHSZero.getBoolValue()) {
1675 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1677 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1678 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1679 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1680 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1681 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1686 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1687 if (N1.getOpcode() == ISD::SHL &&
1688 N1.getOperand(0).getOpcode() == ISD::SUB)
1689 if (ConstantSDNode *C =
1690 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1691 if (C->getAPIntValue() == 0)
1692 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1693 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1694 N1.getOperand(0).getOperand(1),
1696 if (N0.getOpcode() == ISD::SHL &&
1697 N0.getOperand(0).getOpcode() == ISD::SUB)
1698 if (ConstantSDNode *C =
1699 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1700 if (C->getAPIntValue() == 0)
1701 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1702 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1703 N0.getOperand(0).getOperand(1),
1706 if (N1.getOpcode() == ISD::AND) {
1707 SDValue AndOp0 = N1.getOperand(0);
1708 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1709 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1710 unsigned DestBits = VT.getScalarType().getSizeInBits();
1712 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1713 // and similar xforms where the inner op is either ~0 or 0.
1714 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1716 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1720 // add (sext i1), X -> sub X, (zext i1)
1721 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1722 N0.getOperand(0).getValueType() == MVT::i1 &&
1723 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1725 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1726 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1729 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1730 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1731 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1732 if (TN->getVT() == MVT::i1) {
1734 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1735 DAG.getConstant(1, VT));
1736 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1743 SDValue DAGCombiner::visitADDC(SDNode *N) {
1744 SDValue N0 = N->getOperand(0);
1745 SDValue N1 = N->getOperand(1);
1746 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1747 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1748 EVT VT = N0.getValueType();
1750 // If the flag result is dead, turn this into an ADD.
1751 if (!N->hasAnyUseOfValue(1))
1752 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1753 DAG.getNode(ISD::CARRY_FALSE,
1754 SDLoc(N), MVT::Glue));
1756 // canonicalize constant to RHS.
1758 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1760 // fold (addc x, 0) -> x + no carry out
1761 if (N1C && N1C->isNullValue())
1762 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1763 SDLoc(N), MVT::Glue));
1765 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1766 APInt LHSZero, LHSOne;
1767 APInt RHSZero, RHSOne;
1768 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1770 if (LHSZero.getBoolValue()) {
1771 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1773 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1774 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1775 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1776 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1777 DAG.getNode(ISD::CARRY_FALSE,
1778 SDLoc(N), MVT::Glue));
1784 SDValue DAGCombiner::visitADDE(SDNode *N) {
1785 SDValue N0 = N->getOperand(0);
1786 SDValue N1 = N->getOperand(1);
1787 SDValue CarryIn = N->getOperand(2);
1788 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1789 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1791 // canonicalize constant to RHS
1793 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1796 // fold (adde x, y, false) -> (addc x, y)
1797 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1798 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1803 // Since it may not be valid to emit a fold to zero for vector initializers
1804 // check if we can before folding.
1805 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1807 bool LegalOperations, bool LegalTypes) {
1809 return DAG.getConstant(0, VT);
1810 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1811 return DAG.getConstant(0, VT);
1815 SDValue DAGCombiner::visitSUB(SDNode *N) {
1816 SDValue N0 = N->getOperand(0);
1817 SDValue N1 = N->getOperand(1);
1818 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1819 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1820 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1821 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1822 EVT VT = N0.getValueType();
1825 if (VT.isVector()) {
1826 SDValue FoldedVOp = SimplifyVBinOp(N);
1827 if (FoldedVOp.getNode()) return FoldedVOp;
1829 // fold (sub x, 0) -> x, vector edition
1830 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1834 // fold (sub x, x) -> 0
1835 // FIXME: Refactor this and xor and other similar operations together.
1837 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1838 // fold (sub c1, c2) -> c1-c2
1840 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1841 // fold (sub x, c) -> (add x, -c)
1843 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1844 DAG.getConstant(-N1C->getAPIntValue(), VT));
1845 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1846 if (N0C && N0C->isAllOnesValue())
1847 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1848 // fold A-(A-B) -> B
1849 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1850 return N1.getOperand(1);
1851 // fold (A+B)-A -> B
1852 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1853 return N0.getOperand(1);
1854 // fold (A+B)-B -> A
1855 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1856 return N0.getOperand(0);
1857 // fold C2-(A+C1) -> (C2-C1)-A
1858 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1859 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1861 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1864 // fold ((A+(B+or-C))-B) -> A+or-C
1865 if (N0.getOpcode() == ISD::ADD &&
1866 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1867 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1868 N0.getOperand(1).getOperand(0) == N1)
1869 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1870 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1871 // fold ((A+(C+B))-B) -> A+C
1872 if (N0.getOpcode() == ISD::ADD &&
1873 N0.getOperand(1).getOpcode() == ISD::ADD &&
1874 N0.getOperand(1).getOperand(1) == N1)
1875 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1876 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1877 // fold ((A-(B-C))-C) -> A-B
1878 if (N0.getOpcode() == ISD::SUB &&
1879 N0.getOperand(1).getOpcode() == ISD::SUB &&
1880 N0.getOperand(1).getOperand(1) == N1)
1881 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1882 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1884 // If either operand of a sub is undef, the result is undef
1885 if (N0.getOpcode() == ISD::UNDEF)
1887 if (N1.getOpcode() == ISD::UNDEF)
1890 // If the relocation model supports it, consider symbol offsets.
1891 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1892 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1893 // fold (sub Sym, c) -> Sym-c
1894 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1895 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1897 (uint64_t)N1C->getSExtValue());
1898 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1899 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1900 if (GA->getGlobal() == GB->getGlobal())
1901 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1905 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1906 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1907 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1908 if (TN->getVT() == MVT::i1) {
1910 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1911 DAG.getConstant(1, VT));
1912 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1919 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1920 SDValue N0 = N->getOperand(0);
1921 SDValue N1 = N->getOperand(1);
1922 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1923 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1924 EVT VT = N0.getValueType();
1926 // If the flag result is dead, turn this into an SUB.
1927 if (!N->hasAnyUseOfValue(1))
1928 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1929 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1932 // fold (subc x, x) -> 0 + no borrow
1934 return CombineTo(N, DAG.getConstant(0, VT),
1935 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1938 // fold (subc x, 0) -> x + no borrow
1939 if (N1C && N1C->isNullValue())
1940 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1943 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1944 if (N0C && N0C->isAllOnesValue())
1945 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1946 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1952 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1953 SDValue N0 = N->getOperand(0);
1954 SDValue N1 = N->getOperand(1);
1955 SDValue CarryIn = N->getOperand(2);
1957 // fold (sube x, y, false) -> (subc x, y)
1958 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1959 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1964 SDValue DAGCombiner::visitMUL(SDNode *N) {
1965 SDValue N0 = N->getOperand(0);
1966 SDValue N1 = N->getOperand(1);
1967 EVT VT = N0.getValueType();
1969 // fold (mul x, undef) -> 0
1970 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1971 return DAG.getConstant(0, VT);
1973 bool N0IsConst = false;
1974 bool N1IsConst = false;
1975 APInt ConstValue0, ConstValue1;
1977 if (VT.isVector()) {
1978 SDValue FoldedVOp = SimplifyVBinOp(N);
1979 if (FoldedVOp.getNode()) return FoldedVOp;
1981 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1982 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1984 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1985 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1987 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1988 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1992 // fold (mul c1, c2) -> c1*c2
1993 if (N0IsConst && N1IsConst)
1994 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1996 // canonicalize constant to RHS
1997 if (N0IsConst && !N1IsConst)
1998 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1999 // fold (mul x, 0) -> 0
2000 if (N1IsConst && ConstValue1 == 0)
2002 // We require a splat of the entire scalar bit width for non-contiguous
2005 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2006 // fold (mul x, 1) -> x
2007 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2009 // fold (mul x, -1) -> 0-x
2010 if (N1IsConst && ConstValue1.isAllOnesValue())
2011 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2012 DAG.getConstant(0, VT), N0);
2013 // fold (mul x, (1 << c)) -> x << c
2014 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
2015 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2016 DAG.getConstant(ConstValue1.logBase2(),
2017 getShiftAmountTy(N0.getValueType())));
2018 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2019 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2020 unsigned Log2Val = (-ConstValue1).logBase2();
2021 // FIXME: If the input is something that is easily negated (e.g. a
2022 // single-use add), we should put the negate there.
2023 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2024 DAG.getConstant(0, VT),
2025 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2026 DAG.getConstant(Log2Val,
2027 getShiftAmountTy(N0.getValueType()))));
2031 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2032 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2033 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2034 isa<ConstantSDNode>(N0.getOperand(1)))) {
2035 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2036 N1, N0.getOperand(1));
2037 AddToWorklist(C3.getNode());
2038 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2039 N0.getOperand(0), C3);
2042 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2045 SDValue Sh(nullptr,0), Y(nullptr,0);
2046 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2047 if (N0.getOpcode() == ISD::SHL &&
2048 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2049 isa<ConstantSDNode>(N0.getOperand(1))) &&
2050 N0.getNode()->hasOneUse()) {
2052 } else if (N1.getOpcode() == ISD::SHL &&
2053 isa<ConstantSDNode>(N1.getOperand(1)) &&
2054 N1.getNode()->hasOneUse()) {
2059 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2060 Sh.getOperand(0), Y);
2061 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2062 Mul, Sh.getOperand(1));
2066 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2067 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2068 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2069 isa<ConstantSDNode>(N0.getOperand(1))))
2070 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2071 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2072 N0.getOperand(0), N1),
2073 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2074 N0.getOperand(1), N1));
2077 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2084 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2085 SDValue N0 = N->getOperand(0);
2086 SDValue N1 = N->getOperand(1);
2087 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2088 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2089 EVT VT = N->getValueType(0);
2092 if (VT.isVector()) {
2093 SDValue FoldedVOp = SimplifyVBinOp(N);
2094 if (FoldedVOp.getNode()) return FoldedVOp;
2097 // fold (sdiv c1, c2) -> c1/c2
2098 if (N0C && N1C && !N1C->isNullValue())
2099 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2100 // fold (sdiv X, 1) -> X
2101 if (N1C && N1C->getAPIntValue() == 1LL)
2103 // fold (sdiv X, -1) -> 0-X
2104 if (N1C && N1C->isAllOnesValue())
2105 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2106 DAG.getConstant(0, VT), N0);
2107 // If we know the sign bits of both operands are zero, strength reduce to a
2108 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2109 if (!VT.isVector()) {
2110 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2111 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2115 // fold (sdiv X, pow2) -> simple ops after legalize
2116 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2117 (-N1C->getAPIntValue()).isPowerOf2())) {
2118 // If dividing by powers of two is cheap, then don't perform the following
2120 if (TLI.isPow2SDivCheap())
2123 // Target-specific implementation of sdiv x, pow2.
2124 SDValue Res = BuildSDIVPow2(N);
2128 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2130 // Splat the sign bit into the register
2132 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2133 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2134 getShiftAmountTy(N0.getValueType())));
2135 AddToWorklist(SGN.getNode());
2137 // Add (N0 < 0) ? abs2 - 1 : 0;
2139 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2140 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2141 getShiftAmountTy(SGN.getValueType())));
2142 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2143 AddToWorklist(SRL.getNode());
2144 AddToWorklist(ADD.getNode()); // Divide by pow2
2145 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2146 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2148 // If we're dividing by a positive value, we're done. Otherwise, we must
2149 // negate the result.
2150 if (N1C->getAPIntValue().isNonNegative())
2153 AddToWorklist(SRA.getNode());
2154 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2157 // if integer divide is expensive and we satisfy the requirements, emit an
2158 // alternate sequence.
2159 if (N1C && !TLI.isIntDivCheap()) {
2160 SDValue Op = BuildSDIV(N);
2161 if (Op.getNode()) return Op;
2165 if (N0.getOpcode() == ISD::UNDEF)
2166 return DAG.getConstant(0, VT);
2167 // X / undef -> undef
2168 if (N1.getOpcode() == ISD::UNDEF)
2174 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2175 SDValue N0 = N->getOperand(0);
2176 SDValue N1 = N->getOperand(1);
2177 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2178 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2179 EVT VT = N->getValueType(0);
2182 if (VT.isVector()) {
2183 SDValue FoldedVOp = SimplifyVBinOp(N);
2184 if (FoldedVOp.getNode()) return FoldedVOp;
2187 // fold (udiv c1, c2) -> c1/c2
2188 if (N0C && N1C && !N1C->isNullValue())
2189 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2190 // fold (udiv x, (1 << c)) -> x >>u c
2191 if (N1C && N1C->getAPIntValue().isPowerOf2())
2192 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2193 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2194 getShiftAmountTy(N0.getValueType())));
2195 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2196 if (N1.getOpcode() == ISD::SHL) {
2197 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2198 if (SHC->getAPIntValue().isPowerOf2()) {
2199 EVT ADDVT = N1.getOperand(1).getValueType();
2200 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2202 DAG.getConstant(SHC->getAPIntValue()
2205 AddToWorklist(Add.getNode());
2206 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2210 // fold (udiv x, c) -> alternate
2211 if (N1C && !TLI.isIntDivCheap()) {
2212 SDValue Op = BuildUDIV(N);
2213 if (Op.getNode()) return Op;
2217 if (N0.getOpcode() == ISD::UNDEF)
2218 return DAG.getConstant(0, VT);
2219 // X / undef -> undef
2220 if (N1.getOpcode() == ISD::UNDEF)
2226 SDValue DAGCombiner::visitSREM(SDNode *N) {
2227 SDValue N0 = N->getOperand(0);
2228 SDValue N1 = N->getOperand(1);
2229 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2230 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2231 EVT VT = N->getValueType(0);
2233 // fold (srem c1, c2) -> c1%c2
2234 if (N0C && N1C && !N1C->isNullValue())
2235 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2236 // If we know the sign bits of both operands are zero, strength reduce to a
2237 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2238 if (!VT.isVector()) {
2239 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2240 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2243 // If X/C can be simplified by the division-by-constant logic, lower
2244 // X%C to the equivalent of X-X/C*C.
2245 if (N1C && !N1C->isNullValue()) {
2246 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2247 AddToWorklist(Div.getNode());
2248 SDValue OptimizedDiv = combine(Div.getNode());
2249 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2250 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2252 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2253 AddToWorklist(Mul.getNode());
2259 if (N0.getOpcode() == ISD::UNDEF)
2260 return DAG.getConstant(0, VT);
2261 // X % undef -> undef
2262 if (N1.getOpcode() == ISD::UNDEF)
2268 SDValue DAGCombiner::visitUREM(SDNode *N) {
2269 SDValue N0 = N->getOperand(0);
2270 SDValue N1 = N->getOperand(1);
2271 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2272 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2273 EVT VT = N->getValueType(0);
2275 // fold (urem c1, c2) -> c1%c2
2276 if (N0C && N1C && !N1C->isNullValue())
2277 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2278 // fold (urem x, pow2) -> (and x, pow2-1)
2279 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2280 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2281 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2282 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2283 if (N1.getOpcode() == ISD::SHL) {
2284 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2285 if (SHC->getAPIntValue().isPowerOf2()) {
2287 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2288 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2290 AddToWorklist(Add.getNode());
2291 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2296 // If X/C can be simplified by the division-by-constant logic, lower
2297 // X%C to the equivalent of X-X/C*C.
2298 if (N1C && !N1C->isNullValue()) {
2299 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2300 AddToWorklist(Div.getNode());
2301 SDValue OptimizedDiv = combine(Div.getNode());
2302 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2303 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2305 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2306 AddToWorklist(Mul.getNode());
2312 if (N0.getOpcode() == ISD::UNDEF)
2313 return DAG.getConstant(0, VT);
2314 // X % undef -> undef
2315 if (N1.getOpcode() == ISD::UNDEF)
2321 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2322 SDValue N0 = N->getOperand(0);
2323 SDValue N1 = N->getOperand(1);
2324 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2325 EVT VT = N->getValueType(0);
2328 // fold (mulhs x, 0) -> 0
2329 if (N1C && N1C->isNullValue())
2331 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2332 if (N1C && N1C->getAPIntValue() == 1)
2333 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2334 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2335 getShiftAmountTy(N0.getValueType())));
2336 // fold (mulhs x, undef) -> 0
2337 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2338 return DAG.getConstant(0, VT);
2340 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2342 if (VT.isSimple() && !VT.isVector()) {
2343 MVT Simple = VT.getSimpleVT();
2344 unsigned SimpleSize = Simple.getSizeInBits();
2345 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2346 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2347 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2348 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2349 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2350 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2351 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2352 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2359 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2360 SDValue N0 = N->getOperand(0);
2361 SDValue N1 = N->getOperand(1);
2362 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2363 EVT VT = N->getValueType(0);
2366 // fold (mulhu x, 0) -> 0
2367 if (N1C && N1C->isNullValue())
2369 // fold (mulhu x, 1) -> 0
2370 if (N1C && N1C->getAPIntValue() == 1)
2371 return DAG.getConstant(0, N0.getValueType());
2372 // fold (mulhu x, undef) -> 0
2373 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2374 return DAG.getConstant(0, VT);
2376 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2378 if (VT.isSimple() && !VT.isVector()) {
2379 MVT Simple = VT.getSimpleVT();
2380 unsigned SimpleSize = Simple.getSizeInBits();
2381 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2382 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2383 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2384 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2385 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2386 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2387 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2388 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2395 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2396 /// give the opcodes for the two computations that are being performed. Return
2397 /// true if a simplification was made.
2398 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2400 // If the high half is not needed, just compute the low half.
2401 bool HiExists = N->hasAnyUseOfValue(1);
2403 (!LegalOperations ||
2404 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2405 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2406 return CombineTo(N, Res, Res);
2409 // If the low half is not needed, just compute the high half.
2410 bool LoExists = N->hasAnyUseOfValue(0);
2412 (!LegalOperations ||
2413 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2414 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2415 return CombineTo(N, Res, Res);
2418 // If both halves are used, return as it is.
2419 if (LoExists && HiExists)
2422 // If the two computed results can be simplified separately, separate them.
2424 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2425 AddToWorklist(Lo.getNode());
2426 SDValue LoOpt = combine(Lo.getNode());
2427 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2428 (!LegalOperations ||
2429 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2430 return CombineTo(N, LoOpt, LoOpt);
2434 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2435 AddToWorklist(Hi.getNode());
2436 SDValue HiOpt = combine(Hi.getNode());
2437 if (HiOpt.getNode() && HiOpt != Hi &&
2438 (!LegalOperations ||
2439 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2440 return CombineTo(N, HiOpt, HiOpt);
2446 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2447 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
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::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2461 SDValue Hi = DAG.getNode(ISD::SIGN_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::visitUMUL_LOHI(SDNode *N) {
2477 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2478 if (Res.getNode()) return Res;
2480 EVT VT = N->getValueType(0);
2483 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2485 if (VT.isSimple() && !VT.isVector()) {
2486 MVT Simple = VT.getSimpleVT();
2487 unsigned SimpleSize = Simple.getSizeInBits();
2488 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2489 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2490 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2491 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2492 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2493 // Compute the high part as N1.
2494 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2495 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2496 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2497 // Compute the low part as N0.
2498 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2499 return CombineTo(N, Lo, Hi);
2506 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2507 // (smulo x, 2) -> (saddo x, x)
2508 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2509 if (C2->getAPIntValue() == 2)
2510 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2511 N->getOperand(0), N->getOperand(0));
2516 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2517 // (umulo x, 2) -> (uaddo x, x)
2518 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2519 if (C2->getAPIntValue() == 2)
2520 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2521 N->getOperand(0), N->getOperand(0));
2526 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2527 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2528 if (Res.getNode()) return Res;
2533 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2534 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2535 if (Res.getNode()) return Res;
2540 /// If this is a binary operator with two operands of the same opcode, try to
2542 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2543 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2544 EVT VT = N0.getValueType();
2545 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2547 // Bail early if none of these transforms apply.
2548 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2550 // For each of OP in AND/OR/XOR:
2551 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2552 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2553 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2554 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2555 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2557 // do not sink logical op inside of a vector extend, since it may combine
2559 EVT Op0VT = N0.getOperand(0).getValueType();
2560 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2561 N0.getOpcode() == ISD::SIGN_EXTEND ||
2562 N0.getOpcode() == ISD::BSWAP ||
2563 // Avoid infinite looping with PromoteIntBinOp.
2564 (N0.getOpcode() == ISD::ANY_EXTEND &&
2565 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2566 (N0.getOpcode() == ISD::TRUNCATE &&
2567 (!TLI.isZExtFree(VT, Op0VT) ||
2568 !TLI.isTruncateFree(Op0VT, VT)) &&
2569 TLI.isTypeLegal(Op0VT))) &&
2571 Op0VT == N1.getOperand(0).getValueType() &&
2572 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2573 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2574 N0.getOperand(0).getValueType(),
2575 N0.getOperand(0), N1.getOperand(0));
2576 AddToWorklist(ORNode.getNode());
2577 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2580 // For each of OP in SHL/SRL/SRA/AND...
2581 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2582 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2583 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2584 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2585 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2586 N0.getOperand(1) == N1.getOperand(1)) {
2587 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2588 N0.getOperand(0).getValueType(),
2589 N0.getOperand(0), N1.getOperand(0));
2590 AddToWorklist(ORNode.getNode());
2591 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2592 ORNode, N0.getOperand(1));
2595 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2596 // Only perform this optimization after type legalization and before
2597 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2598 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2599 // we don't want to undo this promotion.
2600 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2602 if ((N0.getOpcode() == ISD::BITCAST ||
2603 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2604 Level == AfterLegalizeTypes) {
2605 SDValue In0 = N0.getOperand(0);
2606 SDValue In1 = N1.getOperand(0);
2607 EVT In0Ty = In0.getValueType();
2608 EVT In1Ty = In1.getValueType();
2610 // If both incoming values are integers, and the original types are the
2612 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2613 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2614 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2615 AddToWorklist(Op.getNode());
2620 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2621 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2622 // If both shuffles use the same mask, and both shuffle within a single
2623 // vector, then it is worthwhile to move the swizzle after the operation.
2624 // The type-legalizer generates this pattern when loading illegal
2625 // vector types from memory. In many cases this allows additional shuffle
2627 // There are other cases where moving the shuffle after the xor/and/or
2628 // is profitable even if shuffles don't perform a swizzle.
2629 // If both shuffles use the same mask, and both shuffles have the same first
2630 // or second operand, then it might still be profitable to move the shuffle
2631 // after the xor/and/or operation.
2632 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2633 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2634 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2636 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2637 "Inputs to shuffles are not the same type");
2639 // Check that both shuffles use the same mask. The masks are known to be of
2640 // the same length because the result vector type is the same.
2641 // Check also that shuffles have only one use to avoid introducing extra
2643 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2644 SVN0->getMask().equals(SVN1->getMask())) {
2645 SDValue ShOp = N0->getOperand(1);
2647 // Don't try to fold this node if it requires introducing a
2648 // build vector of all zeros that might be illegal at this stage.
2649 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2651 ShOp = DAG.getConstant(0, VT);
2656 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2657 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2658 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2659 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2660 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2661 N0->getOperand(0), N1->getOperand(0));
2662 AddToWorklist(NewNode.getNode());
2663 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2664 &SVN0->getMask()[0]);
2667 // Don't try to fold this node if it requires introducing a
2668 // build vector of all zeros that might be illegal at this stage.
2669 ShOp = N0->getOperand(0);
2670 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2672 ShOp = DAG.getConstant(0, VT);
2677 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2678 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2679 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2680 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2681 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2682 N0->getOperand(1), N1->getOperand(1));
2683 AddToWorklist(NewNode.getNode());
2684 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2685 &SVN0->getMask()[0]);
2693 SDValue DAGCombiner::visitAND(SDNode *N) {
2694 SDValue N0 = N->getOperand(0);
2695 SDValue N1 = N->getOperand(1);
2696 SDValue LL, LR, RL, RR, CC0, CC1;
2697 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2698 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2699 EVT VT = N1.getValueType();
2700 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2703 if (VT.isVector()) {
2704 SDValue FoldedVOp = SimplifyVBinOp(N);
2705 if (FoldedVOp.getNode()) return FoldedVOp;
2707 // fold (and x, 0) -> 0, vector edition
2708 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2709 // do not return N0, because undef node may exist in N0
2710 return DAG.getConstant(
2711 APInt::getNullValue(
2712 N0.getValueType().getScalarType().getSizeInBits()),
2714 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2715 // do not return N1, because undef node may exist in N1
2716 return DAG.getConstant(
2717 APInt::getNullValue(
2718 N1.getValueType().getScalarType().getSizeInBits()),
2721 // fold (and x, -1) -> x, vector edition
2722 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2724 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2728 // fold (and x, undef) -> 0
2729 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2730 return DAG.getConstant(0, VT);
2731 // fold (and c1, c2) -> c1&c2
2733 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2734 // canonicalize constant to RHS
2736 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2737 // fold (and x, -1) -> x
2738 if (N1C && N1C->isAllOnesValue())
2740 // if (and x, c) is known to be zero, return 0
2741 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2742 APInt::getAllOnesValue(BitWidth)))
2743 return DAG.getConstant(0, VT);
2745 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2748 // fold (and (or x, C), D) -> D if (C & D) == D
2749 if (N1C && N0.getOpcode() == ISD::OR)
2750 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2751 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2753 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2754 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2755 SDValue N0Op0 = N0.getOperand(0);
2756 APInt Mask = ~N1C->getAPIntValue();
2757 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2758 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2759 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2760 N0.getValueType(), N0Op0);
2762 // Replace uses of the AND with uses of the Zero extend node.
2765 // We actually want to replace all uses of the any_extend with the
2766 // zero_extend, to avoid duplicating things. This will later cause this
2767 // AND to be folded.
2768 CombineTo(N0.getNode(), Zext);
2769 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2772 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2773 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2774 // already be zero by virtue of the width of the base type of the load.
2776 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2778 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2779 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2780 N0.getOpcode() == ISD::LOAD) {
2781 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2782 N0 : N0.getOperand(0) );
2784 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2785 // This can be a pure constant or a vector splat, in which case we treat the
2786 // vector as a scalar and use the splat value.
2787 APInt Constant = APInt::getNullValue(1);
2788 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2789 Constant = C->getAPIntValue();
2790 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2791 APInt SplatValue, SplatUndef;
2792 unsigned SplatBitSize;
2794 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2795 SplatBitSize, HasAnyUndefs);
2797 // Undef bits can contribute to a possible optimisation if set, so
2799 SplatValue |= SplatUndef;
2801 // The splat value may be something like "0x00FFFFFF", which means 0 for
2802 // the first vector value and FF for the rest, repeating. We need a mask
2803 // that will apply equally to all members of the vector, so AND all the
2804 // lanes of the constant together.
2805 EVT VT = Vector->getValueType(0);
2806 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2808 // If the splat value has been compressed to a bitlength lower
2809 // than the size of the vector lane, we need to re-expand it to
2811 if (BitWidth > SplatBitSize)
2812 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2813 SplatBitSize < BitWidth;
2814 SplatBitSize = SplatBitSize * 2)
2815 SplatValue |= SplatValue.shl(SplatBitSize);
2817 Constant = APInt::getAllOnesValue(BitWidth);
2818 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2819 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2823 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2824 // actually legal and isn't going to get expanded, else this is a false
2826 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2827 Load->getValueType(0),
2828 Load->getMemoryVT());
2830 // Resize the constant to the same size as the original memory access before
2831 // extension. If it is still the AllOnesValue then this AND is completely
2834 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2837 switch (Load->getExtensionType()) {
2838 default: B = false; break;
2839 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2841 case ISD::NON_EXTLOAD: B = true; break;
2844 if (B && Constant.isAllOnesValue()) {
2845 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2846 // preserve semantics once we get rid of the AND.
2847 SDValue NewLoad(Load, 0);
2848 if (Load->getExtensionType() == ISD::EXTLOAD) {
2849 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2850 Load->getValueType(0), SDLoc(Load),
2851 Load->getChain(), Load->getBasePtr(),
2852 Load->getOffset(), Load->getMemoryVT(),
2853 Load->getMemOperand());
2854 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2855 if (Load->getNumValues() == 3) {
2856 // PRE/POST_INC loads have 3 values.
2857 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2858 NewLoad.getValue(2) };
2859 CombineTo(Load, To, 3, true);
2861 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2865 // Fold the AND away, taking care not to fold to the old load node if we
2867 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2869 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2872 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2873 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2874 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2875 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2877 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2878 LL.getValueType().isInteger()) {
2879 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2880 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2881 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2882 LR.getValueType(), LL, RL);
2883 AddToWorklist(ORNode.getNode());
2884 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2886 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2887 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2888 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2889 LR.getValueType(), LL, RL);
2890 AddToWorklist(ANDNode.getNode());
2891 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2893 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2894 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2895 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2896 LR.getValueType(), LL, RL);
2897 AddToWorklist(ORNode.getNode());
2898 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2901 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2902 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2903 Op0 == Op1 && LL.getValueType().isInteger() &&
2904 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2905 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2906 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2907 cast<ConstantSDNode>(RR)->isNullValue()))) {
2908 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2909 LL, DAG.getConstant(1, LL.getValueType()));
2910 AddToWorklist(ADDNode.getNode());
2911 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2912 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2914 // canonicalize equivalent to ll == rl
2915 if (LL == RR && LR == RL) {
2916 Op1 = ISD::getSetCCSwappedOperands(Op1);
2919 if (LL == RL && LR == RR) {
2920 bool isInteger = LL.getValueType().isInteger();
2921 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2922 if (Result != ISD::SETCC_INVALID &&
2923 (!LegalOperations ||
2924 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2925 TLI.isOperationLegal(ISD::SETCC,
2926 getSetCCResultType(N0.getSimpleValueType())))))
2927 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2932 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2933 if (N0.getOpcode() == N1.getOpcode()) {
2934 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2935 if (Tmp.getNode()) return Tmp;
2938 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2939 // fold (and (sra)) -> (and (srl)) when possible.
2940 if (!VT.isVector() &&
2941 SimplifyDemandedBits(SDValue(N, 0)))
2942 return SDValue(N, 0);
2944 // fold (zext_inreg (extload x)) -> (zextload x)
2945 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2946 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2947 EVT MemVT = LN0->getMemoryVT();
2948 // If we zero all the possible extended bits, then we can turn this into
2949 // a zextload if we are running before legalize or the operation is legal.
2950 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2951 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2952 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2953 ((!LegalOperations && !LN0->isVolatile()) ||
2954 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
2955 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2956 LN0->getChain(), LN0->getBasePtr(),
2957 MemVT, LN0->getMemOperand());
2959 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2960 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2963 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2964 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2966 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2967 EVT MemVT = LN0->getMemoryVT();
2968 // If we zero all the possible extended bits, then we can turn this into
2969 // a zextload if we are running before legalize or the operation is legal.
2970 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2971 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2972 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2973 ((!LegalOperations && !LN0->isVolatile()) ||
2974 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
2975 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2976 LN0->getChain(), LN0->getBasePtr(),
2977 MemVT, LN0->getMemOperand());
2979 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2980 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2984 // fold (and (load x), 255) -> (zextload x, i8)
2985 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2986 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2987 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2988 (N0.getOpcode() == ISD::ANY_EXTEND &&
2989 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2990 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2991 LoadSDNode *LN0 = HasAnyExt
2992 ? cast<LoadSDNode>(N0.getOperand(0))
2993 : cast<LoadSDNode>(N0);
2994 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2995 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2996 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2997 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2998 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2999 EVT LoadedVT = LN0->getMemoryVT();
3000 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3002 if (ExtVT == LoadedVT &&
3003 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3007 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3008 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3009 LN0->getMemOperand());
3011 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3012 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3015 // Do not change the width of a volatile load.
3016 // Do not generate loads of non-round integer types since these can
3017 // be expensive (and would be wrong if the type is not byte sized).
3018 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3019 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3021 EVT PtrType = LN0->getOperand(1).getValueType();
3023 unsigned Alignment = LN0->getAlignment();
3024 SDValue NewPtr = LN0->getBasePtr();
3026 // For big endian targets, we need to add an offset to the pointer
3027 // to load the correct bytes. For little endian systems, we merely
3028 // need to read fewer bytes from the same pointer.
3029 if (TLI.isBigEndian()) {
3030 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3031 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3032 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3033 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3034 NewPtr, DAG.getConstant(PtrOff, PtrType));
3035 Alignment = MinAlign(Alignment, PtrOff);
3038 AddToWorklist(NewPtr.getNode());
3041 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3042 LN0->getChain(), NewPtr,
3043 LN0->getPointerInfo(),
3044 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3045 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3047 CombineTo(LN0, Load, Load.getValue(1));
3048 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3054 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3055 VT.getSizeInBits() <= 64) {
3056 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3057 APInt ADDC = ADDI->getAPIntValue();
3058 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3059 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3060 // immediate for an add, but it is legal if its top c2 bits are set,
3061 // transform the ADD so the immediate doesn't need to be materialized
3063 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3064 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3065 SRLI->getZExtValue());
3066 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3068 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3070 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3071 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3072 CombineTo(N0.getNode(), NewAdd);
3073 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3081 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3082 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3083 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3084 N0.getOperand(1), false);
3085 if (BSwap.getNode())
3092 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3093 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3094 bool DemandHighBits) {
3095 if (!LegalOperations)
3098 EVT VT = N->getValueType(0);
3099 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3101 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3104 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3105 bool LookPassAnd0 = false;
3106 bool LookPassAnd1 = false;
3107 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3109 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3111 if (N0.getOpcode() == ISD::AND) {
3112 if (!N0.getNode()->hasOneUse())
3114 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3115 if (!N01C || N01C->getZExtValue() != 0xFF00)
3117 N0 = N0.getOperand(0);
3118 LookPassAnd0 = true;
3121 if (N1.getOpcode() == ISD::AND) {
3122 if (!N1.getNode()->hasOneUse())
3124 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3125 if (!N11C || N11C->getZExtValue() != 0xFF)
3127 N1 = N1.getOperand(0);
3128 LookPassAnd1 = true;
3131 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3133 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3135 if (!N0.getNode()->hasOneUse() ||
3136 !N1.getNode()->hasOneUse())
3139 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3140 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3143 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3146 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3147 SDValue N00 = N0->getOperand(0);
3148 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3149 if (!N00.getNode()->hasOneUse())
3151 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3152 if (!N001C || N001C->getZExtValue() != 0xFF)
3154 N00 = N00.getOperand(0);
3155 LookPassAnd0 = true;
3158 SDValue N10 = N1->getOperand(0);
3159 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3160 if (!N10.getNode()->hasOneUse())
3162 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3163 if (!N101C || N101C->getZExtValue() != 0xFF00)
3165 N10 = N10.getOperand(0);
3166 LookPassAnd1 = true;
3172 // Make sure everything beyond the low halfword gets set to zero since the SRL
3173 // 16 will clear the top bits.
3174 unsigned OpSizeInBits = VT.getSizeInBits();
3175 if (DemandHighBits && OpSizeInBits > 16) {
3176 // If the left-shift isn't masked out then the only way this is a bswap is
3177 // if all bits beyond the low 8 are 0. In that case the entire pattern
3178 // reduces to a left shift anyway: leave it for other parts of the combiner.
3182 // However, if the right shift isn't masked out then it might be because
3183 // it's not needed. See if we can spot that too.
3184 if (!LookPassAnd1 &&
3185 !DAG.MaskedValueIsZero(
3186 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3190 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3191 if (OpSizeInBits > 16)
3192 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3193 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3197 /// Return true if the specified node is an element that makes up a 32-bit
3198 /// packed halfword byteswap.
3199 /// ((x & 0x000000ff) << 8) |
3200 /// ((x & 0x0000ff00) >> 8) |
3201 /// ((x & 0x00ff0000) << 8) |
3202 /// ((x & 0xff000000) >> 8)
3203 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3204 if (!N.getNode()->hasOneUse())
3207 unsigned Opc = N.getOpcode();
3208 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3211 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3216 switch (N1C->getZExtValue()) {
3219 case 0xFF: Num = 0; break;
3220 case 0xFF00: Num = 1; break;
3221 case 0xFF0000: Num = 2; break;
3222 case 0xFF000000: Num = 3; break;
3225 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3226 SDValue N0 = N.getOperand(0);
3227 if (Opc == ISD::AND) {
3228 if (Num == 0 || Num == 2) {
3230 // (x >> 8) & 0xff0000
3231 if (N0.getOpcode() != ISD::SRL)
3233 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3234 if (!C || C->getZExtValue() != 8)
3237 // (x << 8) & 0xff00
3238 // (x << 8) & 0xff000000
3239 if (N0.getOpcode() != ISD::SHL)
3241 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3242 if (!C || C->getZExtValue() != 8)
3245 } else if (Opc == ISD::SHL) {
3247 // (x & 0xff0000) << 8
3248 if (Num != 0 && Num != 2)
3250 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3251 if (!C || C->getZExtValue() != 8)
3253 } else { // Opc == ISD::SRL
3254 // (x & 0xff00) >> 8
3255 // (x & 0xff000000) >> 8
3256 if (Num != 1 && Num != 3)
3258 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3259 if (!C || C->getZExtValue() != 8)
3266 Parts[Num] = N0.getOperand(0).getNode();
3270 /// Match a 32-bit packed halfword bswap. That is
3271 /// ((x & 0x000000ff) << 8) |
3272 /// ((x & 0x0000ff00) >> 8) |
3273 /// ((x & 0x00ff0000) << 8) |
3274 /// ((x & 0xff000000) >> 8)
3275 /// => (rotl (bswap x), 16)
3276 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3277 if (!LegalOperations)
3280 EVT VT = N->getValueType(0);
3283 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3287 // (or (or (and), (and)), (or (and), (and)))
3288 // (or (or (or (and), (and)), (and)), (and))
3289 if (N0.getOpcode() != ISD::OR)
3291 SDValue N00 = N0.getOperand(0);
3292 SDValue N01 = N0.getOperand(1);
3293 SDNode *Parts[4] = {};
3295 if (N1.getOpcode() == ISD::OR &&
3296 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3297 // (or (or (and), (and)), (or (and), (and)))
3298 SDValue N000 = N00.getOperand(0);
3299 if (!isBSwapHWordElement(N000, Parts))
3302 SDValue N001 = N00.getOperand(1);
3303 if (!isBSwapHWordElement(N001, Parts))
3305 SDValue N010 = N01.getOperand(0);
3306 if (!isBSwapHWordElement(N010, Parts))
3308 SDValue N011 = N01.getOperand(1);
3309 if (!isBSwapHWordElement(N011, Parts))
3312 // (or (or (or (and), (and)), (and)), (and))
3313 if (!isBSwapHWordElement(N1, Parts))
3315 if (!isBSwapHWordElement(N01, Parts))
3317 if (N00.getOpcode() != ISD::OR)
3319 SDValue N000 = N00.getOperand(0);
3320 if (!isBSwapHWordElement(N000, Parts))
3322 SDValue N001 = N00.getOperand(1);
3323 if (!isBSwapHWordElement(N001, Parts))
3327 // Make sure the parts are all coming from the same node.
3328 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3331 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3332 SDValue(Parts[0],0));
3334 // Result of the bswap should be rotated by 16. If it's not legal, then
3335 // do (x << 16) | (x >> 16).
3336 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3337 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3338 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3339 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3340 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3341 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3342 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3343 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3346 SDValue DAGCombiner::visitOR(SDNode *N) {
3347 SDValue N0 = N->getOperand(0);
3348 SDValue N1 = N->getOperand(1);
3349 SDValue LL, LR, RL, RR, CC0, CC1;
3350 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3351 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3352 EVT VT = N1.getValueType();
3355 if (VT.isVector()) {
3356 SDValue FoldedVOp = SimplifyVBinOp(N);
3357 if (FoldedVOp.getNode()) return FoldedVOp;
3359 // fold (or x, 0) -> x, vector edition
3360 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3362 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3365 // fold (or x, -1) -> -1, vector edition
3366 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3367 // do not return N0, because undef node may exist in N0
3368 return DAG.getConstant(
3369 APInt::getAllOnesValue(
3370 N0.getValueType().getScalarType().getSizeInBits()),
3372 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3373 // do not return N1, because undef node may exist in N1
3374 return DAG.getConstant(
3375 APInt::getAllOnesValue(
3376 N1.getValueType().getScalarType().getSizeInBits()),
3379 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3380 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3381 // Do this only if the resulting shuffle is legal.
3382 if (isa<ShuffleVectorSDNode>(N0) &&
3383 isa<ShuffleVectorSDNode>(N1) &&
3384 // Avoid folding a node with illegal type.
3385 TLI.isTypeLegal(VT) &&
3386 N0->getOperand(1) == N1->getOperand(1) &&
3387 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3388 bool CanFold = true;
3389 unsigned NumElts = VT.getVectorNumElements();
3390 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3391 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3392 // We construct two shuffle masks:
3393 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3394 // and N1 as the second operand.
3395 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3396 // and N0 as the second operand.
3397 // We do this because OR is commutable and therefore there might be
3398 // two ways to fold this node into a shuffle.
3399 SmallVector<int,4> Mask1;
3400 SmallVector<int,4> Mask2;
3402 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3403 int M0 = SV0->getMaskElt(i);
3404 int M1 = SV1->getMaskElt(i);
3406 // Both shuffle indexes are undef. Propagate Undef.
3407 if (M0 < 0 && M1 < 0) {
3408 Mask1.push_back(M0);
3409 Mask2.push_back(M0);
3413 if (M0 < 0 || M1 < 0 ||
3414 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3415 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3420 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3421 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3425 // Fold this sequence only if the resulting shuffle is 'legal'.
3426 if (TLI.isShuffleMaskLegal(Mask1, VT))
3427 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3428 N1->getOperand(0), &Mask1[0]);
3429 if (TLI.isShuffleMaskLegal(Mask2, VT))
3430 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3431 N0->getOperand(0), &Mask2[0]);
3436 // fold (or x, undef) -> -1
3437 if (!LegalOperations &&
3438 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3439 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3440 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3442 // fold (or c1, c2) -> c1|c2
3444 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3445 // canonicalize constant to RHS
3447 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3448 // fold (or x, 0) -> x
3449 if (N1C && N1C->isNullValue())
3451 // fold (or x, -1) -> -1
3452 if (N1C && N1C->isAllOnesValue())
3454 // fold (or x, c) -> c iff (x & ~c) == 0
3455 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3458 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3459 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3460 if (BSwap.getNode())
3462 BSwap = MatchBSwapHWordLow(N, N0, N1);
3463 if (BSwap.getNode())
3467 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3470 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3471 // iff (c1 & c2) == 0.
3472 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3473 isa<ConstantSDNode>(N0.getOperand(1))) {
3474 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3475 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3476 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3478 ISD::AND, SDLoc(N), VT,
3479 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3483 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3484 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3485 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3486 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3488 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3489 LL.getValueType().isInteger()) {
3490 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3491 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3492 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3493 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3494 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3495 LR.getValueType(), LL, RL);
3496 AddToWorklist(ORNode.getNode());
3497 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3499 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3500 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3501 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3502 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3503 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3504 LR.getValueType(), LL, RL);
3505 AddToWorklist(ANDNode.getNode());
3506 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3509 // canonicalize equivalent to ll == rl
3510 if (LL == RR && LR == RL) {
3511 Op1 = ISD::getSetCCSwappedOperands(Op1);
3514 if (LL == RL && LR == RR) {
3515 bool isInteger = LL.getValueType().isInteger();
3516 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3517 if (Result != ISD::SETCC_INVALID &&
3518 (!LegalOperations ||
3519 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3520 TLI.isOperationLegal(ISD::SETCC,
3521 getSetCCResultType(N0.getValueType())))))
3522 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3527 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3528 if (N0.getOpcode() == N1.getOpcode()) {
3529 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3530 if (Tmp.getNode()) return Tmp;
3533 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3534 if (N0.getOpcode() == ISD::AND &&
3535 N1.getOpcode() == ISD::AND &&
3536 N0.getOperand(1).getOpcode() == ISD::Constant &&
3537 N1.getOperand(1).getOpcode() == ISD::Constant &&
3538 // Don't increase # computations.
3539 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3540 // We can only do this xform if we know that bits from X that are set in C2
3541 // but not in C1 are already zero. Likewise for Y.
3542 const APInt &LHSMask =
3543 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3544 const APInt &RHSMask =
3545 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3547 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3548 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3549 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3550 N0.getOperand(0), N1.getOperand(0));
3551 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3552 DAG.getConstant(LHSMask | RHSMask, VT));
3556 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3557 if (N0.getOpcode() == ISD::AND &&
3558 N1.getOpcode() == ISD::AND &&
3559 N0.getOperand(0) == N1.getOperand(0) &&
3560 // Don't increase # computations.
3561 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3562 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3563 N0.getOperand(1), N1.getOperand(1));
3564 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), X);
3567 // See if this is some rotate idiom.
3568 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3569 return SDValue(Rot, 0);
3571 // Simplify the operands using demanded-bits information.
3572 if (!VT.isVector() &&
3573 SimplifyDemandedBits(SDValue(N, 0)))
3574 return SDValue(N, 0);
3579 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3580 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3581 if (Op.getOpcode() == ISD::AND) {
3582 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3583 Mask = Op.getOperand(1);
3584 Op = Op.getOperand(0);
3590 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3598 // Return true if we can prove that, whenever Neg and Pos are both in the
3599 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3600 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3602 // (or (shift1 X, Neg), (shift2 X, Pos))
3604 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3605 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3606 // to consider shift amounts with defined behavior.
3607 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3608 // If OpSize is a power of 2 then:
3610 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3611 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3613 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3614 // for the stronger condition:
3616 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3618 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3619 // we can just replace Neg with Neg' for the rest of the function.
3621 // In other cases we check for the even stronger condition:
3623 // Neg == OpSize - Pos [B]
3625 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3626 // behavior if Pos == 0 (and consequently Neg == OpSize).
3628 // We could actually use [A] whenever OpSize is a power of 2, but the
3629 // only extra cases that it would match are those uninteresting ones
3630 // where Neg and Pos are never in range at the same time. E.g. for
3631 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3632 // as well as (sub 32, Pos), but:
3634 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3636 // always invokes undefined behavior for 32-bit X.
3638 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3639 unsigned MaskLoBits = 0;
3640 if (Neg.getOpcode() == ISD::AND &&
3641 isPowerOf2_64(OpSize) &&
3642 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3643 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3644 Neg = Neg.getOperand(0);
3645 MaskLoBits = Log2_64(OpSize);
3648 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3649 if (Neg.getOpcode() != ISD::SUB)
3651 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3654 SDValue NegOp1 = Neg.getOperand(1);
3656 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3657 // Pos'. The truncation is redundant for the purpose of the equality.
3659 Pos.getOpcode() == ISD::AND &&
3660 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3661 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3662 Pos = Pos.getOperand(0);
3664 // The condition we need is now:
3666 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3668 // If NegOp1 == Pos then we need:
3670 // OpSize & Mask == NegC & Mask
3672 // (because "x & Mask" is a truncation and distributes through subtraction).
3675 Width = NegC->getAPIntValue();
3676 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3677 // Then the condition we want to prove becomes:
3679 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3681 // which, again because "x & Mask" is a truncation, becomes:
3683 // NegC & Mask == (OpSize - PosC) & Mask
3684 // OpSize & Mask == (NegC + PosC) & Mask
3685 else if (Pos.getOpcode() == ISD::ADD &&
3686 Pos.getOperand(0) == NegOp1 &&
3687 Pos.getOperand(1).getOpcode() == ISD::Constant)
3688 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3689 NegC->getAPIntValue());
3693 // Now we just need to check that OpSize & Mask == Width & Mask.
3695 // Opsize & Mask is 0 since Mask is Opsize - 1.
3696 return Width.getLoBits(MaskLoBits) == 0;
3697 return Width == OpSize;
3700 // A subroutine of MatchRotate used once we have found an OR of two opposite
3701 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3702 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3703 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3704 // Neg with outer conversions stripped away.
3705 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3706 SDValue Neg, SDValue InnerPos,
3707 SDValue InnerNeg, unsigned PosOpcode,
3708 unsigned NegOpcode, SDLoc DL) {
3709 // fold (or (shl x, (*ext y)),
3710 // (srl x, (*ext (sub 32, y)))) ->
3711 // (rotl x, y) or (rotr x, (sub 32, y))
3713 // fold (or (shl x, (*ext (sub 32, y))),
3714 // (srl x, (*ext y))) ->
3715 // (rotr x, y) or (rotl x, (sub 32, y))
3716 EVT VT = Shifted.getValueType();
3717 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3718 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3719 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3720 HasPos ? Pos : Neg).getNode();
3726 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3727 // idioms for rotate, and if the target supports rotation instructions, generate
3729 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3730 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3731 EVT VT = LHS.getValueType();
3732 if (!TLI.isTypeLegal(VT)) return nullptr;
3734 // The target must have at least one rotate flavor.
3735 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3736 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3737 if (!HasROTL && !HasROTR) return nullptr;
3739 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3740 SDValue LHSShift; // The shift.
3741 SDValue LHSMask; // AND value if any.
3742 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3743 return nullptr; // Not part of a rotate.
3745 SDValue RHSShift; // The shift.
3746 SDValue RHSMask; // AND value if any.
3747 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3748 return nullptr; // Not part of a rotate.
3750 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3751 return nullptr; // Not shifting the same value.
3753 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3754 return nullptr; // Shifts must disagree.
3756 // Canonicalize shl to left side in a shl/srl pair.
3757 if (RHSShift.getOpcode() == ISD::SHL) {
3758 std::swap(LHS, RHS);
3759 std::swap(LHSShift, RHSShift);
3760 std::swap(LHSMask , RHSMask );
3763 unsigned OpSizeInBits = VT.getSizeInBits();
3764 SDValue LHSShiftArg = LHSShift.getOperand(0);
3765 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3766 SDValue RHSShiftArg = RHSShift.getOperand(0);
3767 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3769 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3770 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3771 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3772 RHSShiftAmt.getOpcode() == ISD::Constant) {
3773 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3774 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3775 if ((LShVal + RShVal) != OpSizeInBits)
3778 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3779 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3781 // If there is an AND of either shifted operand, apply it to the result.
3782 if (LHSMask.getNode() || RHSMask.getNode()) {
3783 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3785 if (LHSMask.getNode()) {
3786 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3787 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3789 if (RHSMask.getNode()) {
3790 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3791 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3794 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3797 return Rot.getNode();
3800 // If there is a mask here, and we have a variable shift, we can't be sure
3801 // that we're masking out the right stuff.
3802 if (LHSMask.getNode() || RHSMask.getNode())
3805 // If the shift amount is sign/zext/any-extended just peel it off.
3806 SDValue LExtOp0 = LHSShiftAmt;
3807 SDValue RExtOp0 = RHSShiftAmt;
3808 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3809 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3810 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3811 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3812 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3813 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3814 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3815 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3816 LExtOp0 = LHSShiftAmt.getOperand(0);
3817 RExtOp0 = RHSShiftAmt.getOperand(0);
3820 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3821 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3825 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3826 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3833 SDValue DAGCombiner::visitXOR(SDNode *N) {
3834 SDValue N0 = N->getOperand(0);
3835 SDValue N1 = N->getOperand(1);
3836 SDValue LHS, RHS, CC;
3837 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3838 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3839 EVT VT = N0.getValueType();
3842 if (VT.isVector()) {
3843 SDValue FoldedVOp = SimplifyVBinOp(N);
3844 if (FoldedVOp.getNode()) return FoldedVOp;
3846 // fold (xor x, 0) -> x, vector edition
3847 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3849 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3853 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3854 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3855 return DAG.getConstant(0, VT);
3856 // fold (xor x, undef) -> undef
3857 if (N0.getOpcode() == ISD::UNDEF)
3859 if (N1.getOpcode() == ISD::UNDEF)
3861 // fold (xor c1, c2) -> c1^c2
3863 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3864 // canonicalize constant to RHS
3866 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3867 // fold (xor x, 0) -> x
3868 if (N1C && N1C->isNullValue())
3871 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3875 // fold !(x cc y) -> (x !cc y)
3876 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3877 bool isInt = LHS.getValueType().isInteger();
3878 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3881 if (!LegalOperations ||
3882 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3883 switch (N0.getOpcode()) {
3885 llvm_unreachable("Unhandled SetCC Equivalent!");
3887 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3888 case ISD::SELECT_CC:
3889 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3890 N0.getOperand(3), NotCC);
3895 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3896 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3897 N0.getNode()->hasOneUse() &&
3898 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3899 SDValue V = N0.getOperand(0);
3900 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3901 DAG.getConstant(1, V.getValueType()));
3902 AddToWorklist(V.getNode());
3903 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3906 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3907 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3908 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3909 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3910 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3911 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3912 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3913 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3914 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3915 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3918 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3919 if (N1C && N1C->isAllOnesValue() &&
3920 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3921 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3922 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3923 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3924 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3925 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3926 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3927 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3930 // fold (xor (and x, y), y) -> (and (not x), y)
3931 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3932 N0->getOperand(1) == N1) {
3933 SDValue X = N0->getOperand(0);
3934 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3935 AddToWorklist(NotX.getNode());
3936 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3938 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3939 if (N1C && N0.getOpcode() == ISD::XOR) {
3940 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3941 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3943 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3944 DAG.getConstant(N1C->getAPIntValue() ^
3945 N00C->getAPIntValue(), VT));
3947 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3948 DAG.getConstant(N1C->getAPIntValue() ^
3949 N01C->getAPIntValue(), VT));
3951 // fold (xor x, x) -> 0
3953 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3955 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3956 if (N0.getOpcode() == N1.getOpcode()) {
3957 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3958 if (Tmp.getNode()) return Tmp;
3961 // Simplify the expression using non-local knowledge.
3962 if (!VT.isVector() &&
3963 SimplifyDemandedBits(SDValue(N, 0)))
3964 return SDValue(N, 0);
3969 /// Handle transforms common to the three shifts, when the shift amount is a
3971 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3972 // We can't and shouldn't fold opaque constants.
3973 if (Amt->isOpaque())
3976 SDNode *LHS = N->getOperand(0).getNode();
3977 if (!LHS->hasOneUse()) return SDValue();
3979 // We want to pull some binops through shifts, so that we have (and (shift))
3980 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3981 // thing happens with address calculations, so it's important to canonicalize
3983 bool HighBitSet = false; // Can we transform this if the high bit is set?
3985 switch (LHS->getOpcode()) {
3986 default: return SDValue();
3989 HighBitSet = false; // We can only transform sra if the high bit is clear.
3992 HighBitSet = true; // We can only transform sra if the high bit is set.
3995 if (N->getOpcode() != ISD::SHL)
3996 return SDValue(); // only shl(add) not sr[al](add).
3997 HighBitSet = false; // We can only transform sra if the high bit is clear.
4001 // We require the RHS of the binop to be a constant and not opaque as well.
4002 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4003 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4005 // FIXME: disable this unless the input to the binop is a shift by a constant.
4006 // If it is not a shift, it pessimizes some common cases like:
4008 // void foo(int *X, int i) { X[i & 1235] = 1; }
4009 // int bar(int *X, int i) { return X[i & 255]; }
4010 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4011 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4012 BinOpLHSVal->getOpcode() != ISD::SRA &&
4013 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4014 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4017 EVT VT = N->getValueType(0);
4019 // If this is a signed shift right, and the high bit is modified by the
4020 // logical operation, do not perform the transformation. The highBitSet
4021 // boolean indicates the value of the high bit of the constant which would
4022 // cause it to be modified for this operation.
4023 if (N->getOpcode() == ISD::SRA) {
4024 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4025 if (BinOpRHSSignSet != HighBitSet)
4029 if (!TLI.isDesirableToCommuteWithShift(LHS))
4032 // Fold the constants, shifting the binop RHS by the shift amount.
4033 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4035 LHS->getOperand(1), N->getOperand(1));
4036 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4038 // Create the new shift.
4039 SDValue NewShift = DAG.getNode(N->getOpcode(),
4040 SDLoc(LHS->getOperand(0)),
4041 VT, LHS->getOperand(0), N->getOperand(1));
4043 // Create the new binop.
4044 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4047 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4048 assert(N->getOpcode() == ISD::TRUNCATE);
4049 assert(N->getOperand(0).getOpcode() == ISD::AND);
4051 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4052 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4053 SDValue N01 = N->getOperand(0).getOperand(1);
4055 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4056 EVT TruncVT = N->getValueType(0);
4057 SDValue N00 = N->getOperand(0).getOperand(0);
4058 APInt TruncC = N01C->getAPIntValue();
4059 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4061 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4062 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4063 DAG.getConstant(TruncC, TruncVT));
4070 SDValue DAGCombiner::visitRotate(SDNode *N) {
4071 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4072 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4073 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4074 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4075 if (NewOp1.getNode())
4076 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4077 N->getOperand(0), NewOp1);
4082 SDValue DAGCombiner::visitSHL(SDNode *N) {
4083 SDValue N0 = N->getOperand(0);
4084 SDValue N1 = N->getOperand(1);
4085 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4086 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4087 EVT VT = N0.getValueType();
4088 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4091 if (VT.isVector()) {
4092 SDValue FoldedVOp = SimplifyVBinOp(N);
4093 if (FoldedVOp.getNode()) return FoldedVOp;
4095 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4096 // If setcc produces all-one true value then:
4097 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4098 if (N1CV && N1CV->isConstant()) {
4099 if (N0.getOpcode() == ISD::AND) {
4100 SDValue N00 = N0->getOperand(0);
4101 SDValue N01 = N0->getOperand(1);
4102 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4104 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4105 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4106 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4107 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
4108 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4111 N1C = isConstOrConstSplat(N1);
4116 // fold (shl c1, c2) -> c1<<c2
4118 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4119 // fold (shl 0, x) -> 0
4120 if (N0C && N0C->isNullValue())
4122 // fold (shl x, c >= size(x)) -> undef
4123 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4124 return DAG.getUNDEF(VT);
4125 // fold (shl x, 0) -> x
4126 if (N1C && N1C->isNullValue())
4128 // fold (shl undef, x) -> 0
4129 if (N0.getOpcode() == ISD::UNDEF)
4130 return DAG.getConstant(0, VT);
4131 // if (shl x, c) is known to be zero, return 0
4132 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4133 APInt::getAllOnesValue(OpSizeInBits)))
4134 return DAG.getConstant(0, VT);
4135 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4136 if (N1.getOpcode() == ISD::TRUNCATE &&
4137 N1.getOperand(0).getOpcode() == ISD::AND) {
4138 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4139 if (NewOp1.getNode())
4140 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4143 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4144 return SDValue(N, 0);
4146 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4147 if (N1C && N0.getOpcode() == ISD::SHL) {
4148 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4149 uint64_t c1 = N0C1->getZExtValue();
4150 uint64_t c2 = N1C->getZExtValue();
4151 if (c1 + c2 >= OpSizeInBits)
4152 return DAG.getConstant(0, VT);
4153 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4154 DAG.getConstant(c1 + c2, N1.getValueType()));
4158 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4159 // For this to be valid, the second form must not preserve any of the bits
4160 // that are shifted out by the inner shift in the first form. This means
4161 // the outer shift size must be >= the number of bits added by the ext.
4162 // As a corollary, we don't care what kind of ext it is.
4163 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4164 N0.getOpcode() == ISD::ANY_EXTEND ||
4165 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4166 N0.getOperand(0).getOpcode() == ISD::SHL) {
4167 SDValue N0Op0 = N0.getOperand(0);
4168 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4169 uint64_t c1 = N0Op0C1->getZExtValue();
4170 uint64_t c2 = N1C->getZExtValue();
4171 EVT InnerShiftVT = N0Op0.getValueType();
4172 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4173 if (c2 >= OpSizeInBits - InnerShiftSize) {
4174 if (c1 + c2 >= OpSizeInBits)
4175 return DAG.getConstant(0, VT);
4176 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4177 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4178 N0Op0->getOperand(0)),
4179 DAG.getConstant(c1 + c2, N1.getValueType()));
4184 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4185 // Only fold this if the inner zext has no other uses to avoid increasing
4186 // the total number of instructions.
4187 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4188 N0.getOperand(0).getOpcode() == ISD::SRL) {
4189 SDValue N0Op0 = N0.getOperand(0);
4190 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4191 uint64_t c1 = N0Op0C1->getZExtValue();
4192 if (c1 < VT.getScalarSizeInBits()) {
4193 uint64_t c2 = N1C->getZExtValue();
4195 SDValue NewOp0 = N0.getOperand(0);
4196 EVT CountVT = NewOp0.getOperand(1).getValueType();
4197 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4198 NewOp0, DAG.getConstant(c2, CountVT));
4199 AddToWorklist(NewSHL.getNode());
4200 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4206 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4207 // (and (srl x, (sub c1, c2), MASK)
4208 // Only fold this if the inner shift has no other uses -- if it does, folding
4209 // this will increase the total number of instructions.
4210 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4211 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4212 uint64_t c1 = N0C1->getZExtValue();
4213 if (c1 < OpSizeInBits) {
4214 uint64_t c2 = N1C->getZExtValue();
4215 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4218 Mask = Mask.shl(c2 - c1);
4219 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4220 DAG.getConstant(c2 - c1, N1.getValueType()));
4222 Mask = Mask.lshr(c1 - c2);
4223 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4224 DAG.getConstant(c1 - c2, N1.getValueType()));
4226 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4227 DAG.getConstant(Mask, VT));
4231 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4232 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4233 unsigned BitSize = VT.getScalarSizeInBits();
4234 SDValue HiBitsMask =
4235 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4236 BitSize - N1C->getZExtValue()), VT);
4237 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4241 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4242 // Variant of version done on multiply, except mul by a power of 2 is turned
4245 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4246 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4247 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4248 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4249 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4250 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4254 SDValue NewSHL = visitShiftByConstant(N, N1C);
4255 if (NewSHL.getNode())
4262 SDValue DAGCombiner::visitSRA(SDNode *N) {
4263 SDValue N0 = N->getOperand(0);
4264 SDValue N1 = N->getOperand(1);
4265 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4266 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4267 EVT VT = N0.getValueType();
4268 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4271 if (VT.isVector()) {
4272 SDValue FoldedVOp = SimplifyVBinOp(N);
4273 if (FoldedVOp.getNode()) return FoldedVOp;
4275 N1C = isConstOrConstSplat(N1);
4278 // fold (sra c1, c2) -> (sra c1, c2)
4280 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4281 // fold (sra 0, x) -> 0
4282 if (N0C && N0C->isNullValue())
4284 // fold (sra -1, x) -> -1
4285 if (N0C && N0C->isAllOnesValue())
4287 // fold (sra x, (setge c, size(x))) -> undef
4288 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4289 return DAG.getUNDEF(VT);
4290 // fold (sra x, 0) -> x
4291 if (N1C && N1C->isNullValue())
4293 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4295 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4296 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4297 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4299 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4300 ExtVT, VT.getVectorNumElements());
4301 if ((!LegalOperations ||
4302 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4303 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4304 N0.getOperand(0), DAG.getValueType(ExtVT));
4307 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4308 if (N1C && N0.getOpcode() == ISD::SRA) {
4309 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4310 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4311 if (Sum >= OpSizeInBits)
4312 Sum = OpSizeInBits - 1;
4313 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4314 DAG.getConstant(Sum, N1.getValueType()));
4318 // fold (sra (shl X, m), (sub result_size, n))
4319 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4320 // result_size - n != m.
4321 // If truncate is free for the target sext(shl) is likely to result in better
4323 if (N0.getOpcode() == ISD::SHL && N1C) {
4324 // Get the two constanst of the shifts, CN0 = m, CN = n.
4325 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4327 LLVMContext &Ctx = *DAG.getContext();
4328 // Determine what the truncate's result bitsize and type would be.
4329 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4332 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4334 // Determine the residual right-shift amount.
4335 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4337 // If the shift is not a no-op (in which case this should be just a sign
4338 // extend already), the truncated to type is legal, sign_extend is legal
4339 // on that type, and the truncate to that type is both legal and free,
4340 // perform the transform.
4341 if ((ShiftAmt > 0) &&
4342 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4343 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4344 TLI.isTruncateFree(VT, TruncVT)) {
4346 SDValue Amt = DAG.getConstant(ShiftAmt,
4347 getShiftAmountTy(N0.getOperand(0).getValueType()));
4348 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4349 N0.getOperand(0), Amt);
4350 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4352 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4353 N->getValueType(0), Trunc);
4358 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4359 if (N1.getOpcode() == ISD::TRUNCATE &&
4360 N1.getOperand(0).getOpcode() == ISD::AND) {
4361 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4362 if (NewOp1.getNode())
4363 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4366 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4367 // if c1 is equal to the number of bits the trunc removes
4368 if (N0.getOpcode() == ISD::TRUNCATE &&
4369 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4370 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4371 N0.getOperand(0).hasOneUse() &&
4372 N0.getOperand(0).getOperand(1).hasOneUse() &&
4374 SDValue N0Op0 = N0.getOperand(0);
4375 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4376 unsigned LargeShiftVal = LargeShift->getZExtValue();
4377 EVT LargeVT = N0Op0.getValueType();
4379 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4381 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4382 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4383 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4384 N0Op0.getOperand(0), Amt);
4385 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4390 // Simplify, based on bits shifted out of the LHS.
4391 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4392 return SDValue(N, 0);
4395 // If the sign bit is known to be zero, switch this to a SRL.
4396 if (DAG.SignBitIsZero(N0))
4397 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4400 SDValue NewSRA = visitShiftByConstant(N, N1C);
4401 if (NewSRA.getNode())
4408 SDValue DAGCombiner::visitSRL(SDNode *N) {
4409 SDValue N0 = N->getOperand(0);
4410 SDValue N1 = N->getOperand(1);
4411 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4412 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4413 EVT VT = N0.getValueType();
4414 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4417 if (VT.isVector()) {
4418 SDValue FoldedVOp = SimplifyVBinOp(N);
4419 if (FoldedVOp.getNode()) return FoldedVOp;
4421 N1C = isConstOrConstSplat(N1);
4424 // fold (srl c1, c2) -> c1 >>u c2
4426 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4427 // fold (srl 0, x) -> 0
4428 if (N0C && N0C->isNullValue())
4430 // fold (srl x, c >= size(x)) -> undef
4431 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4432 return DAG.getUNDEF(VT);
4433 // fold (srl x, 0) -> x
4434 if (N1C && N1C->isNullValue())
4436 // if (srl x, c) is known to be zero, return 0
4437 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4438 APInt::getAllOnesValue(OpSizeInBits)))
4439 return DAG.getConstant(0, VT);
4441 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4442 if (N1C && N0.getOpcode() == ISD::SRL) {
4443 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4444 uint64_t c1 = N01C->getZExtValue();
4445 uint64_t c2 = N1C->getZExtValue();
4446 if (c1 + c2 >= OpSizeInBits)
4447 return DAG.getConstant(0, VT);
4448 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4449 DAG.getConstant(c1 + c2, N1.getValueType()));
4453 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4454 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4455 N0.getOperand(0).getOpcode() == ISD::SRL &&
4456 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4458 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4459 uint64_t c2 = N1C->getZExtValue();
4460 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4461 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4462 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4463 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4464 if (c1 + OpSizeInBits == InnerShiftSize) {
4465 if (c1 + c2 >= InnerShiftSize)
4466 return DAG.getConstant(0, VT);
4467 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4468 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4469 N0.getOperand(0)->getOperand(0),
4470 DAG.getConstant(c1 + c2, ShiftCountVT)));
4474 // fold (srl (shl x, c), c) -> (and x, cst2)
4475 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4476 unsigned BitSize = N0.getScalarValueSizeInBits();
4477 if (BitSize <= 64) {
4478 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4479 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4480 DAG.getConstant(~0ULL >> ShAmt, VT));
4484 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4485 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4486 // Shifting in all undef bits?
4487 EVT SmallVT = N0.getOperand(0).getValueType();
4488 unsigned BitSize = SmallVT.getScalarSizeInBits();
4489 if (N1C->getZExtValue() >= BitSize)
4490 return DAG.getUNDEF(VT);
4492 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4493 uint64_t ShiftAmt = N1C->getZExtValue();
4494 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4496 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4497 AddToWorklist(SmallShift.getNode());
4498 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4499 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4500 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4501 DAG.getConstant(Mask, VT));
4505 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4506 // bit, which is unmodified by sra.
4507 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4508 if (N0.getOpcode() == ISD::SRA)
4509 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4512 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4513 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4514 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4515 APInt KnownZero, KnownOne;
4516 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4518 // If any of the input bits are KnownOne, then the input couldn't be all
4519 // zeros, thus the result of the srl will always be zero.
4520 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4522 // If all of the bits input the to ctlz node are known to be zero, then
4523 // the result of the ctlz is "32" and the result of the shift is one.
4524 APInt UnknownBits = ~KnownZero;
4525 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4527 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4528 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4529 // Okay, we know that only that the single bit specified by UnknownBits
4530 // could be set on input to the CTLZ node. If this bit is set, the SRL
4531 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4532 // to an SRL/XOR pair, which is likely to simplify more.
4533 unsigned ShAmt = UnknownBits.countTrailingZeros();
4534 SDValue Op = N0.getOperand(0);
4537 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4538 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4539 AddToWorklist(Op.getNode());
4542 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4543 Op, DAG.getConstant(1, VT));
4547 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4548 if (N1.getOpcode() == ISD::TRUNCATE &&
4549 N1.getOperand(0).getOpcode() == ISD::AND) {
4550 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4551 if (NewOp1.getNode())
4552 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4555 // fold operands of srl based on knowledge that the low bits are not
4557 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4558 return SDValue(N, 0);
4561 SDValue NewSRL = visitShiftByConstant(N, N1C);
4562 if (NewSRL.getNode())
4566 // Attempt to convert a srl of a load into a narrower zero-extending load.
4567 SDValue NarrowLoad = ReduceLoadWidth(N);
4568 if (NarrowLoad.getNode())
4571 // Here is a common situation. We want to optimize:
4574 // %b = and i32 %a, 2
4575 // %c = srl i32 %b, 1
4576 // brcond i32 %c ...
4582 // %c = setcc eq %b, 0
4585 // However when after the source operand of SRL is optimized into AND, the SRL
4586 // itself may not be optimized further. Look for it and add the BRCOND into
4588 if (N->hasOneUse()) {
4589 SDNode *Use = *N->use_begin();
4590 if (Use->getOpcode() == ISD::BRCOND)
4592 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4593 // Also look pass the truncate.
4594 Use = *Use->use_begin();
4595 if (Use->getOpcode() == ISD::BRCOND)
4603 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4604 SDValue N0 = N->getOperand(0);
4605 EVT VT = N->getValueType(0);
4607 // fold (ctlz c1) -> c2
4608 if (isa<ConstantSDNode>(N0))
4609 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4613 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4614 SDValue N0 = N->getOperand(0);
4615 EVT VT = N->getValueType(0);
4617 // fold (ctlz_zero_undef c1) -> c2
4618 if (isa<ConstantSDNode>(N0))
4619 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4623 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4624 SDValue N0 = N->getOperand(0);
4625 EVT VT = N->getValueType(0);
4627 // fold (cttz c1) -> c2
4628 if (isa<ConstantSDNode>(N0))
4629 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4633 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4634 SDValue N0 = N->getOperand(0);
4635 EVT VT = N->getValueType(0);
4637 // fold (cttz_zero_undef c1) -> c2
4638 if (isa<ConstantSDNode>(N0))
4639 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4643 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4644 SDValue N0 = N->getOperand(0);
4645 EVT VT = N->getValueType(0);
4647 // fold (ctpop c1) -> c2
4648 if (isa<ConstantSDNode>(N0))
4649 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4654 /// \brief Generate Min/Max node
4655 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4656 SDValue True, SDValue False,
4657 ISD::CondCode CC, const TargetLowering &TLI,
4658 SelectionDAG &DAG) {
4659 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4669 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4670 if (TLI.isOperationLegal(Opcode, VT))
4671 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4680 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4681 if (TLI.isOperationLegal(Opcode, VT))
4682 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4690 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4691 SDValue N0 = N->getOperand(0);
4692 SDValue N1 = N->getOperand(1);
4693 SDValue N2 = N->getOperand(2);
4694 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4695 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4696 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4697 EVT VT = N->getValueType(0);
4698 EVT VT0 = N0.getValueType();
4700 // fold (select C, X, X) -> X
4703 // fold (select true, X, Y) -> X
4704 if (N0C && !N0C->isNullValue())
4706 // fold (select false, X, Y) -> Y
4707 if (N0C && N0C->isNullValue())
4709 // fold (select C, 1, X) -> (or C, X)
4710 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4711 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4712 // fold (select C, 0, 1) -> (xor C, 1)
4713 // We can't do this reliably if integer based booleans have different contents
4714 // to floating point based booleans. This is because we can't tell whether we
4715 // have an integer-based boolean or a floating-point-based boolean unless we
4716 // can find the SETCC that produced it and inspect its operands. This is
4717 // fairly easy if C is the SETCC node, but it can potentially be
4718 // undiscoverable (or not reasonably discoverable). For example, it could be
4719 // in another basic block or it could require searching a complicated
4721 if (VT.isInteger() &&
4722 (VT0 == MVT::i1 || (VT0.isInteger() &&
4723 TLI.getBooleanContents(false, false) ==
4724 TLI.getBooleanContents(false, true) &&
4725 TLI.getBooleanContents(false, false) ==
4726 TargetLowering::ZeroOrOneBooleanContent)) &&
4727 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4730 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4731 N0, DAG.getConstant(1, VT0));
4732 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4733 N0, DAG.getConstant(1, VT0));
4734 AddToWorklist(XORNode.getNode());
4736 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4737 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4739 // fold (select C, 0, X) -> (and (not C), X)
4740 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4741 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4742 AddToWorklist(NOTNode.getNode());
4743 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4745 // fold (select C, X, 1) -> (or (not C), X)
4746 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4747 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4748 AddToWorklist(NOTNode.getNode());
4749 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4751 // fold (select C, X, 0) -> (and C, X)
4752 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4753 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4754 // fold (select X, X, Y) -> (or X, Y)
4755 // fold (select X, 1, Y) -> (or X, Y)
4756 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4757 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4758 // fold (select X, Y, X) -> (and X, Y)
4759 // fold (select X, Y, 0) -> (and X, Y)
4760 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4761 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4763 // If we can fold this based on the true/false value, do so.
4764 if (SimplifySelectOps(N, N1, N2))
4765 return SDValue(N, 0); // Don't revisit N.
4767 // fold selects based on a setcc into other things, such as min/max/abs
4768 if (N0.getOpcode() == ISD::SETCC) {
4769 // select x, y (fcmp lt x, y) -> fminnum x, y
4770 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4772 // This is OK if we don't care about what happens if either operand is a
4776 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4777 // no signed zeros as well as no nans.
4778 const TargetOptions &Options = DAG.getTarget().Options;
4779 if (Options.UnsafeFPMath &&
4780 VT.isFloatingPoint() && N0.hasOneUse() &&
4781 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4782 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4785 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4786 N1, N2, CC, TLI, DAG);
4791 if ((!LegalOperations &&
4792 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4793 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4794 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4795 N0.getOperand(0), N0.getOperand(1),
4796 N1, N2, N0.getOperand(2));
4797 return SimplifySelect(SDLoc(N), N0, N1, N2);
4804 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4807 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4809 // Split the inputs.
4810 SDValue Lo, Hi, LL, LH, RL, RH;
4811 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4812 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4814 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4815 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4817 return std::make_pair(Lo, Hi);
4820 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4821 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4822 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4824 SDValue Cond = N->getOperand(0);
4825 SDValue LHS = N->getOperand(1);
4826 SDValue RHS = N->getOperand(2);
4827 EVT VT = N->getValueType(0);
4828 int NumElems = VT.getVectorNumElements();
4829 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4830 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4831 Cond.getOpcode() == ISD::BUILD_VECTOR);
4833 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4834 // binary ones here.
4835 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4838 // We're sure we have an even number of elements due to the
4839 // concat_vectors we have as arguments to vselect.
4840 // Skip BV elements until we find one that's not an UNDEF
4841 // After we find an UNDEF element, keep looping until we get to half the
4842 // length of the BV and see if all the non-undef nodes are the same.
4843 ConstantSDNode *BottomHalf = nullptr;
4844 for (int i = 0; i < NumElems / 2; ++i) {
4845 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4848 if (BottomHalf == nullptr)
4849 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4850 else if (Cond->getOperand(i).getNode() != BottomHalf)
4854 // Do the same for the second half of the BuildVector
4855 ConstantSDNode *TopHalf = nullptr;
4856 for (int i = NumElems / 2; i < NumElems; ++i) {
4857 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4860 if (TopHalf == nullptr)
4861 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4862 else if (Cond->getOperand(i).getNode() != TopHalf)
4866 assert(TopHalf && BottomHalf &&
4867 "One half of the selector was all UNDEFs and the other was all the "
4868 "same value. This should have been addressed before this function.");
4870 ISD::CONCAT_VECTORS, dl, VT,
4871 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4872 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4875 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4877 if (Level >= AfterLegalizeTypes)
4880 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4881 SDValue Mask = MST->getMask();
4882 SDValue Data = MST->getValue();
4885 // If the MSTORE data type requires splitting and the mask is provided by a
4886 // SETCC, then split both nodes and its operands before legalization. This
4887 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4888 // and enables future optimizations (e.g. min/max pattern matching on X86).
4889 if (Mask.getOpcode() == ISD::SETCC) {
4891 // Check if any splitting is required.
4892 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4893 TargetLowering::TypeSplitVector)
4896 SDValue MaskLo, MaskHi, Lo, Hi;
4897 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4900 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4902 SDValue Chain = MST->getChain();
4903 SDValue Ptr = MST->getBasePtr();
4905 EVT MemoryVT = MST->getMemoryVT();
4906 unsigned Alignment = MST->getOriginalAlignment();
4908 // if Alignment is equal to the vector size,
4909 // take the half of it for the second part
4910 unsigned SecondHalfAlignment =
4911 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4912 Alignment/2 : Alignment;
4914 EVT LoMemVT, HiMemVT;
4915 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4917 SDValue DataLo, DataHi;
4918 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4920 MachineMemOperand *MMO = DAG.getMachineFunction().
4921 getMachineMemOperand(MST->getPointerInfo(),
4922 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
4923 Alignment, MST->getAAInfo(), MST->getRanges());
4925 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
4926 MST->isTruncatingStore());
4928 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4929 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4930 DAG.getConstant(IncrementSize, Ptr.getValueType()));
4932 MMO = DAG.getMachineFunction().
4933 getMachineMemOperand(MST->getPointerInfo(),
4934 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
4935 SecondHalfAlignment, MST->getAAInfo(),
4938 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
4939 MST->isTruncatingStore());
4941 AddToWorklist(Lo.getNode());
4942 AddToWorklist(Hi.getNode());
4944 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4949 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4951 if (Level >= AfterLegalizeTypes)
4954 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4955 SDValue Mask = MLD->getMask();
4958 // If the MLOAD result requires splitting and the mask is provided by a
4959 // SETCC, then split both nodes and its operands before legalization. This
4960 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4961 // and enables future optimizations (e.g. min/max pattern matching on X86).
4963 if (Mask.getOpcode() == ISD::SETCC) {
4964 EVT VT = N->getValueType(0);
4966 // Check if any splitting is required.
4967 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4968 TargetLowering::TypeSplitVector)
4971 SDValue MaskLo, MaskHi, Lo, Hi;
4972 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4974 SDValue Src0 = MLD->getSrc0();
4975 SDValue Src0Lo, Src0Hi;
4976 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4979 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4981 SDValue Chain = MLD->getChain();
4982 SDValue Ptr = MLD->getBasePtr();
4983 EVT MemoryVT = MLD->getMemoryVT();
4984 unsigned Alignment = MLD->getOriginalAlignment();
4986 // if Alignment is equal to the vector size,
4987 // take the half of it for the second part
4988 unsigned SecondHalfAlignment =
4989 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4990 Alignment/2 : Alignment;
4992 EVT LoMemVT, HiMemVT;
4993 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4995 MachineMemOperand *MMO = DAG.getMachineFunction().
4996 getMachineMemOperand(MLD->getPointerInfo(),
4997 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
4998 Alignment, MLD->getAAInfo(), MLD->getRanges());
5000 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5003 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5004 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5005 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5007 MMO = DAG.getMachineFunction().
5008 getMachineMemOperand(MLD->getPointerInfo(),
5009 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5010 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5012 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5015 AddToWorklist(Lo.getNode());
5016 AddToWorklist(Hi.getNode());
5018 // Build a factor node to remember that this load is independent of the
5020 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5023 // Legalized the chain result - switch anything that used the old chain to
5025 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5027 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5029 SDValue RetOps[] = { LoadRes, Chain };
5030 return DAG.getMergeValues(RetOps, DL);
5035 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5036 SDValue N0 = N->getOperand(0);
5037 SDValue N1 = N->getOperand(1);
5038 SDValue N2 = N->getOperand(2);
5041 // Canonicalize integer abs.
5042 // vselect (setg[te] X, 0), X, -X ->
5043 // vselect (setgt X, -1), X, -X ->
5044 // vselect (setl[te] X, 0), -X, X ->
5045 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5046 if (N0.getOpcode() == ISD::SETCC) {
5047 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5048 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5050 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5052 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5053 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5054 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5055 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5056 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5057 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5058 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5061 EVT VT = LHS.getValueType();
5062 SDValue Shift = DAG.getNode(
5063 ISD::SRA, DL, VT, LHS,
5064 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5065 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5066 AddToWorklist(Shift.getNode());
5067 AddToWorklist(Add.getNode());
5068 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5072 // If the VSELECT result requires splitting and the mask is provided by a
5073 // SETCC, then split both nodes and its operands before legalization. This
5074 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5075 // and enables future optimizations (e.g. min/max pattern matching on X86).
5076 if (N0.getOpcode() == ISD::SETCC) {
5077 EVT VT = N->getValueType(0);
5079 // Check if any splitting is required.
5080 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5081 TargetLowering::TypeSplitVector)
5084 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5085 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5086 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5087 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5089 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5090 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5092 // Add the new VSELECT nodes to the work list in case they need to be split
5094 AddToWorklist(Lo.getNode());
5095 AddToWorklist(Hi.getNode());
5097 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5100 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5101 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5103 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5104 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5107 // The ConvertSelectToConcatVector function is assuming both the above
5108 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5110 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5111 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5112 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5113 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5121 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5122 SDValue N0 = N->getOperand(0);
5123 SDValue N1 = N->getOperand(1);
5124 SDValue N2 = N->getOperand(2);
5125 SDValue N3 = N->getOperand(3);
5126 SDValue N4 = N->getOperand(4);
5127 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5129 // fold select_cc lhs, rhs, x, x, cc -> x
5133 // Determine if the condition we're dealing with is constant
5134 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5135 N0, N1, CC, SDLoc(N), false);
5136 if (SCC.getNode()) {
5137 AddToWorklist(SCC.getNode());
5139 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5140 if (!SCCC->isNullValue())
5141 return N2; // cond always true -> true val
5143 return N3; // cond always false -> false val
5144 } else if (SCC->getOpcode() == ISD::UNDEF) {
5145 // When the condition is UNDEF, just return the first operand. This is
5146 // coherent the DAG creation, no setcc node is created in this case
5148 } else if (SCC.getOpcode() == ISD::SETCC) {
5149 // Fold to a simpler select_cc
5150 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5151 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5156 // If we can fold this based on the true/false value, do so.
5157 if (SimplifySelectOps(N, N2, N3))
5158 return SDValue(N, 0); // Don't revisit N.
5160 // fold select_cc into other things, such as min/max/abs
5161 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5164 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5165 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5166 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5170 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5171 // dag node into a ConstantSDNode or a build_vector of constants.
5172 // This function is called by the DAGCombiner when visiting sext/zext/aext
5173 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5174 // Vector extends are not folded if operations are legal; this is to
5175 // avoid introducing illegal build_vector dag nodes.
5176 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5177 SelectionDAG &DAG, bool LegalTypes,
5178 bool LegalOperations) {
5179 unsigned Opcode = N->getOpcode();
5180 SDValue N0 = N->getOperand(0);
5181 EVT VT = N->getValueType(0);
5183 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5184 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5186 // fold (sext c1) -> c1
5187 // fold (zext c1) -> c1
5188 // fold (aext c1) -> c1
5189 if (isa<ConstantSDNode>(N0))
5190 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5192 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5193 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5194 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5195 EVT SVT = VT.getScalarType();
5196 if (!(VT.isVector() &&
5197 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5198 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5201 // We can fold this node into a build_vector.
5202 unsigned VTBits = SVT.getSizeInBits();
5203 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5204 unsigned ShAmt = VTBits - EVTBits;
5205 SmallVector<SDValue, 8> Elts;
5206 unsigned NumElts = N0->getNumOperands();
5209 for (unsigned i=0; i != NumElts; ++i) {
5210 SDValue Op = N0->getOperand(i);
5211 if (Op->getOpcode() == ISD::UNDEF) {
5212 Elts.push_back(DAG.getUNDEF(SVT));
5216 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5217 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5218 if (Opcode == ISD::SIGN_EXTEND)
5219 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5222 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5226 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5229 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5230 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5231 // transformation. Returns true if extension are possible and the above
5232 // mentioned transformation is profitable.
5233 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5235 SmallVectorImpl<SDNode *> &ExtendNodes,
5236 const TargetLowering &TLI) {
5237 bool HasCopyToRegUses = false;
5238 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5239 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5240 UE = N0.getNode()->use_end();
5245 if (UI.getUse().getResNo() != N0.getResNo())
5247 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5248 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5249 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5250 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5251 // Sign bits will be lost after a zext.
5254 for (unsigned i = 0; i != 2; ++i) {
5255 SDValue UseOp = User->getOperand(i);
5258 if (!isa<ConstantSDNode>(UseOp))
5263 ExtendNodes.push_back(User);
5266 // If truncates aren't free and there are users we can't
5267 // extend, it isn't worthwhile.
5270 // Remember if this value is live-out.
5271 if (User->getOpcode() == ISD::CopyToReg)
5272 HasCopyToRegUses = true;
5275 if (HasCopyToRegUses) {
5276 bool BothLiveOut = false;
5277 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5279 SDUse &Use = UI.getUse();
5280 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5286 // Both unextended and extended values are live out. There had better be
5287 // a good reason for the transformation.
5288 return ExtendNodes.size();
5293 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5294 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5295 ISD::NodeType ExtType) {
5296 // Extend SetCC uses if necessary.
5297 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5298 SDNode *SetCC = SetCCs[i];
5299 SmallVector<SDValue, 4> Ops;
5301 for (unsigned j = 0; j != 2; ++j) {
5302 SDValue SOp = SetCC->getOperand(j);
5304 Ops.push_back(ExtLoad);
5306 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5309 Ops.push_back(SetCC->getOperand(2));
5310 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5314 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5315 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5316 SDValue N0 = N->getOperand(0);
5317 EVT DstVT = N->getValueType(0);
5318 EVT SrcVT = N0.getValueType();
5320 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5321 N->getOpcode() == ISD::ZERO_EXTEND) &&
5322 "Unexpected node type (not an extend)!");
5324 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5325 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5326 // (v8i32 (sext (v8i16 (load x))))
5328 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5329 // (v4i32 (sextload (x + 16)))))
5330 // Where uses of the original load, i.e.:
5332 // are replaced with:
5334 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5335 // (v4i32 (sextload (x + 16)))))))
5337 // This combine is only applicable to illegal, but splittable, vectors.
5338 // All legal types, and illegal non-vector types, are handled elsewhere.
5339 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5341 if (N0->getOpcode() != ISD::LOAD)
5344 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5346 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5347 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5348 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5351 SmallVector<SDNode *, 4> SetCCs;
5352 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5355 ISD::LoadExtType ExtType =
5356 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5358 // Try to split the vector types to get down to legal types.
5359 EVT SplitSrcVT = SrcVT;
5360 EVT SplitDstVT = DstVT;
5361 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5362 SplitSrcVT.getVectorNumElements() > 1) {
5363 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5364 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5367 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5371 const unsigned NumSplits =
5372 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5373 const unsigned Stride = SplitSrcVT.getStoreSize();
5374 SmallVector<SDValue, 4> Loads;
5375 SmallVector<SDValue, 4> Chains;
5377 SDValue BasePtr = LN0->getBasePtr();
5378 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5379 const unsigned Offset = Idx * Stride;
5380 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5382 SDValue SplitLoad = DAG.getExtLoad(
5383 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5384 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5385 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5386 Align, LN0->getAAInfo());
5388 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5389 DAG.getConstant(Stride, BasePtr.getValueType()));
5391 Loads.push_back(SplitLoad.getValue(0));
5392 Chains.push_back(SplitLoad.getValue(1));
5395 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5396 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5398 CombineTo(N, NewValue);
5400 // Replace uses of the original load (before extension)
5401 // with a truncate of the concatenated sextloaded vectors.
5403 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5404 CombineTo(N0.getNode(), Trunc, NewChain);
5405 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5406 (ISD::NodeType)N->getOpcode());
5407 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5410 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5411 SDValue N0 = N->getOperand(0);
5412 EVT VT = N->getValueType(0);
5414 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5416 return SDValue(Res, 0);
5418 // fold (sext (sext x)) -> (sext x)
5419 // fold (sext (aext x)) -> (sext x)
5420 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5421 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5424 if (N0.getOpcode() == ISD::TRUNCATE) {
5425 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5426 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5427 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5428 if (NarrowLoad.getNode()) {
5429 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5430 if (NarrowLoad.getNode() != N0.getNode()) {
5431 CombineTo(N0.getNode(), NarrowLoad);
5432 // CombineTo deleted the truncate, if needed, but not what's under it.
5435 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5438 // See if the value being truncated is already sign extended. If so, just
5439 // eliminate the trunc/sext pair.
5440 SDValue Op = N0.getOperand(0);
5441 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5442 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5443 unsigned DestBits = VT.getScalarType().getSizeInBits();
5444 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5446 if (OpBits == DestBits) {
5447 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5448 // bits, it is already ready.
5449 if (NumSignBits > DestBits-MidBits)
5451 } else if (OpBits < DestBits) {
5452 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5453 // bits, just sext from i32.
5454 if (NumSignBits > OpBits-MidBits)
5455 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5457 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5458 // bits, just truncate to i32.
5459 if (NumSignBits > OpBits-MidBits)
5460 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5463 // fold (sext (truncate x)) -> (sextinreg x).
5464 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5465 N0.getValueType())) {
5466 if (OpBits < DestBits)
5467 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5468 else if (OpBits > DestBits)
5469 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5470 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5471 DAG.getValueType(N0.getValueType()));
5475 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5476 // Only generate vector extloads when 1) they're legal, and 2) they are
5477 // deemed desirable by the target.
5478 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5479 ((!LegalOperations && !VT.isVector() &&
5480 !cast<LoadSDNode>(N0)->isVolatile()) ||
5481 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5482 bool DoXform = true;
5483 SmallVector<SDNode*, 4> SetCCs;
5484 if (!N0.hasOneUse())
5485 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5487 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5489 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5490 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5492 LN0->getBasePtr(), N0.getValueType(),
5493 LN0->getMemOperand());
5494 CombineTo(N, ExtLoad);
5495 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5496 N0.getValueType(), ExtLoad);
5497 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5498 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5500 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5504 // fold (sext (load x)) to multiple smaller sextloads.
5505 // Only on illegal but splittable vectors.
5506 if (SDValue ExtLoad = CombineExtLoad(N))
5509 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5510 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5511 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5512 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5513 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5514 EVT MemVT = LN0->getMemoryVT();
5515 if ((!LegalOperations && !LN0->isVolatile()) ||
5516 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5517 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5519 LN0->getBasePtr(), MemVT,
5520 LN0->getMemOperand());
5521 CombineTo(N, ExtLoad);
5522 CombineTo(N0.getNode(),
5523 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5524 N0.getValueType(), ExtLoad),
5525 ExtLoad.getValue(1));
5526 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5530 // fold (sext (and/or/xor (load x), cst)) ->
5531 // (and/or/xor (sextload x), (sext cst))
5532 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5533 N0.getOpcode() == ISD::XOR) &&
5534 isa<LoadSDNode>(N0.getOperand(0)) &&
5535 N0.getOperand(1).getOpcode() == ISD::Constant &&
5536 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5537 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5538 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5539 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5540 bool DoXform = true;
5541 SmallVector<SDNode*, 4> SetCCs;
5542 if (!N0.hasOneUse())
5543 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5546 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5547 LN0->getChain(), LN0->getBasePtr(),
5549 LN0->getMemOperand());
5550 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5551 Mask = Mask.sext(VT.getSizeInBits());
5552 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5553 ExtLoad, DAG.getConstant(Mask, VT));
5554 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5555 SDLoc(N0.getOperand(0)),
5556 N0.getOperand(0).getValueType(), ExtLoad);
5558 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5559 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5561 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5566 if (N0.getOpcode() == ISD::SETCC) {
5567 EVT N0VT = N0.getOperand(0).getValueType();
5568 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5569 // Only do this before legalize for now.
5570 if (VT.isVector() && !LegalOperations &&
5571 TLI.getBooleanContents(N0VT) ==
5572 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5573 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5574 // of the same size as the compared operands. Only optimize sext(setcc())
5575 // if this is the case.
5576 EVT SVT = getSetCCResultType(N0VT);
5578 // We know that the # elements of the results is the same as the
5579 // # elements of the compare (and the # elements of the compare result
5580 // for that matter). Check to see that they are the same size. If so,
5581 // we know that the element size of the sext'd result matches the
5582 // element size of the compare operands.
5583 if (VT.getSizeInBits() == SVT.getSizeInBits())
5584 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5586 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5588 // If the desired elements are smaller or larger than the source
5589 // elements we can use a matching integer vector type and then
5590 // truncate/sign extend
5591 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5592 if (SVT == MatchingVectorType) {
5593 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5594 N0.getOperand(0), N0.getOperand(1),
5595 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5596 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5600 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5601 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5603 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5605 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5606 NegOne, DAG.getConstant(0, VT),
5607 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5608 if (SCC.getNode()) return SCC;
5610 if (!VT.isVector()) {
5611 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5612 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5614 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5615 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5616 N0.getOperand(0), N0.getOperand(1), CC);
5617 return DAG.getSelect(DL, VT, SetCC,
5618 NegOne, DAG.getConstant(0, VT));
5623 // fold (sext x) -> (zext x) if the sign bit is known zero.
5624 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5625 DAG.SignBitIsZero(N0))
5626 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5631 // isTruncateOf - If N is a truncate of some other value, return true, record
5632 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5633 // This function computes KnownZero to avoid a duplicated call to
5634 // computeKnownBits in the caller.
5635 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5638 if (N->getOpcode() == ISD::TRUNCATE) {
5639 Op = N->getOperand(0);
5640 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5644 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5645 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5648 SDValue Op0 = N->getOperand(0);
5649 SDValue Op1 = N->getOperand(1);
5650 assert(Op0.getValueType() == Op1.getValueType());
5652 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5653 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5654 if (COp0 && COp0->isNullValue())
5656 else if (COp1 && COp1->isNullValue())
5661 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5663 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5669 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5670 SDValue N0 = N->getOperand(0);
5671 EVT VT = N->getValueType(0);
5673 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5675 return SDValue(Res, 0);
5677 // fold (zext (zext x)) -> (zext x)
5678 // fold (zext (aext x)) -> (zext x)
5679 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5680 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5683 // fold (zext (truncate x)) -> (zext x) or
5684 // (zext (truncate x)) -> (truncate x)
5685 // This is valid when the truncated bits of x are already zero.
5686 // FIXME: We should extend this to work for vectors too.
5689 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5690 APInt TruncatedBits =
5691 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5692 APInt(Op.getValueSizeInBits(), 0) :
5693 APInt::getBitsSet(Op.getValueSizeInBits(),
5694 N0.getValueSizeInBits(),
5695 std::min(Op.getValueSizeInBits(),
5696 VT.getSizeInBits()));
5697 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5698 if (VT.bitsGT(Op.getValueType()))
5699 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5700 if (VT.bitsLT(Op.getValueType()))
5701 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5707 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5708 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5709 if (N0.getOpcode() == ISD::TRUNCATE) {
5710 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5711 if (NarrowLoad.getNode()) {
5712 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5713 if (NarrowLoad.getNode() != N0.getNode()) {
5714 CombineTo(N0.getNode(), NarrowLoad);
5715 // CombineTo deleted the truncate, if needed, but not what's under it.
5718 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5722 // fold (zext (truncate x)) -> (and x, mask)
5723 if (N0.getOpcode() == ISD::TRUNCATE &&
5724 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5726 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5727 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5728 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5729 if (NarrowLoad.getNode()) {
5730 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5731 if (NarrowLoad.getNode() != N0.getNode()) {
5732 CombineTo(N0.getNode(), NarrowLoad);
5733 // CombineTo deleted the truncate, if needed, but not what's under it.
5736 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5739 SDValue Op = N0.getOperand(0);
5740 if (Op.getValueType().bitsLT(VT)) {
5741 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5742 AddToWorklist(Op.getNode());
5743 } else if (Op.getValueType().bitsGT(VT)) {
5744 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5745 AddToWorklist(Op.getNode());
5747 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5748 N0.getValueType().getScalarType());
5751 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5752 // if either of the casts is not free.
5753 if (N0.getOpcode() == ISD::AND &&
5754 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5755 N0.getOperand(1).getOpcode() == ISD::Constant &&
5756 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5757 N0.getValueType()) ||
5758 !TLI.isZExtFree(N0.getValueType(), VT))) {
5759 SDValue X = N0.getOperand(0).getOperand(0);
5760 if (X.getValueType().bitsLT(VT)) {
5761 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5762 } else if (X.getValueType().bitsGT(VT)) {
5763 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5765 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5766 Mask = Mask.zext(VT.getSizeInBits());
5767 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5768 X, DAG.getConstant(Mask, VT));
5771 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5772 // Only generate vector extloads when 1) they're legal, and 2) they are
5773 // deemed desirable by the target.
5774 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5775 ((!LegalOperations && !VT.isVector() &&
5776 !cast<LoadSDNode>(N0)->isVolatile()) ||
5777 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5778 bool DoXform = true;
5779 SmallVector<SDNode*, 4> SetCCs;
5780 if (!N0.hasOneUse())
5781 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5783 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5785 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5786 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5788 LN0->getBasePtr(), N0.getValueType(),
5789 LN0->getMemOperand());
5790 CombineTo(N, ExtLoad);
5791 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5792 N0.getValueType(), ExtLoad);
5793 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5795 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5797 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5801 // fold (zext (load x)) to multiple smaller zextloads.
5802 // Only on illegal but splittable vectors.
5803 if (SDValue ExtLoad = CombineExtLoad(N))
5806 // fold (zext (and/or/xor (load x), cst)) ->
5807 // (and/or/xor (zextload x), (zext cst))
5808 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5809 N0.getOpcode() == ISD::XOR) &&
5810 isa<LoadSDNode>(N0.getOperand(0)) &&
5811 N0.getOperand(1).getOpcode() == ISD::Constant &&
5812 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5813 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5814 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5815 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5816 bool DoXform = true;
5817 SmallVector<SDNode*, 4> SetCCs;
5818 if (!N0.hasOneUse())
5819 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5822 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5823 LN0->getChain(), LN0->getBasePtr(),
5825 LN0->getMemOperand());
5826 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5827 Mask = Mask.zext(VT.getSizeInBits());
5828 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5829 ExtLoad, DAG.getConstant(Mask, VT));
5830 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5831 SDLoc(N0.getOperand(0)),
5832 N0.getOperand(0).getValueType(), ExtLoad);
5834 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5835 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5837 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5842 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5843 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5844 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5845 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5846 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5847 EVT MemVT = LN0->getMemoryVT();
5848 if ((!LegalOperations && !LN0->isVolatile()) ||
5849 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5850 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5852 LN0->getBasePtr(), MemVT,
5853 LN0->getMemOperand());
5854 CombineTo(N, ExtLoad);
5855 CombineTo(N0.getNode(),
5856 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5858 ExtLoad.getValue(1));
5859 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5863 if (N0.getOpcode() == ISD::SETCC) {
5864 if (!LegalOperations && VT.isVector() &&
5865 N0.getValueType().getVectorElementType() == MVT::i1) {
5866 EVT N0VT = N0.getOperand(0).getValueType();
5867 if (getSetCCResultType(N0VT) == N0.getValueType())
5870 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5871 // Only do this before legalize for now.
5872 EVT EltVT = VT.getVectorElementType();
5873 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5874 DAG.getConstant(1, EltVT));
5875 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5876 // We know that the # elements of the results is the same as the
5877 // # elements of the compare (and the # elements of the compare result
5878 // for that matter). Check to see that they are the same size. If so,
5879 // we know that the element size of the sext'd result matches the
5880 // element size of the compare operands.
5881 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5882 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5884 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5885 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5888 // If the desired elements are smaller or larger than the source
5889 // elements we can use a matching integer vector type and then
5890 // truncate/sign extend
5891 EVT MatchingElementType =
5892 EVT::getIntegerVT(*DAG.getContext(),
5893 N0VT.getScalarType().getSizeInBits());
5894 EVT MatchingVectorType =
5895 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5896 N0VT.getVectorNumElements());
5898 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5900 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5901 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5902 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5903 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5906 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5908 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5909 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5910 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5911 if (SCC.getNode()) return SCC;
5914 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5915 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5916 isa<ConstantSDNode>(N0.getOperand(1)) &&
5917 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5919 SDValue ShAmt = N0.getOperand(1);
5920 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5921 if (N0.getOpcode() == ISD::SHL) {
5922 SDValue InnerZExt = N0.getOperand(0);
5923 // If the original shl may be shifting out bits, do not perform this
5925 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5926 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5927 if (ShAmtVal > KnownZeroBits)
5933 // Ensure that the shift amount is wide enough for the shifted value.
5934 if (VT.getSizeInBits() >= 256)
5935 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5937 return DAG.getNode(N0.getOpcode(), DL, VT,
5938 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5945 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5946 SDValue N0 = N->getOperand(0);
5947 EVT VT = N->getValueType(0);
5949 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5951 return SDValue(Res, 0);
5953 // fold (aext (aext x)) -> (aext x)
5954 // fold (aext (zext x)) -> (zext x)
5955 // fold (aext (sext x)) -> (sext x)
5956 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5957 N0.getOpcode() == ISD::ZERO_EXTEND ||
5958 N0.getOpcode() == ISD::SIGN_EXTEND)
5959 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5961 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5962 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5963 if (N0.getOpcode() == ISD::TRUNCATE) {
5964 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5965 if (NarrowLoad.getNode()) {
5966 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5967 if (NarrowLoad.getNode() != N0.getNode()) {
5968 CombineTo(N0.getNode(), NarrowLoad);
5969 // CombineTo deleted the truncate, if needed, but not what's under it.
5972 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5976 // fold (aext (truncate x))
5977 if (N0.getOpcode() == ISD::TRUNCATE) {
5978 SDValue TruncOp = N0.getOperand(0);
5979 if (TruncOp.getValueType() == VT)
5980 return TruncOp; // x iff x size == zext size.
5981 if (TruncOp.getValueType().bitsGT(VT))
5982 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5983 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5986 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5987 // if the trunc is not free.
5988 if (N0.getOpcode() == ISD::AND &&
5989 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5990 N0.getOperand(1).getOpcode() == ISD::Constant &&
5991 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5992 N0.getValueType())) {
5993 SDValue X = N0.getOperand(0).getOperand(0);
5994 if (X.getValueType().bitsLT(VT)) {
5995 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5996 } else if (X.getValueType().bitsGT(VT)) {
5997 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5999 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6000 Mask = Mask.zext(VT.getSizeInBits());
6001 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6002 X, DAG.getConstant(Mask, VT));
6005 // fold (aext (load x)) -> (aext (truncate (extload x)))
6006 // None of the supported targets knows how to perform load and any_ext
6007 // on vectors in one instruction. We only perform this transformation on
6009 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6010 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6011 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6012 bool DoXform = true;
6013 SmallVector<SDNode*, 4> SetCCs;
6014 if (!N0.hasOneUse())
6015 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6017 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6018 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6020 LN0->getBasePtr(), N0.getValueType(),
6021 LN0->getMemOperand());
6022 CombineTo(N, ExtLoad);
6023 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6024 N0.getValueType(), ExtLoad);
6025 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6026 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6028 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6032 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6033 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6034 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6035 if (N0.getOpcode() == ISD::LOAD &&
6036 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6038 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6039 ISD::LoadExtType ExtType = LN0->getExtensionType();
6040 EVT MemVT = LN0->getMemoryVT();
6041 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6042 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6043 VT, LN0->getChain(), LN0->getBasePtr(),
6044 MemVT, LN0->getMemOperand());
6045 CombineTo(N, ExtLoad);
6046 CombineTo(N0.getNode(),
6047 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6048 N0.getValueType(), ExtLoad),
6049 ExtLoad.getValue(1));
6050 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6054 if (N0.getOpcode() == ISD::SETCC) {
6056 // aext(setcc) -> vsetcc
6057 // aext(setcc) -> truncate(vsetcc)
6058 // aext(setcc) -> aext(vsetcc)
6059 // Only do this before legalize for now.
6060 if (VT.isVector() && !LegalOperations) {
6061 EVT N0VT = N0.getOperand(0).getValueType();
6062 // We know that the # elements of the results is the same as the
6063 // # elements of the compare (and the # elements of the compare result
6064 // for that matter). Check to see that they are the same size. If so,
6065 // we know that the element size of the sext'd result matches the
6066 // element size of the compare operands.
6067 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6068 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6070 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6071 // If the desired elements are smaller or larger than the source
6072 // elements we can use a matching integer vector type and then
6073 // truncate/any extend
6075 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6077 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6079 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6080 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6084 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6086 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6087 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6088 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6096 /// See if the specified operand can be simplified with the knowledge that only
6097 /// the bits specified by Mask are used. If so, return the simpler operand,
6098 /// otherwise return a null SDValue.
6099 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6100 switch (V.getOpcode()) {
6102 case ISD::Constant: {
6103 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6104 assert(CV && "Const value should be ConstSDNode.");
6105 const APInt &CVal = CV->getAPIntValue();
6106 APInt NewVal = CVal & Mask;
6108 return DAG.getConstant(NewVal, V.getValueType());
6113 // If the LHS or RHS don't contribute bits to the or, drop them.
6114 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6115 return V.getOperand(1);
6116 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6117 return V.getOperand(0);
6120 // Only look at single-use SRLs.
6121 if (!V.getNode()->hasOneUse())
6123 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6124 // See if we can recursively simplify the LHS.
6125 unsigned Amt = RHSC->getZExtValue();
6127 // Watch out for shift count overflow though.
6128 if (Amt >= Mask.getBitWidth()) break;
6129 APInt NewMask = Mask << Amt;
6130 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6131 if (SimplifyLHS.getNode())
6132 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6133 SimplifyLHS, V.getOperand(1));
6139 /// If the result of a wider load is shifted to right of N bits and then
6140 /// truncated to a narrower type and where N is a multiple of number of bits of
6141 /// the narrower type, transform it to a narrower load from address + N / num of
6142 /// bits of new type. If the result is to be extended, also fold the extension
6143 /// to form a extending load.
6144 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6145 unsigned Opc = N->getOpcode();
6147 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6148 SDValue N0 = N->getOperand(0);
6149 EVT VT = N->getValueType(0);
6152 // This transformation isn't valid for vector loads.
6156 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6158 if (Opc == ISD::SIGN_EXTEND_INREG) {
6159 ExtType = ISD::SEXTLOAD;
6160 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6161 } else if (Opc == ISD::SRL) {
6162 // Another special-case: SRL is basically zero-extending a narrower value.
6163 ExtType = ISD::ZEXTLOAD;
6165 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6166 if (!N01) return SDValue();
6167 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6168 VT.getSizeInBits() - N01->getZExtValue());
6170 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6173 unsigned EVTBits = ExtVT.getSizeInBits();
6175 // Do not generate loads of non-round integer types since these can
6176 // be expensive (and would be wrong if the type is not byte sized).
6177 if (!ExtVT.isRound())
6181 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6182 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6183 ShAmt = N01->getZExtValue();
6184 // Is the shift amount a multiple of size of VT?
6185 if ((ShAmt & (EVTBits-1)) == 0) {
6186 N0 = N0.getOperand(0);
6187 // Is the load width a multiple of size of VT?
6188 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6192 // At this point, we must have a load or else we can't do the transform.
6193 if (!isa<LoadSDNode>(N0)) return SDValue();
6195 // Because a SRL must be assumed to *need* to zero-extend the high bits
6196 // (as opposed to anyext the high bits), we can't combine the zextload
6197 // lowering of SRL and an sextload.
6198 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6201 // If the shift amount is larger than the input type then we're not
6202 // accessing any of the loaded bytes. If the load was a zextload/extload
6203 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6204 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6209 // If the load is shifted left (and the result isn't shifted back right),
6210 // we can fold the truncate through the shift.
6211 unsigned ShLeftAmt = 0;
6212 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6213 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6214 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6215 ShLeftAmt = N01->getZExtValue();
6216 N0 = N0.getOperand(0);
6220 // If we haven't found a load, we can't narrow it. Don't transform one with
6221 // multiple uses, this would require adding a new load.
6222 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6225 // Don't change the width of a volatile load.
6226 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6227 if (LN0->isVolatile())
6230 // Verify that we are actually reducing a load width here.
6231 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6234 // For the transform to be legal, the load must produce only two values
6235 // (the value loaded and the chain). Don't transform a pre-increment
6236 // load, for example, which produces an extra value. Otherwise the
6237 // transformation is not equivalent, and the downstream logic to replace
6238 // uses gets things wrong.
6239 if (LN0->getNumValues() > 2)
6242 // If the load that we're shrinking is an extload and we're not just
6243 // discarding the extension we can't simply shrink the load. Bail.
6244 // TODO: It would be possible to merge the extensions in some cases.
6245 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6246 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6249 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6252 EVT PtrType = N0.getOperand(1).getValueType();
6254 if (PtrType == MVT::Untyped || PtrType.isExtended())
6255 // It's not possible to generate a constant of extended or untyped type.
6258 // For big endian targets, we need to adjust the offset to the pointer to
6259 // load the correct bytes.
6260 if (TLI.isBigEndian()) {
6261 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6262 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6263 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6266 uint64_t PtrOff = ShAmt / 8;
6267 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6268 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6269 PtrType, LN0->getBasePtr(),
6270 DAG.getConstant(PtrOff, PtrType));
6271 AddToWorklist(NewPtr.getNode());
6274 if (ExtType == ISD::NON_EXTLOAD)
6275 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6276 LN0->getPointerInfo().getWithOffset(PtrOff),
6277 LN0->isVolatile(), LN0->isNonTemporal(),
6278 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6280 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6281 LN0->getPointerInfo().getWithOffset(PtrOff),
6282 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6283 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6285 // Replace the old load's chain with the new load's chain.
6286 WorklistRemover DeadNodes(*this);
6287 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6289 // Shift the result left, if we've swallowed a left shift.
6290 SDValue Result = Load;
6291 if (ShLeftAmt != 0) {
6292 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6293 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6295 // If the shift amount is as large as the result size (but, presumably,
6296 // no larger than the source) then the useful bits of the result are
6297 // zero; we can't simply return the shortened shift, because the result
6298 // of that operation is undefined.
6299 if (ShLeftAmt >= VT.getSizeInBits())
6300 Result = DAG.getConstant(0, VT);
6302 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6303 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6306 // Return the new loaded value.
6310 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6311 SDValue N0 = N->getOperand(0);
6312 SDValue N1 = N->getOperand(1);
6313 EVT VT = N->getValueType(0);
6314 EVT EVT = cast<VTSDNode>(N1)->getVT();
6315 unsigned VTBits = VT.getScalarType().getSizeInBits();
6316 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6318 // fold (sext_in_reg c1) -> c1
6319 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6320 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6322 // If the input is already sign extended, just drop the extension.
6323 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6326 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6327 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6328 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6329 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6330 N0.getOperand(0), N1);
6332 // fold (sext_in_reg (sext x)) -> (sext x)
6333 // fold (sext_in_reg (aext x)) -> (sext x)
6334 // if x is small enough.
6335 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6336 SDValue N00 = N0.getOperand(0);
6337 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6338 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6339 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6342 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6343 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6344 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6346 // fold operands of sext_in_reg based on knowledge that the top bits are not
6348 if (SimplifyDemandedBits(SDValue(N, 0)))
6349 return SDValue(N, 0);
6351 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6352 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6353 SDValue NarrowLoad = ReduceLoadWidth(N);
6354 if (NarrowLoad.getNode())
6357 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6358 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6359 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6360 if (N0.getOpcode() == ISD::SRL) {
6361 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6362 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6363 // We can turn this into an SRA iff the input to the SRL is already sign
6365 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6366 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6367 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6368 N0.getOperand(0), N0.getOperand(1));
6372 // fold (sext_inreg (extload x)) -> (sextload x)
6373 if (ISD::isEXTLoad(N0.getNode()) &&
6374 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6375 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6376 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6377 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6378 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6379 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6381 LN0->getBasePtr(), EVT,
6382 LN0->getMemOperand());
6383 CombineTo(N, ExtLoad);
6384 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6385 AddToWorklist(ExtLoad.getNode());
6386 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6388 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6389 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6391 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6392 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6393 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6394 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6395 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6397 LN0->getBasePtr(), EVT,
6398 LN0->getMemOperand());
6399 CombineTo(N, ExtLoad);
6400 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6401 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6404 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6405 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6406 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6407 N0.getOperand(1), false);
6408 if (BSwap.getNode())
6409 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6413 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6414 // into a build_vector.
6415 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6416 SmallVector<SDValue, 8> Elts;
6417 unsigned NumElts = N0->getNumOperands();
6418 unsigned ShAmt = VTBits - EVTBits;
6420 for (unsigned i = 0; i != NumElts; ++i) {
6421 SDValue Op = N0->getOperand(i);
6422 if (Op->getOpcode() == ISD::UNDEF) {
6427 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6428 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6429 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6430 Op.getValueType()));
6433 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6439 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6440 SDValue N0 = N->getOperand(0);
6441 EVT VT = N->getValueType(0);
6442 bool isLE = TLI.isLittleEndian();
6445 if (N0.getValueType() == N->getValueType(0))
6447 // fold (truncate c1) -> c1
6448 if (isa<ConstantSDNode>(N0))
6449 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6450 // fold (truncate (truncate x)) -> (truncate x)
6451 if (N0.getOpcode() == ISD::TRUNCATE)
6452 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6453 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6454 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6455 N0.getOpcode() == ISD::SIGN_EXTEND ||
6456 N0.getOpcode() == ISD::ANY_EXTEND) {
6457 if (N0.getOperand(0).getValueType().bitsLT(VT))
6458 // if the source is smaller than the dest, we still need an extend
6459 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6461 if (N0.getOperand(0).getValueType().bitsGT(VT))
6462 // if the source is larger than the dest, than we just need the truncate
6463 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6464 // if the source and dest are the same type, we can drop both the extend
6465 // and the truncate.
6466 return N0.getOperand(0);
6469 // Fold extract-and-trunc into a narrow extract. For example:
6470 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6471 // i32 y = TRUNCATE(i64 x)
6473 // v16i8 b = BITCAST (v2i64 val)
6474 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6476 // Note: We only run this optimization after type legalization (which often
6477 // creates this pattern) and before operation legalization after which
6478 // we need to be more careful about the vector instructions that we generate.
6479 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6480 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6482 EVT VecTy = N0.getOperand(0).getValueType();
6483 EVT ExTy = N0.getValueType();
6484 EVT TrTy = N->getValueType(0);
6486 unsigned NumElem = VecTy.getVectorNumElements();
6487 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6489 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6490 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6492 SDValue EltNo = N0->getOperand(1);
6493 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6494 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6495 EVT IndexTy = TLI.getVectorIdxTy();
6496 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6498 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6499 NVT, N0.getOperand(0));
6501 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6503 DAG.getConstant(Index, IndexTy));
6507 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6508 if (N0.getOpcode() == ISD::SELECT) {
6509 EVT SrcVT = N0.getValueType();
6510 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6511 TLI.isTruncateFree(SrcVT, VT)) {
6513 SDValue Cond = N0.getOperand(0);
6514 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6515 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6516 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6520 // Fold a series of buildvector, bitcast, and truncate if possible.
6522 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6523 // (2xi32 (buildvector x, y)).
6524 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6525 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6526 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6527 N0.getOperand(0).hasOneUse()) {
6529 SDValue BuildVect = N0.getOperand(0);
6530 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6531 EVT TruncVecEltTy = VT.getVectorElementType();
6533 // Check that the element types match.
6534 if (BuildVectEltTy == TruncVecEltTy) {
6535 // Now we only need to compute the offset of the truncated elements.
6536 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6537 unsigned TruncVecNumElts = VT.getVectorNumElements();
6538 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6540 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6541 "Invalid number of elements");
6543 SmallVector<SDValue, 8> Opnds;
6544 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6545 Opnds.push_back(BuildVect.getOperand(i));
6547 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6551 // See if we can simplify the input to this truncate through knowledge that
6552 // only the low bits are being used.
6553 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6554 // Currently we only perform this optimization on scalars because vectors
6555 // may have different active low bits.
6556 if (!VT.isVector()) {
6558 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6559 VT.getSizeInBits()));
6560 if (Shorter.getNode())
6561 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6563 // fold (truncate (load x)) -> (smaller load x)
6564 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6565 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6566 SDValue Reduced = ReduceLoadWidth(N);
6567 if (Reduced.getNode())
6569 // Handle the case where the load remains an extending load even
6570 // after truncation.
6571 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6572 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6573 if (!LN0->isVolatile() &&
6574 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6575 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6576 VT, LN0->getChain(), LN0->getBasePtr(),
6578 LN0->getMemOperand());
6579 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6584 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6585 // where ... are all 'undef'.
6586 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6587 SmallVector<EVT, 8> VTs;
6590 unsigned NumDefs = 0;
6592 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6593 SDValue X = N0.getOperand(i);
6594 if (X.getOpcode() != ISD::UNDEF) {
6599 // Stop if more than one members are non-undef.
6602 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6603 VT.getVectorElementType(),
6604 X.getValueType().getVectorNumElements()));
6608 return DAG.getUNDEF(VT);
6611 assert(V.getNode() && "The single defined operand is empty!");
6612 SmallVector<SDValue, 8> Opnds;
6613 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6615 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6618 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6619 AddToWorklist(NV.getNode());
6620 Opnds.push_back(NV);
6622 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6626 // Simplify the operands using demanded-bits information.
6627 if (!VT.isVector() &&
6628 SimplifyDemandedBits(SDValue(N, 0)))
6629 return SDValue(N, 0);
6634 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6635 SDValue Elt = N->getOperand(i);
6636 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6637 return Elt.getNode();
6638 return Elt.getOperand(Elt.getResNo()).getNode();
6641 /// build_pair (load, load) -> load
6642 /// if load locations are consecutive.
6643 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6644 assert(N->getOpcode() == ISD::BUILD_PAIR);
6646 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6647 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6648 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6649 LD1->getAddressSpace() != LD2->getAddressSpace())
6651 EVT LD1VT = LD1->getValueType(0);
6653 if (ISD::isNON_EXTLoad(LD2) &&
6655 // If both are volatile this would reduce the number of volatile loads.
6656 // If one is volatile it might be ok, but play conservative and bail out.
6657 !LD1->isVolatile() &&
6658 !LD2->isVolatile() &&
6659 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6660 unsigned Align = LD1->getAlignment();
6661 unsigned NewAlign = TLI.getDataLayout()->
6662 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6664 if (NewAlign <= Align &&
6665 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6666 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6667 LD1->getBasePtr(), LD1->getPointerInfo(),
6668 false, false, false, Align);
6674 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6675 SDValue N0 = N->getOperand(0);
6676 EVT VT = N->getValueType(0);
6678 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6679 // Only do this before legalize, since afterward the target may be depending
6680 // on the bitconvert.
6681 // First check to see if this is all constant.
6683 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6685 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6687 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6688 assert(!DestEltVT.isVector() &&
6689 "Element type of vector ValueType must not be vector!");
6691 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6694 // If the input is a constant, let getNode fold it.
6695 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6696 // If we can't allow illegal operations, we need to check that this is just
6697 // a fp -> int or int -> conversion and that the resulting operation will
6699 if (!LegalOperations ||
6700 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6701 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6702 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6703 TLI.isOperationLegal(ISD::Constant, VT)))
6704 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6707 // (conv (conv x, t1), t2) -> (conv x, t2)
6708 if (N0.getOpcode() == ISD::BITCAST)
6709 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6712 // fold (conv (load x)) -> (load (conv*)x)
6713 // If the resultant load doesn't need a higher alignment than the original!
6714 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6715 // Do not change the width of a volatile load.
6716 !cast<LoadSDNode>(N0)->isVolatile() &&
6717 // Do not remove the cast if the types differ in endian layout.
6718 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6719 TLI.hasBigEndianPartOrdering(VT) &&
6720 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6721 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6722 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6723 unsigned Align = TLI.getDataLayout()->
6724 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6725 unsigned OrigAlign = LN0->getAlignment();
6727 if (Align <= OrigAlign) {
6728 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6729 LN0->getBasePtr(), LN0->getPointerInfo(),
6730 LN0->isVolatile(), LN0->isNonTemporal(),
6731 LN0->isInvariant(), OrigAlign,
6733 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6738 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6739 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6740 // This often reduces constant pool loads.
6741 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6742 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6743 N0.getNode()->hasOneUse() && VT.isInteger() &&
6744 !VT.isVector() && !N0.getValueType().isVector()) {
6745 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6747 AddToWorklist(NewConv.getNode());
6749 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6750 if (N0.getOpcode() == ISD::FNEG)
6751 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6752 NewConv, DAG.getConstant(SignBit, VT));
6753 assert(N0.getOpcode() == ISD::FABS);
6754 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6755 NewConv, DAG.getConstant(~SignBit, VT));
6758 // fold (bitconvert (fcopysign cst, x)) ->
6759 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6760 // Note that we don't handle (copysign x, cst) because this can always be
6761 // folded to an fneg or fabs.
6762 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6763 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6764 VT.isInteger() && !VT.isVector()) {
6765 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6766 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6767 if (isTypeLegal(IntXVT)) {
6768 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6769 IntXVT, N0.getOperand(1));
6770 AddToWorklist(X.getNode());
6772 // If X has a different width than the result/lhs, sext it or truncate it.
6773 unsigned VTWidth = VT.getSizeInBits();
6774 if (OrigXWidth < VTWidth) {
6775 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6776 AddToWorklist(X.getNode());
6777 } else if (OrigXWidth > VTWidth) {
6778 // To get the sign bit in the right place, we have to shift it right
6779 // before truncating.
6780 X = DAG.getNode(ISD::SRL, SDLoc(X),
6781 X.getValueType(), X,
6782 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6783 AddToWorklist(X.getNode());
6784 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6785 AddToWorklist(X.getNode());
6788 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6789 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6790 X, DAG.getConstant(SignBit, VT));
6791 AddToWorklist(X.getNode());
6793 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6794 VT, N0.getOperand(0));
6795 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6796 Cst, DAG.getConstant(~SignBit, VT));
6797 AddToWorklist(Cst.getNode());
6799 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6803 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6804 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6805 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6806 if (CombineLD.getNode())
6813 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6814 EVT VT = N->getValueType(0);
6815 return CombineConsecutiveLoads(N, VT);
6818 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6819 /// operands. DstEltVT indicates the destination element value type.
6820 SDValue DAGCombiner::
6821 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6822 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6824 // If this is already the right type, we're done.
6825 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6827 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6828 unsigned DstBitSize = DstEltVT.getSizeInBits();
6830 // If this is a conversion of N elements of one type to N elements of another
6831 // type, convert each element. This handles FP<->INT cases.
6832 if (SrcBitSize == DstBitSize) {
6833 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6834 BV->getValueType(0).getVectorNumElements());
6836 // Due to the FP element handling below calling this routine recursively,
6837 // we can end up with a scalar-to-vector node here.
6838 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6839 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6840 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6841 DstEltVT, BV->getOperand(0)));
6843 SmallVector<SDValue, 8> Ops;
6844 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6845 SDValue Op = BV->getOperand(i);
6846 // If the vector element type is not legal, the BUILD_VECTOR operands
6847 // are promoted and implicitly truncated. Make that explicit here.
6848 if (Op.getValueType() != SrcEltVT)
6849 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6850 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6852 AddToWorklist(Ops.back().getNode());
6854 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6857 // Otherwise, we're growing or shrinking the elements. To avoid having to
6858 // handle annoying details of growing/shrinking FP values, we convert them to
6860 if (SrcEltVT.isFloatingPoint()) {
6861 // Convert the input float vector to a int vector where the elements are the
6863 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6864 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6868 // Now we know the input is an integer vector. If the output is a FP type,
6869 // convert to integer first, then to FP of the right size.
6870 if (DstEltVT.isFloatingPoint()) {
6871 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6872 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6874 // Next, convert to FP elements of the same size.
6875 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6878 // Okay, we know the src/dst types are both integers of differing types.
6879 // Handling growing first.
6880 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6881 if (SrcBitSize < DstBitSize) {
6882 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6884 SmallVector<SDValue, 8> Ops;
6885 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6886 i += NumInputsPerOutput) {
6887 bool isLE = TLI.isLittleEndian();
6888 APInt NewBits = APInt(DstBitSize, 0);
6889 bool EltIsUndef = true;
6890 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6891 // Shift the previously computed bits over.
6892 NewBits <<= SrcBitSize;
6893 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6894 if (Op.getOpcode() == ISD::UNDEF) continue;
6897 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6898 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6902 Ops.push_back(DAG.getUNDEF(DstEltVT));
6904 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6907 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6908 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6911 // Finally, this must be the case where we are shrinking elements: each input
6912 // turns into multiple outputs.
6913 bool isS2V = ISD::isScalarToVector(BV);
6914 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6915 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6916 NumOutputsPerInput*BV->getNumOperands());
6917 SmallVector<SDValue, 8> Ops;
6919 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6920 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6921 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6922 Ops.push_back(DAG.getUNDEF(DstEltVT));
6926 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6927 getAPIntValue().zextOrTrunc(SrcBitSize);
6929 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6930 APInt ThisVal = OpVal.trunc(DstBitSize);
6931 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6932 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6933 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6934 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6936 OpVal = OpVal.lshr(DstBitSize);
6939 // For big endian targets, swap the order of the pieces of each element.
6940 if (TLI.isBigEndian())
6941 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6944 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6947 SDValue DAGCombiner::visitFADD(SDNode *N) {
6948 SDValue N0 = N->getOperand(0);
6949 SDValue N1 = N->getOperand(1);
6950 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6951 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6952 EVT VT = N->getValueType(0);
6953 const TargetOptions &Options = DAG.getTarget().Options;
6956 if (VT.isVector()) {
6957 SDValue FoldedVOp = SimplifyVBinOp(N);
6958 if (FoldedVOp.getNode()) return FoldedVOp;
6961 // fold (fadd c1, c2) -> c1 + c2
6963 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6965 // canonicalize constant to RHS
6966 if (N0CFP && !N1CFP)
6967 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6969 // fold (fadd A, (fneg B)) -> (fsub A, B)
6970 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6971 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6972 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6973 GetNegatedExpression(N1, DAG, LegalOperations));
6975 // fold (fadd (fneg A), B) -> (fsub B, A)
6976 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6977 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6978 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6979 GetNegatedExpression(N0, DAG, LegalOperations));
6981 // If 'unsafe math' is enabled, fold lots of things.
6982 if (Options.UnsafeFPMath) {
6983 // No FP constant should be created after legalization as Instruction
6984 // Selection pass has a hard time dealing with FP constants.
6985 bool AllowNewConst = (Level < AfterLegalizeDAG);
6987 // fold (fadd A, 0) -> A
6988 if (N1CFP && N1CFP->getValueAPF().isZero())
6991 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6992 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6993 isa<ConstantFPSDNode>(N0.getOperand(1)))
6994 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6995 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6996 N0.getOperand(1), N1));
6998 // If allowed, fold (fadd (fneg x), x) -> 0.0
6999 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7000 return DAG.getConstantFP(0.0, VT);
7002 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7003 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7004 return DAG.getConstantFP(0.0, VT);
7006 // We can fold chains of FADD's of the same value into multiplications.
7007 // This transform is not safe in general because we are reducing the number
7008 // of rounding steps.
7009 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7010 if (N0.getOpcode() == ISD::FMUL) {
7011 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7012 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7014 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7015 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7016 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7018 DAG.getConstantFP(1.0, VT));
7019 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7022 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7023 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7024 N1.getOperand(0) == N1.getOperand(1) &&
7025 N0.getOperand(0) == N1.getOperand(0)) {
7026 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7028 DAG.getConstantFP(2.0, VT));
7029 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7030 N0.getOperand(0), NewCFP);
7034 if (N1.getOpcode() == ISD::FMUL) {
7035 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7036 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7038 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7039 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7040 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7042 DAG.getConstantFP(1.0, VT));
7043 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7046 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7047 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7048 N0.getOperand(0) == N0.getOperand(1) &&
7049 N1.getOperand(0) == N0.getOperand(0)) {
7050 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7052 DAG.getConstantFP(2.0, VT));
7053 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7057 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7058 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7059 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7060 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7061 (N0.getOperand(0) == N1))
7062 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7063 N1, DAG.getConstantFP(3.0, VT));
7066 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7067 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7068 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7069 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7070 N1.getOperand(0) == N0)
7071 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7072 N0, DAG.getConstantFP(3.0, VT));
7075 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7076 if (AllowNewConst &&
7077 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7078 N0.getOperand(0) == N0.getOperand(1) &&
7079 N1.getOperand(0) == N1.getOperand(1) &&
7080 N0.getOperand(0) == N1.getOperand(0))
7081 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7082 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
7084 } // enable-unsafe-fp-math
7086 // FADD -> FMA combines:
7087 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7088 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7089 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7091 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7092 if (N0.getOpcode() == ISD::FMUL &&
7093 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7094 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7095 N0.getOperand(0), N0.getOperand(1), N1);
7097 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7098 // Note: Commutes FADD operands.
7099 if (N1.getOpcode() == ISD::FMUL &&
7100 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7101 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7102 N1.getOperand(0), N1.getOperand(1), N0);
7104 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7105 // to combine into FMA, arrange such nodes accordingly.
7106 if (TLI.isFPExtFree(VT)) {
7108 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7109 if (N0.getOpcode() == ISD::FP_EXTEND) {
7110 SDValue N00 = N0.getOperand(0);
7111 if (N00.getOpcode() == ISD::FMUL)
7112 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7113 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7115 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7116 N00.getOperand(1)), N1);
7119 // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
7120 // Note: Commutes FADD operands.
7121 if (N1.getOpcode() == ISD::FP_EXTEND) {
7122 SDValue N10 = N1.getOperand(0);
7123 if (N10.getOpcode() == ISD::FMUL)
7124 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7125 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7127 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7128 N10.getOperand(1)), N0);
7132 // More folding opportunities when target permits.
7133 if (TLI.enableAggressiveFMAFusion(VT)) {
7135 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7136 if (N0.getOpcode() == ISD::FMA &&
7137 N0.getOperand(2).getOpcode() == ISD::FMUL)
7138 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7139 N0.getOperand(0), N0.getOperand(1),
7140 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7141 N0.getOperand(2).getOperand(0),
7142 N0.getOperand(2).getOperand(1),
7145 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7146 if (N1->getOpcode() == ISD::FMA &&
7147 N1.getOperand(2).getOpcode() == ISD::FMUL)
7148 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7149 N1.getOperand(0), N1.getOperand(1),
7150 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7151 N1.getOperand(2).getOperand(0),
7152 N1.getOperand(2).getOperand(1),
7160 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7161 SDValue N0 = N->getOperand(0);
7162 SDValue N1 = N->getOperand(1);
7163 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7164 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7165 EVT VT = N->getValueType(0);
7167 const TargetOptions &Options = DAG.getTarget().Options;
7170 if (VT.isVector()) {
7171 SDValue FoldedVOp = SimplifyVBinOp(N);
7172 if (FoldedVOp.getNode()) return FoldedVOp;
7175 // fold (fsub c1, c2) -> c1-c2
7177 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7179 // fold (fsub A, (fneg B)) -> (fadd A, B)
7180 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7181 return DAG.getNode(ISD::FADD, dl, VT, N0,
7182 GetNegatedExpression(N1, DAG, LegalOperations));
7184 // If 'unsafe math' is enabled, fold lots of things.
7185 if (Options.UnsafeFPMath) {
7187 if (N1CFP && N1CFP->getValueAPF().isZero())
7190 // (fsub 0, B) -> -B
7191 if (N0CFP && N0CFP->getValueAPF().isZero()) {
7192 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7193 return GetNegatedExpression(N1, DAG, LegalOperations);
7194 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7195 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7198 // (fsub x, x) -> 0.0
7200 return DAG.getConstantFP(0.0f, VT);
7202 // (fsub x, (fadd x, y)) -> (fneg y)
7203 // (fsub x, (fadd y, x)) -> (fneg y)
7204 if (N1.getOpcode() == ISD::FADD) {
7205 SDValue N10 = N1->getOperand(0);
7206 SDValue N11 = N1->getOperand(1);
7208 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7209 return GetNegatedExpression(N11, DAG, LegalOperations);
7211 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7212 return GetNegatedExpression(N10, DAG, LegalOperations);
7216 // FSUB -> FMA combines:
7217 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7218 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7219 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7221 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7222 if (N0.getOpcode() == ISD::FMUL &&
7223 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7224 return DAG.getNode(ISD::FMA, dl, VT,
7225 N0.getOperand(0), N0.getOperand(1),
7226 DAG.getNode(ISD::FNEG, dl, VT, N1));
7228 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7229 // Note: Commutes FSUB operands.
7230 if (N1.getOpcode() == ISD::FMUL &&
7231 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7232 return DAG.getNode(ISD::FMA, dl, VT,
7233 DAG.getNode(ISD::FNEG, dl, VT,
7235 N1.getOperand(1), N0);
7237 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7238 if (N0.getOpcode() == ISD::FNEG &&
7239 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7240 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
7241 TLI.enableAggressiveFMAFusion(VT))) {
7242 SDValue N00 = N0.getOperand(0).getOperand(0);
7243 SDValue N01 = N0.getOperand(0).getOperand(1);
7244 return DAG.getNode(ISD::FMA, dl, VT,
7245 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
7246 DAG.getNode(ISD::FNEG, dl, VT, N1));
7249 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7250 // to combine into FMA, arrange such nodes accordingly.
7251 if (TLI.isFPExtFree(VT)) {
7253 // fold (fsub (fpext (fmul x, y)), z)
7254 // -> (fma (fpext x), (fpext y), (fneg z))
7255 if (N0.getOpcode() == ISD::FP_EXTEND) {
7256 SDValue N00 = N0.getOperand(0);
7257 if (N00.getOpcode() == ISD::FMUL)
7258 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7259 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7261 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7263 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7266 // fold (fsub x, (fpext (fmul y, z)))
7267 // -> (fma (fneg (fpext y)), (fpext z), x)
7268 // Note: Commutes FSUB operands.
7269 if (N1.getOpcode() == ISD::FP_EXTEND) {
7270 SDValue N10 = N1.getOperand(0);
7271 if (N10.getOpcode() == ISD::FMUL)
7272 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7273 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7274 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7275 VT, N10.getOperand(0))),
7276 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7281 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7282 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7283 if (N0.getOpcode() == ISD::FP_EXTEND) {
7284 SDValue N00 = N0.getOperand(0);
7285 if (N00.getOpcode() == ISD::FNEG) {
7286 SDValue N000 = N00.getOperand(0);
7287 if (N000.getOpcode() == ISD::FMUL) {
7288 return DAG.getNode(ISD::FMA, dl, VT,
7289 DAG.getNode(ISD::FNEG, dl, VT,
7290 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7291 VT, N000.getOperand(0))),
7292 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7293 N000.getOperand(1)),
7294 DAG.getNode(ISD::FNEG, dl, VT, N1));
7299 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7300 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7301 if (N0.getOpcode() == ISD::FNEG) {
7302 SDValue N00 = N0.getOperand(0);
7303 if (N00.getOpcode() == ISD::FP_EXTEND) {
7304 SDValue N000 = N00.getOperand(0);
7305 if (N000.getOpcode() == ISD::FMUL) {
7306 return DAG.getNode(ISD::FMA, dl, VT,
7307 DAG.getNode(ISD::FNEG, dl, VT,
7308 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7309 VT, N000.getOperand(0))),
7310 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7311 N000.getOperand(1)),
7312 DAG.getNode(ISD::FNEG, dl, VT, N1));
7318 // More folding opportunities when target permits.
7319 if (TLI.enableAggressiveFMAFusion(VT)) {
7321 // fold (fsub (fma x, y, (fmul u, v)), z)
7322 // -> (fma x, y (fma u, v, (fneg z)))
7323 if (N0.getOpcode() == ISD::FMA &&
7324 N0.getOperand(2).getOpcode() == ISD::FMUL)
7325 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7326 N0.getOperand(0), N0.getOperand(1),
7327 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7328 N0.getOperand(2).getOperand(0),
7329 N0.getOperand(2).getOperand(1),
7330 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7333 // fold (fsub x, (fma y, z, (fmul u, v)))
7334 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7335 if (N1.getOpcode() == ISD::FMA &&
7336 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7337 SDValue N20 = N1.getOperand(2).getOperand(0);
7338 SDValue N21 = N1.getOperand(2).getOperand(1);
7339 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7340 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7343 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7344 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7354 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7355 SDValue N0 = N->getOperand(0);
7356 SDValue N1 = N->getOperand(1);
7357 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7358 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7359 EVT VT = N->getValueType(0);
7360 const TargetOptions &Options = DAG.getTarget().Options;
7363 if (VT.isVector()) {
7364 // This just handles C1 * C2 for vectors. Other vector folds are below.
7365 SDValue FoldedVOp = SimplifyVBinOp(N);
7366 if (FoldedVOp.getNode())
7368 // Canonicalize vector constant to RHS.
7369 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7370 N1.getOpcode() != ISD::BUILD_VECTOR)
7371 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7372 if (BV0->isConstant())
7373 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7376 // fold (fmul c1, c2) -> c1*c2
7378 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7380 // canonicalize constant to RHS
7381 if (N0CFP && !N1CFP)
7382 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7384 // fold (fmul A, 1.0) -> A
7385 if (N1CFP && N1CFP->isExactlyValue(1.0))
7388 if (Options.UnsafeFPMath) {
7389 // fold (fmul A, 0) -> 0
7390 if (N1CFP && N1CFP->getValueAPF().isZero())
7393 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7394 if (N0.getOpcode() == ISD::FMUL) {
7395 // Fold scalars or any vector constants (not just splats).
7396 // This fold is done in general by InstCombine, but extra fmul insts
7397 // may have been generated during lowering.
7398 SDValue N01 = N0.getOperand(1);
7399 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7400 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7401 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7402 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7404 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7405 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7409 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7410 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7411 // during an early run of DAGCombiner can prevent folding with fmuls
7412 // inserted during lowering.
7413 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7415 const SDValue Two = DAG.getConstantFP(2.0, VT);
7416 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7417 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7421 // fold (fmul X, 2.0) -> (fadd X, X)
7422 if (N1CFP && N1CFP->isExactlyValue(+2.0))
7423 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7425 // fold (fmul X, -1.0) -> (fneg X)
7426 if (N1CFP && N1CFP->isExactlyValue(-1.0))
7427 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7428 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7430 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7431 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7432 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7433 // Both can be negated for free, check to see if at least one is cheaper
7435 if (LHSNeg == 2 || RHSNeg == 2)
7436 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7437 GetNegatedExpression(N0, DAG, LegalOperations),
7438 GetNegatedExpression(N1, DAG, LegalOperations));
7445 SDValue DAGCombiner::visitFMA(SDNode *N) {
7446 SDValue N0 = N->getOperand(0);
7447 SDValue N1 = N->getOperand(1);
7448 SDValue N2 = N->getOperand(2);
7449 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7450 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7451 EVT VT = N->getValueType(0);
7453 const TargetOptions &Options = DAG.getTarget().Options;
7455 // Constant fold FMA.
7456 if (isa<ConstantFPSDNode>(N0) &&
7457 isa<ConstantFPSDNode>(N1) &&
7458 isa<ConstantFPSDNode>(N2)) {
7459 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7462 if (Options.UnsafeFPMath) {
7463 if (N0CFP && N0CFP->isZero())
7465 if (N1CFP && N1CFP->isZero())
7468 if (N0CFP && N0CFP->isExactlyValue(1.0))
7469 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7470 if (N1CFP && N1CFP->isExactlyValue(1.0))
7471 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7473 // Canonicalize (fma c, x, y) -> (fma x, c, y)
7474 if (N0CFP && !N1CFP)
7475 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7477 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7478 if (Options.UnsafeFPMath && N1CFP &&
7479 N2.getOpcode() == ISD::FMUL &&
7480 N0 == N2.getOperand(0) &&
7481 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7482 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7483 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7487 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7488 if (Options.UnsafeFPMath &&
7489 N0.getOpcode() == ISD::FMUL && N1CFP &&
7490 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7491 return DAG.getNode(ISD::FMA, dl, VT,
7493 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7497 // (fma x, 1, y) -> (fadd x, y)
7498 // (fma x, -1, y) -> (fadd (fneg x), y)
7500 if (N1CFP->isExactlyValue(1.0))
7501 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7503 if (N1CFP->isExactlyValue(-1.0) &&
7504 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7505 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7506 AddToWorklist(RHSNeg.getNode());
7507 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7511 // (fma x, c, x) -> (fmul x, (c+1))
7512 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7513 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7514 DAG.getNode(ISD::FADD, dl, VT,
7515 N1, DAG.getConstantFP(1.0, VT)));
7517 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7518 if (Options.UnsafeFPMath && N1CFP &&
7519 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7520 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7521 DAG.getNode(ISD::FADD, dl, VT,
7522 N1, DAG.getConstantFP(-1.0, VT)));
7528 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7529 SDValue N0 = N->getOperand(0);
7530 SDValue N1 = N->getOperand(1);
7531 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7532 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7533 EVT VT = N->getValueType(0);
7535 const TargetOptions &Options = DAG.getTarget().Options;
7538 if (VT.isVector()) {
7539 SDValue FoldedVOp = SimplifyVBinOp(N);
7540 if (FoldedVOp.getNode()) return FoldedVOp;
7543 // fold (fdiv c1, c2) -> c1/c2
7545 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7547 if (Options.UnsafeFPMath) {
7548 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7550 // Compute the reciprocal 1.0 / c2.
7551 APFloat N1APF = N1CFP->getValueAPF();
7552 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7553 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7554 // Only do the transform if the reciprocal is a legal fp immediate that
7555 // isn't too nasty (eg NaN, denormal, ...).
7556 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7557 (!LegalOperations ||
7558 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7559 // backend)... we should handle this gracefully after Legalize.
7560 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7561 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7562 TLI.isFPImmLegal(Recip, VT)))
7563 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7564 DAG.getConstantFP(Recip, VT));
7567 // If this FDIV is part of a reciprocal square root, it may be folded
7568 // into a target-specific square root estimate instruction.
7569 if (N1.getOpcode() == ISD::FSQRT) {
7570 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7571 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7573 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7574 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7575 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7576 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7577 AddToWorklist(RV.getNode());
7578 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7580 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7581 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7582 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7583 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7584 AddToWorklist(RV.getNode());
7585 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7587 } else if (N1.getOpcode() == ISD::FMUL) {
7588 // Look through an FMUL. Even though this won't remove the FDIV directly,
7589 // it's still worthwhile to get rid of the FSQRT if possible.
7592 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7593 SqrtOp = N1.getOperand(0);
7594 OtherOp = N1.getOperand(1);
7595 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7596 SqrtOp = N1.getOperand(1);
7597 OtherOp = N1.getOperand(0);
7599 if (SqrtOp.getNode()) {
7600 // We found a FSQRT, so try to make this fold:
7601 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7602 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7603 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7604 AddToWorklist(RV.getNode());
7605 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7610 // Fold into a reciprocal estimate and multiply instead of a real divide.
7611 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7612 AddToWorklist(RV.getNode());
7613 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7617 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7618 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7619 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7620 // Both can be negated for free, check to see if at least one is cheaper
7622 if (LHSNeg == 2 || RHSNeg == 2)
7623 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7624 GetNegatedExpression(N0, DAG, LegalOperations),
7625 GetNegatedExpression(N1, DAG, LegalOperations));
7629 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7631 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7632 // Notice that this is not always beneficial. One reason is different target
7633 // may have different costs for FDIV and FMUL, so sometimes the cost of two
7634 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7635 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7636 if (Options.UnsafeFPMath) {
7637 // Skip if current node is a reciprocal.
7638 if (N0CFP && N0CFP->isExactlyValue(1.0))
7641 SmallVector<SDNode *, 4> Users;
7642 // Find all FDIV users of the same divisor.
7643 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7644 UE = N1.getNode()->use_end();
7646 SDNode *User = UI.getUse().getUser();
7647 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7648 Users.push_back(User);
7651 if (TLI.combineRepeatedFPDivisors(Users.size())) {
7652 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7653 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7655 // Dividend / Divisor -> Dividend * Reciprocal
7656 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7657 if ((*I)->getOperand(0) != FPOne) {
7658 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7659 (*I)->getOperand(0), Reciprocal);
7660 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7670 SDValue DAGCombiner::visitFREM(SDNode *N) {
7671 SDValue N0 = N->getOperand(0);
7672 SDValue N1 = N->getOperand(1);
7673 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7674 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7675 EVT VT = N->getValueType(0);
7677 // fold (frem c1, c2) -> fmod(c1,c2)
7679 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7684 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7685 if (DAG.getTarget().Options.UnsafeFPMath &&
7686 !TLI.isFsqrtCheap()) {
7687 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7688 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7689 EVT VT = RV.getValueType();
7690 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7691 AddToWorklist(RV.getNode());
7693 // Unfortunately, RV is now NaN if the input was exactly 0.
7694 // Select out this case and force the answer to 0.
7695 SDValue Zero = DAG.getConstantFP(0.0, VT);
7697 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7698 N->getOperand(0), Zero, ISD::SETEQ);
7699 AddToWorklist(ZeroCmp.getNode());
7700 AddToWorklist(RV.getNode());
7702 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7703 SDLoc(N), VT, ZeroCmp, Zero, RV);
7710 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7711 SDValue N0 = N->getOperand(0);
7712 SDValue N1 = N->getOperand(1);
7713 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7714 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7715 EVT VT = N->getValueType(0);
7717 if (N0CFP && N1CFP) // Constant fold
7718 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7721 const APFloat& V = N1CFP->getValueAPF();
7722 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7723 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7724 if (!V.isNegative()) {
7725 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7726 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7728 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7729 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7730 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7734 // copysign(fabs(x), y) -> copysign(x, y)
7735 // copysign(fneg(x), y) -> copysign(x, y)
7736 // copysign(copysign(x,z), y) -> copysign(x, y)
7737 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7738 N0.getOpcode() == ISD::FCOPYSIGN)
7739 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7740 N0.getOperand(0), N1);
7742 // copysign(x, abs(y)) -> abs(x)
7743 if (N1.getOpcode() == ISD::FABS)
7744 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7746 // copysign(x, copysign(y,z)) -> copysign(x, z)
7747 if (N1.getOpcode() == ISD::FCOPYSIGN)
7748 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7749 N0, N1.getOperand(1));
7751 // copysign(x, fp_extend(y)) -> copysign(x, y)
7752 // copysign(x, fp_round(y)) -> copysign(x, y)
7753 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7754 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7755 N0, N1.getOperand(0));
7760 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7761 SDValue N0 = N->getOperand(0);
7762 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7763 EVT VT = N->getValueType(0);
7764 EVT OpVT = N0.getValueType();
7766 // fold (sint_to_fp c1) -> c1fp
7768 // ...but only if the target supports immediate floating-point values
7769 (!LegalOperations ||
7770 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7771 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7773 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7774 // but UINT_TO_FP is legal on this target, try to convert.
7775 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7776 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7777 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7778 if (DAG.SignBitIsZero(N0))
7779 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7782 // The next optimizations are desirable only if SELECT_CC can be lowered.
7783 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7784 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7785 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7787 (!LegalOperations ||
7788 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7790 { N0.getOperand(0), N0.getOperand(1),
7791 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7793 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7796 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7797 // (select_cc x, y, 1.0, 0.0,, cc)
7798 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7799 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7800 (!LegalOperations ||
7801 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7803 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7804 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7805 N0.getOperand(0).getOperand(2) };
7806 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7813 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7814 SDValue N0 = N->getOperand(0);
7815 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7816 EVT VT = N->getValueType(0);
7817 EVT OpVT = N0.getValueType();
7819 // fold (uint_to_fp c1) -> c1fp
7821 // ...but only if the target supports immediate floating-point values
7822 (!LegalOperations ||
7823 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7824 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7826 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7827 // but SINT_TO_FP is legal on this target, try to convert.
7828 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7829 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7830 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7831 if (DAG.SignBitIsZero(N0))
7832 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7835 // The next optimizations are desirable only if SELECT_CC can be lowered.
7836 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7837 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7839 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7840 (!LegalOperations ||
7841 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7843 { N0.getOperand(0), N0.getOperand(1),
7844 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7846 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7853 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7854 SDValue N0 = N->getOperand(0);
7855 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7856 EVT VT = N->getValueType(0);
7858 // fold (fp_to_sint c1fp) -> c1
7860 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7865 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7866 SDValue N0 = N->getOperand(0);
7867 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7868 EVT VT = N->getValueType(0);
7870 // fold (fp_to_uint c1fp) -> c1
7872 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7877 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7878 SDValue N0 = N->getOperand(0);
7879 SDValue N1 = N->getOperand(1);
7880 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7881 EVT VT = N->getValueType(0);
7883 // fold (fp_round c1fp) -> c1fp
7885 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7887 // fold (fp_round (fp_extend x)) -> x
7888 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7889 return N0.getOperand(0);
7891 // fold (fp_round (fp_round x)) -> (fp_round x)
7892 if (N0.getOpcode() == ISD::FP_ROUND) {
7893 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
7894 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
7895 // If the first fp_round isn't a value preserving truncation, it might
7896 // introduce a tie in the second fp_round, that wouldn't occur in the
7897 // single-step fp_round we want to fold to.
7898 // In other words, double rounding isn't the same as rounding.
7899 // Also, this is a value preserving truncation iff both fp_round's are.
7900 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
7901 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7902 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
7905 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7906 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7907 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7908 N0.getOperand(0), N1);
7909 AddToWorklist(Tmp.getNode());
7910 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7911 Tmp, N0.getOperand(1));
7917 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7918 SDValue N0 = N->getOperand(0);
7919 EVT VT = N->getValueType(0);
7920 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7921 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7923 // fold (fp_round_inreg c1fp) -> c1fp
7924 if (N0CFP && isTypeLegal(EVT)) {
7925 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7926 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7932 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7933 SDValue N0 = N->getOperand(0);
7934 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7935 EVT VT = N->getValueType(0);
7937 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7938 if (N->hasOneUse() &&
7939 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7942 // fold (fp_extend c1fp) -> c1fp
7944 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7946 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7948 if (N0.getOpcode() == ISD::FP_ROUND
7949 && N0.getNode()->getConstantOperandVal(1) == 1) {
7950 SDValue In = N0.getOperand(0);
7951 if (In.getValueType() == VT) return In;
7952 if (VT.bitsLT(In.getValueType()))
7953 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7954 In, N0.getOperand(1));
7955 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7958 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7959 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7960 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7961 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7962 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7964 LN0->getBasePtr(), N0.getValueType(),
7965 LN0->getMemOperand());
7966 CombineTo(N, ExtLoad);
7967 CombineTo(N0.getNode(),
7968 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7969 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7970 ExtLoad.getValue(1));
7971 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7977 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7978 SDValue N0 = N->getOperand(0);
7979 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7980 EVT VT = N->getValueType(0);
7982 // fold (fceil c1) -> fceil(c1)
7984 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7989 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7990 SDValue N0 = N->getOperand(0);
7991 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7992 EVT VT = N->getValueType(0);
7994 // fold (ftrunc c1) -> ftrunc(c1)
7996 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8001 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8002 SDValue N0 = N->getOperand(0);
8003 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8004 EVT VT = N->getValueType(0);
8006 // fold (ffloor c1) -> ffloor(c1)
8008 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8013 // FIXME: FNEG and FABS have a lot in common; refactor.
8014 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8015 SDValue N0 = N->getOperand(0);
8016 EVT VT = N->getValueType(0);
8018 if (VT.isVector()) {
8019 SDValue FoldedVOp = SimplifyVUnaryOp(N);
8020 if (FoldedVOp.getNode()) return FoldedVOp;
8023 // Constant fold FNEG.
8024 if (isa<ConstantFPSDNode>(N0))
8025 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
8027 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8028 &DAG.getTarget().Options))
8029 return GetNegatedExpression(N0, DAG, LegalOperations);
8031 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8032 // constant pool values.
8033 if (!TLI.isFNegFree(VT) &&
8034 N0.getOpcode() == ISD::BITCAST &&
8035 N0.getNode()->hasOneUse()) {
8036 SDValue Int = N0.getOperand(0);
8037 EVT IntVT = Int.getValueType();
8038 if (IntVT.isInteger() && !IntVT.isVector()) {
8040 if (N0.getValueType().isVector()) {
8041 // For a vector, get a mask such as 0x80... per scalar element
8043 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8044 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8046 // For a scalar, just generate 0x80...
8047 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8049 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
8050 DAG.getConstant(SignMask, IntVT));
8051 AddToWorklist(Int.getNode());
8052 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8056 // (fneg (fmul c, x)) -> (fmul -c, x)
8057 if (N0.getOpcode() == ISD::FMUL) {
8058 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8060 APFloat CVal = CFP1->getValueAPF();
8062 if (Level >= AfterLegalizeDAG &&
8063 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8064 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8066 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8067 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8074 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8075 SDValue N0 = N->getOperand(0);
8076 SDValue N1 = N->getOperand(1);
8077 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8078 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8080 if (N0CFP && N1CFP) {
8081 const APFloat &C0 = N0CFP->getValueAPF();
8082 const APFloat &C1 = N1CFP->getValueAPF();
8083 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8087 EVT VT = N->getValueType(0);
8088 // Canonicalize to constant on RHS.
8089 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8095 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8096 SDValue N0 = N->getOperand(0);
8097 SDValue N1 = N->getOperand(1);
8098 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8099 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8101 if (N0CFP && N1CFP) {
8102 const APFloat &C0 = N0CFP->getValueAPF();
8103 const APFloat &C1 = N1CFP->getValueAPF();
8104 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8108 EVT VT = N->getValueType(0);
8109 // Canonicalize to constant on RHS.
8110 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8116 SDValue DAGCombiner::visitFABS(SDNode *N) {
8117 SDValue N0 = N->getOperand(0);
8118 EVT VT = N->getValueType(0);
8120 if (VT.isVector()) {
8121 SDValue FoldedVOp = SimplifyVUnaryOp(N);
8122 if (FoldedVOp.getNode()) return FoldedVOp;
8125 // fold (fabs c1) -> fabs(c1)
8126 if (isa<ConstantFPSDNode>(N0))
8127 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8129 // fold (fabs (fabs x)) -> (fabs x)
8130 if (N0.getOpcode() == ISD::FABS)
8131 return N->getOperand(0);
8133 // fold (fabs (fneg x)) -> (fabs x)
8134 // fold (fabs (fcopysign x, y)) -> (fabs x)
8135 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8136 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8138 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8139 // constant pool values.
8140 if (!TLI.isFAbsFree(VT) &&
8141 N0.getOpcode() == ISD::BITCAST &&
8142 N0.getNode()->hasOneUse()) {
8143 SDValue Int = N0.getOperand(0);
8144 EVT IntVT = Int.getValueType();
8145 if (IntVT.isInteger() && !IntVT.isVector()) {
8147 if (N0.getValueType().isVector()) {
8148 // For a vector, get a mask such as 0x7f... per scalar element
8150 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8151 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8153 // For a scalar, just generate 0x7f...
8154 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8156 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8157 DAG.getConstant(SignMask, IntVT));
8158 AddToWorklist(Int.getNode());
8159 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8166 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8167 SDValue Chain = N->getOperand(0);
8168 SDValue N1 = N->getOperand(1);
8169 SDValue N2 = N->getOperand(2);
8171 // If N is a constant we could fold this into a fallthrough or unconditional
8172 // branch. However that doesn't happen very often in normal code, because
8173 // Instcombine/SimplifyCFG should have handled the available opportunities.
8174 // If we did this folding here, it would be necessary to update the
8175 // MachineBasicBlock CFG, which is awkward.
8177 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8179 if (N1.getOpcode() == ISD::SETCC &&
8180 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8181 N1.getOperand(0).getValueType())) {
8182 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8183 Chain, N1.getOperand(2),
8184 N1.getOperand(0), N1.getOperand(1), N2);
8187 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8188 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8189 (N1.getOperand(0).hasOneUse() &&
8190 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8191 SDNode *Trunc = nullptr;
8192 if (N1.getOpcode() == ISD::TRUNCATE) {
8193 // Look pass the truncate.
8194 Trunc = N1.getNode();
8195 N1 = N1.getOperand(0);
8198 // Match this pattern so that we can generate simpler code:
8201 // %b = and i32 %a, 2
8202 // %c = srl i32 %b, 1
8203 // brcond i32 %c ...
8208 // %b = and i32 %a, 2
8209 // %c = setcc eq %b, 0
8212 // This applies only when the AND constant value has one bit set and the
8213 // SRL constant is equal to the log2 of the AND constant. The back-end is
8214 // smart enough to convert the result into a TEST/JMP sequence.
8215 SDValue Op0 = N1.getOperand(0);
8216 SDValue Op1 = N1.getOperand(1);
8218 if (Op0.getOpcode() == ISD::AND &&
8219 Op1.getOpcode() == ISD::Constant) {
8220 SDValue AndOp1 = Op0.getOperand(1);
8222 if (AndOp1.getOpcode() == ISD::Constant) {
8223 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8225 if (AndConst.isPowerOf2() &&
8226 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8228 DAG.getSetCC(SDLoc(N),
8229 getSetCCResultType(Op0.getValueType()),
8230 Op0, DAG.getConstant(0, Op0.getValueType()),
8233 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8234 MVT::Other, Chain, SetCC, N2);
8235 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8236 // will convert it back to (X & C1) >> C2.
8237 CombineTo(N, NewBRCond, false);
8238 // Truncate is dead.
8240 deleteAndRecombine(Trunc);
8241 // Replace the uses of SRL with SETCC
8242 WorklistRemover DeadNodes(*this);
8243 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8244 deleteAndRecombine(N1.getNode());
8245 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8251 // Restore N1 if the above transformation doesn't match.
8252 N1 = N->getOperand(1);
8255 // Transform br(xor(x, y)) -> br(x != y)
8256 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8257 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8258 SDNode *TheXor = N1.getNode();
8259 SDValue Op0 = TheXor->getOperand(0);
8260 SDValue Op1 = TheXor->getOperand(1);
8261 if (Op0.getOpcode() == Op1.getOpcode()) {
8262 // Avoid missing important xor optimizations.
8263 SDValue Tmp = visitXOR(TheXor);
8264 if (Tmp.getNode()) {
8265 if (Tmp.getNode() != TheXor) {
8266 DEBUG(dbgs() << "\nReplacing.8 ";
8268 dbgs() << "\nWith: ";
8269 Tmp.getNode()->dump(&DAG);
8271 WorklistRemover DeadNodes(*this);
8272 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8273 deleteAndRecombine(TheXor);
8274 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8275 MVT::Other, Chain, Tmp, N2);
8278 // visitXOR has changed XOR's operands or replaced the XOR completely,
8280 return SDValue(N, 0);
8284 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8286 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8287 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8288 Op0.getOpcode() == ISD::XOR) {
8289 TheXor = Op0.getNode();
8293 EVT SetCCVT = N1.getValueType();
8295 SetCCVT = getSetCCResultType(SetCCVT);
8296 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8299 Equal ? ISD::SETEQ : ISD::SETNE);
8300 // Replace the uses of XOR with SETCC
8301 WorklistRemover DeadNodes(*this);
8302 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8303 deleteAndRecombine(N1.getNode());
8304 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8305 MVT::Other, Chain, SetCC, N2);
8312 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8314 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8315 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8316 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8318 // If N is a constant we could fold this into a fallthrough or unconditional
8319 // branch. However that doesn't happen very often in normal code, because
8320 // Instcombine/SimplifyCFG should have handled the available opportunities.
8321 // If we did this folding here, it would be necessary to update the
8322 // MachineBasicBlock CFG, which is awkward.
8324 // Use SimplifySetCC to simplify SETCC's.
8325 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8326 CondLHS, CondRHS, CC->get(), SDLoc(N),
8328 if (Simp.getNode()) AddToWorklist(Simp.getNode());
8330 // fold to a simpler setcc
8331 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8332 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8333 N->getOperand(0), Simp.getOperand(2),
8334 Simp.getOperand(0), Simp.getOperand(1),
8340 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8341 /// and that N may be folded in the load / store addressing mode.
8342 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8344 const TargetLowering &TLI) {
8346 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
8347 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8349 VT = Use->getValueType(0);
8350 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
8351 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8353 VT = ST->getValue().getValueType();
8357 TargetLowering::AddrMode AM;
8358 if (N->getOpcode() == ISD::ADD) {
8359 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8362 AM.BaseOffs = Offset->getSExtValue();
8366 } else if (N->getOpcode() == ISD::SUB) {
8367 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8370 AM.BaseOffs = -Offset->getSExtValue();
8377 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8380 /// Try turning a load/store into a pre-indexed load/store when the base
8381 /// pointer is an add or subtract and it has other uses besides the load/store.
8382 /// After the transformation, the new indexed load/store has effectively folded
8383 /// the add/subtract in and all of its other uses are redirected to the
8385 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8386 if (Level < AfterLegalizeDAG)
8392 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8393 if (LD->isIndexed())
8395 VT = LD->getMemoryVT();
8396 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8397 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8399 Ptr = LD->getBasePtr();
8400 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8401 if (ST->isIndexed())
8403 VT = ST->getMemoryVT();
8404 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8405 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8407 Ptr = ST->getBasePtr();
8413 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8414 // out. There is no reason to make this a preinc/predec.
8415 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8416 Ptr.getNode()->hasOneUse())
8419 // Ask the target to do addressing mode selection.
8422 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8423 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8426 // Backends without true r+i pre-indexed forms may need to pass a
8427 // constant base with a variable offset so that constant coercion
8428 // will work with the patterns in canonical form.
8429 bool Swapped = false;
8430 if (isa<ConstantSDNode>(BasePtr)) {
8431 std::swap(BasePtr, Offset);
8435 // Don't create a indexed load / store with zero offset.
8436 if (isa<ConstantSDNode>(Offset) &&
8437 cast<ConstantSDNode>(Offset)->isNullValue())
8440 // Try turning it into a pre-indexed load / store except when:
8441 // 1) The new base ptr is a frame index.
8442 // 2) If N is a store and the new base ptr is either the same as or is a
8443 // predecessor of the value being stored.
8444 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8445 // that would create a cycle.
8446 // 4) All uses are load / store ops that use it as old base ptr.
8448 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8449 // (plus the implicit offset) to a register to preinc anyway.
8450 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8455 SDValue Val = cast<StoreSDNode>(N)->getValue();
8456 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8460 // If the offset is a constant, there may be other adds of constants that
8461 // can be folded with this one. We should do this to avoid having to keep
8462 // a copy of the original base pointer.
8463 SmallVector<SDNode *, 16> OtherUses;
8464 if (isa<ConstantSDNode>(Offset))
8465 for (SDNode *Use : BasePtr.getNode()->uses()) {
8466 if (Use == Ptr.getNode())
8469 if (Use->isPredecessorOf(N))
8472 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8477 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8478 if (Op1.getNode() == BasePtr.getNode())
8479 std::swap(Op0, Op1);
8480 assert(Op0.getNode() == BasePtr.getNode() &&
8481 "Use of ADD/SUB but not an operand");
8483 if (!isa<ConstantSDNode>(Op1)) {
8488 // FIXME: In some cases, we can be smarter about this.
8489 if (Op1.getValueType() != Offset.getValueType()) {
8494 OtherUses.push_back(Use);
8498 std::swap(BasePtr, Offset);
8500 // Now check for #3 and #4.
8501 bool RealUse = false;
8503 // Caches for hasPredecessorHelper
8504 SmallPtrSet<const SDNode *, 32> Visited;
8505 SmallVector<const SDNode *, 16> Worklist;
8507 for (SDNode *Use : Ptr.getNode()->uses()) {
8510 if (N->hasPredecessorHelper(Use, Visited, Worklist))
8513 // If Ptr may be folded in addressing mode of other use, then it's
8514 // not profitable to do this transformation.
8515 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8524 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8525 BasePtr, Offset, AM);
8527 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8528 BasePtr, Offset, AM);
8531 DEBUG(dbgs() << "\nReplacing.4 ";
8533 dbgs() << "\nWith: ";
8534 Result.getNode()->dump(&DAG);
8536 WorklistRemover DeadNodes(*this);
8538 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8539 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8541 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8544 // Finally, since the node is now dead, remove it from the graph.
8545 deleteAndRecombine(N);
8548 std::swap(BasePtr, Offset);
8550 // Replace other uses of BasePtr that can be updated to use Ptr
8551 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8552 unsigned OffsetIdx = 1;
8553 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8555 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8556 BasePtr.getNode() && "Expected BasePtr operand");
8558 // We need to replace ptr0 in the following expression:
8559 // x0 * offset0 + y0 * ptr0 = t0
8561 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8563 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8564 // indexed load/store and the expresion that needs to be re-written.
8566 // Therefore, we have:
8567 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8569 ConstantSDNode *CN =
8570 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8572 APInt Offset0 = CN->getAPIntValue();
8573 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8575 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8576 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8577 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8578 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8580 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8582 APInt CNV = Offset0;
8583 if (X0 < 0) CNV = -CNV;
8584 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8585 else CNV = CNV - Offset1;
8587 // We can now generate the new expression.
8588 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8589 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8591 SDValue NewUse = DAG.getNode(Opcode,
8592 SDLoc(OtherUses[i]),
8593 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8594 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8595 deleteAndRecombine(OtherUses[i]);
8598 // Replace the uses of Ptr with uses of the updated base value.
8599 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8600 deleteAndRecombine(Ptr.getNode());
8605 /// Try to combine a load/store with a add/sub of the base pointer node into a
8606 /// post-indexed load/store. The transformation folded the add/subtract into the
8607 /// new indexed load/store effectively and all of its uses are redirected to the
8609 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8610 if (Level < AfterLegalizeDAG)
8616 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8617 if (LD->isIndexed())
8619 VT = LD->getMemoryVT();
8620 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8621 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8623 Ptr = LD->getBasePtr();
8624 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8625 if (ST->isIndexed())
8627 VT = ST->getMemoryVT();
8628 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8629 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8631 Ptr = ST->getBasePtr();
8637 if (Ptr.getNode()->hasOneUse())
8640 for (SDNode *Op : Ptr.getNode()->uses()) {
8642 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8647 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8648 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8649 // Don't create a indexed load / store with zero offset.
8650 if (isa<ConstantSDNode>(Offset) &&
8651 cast<ConstantSDNode>(Offset)->isNullValue())
8654 // Try turning it into a post-indexed load / store except when
8655 // 1) All uses are load / store ops that use it as base ptr (and
8656 // it may be folded as addressing mmode).
8657 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8658 // nor a successor of N. Otherwise, if Op is folded that would
8661 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8665 bool TryNext = false;
8666 for (SDNode *Use : BasePtr.getNode()->uses()) {
8667 if (Use == Ptr.getNode())
8670 // If all the uses are load / store addresses, then don't do the
8672 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8673 bool RealUse = false;
8674 for (SDNode *UseUse : Use->uses()) {
8675 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8690 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8691 SDValue Result = isLoad
8692 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8693 BasePtr, Offset, AM)
8694 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8695 BasePtr, Offset, AM);
8698 DEBUG(dbgs() << "\nReplacing.5 ";
8700 dbgs() << "\nWith: ";
8701 Result.getNode()->dump(&DAG);
8703 WorklistRemover DeadNodes(*this);
8705 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8706 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8708 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8711 // Finally, since the node is now dead, remove it from the graph.
8712 deleteAndRecombine(N);
8714 // Replace the uses of Use with uses of the updated base value.
8715 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8716 Result.getValue(isLoad ? 1 : 0));
8717 deleteAndRecombine(Op);
8726 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8727 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8728 ISD::MemIndexedMode AM = LD->getAddressingMode();
8729 assert(AM != ISD::UNINDEXED);
8730 SDValue BP = LD->getOperand(1);
8731 SDValue Inc = LD->getOperand(2);
8733 // Some backends use TargetConstants for load offsets, but don't expect
8734 // TargetConstants in general ADD nodes. We can convert these constants into
8735 // regular Constants (if the constant is not opaque).
8736 assert((Inc.getOpcode() != ISD::TargetConstant ||
8737 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8738 "Cannot split out indexing using opaque target constants");
8739 if (Inc.getOpcode() == ISD::TargetConstant) {
8740 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8741 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8742 ConstInc->getValueType(0));
8746 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8747 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8750 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8751 LoadSDNode *LD = cast<LoadSDNode>(N);
8752 SDValue Chain = LD->getChain();
8753 SDValue Ptr = LD->getBasePtr();
8755 // If load is not volatile and there are no uses of the loaded value (and
8756 // the updated indexed value in case of indexed loads), change uses of the
8757 // chain value into uses of the chain input (i.e. delete the dead load).
8758 if (!LD->isVolatile()) {
8759 if (N->getValueType(1) == MVT::Other) {
8761 if (!N->hasAnyUseOfValue(0)) {
8762 // It's not safe to use the two value CombineTo variant here. e.g.
8763 // v1, chain2 = load chain1, loc
8764 // v2, chain3 = load chain2, loc
8766 // Now we replace use of chain2 with chain1. This makes the second load
8767 // isomorphic to the one we are deleting, and thus makes this load live.
8768 DEBUG(dbgs() << "\nReplacing.6 ";
8770 dbgs() << "\nWith chain: ";
8771 Chain.getNode()->dump(&DAG);
8773 WorklistRemover DeadNodes(*this);
8774 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8777 deleteAndRecombine(N);
8779 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8783 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8785 // If this load has an opaque TargetConstant offset, then we cannot split
8786 // the indexing into an add/sub directly (that TargetConstant may not be
8787 // valid for a different type of node, and we cannot convert an opaque
8788 // target constant into a regular constant).
8789 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8790 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8792 if (!N->hasAnyUseOfValue(0) &&
8793 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8794 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8796 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8797 Index = SplitIndexingFromLoad(LD);
8798 // Try to fold the base pointer arithmetic into subsequent loads and
8800 AddUsersToWorklist(N);
8802 Index = DAG.getUNDEF(N->getValueType(1));
8803 DEBUG(dbgs() << "\nReplacing.7 ";
8805 dbgs() << "\nWith: ";
8806 Undef.getNode()->dump(&DAG);
8807 dbgs() << " and 2 other values\n");
8808 WorklistRemover DeadNodes(*this);
8809 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8810 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8811 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8812 deleteAndRecombine(N);
8813 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8818 // If this load is directly stored, replace the load value with the stored
8820 // TODO: Handle store large -> read small portion.
8821 // TODO: Handle TRUNCSTORE/LOADEXT
8822 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8823 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8824 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8825 if (PrevST->getBasePtr() == Ptr &&
8826 PrevST->getValue().getValueType() == N->getValueType(0))
8827 return CombineTo(N, Chain.getOperand(1), Chain);
8831 // Try to infer better alignment information than the load already has.
8832 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8833 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8834 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8836 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8837 LD->getValueType(0),
8838 Chain, Ptr, LD->getPointerInfo(),
8840 LD->isVolatile(), LD->isNonTemporal(),
8841 LD->isInvariant(), Align, LD->getAAInfo());
8842 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8847 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8848 : DAG.getSubtarget().useAA();
8850 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8851 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8854 if (UseAA && LD->isUnindexed()) {
8855 // Walk up chain skipping non-aliasing memory nodes.
8856 SDValue BetterChain = FindBetterChain(N, Chain);
8858 // If there is a better chain.
8859 if (Chain != BetterChain) {
8862 // Replace the chain to void dependency.
8863 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8864 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8865 BetterChain, Ptr, LD->getMemOperand());
8867 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8868 LD->getValueType(0),
8869 BetterChain, Ptr, LD->getMemoryVT(),
8870 LD->getMemOperand());
8873 // Create token factor to keep old chain connected.
8874 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8875 MVT::Other, Chain, ReplLoad.getValue(1));
8877 // Make sure the new and old chains are cleaned up.
8878 AddToWorklist(Token.getNode());
8880 // Replace uses with load result and token factor. Don't add users
8882 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8886 // Try transforming N to an indexed load.
8887 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8888 return SDValue(N, 0);
8890 // Try to slice up N to more direct loads if the slices are mapped to
8891 // different register banks or pairing can take place.
8893 return SDValue(N, 0);
8899 /// \brief Helper structure used to slice a load in smaller loads.
8900 /// Basically a slice is obtained from the following sequence:
8901 /// Origin = load Ty1, Base
8902 /// Shift = srl Ty1 Origin, CstTy Amount
8903 /// Inst = trunc Shift to Ty2
8905 /// Then, it will be rewriten into:
8906 /// Slice = load SliceTy, Base + SliceOffset
8907 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8909 /// SliceTy is deduced from the number of bits that are actually used to
8911 struct LoadedSlice {
8912 /// \brief Helper structure used to compute the cost of a slice.
8914 /// Are we optimizing for code size.
8919 unsigned CrossRegisterBanksCopies;
8923 Cost(bool ForCodeSize = false)
8924 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8925 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8927 /// \brief Get the cost of one isolated slice.
8928 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8929 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8930 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8931 EVT TruncType = LS.Inst->getValueType(0);
8932 EVT LoadedType = LS.getLoadedType();
8933 if (TruncType != LoadedType &&
8934 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8938 /// \brief Account for slicing gain in the current cost.
8939 /// Slicing provide a few gains like removing a shift or a
8940 /// truncate. This method allows to grow the cost of the original
8941 /// load with the gain from this slice.
8942 void addSliceGain(const LoadedSlice &LS) {
8943 // Each slice saves a truncate.
8944 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8945 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8946 LS.Inst->getOperand(0).getValueType()))
8948 // If there is a shift amount, this slice gets rid of it.
8951 // If this slice can merge a cross register bank copy, account for it.
8952 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8953 ++CrossRegisterBanksCopies;
8956 Cost &operator+=(const Cost &RHS) {
8958 Truncates += RHS.Truncates;
8959 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8965 bool operator==(const Cost &RHS) const {
8966 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8967 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8968 ZExts == RHS.ZExts && Shift == RHS.Shift;
8971 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8973 bool operator<(const Cost &RHS) const {
8974 // Assume cross register banks copies are as expensive as loads.
8975 // FIXME: Do we want some more target hooks?
8976 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8977 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8978 // Unless we are optimizing for code size, consider the
8979 // expensive operation first.
8980 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8981 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8982 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8983 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8986 bool operator>(const Cost &RHS) const { return RHS < *this; }
8988 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8990 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8992 // The last instruction that represent the slice. This should be a
8993 // truncate instruction.
8995 // The original load instruction.
8997 // The right shift amount in bits from the original load.
8999 // The DAG from which Origin came from.
9000 // This is used to get some contextual information about legal types, etc.
9003 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9004 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9005 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9007 LoadedSlice(const LoadedSlice &LS)
9008 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
9010 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9011 /// \return Result is \p BitWidth and has used bits set to 1 and
9012 /// not used bits set to 0.
9013 APInt getUsedBits() const {
9014 // Reproduce the trunc(lshr) sequence:
9015 // - Start from the truncated value.
9016 // - Zero extend to the desired bit width.
9018 assert(Origin && "No original load to compare against.");
9019 unsigned BitWidth = Origin->getValueSizeInBits(0);
9020 assert(Inst && "This slice is not bound to an instruction");
9021 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9022 "Extracted slice is bigger than the whole type!");
9023 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9024 UsedBits.setAllBits();
9025 UsedBits = UsedBits.zext(BitWidth);
9030 /// \brief Get the size of the slice to be loaded in bytes.
9031 unsigned getLoadedSize() const {
9032 unsigned SliceSize = getUsedBits().countPopulation();
9033 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9034 return SliceSize / 8;
9037 /// \brief Get the type that will be loaded for this slice.
9038 /// Note: This may not be the final type for the slice.
9039 EVT getLoadedType() const {
9040 assert(DAG && "Missing context");
9041 LLVMContext &Ctxt = *DAG->getContext();
9042 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9045 /// \brief Get the alignment of the load used for this slice.
9046 unsigned getAlignment() const {
9047 unsigned Alignment = Origin->getAlignment();
9048 unsigned Offset = getOffsetFromBase();
9050 Alignment = MinAlign(Alignment, Alignment + Offset);
9054 /// \brief Check if this slice can be rewritten with legal operations.
9055 bool isLegal() const {
9056 // An invalid slice is not legal.
9057 if (!Origin || !Inst || !DAG)
9060 // Offsets are for indexed load only, we do not handle that.
9061 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9064 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9066 // Check that the type is legal.
9067 EVT SliceType = getLoadedType();
9068 if (!TLI.isTypeLegal(SliceType))
9071 // Check that the load is legal for this type.
9072 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9075 // Check that the offset can be computed.
9076 // 1. Check its type.
9077 EVT PtrType = Origin->getBasePtr().getValueType();
9078 if (PtrType == MVT::Untyped || PtrType.isExtended())
9081 // 2. Check that it fits in the immediate.
9082 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9085 // 3. Check that the computation is legal.
9086 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9089 // Check that the zext is legal if it needs one.
9090 EVT TruncateType = Inst->getValueType(0);
9091 if (TruncateType != SliceType &&
9092 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9098 /// \brief Get the offset in bytes of this slice in the original chunk of
9100 /// \pre DAG != nullptr.
9101 uint64_t getOffsetFromBase() const {
9102 assert(DAG && "Missing context.");
9104 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9105 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9106 uint64_t Offset = Shift / 8;
9107 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9108 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9109 "The size of the original loaded type is not a multiple of a"
9111 // If Offset is bigger than TySizeInBytes, it means we are loading all
9112 // zeros. This should have been optimized before in the process.
9113 assert(TySizeInBytes > Offset &&
9114 "Invalid shift amount for given loaded size");
9116 Offset = TySizeInBytes - Offset - getLoadedSize();
9120 /// \brief Generate the sequence of instructions to load the slice
9121 /// represented by this object and redirect the uses of this slice to
9122 /// this new sequence of instructions.
9123 /// \pre this->Inst && this->Origin are valid Instructions and this
9124 /// object passed the legal check: LoadedSlice::isLegal returned true.
9125 /// \return The last instruction of the sequence used to load the slice.
9126 SDValue loadSlice() const {
9127 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9128 const SDValue &OldBaseAddr = Origin->getBasePtr();
9129 SDValue BaseAddr = OldBaseAddr;
9130 // Get the offset in that chunk of bytes w.r.t. the endianess.
9131 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9132 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9134 // BaseAddr = BaseAddr + Offset.
9135 EVT ArithType = BaseAddr.getValueType();
9136 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9137 DAG->getConstant(Offset, ArithType));
9140 // Create the type of the loaded slice according to its size.
9141 EVT SliceType = getLoadedType();
9143 // Create the load for the slice.
9144 SDValue LastInst = DAG->getLoad(
9145 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9146 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9147 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9148 // If the final type is not the same as the loaded type, this means that
9149 // we have to pad with zero. Create a zero extend for that.
9150 EVT FinalType = Inst->getValueType(0);
9151 if (SliceType != FinalType)
9153 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9157 /// \brief Check if this slice can be merged with an expensive cross register
9158 /// bank copy. E.g.,
9160 /// f = bitcast i32 i to float
9161 bool canMergeExpensiveCrossRegisterBankCopy() const {
9162 if (!Inst || !Inst->hasOneUse())
9164 SDNode *Use = *Inst->use_begin();
9165 if (Use->getOpcode() != ISD::BITCAST)
9167 assert(DAG && "Missing context");
9168 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9169 EVT ResVT = Use->getValueType(0);
9170 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9171 const TargetRegisterClass *ArgRC =
9172 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9173 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9176 // At this point, we know that we perform a cross-register-bank copy.
9177 // Check if it is expensive.
9178 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9179 // Assume bitcasts are cheap, unless both register classes do not
9180 // explicitly share a common sub class.
9181 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9184 // Check if it will be merged with the load.
9185 // 1. Check the alignment constraint.
9186 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9187 ResVT.getTypeForEVT(*DAG->getContext()));
9189 if (RequiredAlignment > getAlignment())
9192 // 2. Check that the load is a legal operation for that type.
9193 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9196 // 3. Check that we do not have a zext in the way.
9197 if (Inst->getValueType(0) != getLoadedType())
9205 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9206 /// \p UsedBits looks like 0..0 1..1 0..0.
9207 static bool areUsedBitsDense(const APInt &UsedBits) {
9208 // If all the bits are one, this is dense!
9209 if (UsedBits.isAllOnesValue())
9212 // Get rid of the unused bits on the right.
9213 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9214 // Get rid of the unused bits on the left.
9215 if (NarrowedUsedBits.countLeadingZeros())
9216 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9217 // Check that the chunk of bits is completely used.
9218 return NarrowedUsedBits.isAllOnesValue();
9221 /// \brief Check whether or not \p First and \p Second are next to each other
9222 /// in memory. This means that there is no hole between the bits loaded
9223 /// by \p First and the bits loaded by \p Second.
9224 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9225 const LoadedSlice &Second) {
9226 assert(First.Origin == Second.Origin && First.Origin &&
9227 "Unable to match different memory origins.");
9228 APInt UsedBits = First.getUsedBits();
9229 assert((UsedBits & Second.getUsedBits()) == 0 &&
9230 "Slices are not supposed to overlap.");
9231 UsedBits |= Second.getUsedBits();
9232 return areUsedBitsDense(UsedBits);
9235 /// \brief Adjust the \p GlobalLSCost according to the target
9236 /// paring capabilities and the layout of the slices.
9237 /// \pre \p GlobalLSCost should account for at least as many loads as
9238 /// there is in the slices in \p LoadedSlices.
9239 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9240 LoadedSlice::Cost &GlobalLSCost) {
9241 unsigned NumberOfSlices = LoadedSlices.size();
9242 // If there is less than 2 elements, no pairing is possible.
9243 if (NumberOfSlices < 2)
9246 // Sort the slices so that elements that are likely to be next to each
9247 // other in memory are next to each other in the list.
9248 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9249 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9250 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9251 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9253 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9254 // First (resp. Second) is the first (resp. Second) potentially candidate
9255 // to be placed in a paired load.
9256 const LoadedSlice *First = nullptr;
9257 const LoadedSlice *Second = nullptr;
9258 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9259 // Set the beginning of the pair.
9262 Second = &LoadedSlices[CurrSlice];
9264 // If First is NULL, it means we start a new pair.
9265 // Get to the next slice.
9269 EVT LoadedType = First->getLoadedType();
9271 // If the types of the slices are different, we cannot pair them.
9272 if (LoadedType != Second->getLoadedType())
9275 // Check if the target supplies paired loads for this type.
9276 unsigned RequiredAlignment = 0;
9277 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9278 // move to the next pair, this type is hopeless.
9282 // Check if we meet the alignment requirement.
9283 if (RequiredAlignment > First->getAlignment())
9286 // Check that both loads are next to each other in memory.
9287 if (!areSlicesNextToEachOther(*First, *Second))
9290 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9291 --GlobalLSCost.Loads;
9292 // Move to the next pair.
9297 /// \brief Check the profitability of all involved LoadedSlice.
9298 /// Currently, it is considered profitable if there is exactly two
9299 /// involved slices (1) which are (2) next to each other in memory, and
9300 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9302 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9303 /// the elements themselves.
9305 /// FIXME: When the cost model will be mature enough, we can relax
9306 /// constraints (1) and (2).
9307 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9308 const APInt &UsedBits, bool ForCodeSize) {
9309 unsigned NumberOfSlices = LoadedSlices.size();
9310 if (StressLoadSlicing)
9311 return NumberOfSlices > 1;
9314 if (NumberOfSlices != 2)
9318 if (!areUsedBitsDense(UsedBits))
9322 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9323 // The original code has one big load.
9325 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9326 const LoadedSlice &LS = LoadedSlices[CurrSlice];
9327 // Accumulate the cost of all the slices.
9328 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9329 GlobalSlicingCost += SliceCost;
9331 // Account as cost in the original configuration the gain obtained
9332 // with the current slices.
9333 OrigCost.addSliceGain(LS);
9336 // If the target supports paired load, adjust the cost accordingly.
9337 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9338 return OrigCost > GlobalSlicingCost;
9341 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9342 /// operations, split it in the various pieces being extracted.
9344 /// This sort of thing is introduced by SROA.
9345 /// This slicing takes care not to insert overlapping loads.
9346 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9347 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9348 if (Level < AfterLegalizeDAG)
9351 LoadSDNode *LD = cast<LoadSDNode>(N);
9352 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9353 !LD->getValueType(0).isInteger())
9356 // Keep track of already used bits to detect overlapping values.
9357 // In that case, we will just abort the transformation.
9358 APInt UsedBits(LD->getValueSizeInBits(0), 0);
9360 SmallVector<LoadedSlice, 4> LoadedSlices;
9362 // Check if this load is used as several smaller chunks of bits.
9363 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9364 // of computation for each trunc.
9365 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9366 UI != UIEnd; ++UI) {
9367 // Skip the uses of the chain.
9368 if (UI.getUse().getResNo() != 0)
9374 // Check if this is a trunc(lshr).
9375 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9376 isa<ConstantSDNode>(User->getOperand(1))) {
9377 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9378 User = *User->use_begin();
9381 // At this point, User is a Truncate, iff we encountered, trunc or
9383 if (User->getOpcode() != ISD::TRUNCATE)
9386 // The width of the type must be a power of 2 and greater than 8-bits.
9387 // Otherwise the load cannot be represented in LLVM IR.
9388 // Moreover, if we shifted with a non-8-bits multiple, the slice
9389 // will be across several bytes. We do not support that.
9390 unsigned Width = User->getValueSizeInBits(0);
9391 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9394 // Build the slice for this chain of computations.
9395 LoadedSlice LS(User, LD, Shift, &DAG);
9396 APInt CurrentUsedBits = LS.getUsedBits();
9398 // Check if this slice overlaps with another.
9399 if ((CurrentUsedBits & UsedBits) != 0)
9401 // Update the bits used globally.
9402 UsedBits |= CurrentUsedBits;
9404 // Check if the new slice would be legal.
9408 // Record the slice.
9409 LoadedSlices.push_back(LS);
9412 // Abort slicing if it does not seem to be profitable.
9413 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9418 // Rewrite each chain to use an independent load.
9419 // By construction, each chain can be represented by a unique load.
9421 // Prepare the argument for the new token factor for all the slices.
9422 SmallVector<SDValue, 8> ArgChains;
9423 for (SmallVectorImpl<LoadedSlice>::const_iterator
9424 LSIt = LoadedSlices.begin(),
9425 LSItEnd = LoadedSlices.end();
9426 LSIt != LSItEnd; ++LSIt) {
9427 SDValue SliceInst = LSIt->loadSlice();
9428 CombineTo(LSIt->Inst, SliceInst, true);
9429 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9430 SliceInst = SliceInst.getOperand(0);
9431 assert(SliceInst->getOpcode() == ISD::LOAD &&
9432 "It takes more than a zext to get to the loaded slice!!");
9433 ArgChains.push_back(SliceInst.getValue(1));
9436 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9438 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9442 /// Check to see if V is (and load (ptr), imm), where the load is having
9443 /// specific bytes cleared out. If so, return the byte size being masked out
9444 /// and the shift amount.
9445 static std::pair<unsigned, unsigned>
9446 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9447 std::pair<unsigned, unsigned> Result(0, 0);
9449 // Check for the structure we're looking for.
9450 if (V->getOpcode() != ISD::AND ||
9451 !isa<ConstantSDNode>(V->getOperand(1)) ||
9452 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9455 // Check the chain and pointer.
9456 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9457 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
9459 // The store should be chained directly to the load or be an operand of a
9461 if (LD == Chain.getNode())
9463 else if (Chain->getOpcode() != ISD::TokenFactor)
9464 return Result; // Fail.
9467 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9468 if (Chain->getOperand(i).getNode() == LD) {
9472 if (!isOk) return Result;
9475 // This only handles simple types.
9476 if (V.getValueType() != MVT::i16 &&
9477 V.getValueType() != MVT::i32 &&
9478 V.getValueType() != MVT::i64)
9481 // Check the constant mask. Invert it so that the bits being masked out are
9482 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9483 // follow the sign bit for uniformity.
9484 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9485 unsigned NotMaskLZ = countLeadingZeros(NotMask);
9486 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
9487 unsigned NotMaskTZ = countTrailingZeros(NotMask);
9488 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9489 if (NotMaskLZ == 64) return Result; // All zero mask.
9491 // See if we have a continuous run of bits. If so, we have 0*1+0*
9492 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
9495 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9496 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9497 NotMaskLZ -= 64-V.getValueSizeInBits();
9499 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9500 switch (MaskedBytes) {
9504 default: return Result; // All one mask, or 5-byte mask.
9507 // Verify that the first bit starts at a multiple of mask so that the access
9508 // is aligned the same as the access width.
9509 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9511 Result.first = MaskedBytes;
9512 Result.second = NotMaskTZ/8;
9517 /// Check to see if IVal is something that provides a value as specified by
9518 /// MaskInfo. If so, replace the specified store with a narrower store of
9521 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9522 SDValue IVal, StoreSDNode *St,
9524 unsigned NumBytes = MaskInfo.first;
9525 unsigned ByteShift = MaskInfo.second;
9526 SelectionDAG &DAG = DC->getDAG();
9528 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9529 // that uses this. If not, this is not a replacement.
9530 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9531 ByteShift*8, (ByteShift+NumBytes)*8);
9532 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9534 // Check that it is legal on the target to do this. It is legal if the new
9535 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9537 MVT VT = MVT::getIntegerVT(NumBytes*8);
9538 if (!DC->isTypeLegal(VT))
9541 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9542 // shifted by ByteShift and truncated down to NumBytes.
9544 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9545 DAG.getConstant(ByteShift*8,
9546 DC->getShiftAmountTy(IVal.getValueType())));
9548 // Figure out the offset for the store and the alignment of the access.
9550 unsigned NewAlign = St->getAlignment();
9552 if (DAG.getTargetLoweringInfo().isLittleEndian())
9553 StOffset = ByteShift;
9555 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9557 SDValue Ptr = St->getBasePtr();
9559 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9560 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9561 NewAlign = MinAlign(NewAlign, StOffset);
9564 // Truncate down to the new size.
9565 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9568 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9569 St->getPointerInfo().getWithOffset(StOffset),
9570 false, false, NewAlign).getNode();
9574 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9575 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9576 /// narrowing the load and store if it would end up being a win for performance
9578 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9579 StoreSDNode *ST = cast<StoreSDNode>(N);
9580 if (ST->isVolatile())
9583 SDValue Chain = ST->getChain();
9584 SDValue Value = ST->getValue();
9585 SDValue Ptr = ST->getBasePtr();
9586 EVT VT = Value.getValueType();
9588 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9591 unsigned Opc = Value.getOpcode();
9593 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9594 // is a byte mask indicating a consecutive number of bytes, check to see if
9595 // Y is known to provide just those bytes. If so, we try to replace the
9596 // load + replace + store sequence with a single (narrower) store, which makes
9598 if (Opc == ISD::OR) {
9599 std::pair<unsigned, unsigned> MaskedLoad;
9600 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9601 if (MaskedLoad.first)
9602 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9603 Value.getOperand(1), ST,this))
9604 return SDValue(NewST, 0);
9606 // Or is commutative, so try swapping X and Y.
9607 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9608 if (MaskedLoad.first)
9609 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9610 Value.getOperand(0), ST,this))
9611 return SDValue(NewST, 0);
9614 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9615 Value.getOperand(1).getOpcode() != ISD::Constant)
9618 SDValue N0 = Value.getOperand(0);
9619 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9620 Chain == SDValue(N0.getNode(), 1)) {
9621 LoadSDNode *LD = cast<LoadSDNode>(N0);
9622 if (LD->getBasePtr() != Ptr ||
9623 LD->getPointerInfo().getAddrSpace() !=
9624 ST->getPointerInfo().getAddrSpace())
9627 // Find the type to narrow it the load / op / store to.
9628 SDValue N1 = Value.getOperand(1);
9629 unsigned BitWidth = N1.getValueSizeInBits();
9630 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9631 if (Opc == ISD::AND)
9632 Imm ^= APInt::getAllOnesValue(BitWidth);
9633 if (Imm == 0 || Imm.isAllOnesValue())
9635 unsigned ShAmt = Imm.countTrailingZeros();
9636 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9637 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9638 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9639 // The narrowing should be profitable, the load/store operation should be
9640 // legal (or custom) and the store size should be equal to the NewVT width.
9641 while (NewBW < BitWidth &&
9642 (NewVT.getStoreSizeInBits() != NewBW ||
9643 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
9644 !TLI.isNarrowingProfitable(VT, NewVT))) {
9645 NewBW = NextPowerOf2(NewBW);
9646 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9648 if (NewBW >= BitWidth)
9651 // If the lsb changed does not start at the type bitwidth boundary,
9652 // start at the previous one.
9654 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9655 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9656 std::min(BitWidth, ShAmt + NewBW));
9657 if ((Imm & Mask) == Imm) {
9658 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9659 if (Opc == ISD::AND)
9660 NewImm ^= APInt::getAllOnesValue(NewBW);
9661 uint64_t PtrOff = ShAmt / 8;
9662 // For big endian targets, we need to adjust the offset to the pointer to
9663 // load the correct bytes.
9664 if (TLI.isBigEndian())
9665 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9667 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9668 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9669 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9672 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9673 Ptr.getValueType(), Ptr,
9674 DAG.getConstant(PtrOff, Ptr.getValueType()));
9675 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9676 LD->getChain(), NewPtr,
9677 LD->getPointerInfo().getWithOffset(PtrOff),
9678 LD->isVolatile(), LD->isNonTemporal(),
9679 LD->isInvariant(), NewAlign,
9681 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9682 DAG.getConstant(NewImm, NewVT));
9683 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9685 ST->getPointerInfo().getWithOffset(PtrOff),
9686 false, false, NewAlign);
9688 AddToWorklist(NewPtr.getNode());
9689 AddToWorklist(NewLD.getNode());
9690 AddToWorklist(NewVal.getNode());
9691 WorklistRemover DeadNodes(*this);
9692 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9701 /// For a given floating point load / store pair, if the load value isn't used
9702 /// by any other operations, then consider transforming the pair to integer
9703 /// load / store operations if the target deems the transformation profitable.
9704 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9705 StoreSDNode *ST = cast<StoreSDNode>(N);
9706 SDValue Chain = ST->getChain();
9707 SDValue Value = ST->getValue();
9708 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9709 Value.hasOneUse() &&
9710 Chain == SDValue(Value.getNode(), 1)) {
9711 LoadSDNode *LD = cast<LoadSDNode>(Value);
9712 EVT VT = LD->getMemoryVT();
9713 if (!VT.isFloatingPoint() ||
9714 VT != ST->getMemoryVT() ||
9715 LD->isNonTemporal() ||
9716 ST->isNonTemporal() ||
9717 LD->getPointerInfo().getAddrSpace() != 0 ||
9718 ST->getPointerInfo().getAddrSpace() != 0)
9721 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9722 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9723 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9724 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9725 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9728 unsigned LDAlign = LD->getAlignment();
9729 unsigned STAlign = ST->getAlignment();
9730 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9731 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9732 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9735 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9736 LD->getChain(), LD->getBasePtr(),
9737 LD->getPointerInfo(),
9738 false, false, false, LDAlign);
9740 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9741 NewLD, ST->getBasePtr(),
9742 ST->getPointerInfo(),
9743 false, false, STAlign);
9745 AddToWorklist(NewLD.getNode());
9746 AddToWorklist(NewST.getNode());
9747 WorklistRemover DeadNodes(*this);
9748 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9756 /// Helper struct to parse and store a memory address as base + index + offset.
9757 /// We ignore sign extensions when it is safe to do so.
9758 /// The following two expressions are not equivalent. To differentiate we need
9759 /// to store whether there was a sign extension involved in the index
9761 /// (load (i64 add (i64 copyfromreg %c)
9762 /// (i64 signextend (add (i8 load %index)
9766 /// (load (i64 add (i64 copyfromreg %c)
9767 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9769 struct BaseIndexOffset {
9773 bool IsIndexSignExt;
9775 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9777 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9778 bool IsIndexSignExt) :
9779 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9781 bool equalBaseIndex(const BaseIndexOffset &Other) {
9782 return Other.Base == Base && Other.Index == Index &&
9783 Other.IsIndexSignExt == IsIndexSignExt;
9786 /// Parses tree in Ptr for base, index, offset addresses.
9787 static BaseIndexOffset match(SDValue Ptr) {
9788 bool IsIndexSignExt = false;
9790 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9791 // instruction, then it could be just the BASE or everything else we don't
9792 // know how to handle. Just use Ptr as BASE and give up.
9793 if (Ptr->getOpcode() != ISD::ADD)
9794 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9796 // We know that we have at least an ADD instruction. Try to pattern match
9797 // the simple case of BASE + OFFSET.
9798 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9799 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9800 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9804 // Inside a loop the current BASE pointer is calculated using an ADD and a
9805 // MUL instruction. In this case Ptr is the actual BASE pointer.
9806 // (i64 add (i64 %array_ptr)
9807 // (i64 mul (i64 %induction_var)
9808 // (i64 %element_size)))
9809 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9810 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9812 // Look at Base + Index + Offset cases.
9813 SDValue Base = Ptr->getOperand(0);
9814 SDValue IndexOffset = Ptr->getOperand(1);
9816 // Skip signextends.
9817 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9818 IndexOffset = IndexOffset->getOperand(0);
9819 IsIndexSignExt = true;
9822 // Either the case of Base + Index (no offset) or something else.
9823 if (IndexOffset->getOpcode() != ISD::ADD)
9824 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9826 // Now we have the case of Base + Index + offset.
9827 SDValue Index = IndexOffset->getOperand(0);
9828 SDValue Offset = IndexOffset->getOperand(1);
9830 if (!isa<ConstantSDNode>(Offset))
9831 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9833 // Ignore signextends.
9834 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9835 Index = Index->getOperand(0);
9836 IsIndexSignExt = true;
9837 } else IsIndexSignExt = false;
9839 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9840 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9844 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
9845 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
9846 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
9847 // Make sure we have something to merge.
9851 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
9852 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9853 unsigned EarliestNodeUsed = 0;
9855 for (unsigned i=0; i < NumElem; ++i) {
9856 // Find a chain for the new wide-store operand. Notice that some
9857 // of the store nodes that we found may not be selected for inclusion
9858 // in the wide store. The chain we use needs to be the chain of the
9859 // earliest store node which is *used* and replaced by the wide store.
9860 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9861 EarliestNodeUsed = i;
9864 // The earliest Node in the DAG.
9865 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9866 SDLoc DL(StoreNodes[0].MemNode);
9870 // Find a legal type for the vector store.
9871 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9872 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9873 if (IsConstantSrc) {
9874 // A vector store with a constant source implies that the constant is
9875 // zero; we only handle merging stores of constant zeros because the zero
9876 // can be materialized without a load.
9877 // It may be beneficial to loosen this restriction to allow non-zero
9879 StoredVal = DAG.getConstant(0, Ty);
9881 SmallVector<SDValue, 8> Ops;
9882 for (unsigned i = 0; i < NumElem ; ++i) {
9883 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9884 SDValue Val = St->getValue();
9885 // All of the operands of a BUILD_VECTOR must have the same type.
9886 if (Val.getValueType() != MemVT)
9891 // Build the extracted vector elements back into a vector.
9892 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
9895 // We should always use a vector store when merging extracted vector
9896 // elements, so this path implies a store of constants.
9897 assert(IsConstantSrc && "Merged vector elements should use vector store");
9899 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9900 APInt StoreInt(StoreBW, 0);
9902 // Construct a single integer constant which is made of the smaller
9904 bool IsLE = TLI.isLittleEndian();
9905 for (unsigned i = 0; i < NumElem ; ++i) {
9906 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
9907 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9908 SDValue Val = St->getValue();
9909 StoreInt <<= ElementSizeBytes*8;
9910 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9911 StoreInt |= C->getAPIntValue().zext(StoreBW);
9912 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9913 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9915 llvm_unreachable("Invalid constant element type");
9919 // Create the new Load and Store operations.
9920 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9921 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9924 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9925 FirstInChain->getBasePtr(),
9926 FirstInChain->getPointerInfo(),
9928 FirstInChain->getAlignment());
9930 // Replace the first store with the new store
9931 CombineTo(EarliestOp, NewStore);
9932 // Erase all other stores.
9933 for (unsigned i = 0; i < NumElem ; ++i) {
9934 if (StoreNodes[i].MemNode == EarliestOp)
9936 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9937 // ReplaceAllUsesWith will replace all uses that existed when it was
9938 // called, but graph optimizations may cause new ones to appear. For
9939 // example, the case in pr14333 looks like
9941 // St's chain -> St -> another store -> X
9943 // And the only difference from St to the other store is the chain.
9944 // When we change it's chain to be St's chain they become identical,
9945 // get CSEed and the net result is that X is now a use of St.
9946 // Since we know that St is redundant, just iterate.
9947 while (!St->use_empty())
9948 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9949 deleteAndRecombine(St);
9955 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9956 EVT MemVT = St->getMemoryVT();
9957 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9958 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9959 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9961 // Don't merge vectors into wider inputs.
9962 if (MemVT.isVector() || !MemVT.isSimple())
9965 // Perform an early exit check. Do not bother looking at stored values that
9966 // are not constants, loads, or extracted vector elements.
9967 SDValue StoredVal = St->getValue();
9968 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9969 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
9970 isa<ConstantFPSDNode>(StoredVal);
9971 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
9973 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
9976 // Only look at ends of store sequences.
9977 SDValue Chain = SDValue(St, 0);
9978 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9981 // This holds the base pointer, index, and the offset in bytes from the base
9983 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9985 // We must have a base and an offset.
9986 if (!BasePtr.Base.getNode())
9989 // Do not handle stores to undef base pointers.
9990 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9993 // Save the LoadSDNodes that we find in the chain.
9994 // We need to make sure that these nodes do not interfere with
9995 // any of the store nodes.
9996 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9998 // Save the StoreSDNodes that we find in the chain.
9999 SmallVector<MemOpLink, 8> StoreNodes;
10001 // Walk up the chain and look for nodes with offsets from the same
10002 // base pointer. Stop when reaching an instruction with a different kind
10003 // or instruction which has a different base pointer.
10005 StoreSDNode *Index = St;
10007 // If the chain has more than one use, then we can't reorder the mem ops.
10008 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10011 // Find the base pointer and offset for this memory node.
10012 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10014 // Check that the base pointer is the same as the original one.
10015 if (!Ptr.equalBaseIndex(BasePtr))
10018 // Check that the alignment is the same.
10019 if (Index->getAlignment() != St->getAlignment())
10022 // The memory operands must not be volatile.
10023 if (Index->isVolatile() || Index->isIndexed())
10027 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10028 if (St->isTruncatingStore())
10031 // The stored memory type must be the same.
10032 if (Index->getMemoryVT() != MemVT)
10035 // We do not allow unaligned stores because we want to prevent overriding
10037 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10040 // We found a potential memory operand to merge.
10041 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10043 // Find the next memory operand in the chain. If the next operand in the
10044 // chain is a store then move up and continue the scan with the next
10045 // memory operand. If the next operand is a load save it and use alias
10046 // information to check if it interferes with anything.
10047 SDNode *NextInChain = Index->getChain().getNode();
10049 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10050 // We found a store node. Use it for the next iteration.
10053 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10054 if (Ldn->isVolatile()) {
10059 // Save the load node for later. Continue the scan.
10060 AliasLoadNodes.push_back(Ldn);
10061 NextInChain = Ldn->getChain().getNode();
10070 // Check if there is anything to merge.
10071 if (StoreNodes.size() < 2)
10074 // Sort the memory operands according to their distance from the base pointer.
10075 std::sort(StoreNodes.begin(), StoreNodes.end(),
10076 [](MemOpLink LHS, MemOpLink RHS) {
10077 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10078 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10079 LHS.SequenceNum > RHS.SequenceNum);
10082 // Scan the memory operations on the chain and find the first non-consecutive
10083 // store memory address.
10084 unsigned LastConsecutiveStore = 0;
10085 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10086 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10088 // Check that the addresses are consecutive starting from the second
10089 // element in the list of stores.
10091 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10092 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10096 bool Alias = false;
10097 // Check if this store interferes with any of the loads that we found.
10098 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10099 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10103 // We found a load that alias with this store. Stop the sequence.
10107 // Mark this node as useful.
10108 LastConsecutiveStore = i;
10111 // The node with the lowest store address.
10112 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10114 // Store the constants into memory as one consecutive store.
10115 if (IsConstantSrc) {
10116 unsigned LastLegalType = 0;
10117 unsigned LastLegalVectorType = 0;
10118 bool NonZero = false;
10119 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10120 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10121 SDValue StoredVal = St->getValue();
10123 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10124 NonZero |= !C->isNullValue();
10125 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10126 NonZero |= !C->getConstantFPValue()->isNullValue();
10132 // Find a legal type for the constant store.
10133 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10134 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10135 if (TLI.isTypeLegal(StoreTy))
10136 LastLegalType = i+1;
10137 // Or check whether a truncstore is legal.
10138 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10139 TargetLowering::TypePromoteInteger) {
10140 EVT LegalizedStoredValueTy =
10141 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10142 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10143 LastLegalType = i+1;
10146 // Find a legal type for the vector store.
10147 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10148 if (TLI.isTypeLegal(Ty))
10149 LastLegalVectorType = i + 1;
10152 // We only use vectors if the constant is known to be zero and the
10153 // function is not marked with the noimplicitfloat attribute.
10154 if (NonZero || NoVectors)
10155 LastLegalVectorType = 0;
10157 // Check if we found a legal integer type to store.
10158 if (LastLegalType == 0 && LastLegalVectorType == 0)
10161 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10162 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10164 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10168 // When extracting multiple vector elements, try to store them
10169 // in one vector store rather than a sequence of scalar stores.
10170 if (IsExtractVecEltSrc) {
10171 unsigned NumElem = 0;
10172 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10173 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10174 SDValue StoredVal = St->getValue();
10175 // This restriction could be loosened.
10176 // Bail out if any stored values are not elements extracted from a vector.
10177 // It should be possible to handle mixed sources, but load sources need
10178 // more careful handling (see the block of code below that handles
10179 // consecutive loads).
10180 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10183 // Find a legal type for the vector store.
10184 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10185 if (TLI.isTypeLegal(Ty))
10189 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10193 // Below we handle the case of multiple consecutive stores that
10194 // come from multiple consecutive loads. We merge them into a single
10195 // wide load and a single wide store.
10197 // Look for load nodes which are used by the stored values.
10198 SmallVector<MemOpLink, 8> LoadNodes;
10200 // Find acceptable loads. Loads need to have the same chain (token factor),
10201 // must not be zext, volatile, indexed, and they must be consecutive.
10202 BaseIndexOffset LdBasePtr;
10203 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10204 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10205 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10208 // Loads must only have one use.
10209 if (!Ld->hasNUsesOfValue(1, 0))
10212 // Check that the alignment is the same as the stores.
10213 if (Ld->getAlignment() != St->getAlignment())
10216 // The memory operands must not be volatile.
10217 if (Ld->isVolatile() || Ld->isIndexed())
10220 // We do not accept ext loads.
10221 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10224 // The stored memory type must be the same.
10225 if (Ld->getMemoryVT() != MemVT)
10228 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10229 // If this is not the first ptr that we check.
10230 if (LdBasePtr.Base.getNode()) {
10231 // The base ptr must be the same.
10232 if (!LdPtr.equalBaseIndex(LdBasePtr))
10235 // Check that all other base pointers are the same as this one.
10239 // We found a potential memory operand to merge.
10240 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10243 if (LoadNodes.size() < 2)
10246 // If we have load/store pair instructions and we only have two values,
10248 unsigned RequiredAlignment;
10249 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10250 St->getAlignment() >= RequiredAlignment)
10253 // Scan the memory operations on the chain and find the first non-consecutive
10254 // load memory address. These variables hold the index in the store node
10256 unsigned LastConsecutiveLoad = 0;
10257 // This variable refers to the size and not index in the array.
10258 unsigned LastLegalVectorType = 0;
10259 unsigned LastLegalIntegerType = 0;
10260 StartAddress = LoadNodes[0].OffsetFromBase;
10261 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10262 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10263 // All loads much share the same chain.
10264 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10267 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10268 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10270 LastConsecutiveLoad = i;
10272 // Find a legal type for the vector store.
10273 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10274 if (TLI.isTypeLegal(StoreTy))
10275 LastLegalVectorType = i + 1;
10277 // Find a legal type for the integer store.
10278 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10279 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10280 if (TLI.isTypeLegal(StoreTy))
10281 LastLegalIntegerType = i + 1;
10282 // Or check whether a truncstore and extload is legal.
10283 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10284 TargetLowering::TypePromoteInteger) {
10285 EVT LegalizedStoredValueTy =
10286 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10287 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10288 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10289 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10290 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10291 LastLegalIntegerType = i+1;
10295 // Only use vector types if the vector type is larger than the integer type.
10296 // If they are the same, use integers.
10297 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10298 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10300 // We add +1 here because the LastXXX variables refer to location while
10301 // the NumElem refers to array/index size.
10302 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10303 NumElem = std::min(LastLegalType, NumElem);
10308 // The earliest Node in the DAG.
10309 unsigned EarliestNodeUsed = 0;
10310 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10311 for (unsigned i=1; i<NumElem; ++i) {
10312 // Find a chain for the new wide-store operand. Notice that some
10313 // of the store nodes that we found may not be selected for inclusion
10314 // in the wide store. The chain we use needs to be the chain of the
10315 // earliest store node which is *used* and replaced by the wide store.
10316 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10317 EarliestNodeUsed = i;
10320 // Find if it is better to use vectors or integers to load and store
10324 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10326 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10327 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10330 SDLoc LoadDL(LoadNodes[0].MemNode);
10331 SDLoc StoreDL(StoreNodes[0].MemNode);
10333 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10334 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10335 FirstLoad->getChain(),
10336 FirstLoad->getBasePtr(),
10337 FirstLoad->getPointerInfo(),
10338 false, false, false,
10339 FirstLoad->getAlignment());
10341 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10342 FirstInChain->getBasePtr(),
10343 FirstInChain->getPointerInfo(), false, false,
10344 FirstInChain->getAlignment());
10346 // Replace one of the loads with the new load.
10347 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10348 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10349 SDValue(NewLoad.getNode(), 1));
10351 // Remove the rest of the load chains.
10352 for (unsigned i = 1; i < NumElem ; ++i) {
10353 // Replace all chain users of the old load nodes with the chain of the new
10355 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10356 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10359 // Replace the first store with the new store.
10360 CombineTo(EarliestOp, NewStore);
10361 // Erase all other stores.
10362 for (unsigned i = 0; i < NumElem ; ++i) {
10363 // Remove all Store nodes.
10364 if (StoreNodes[i].MemNode == EarliestOp)
10366 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10367 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10368 deleteAndRecombine(St);
10374 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10375 StoreSDNode *ST = cast<StoreSDNode>(N);
10376 SDValue Chain = ST->getChain();
10377 SDValue Value = ST->getValue();
10378 SDValue Ptr = ST->getBasePtr();
10380 // If this is a store of a bit convert, store the input value if the
10381 // resultant store does not need a higher alignment than the original.
10382 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10383 ST->isUnindexed()) {
10384 unsigned OrigAlign = ST->getAlignment();
10385 EVT SVT = Value.getOperand(0).getValueType();
10386 unsigned Align = TLI.getDataLayout()->
10387 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10388 if (Align <= OrigAlign &&
10389 ((!LegalOperations && !ST->isVolatile()) ||
10390 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10391 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10392 Ptr, ST->getPointerInfo(), ST->isVolatile(),
10393 ST->isNonTemporal(), OrigAlign,
10397 // Turn 'store undef, Ptr' -> nothing.
10398 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10401 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10402 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10403 // NOTE: If the original store is volatile, this transform must not increase
10404 // the number of stores. For example, on x86-32 an f64 can be stored in one
10405 // processor operation but an i64 (which is not legal) requires two. So the
10406 // transform should not be done in this case.
10407 if (Value.getOpcode() != ISD::TargetConstantFP) {
10409 switch (CFP->getSimpleValueType(0).SimpleTy) {
10410 default: llvm_unreachable("Unknown FP type");
10411 case MVT::f16: // We don't do this for these yet.
10417 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10418 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10419 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10420 bitcastToAPInt().getZExtValue(), MVT::i32);
10421 return DAG.getStore(Chain, SDLoc(N), Tmp,
10422 Ptr, ST->getMemOperand());
10426 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10427 !ST->isVolatile()) ||
10428 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10429 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10430 getZExtValue(), MVT::i64);
10431 return DAG.getStore(Chain, SDLoc(N), Tmp,
10432 Ptr, ST->getMemOperand());
10435 if (!ST->isVolatile() &&
10436 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10437 // Many FP stores are not made apparent until after legalize, e.g. for
10438 // argument passing. Since this is so common, custom legalize the
10439 // 64-bit integer store into two 32-bit stores.
10440 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10441 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10442 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10443 if (TLI.isBigEndian()) std::swap(Lo, Hi);
10445 unsigned Alignment = ST->getAlignment();
10446 bool isVolatile = ST->isVolatile();
10447 bool isNonTemporal = ST->isNonTemporal();
10448 AAMDNodes AAInfo = ST->getAAInfo();
10450 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10451 Ptr, ST->getPointerInfo(),
10452 isVolatile, isNonTemporal,
10453 ST->getAlignment(), AAInfo);
10454 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10455 DAG.getConstant(4, Ptr.getValueType()));
10456 Alignment = MinAlign(Alignment, 4U);
10457 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10458 Ptr, ST->getPointerInfo().getWithOffset(4),
10459 isVolatile, isNonTemporal,
10460 Alignment, AAInfo);
10461 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10470 // Try to infer better alignment information than the store already has.
10471 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10472 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10473 if (Align > ST->getAlignment())
10474 return DAG.getTruncStore(Chain, SDLoc(N), Value,
10475 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10476 ST->isVolatile(), ST->isNonTemporal(), Align,
10481 // Try transforming a pair floating point load / store ops to integer
10482 // load / store ops.
10483 SDValue NewST = TransformFPLoadStorePair(N);
10484 if (NewST.getNode())
10487 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10488 : DAG.getSubtarget().useAA();
10490 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10491 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10494 if (UseAA && ST->isUnindexed()) {
10495 // Walk up chain skipping non-aliasing memory nodes.
10496 SDValue BetterChain = FindBetterChain(N, Chain);
10498 // If there is a better chain.
10499 if (Chain != BetterChain) {
10502 // Replace the chain to avoid dependency.
10503 if (ST->isTruncatingStore()) {
10504 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10505 ST->getMemoryVT(), ST->getMemOperand());
10507 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10508 ST->getMemOperand());
10511 // Create token to keep both nodes around.
10512 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10513 MVT::Other, Chain, ReplStore);
10515 // Make sure the new and old chains are cleaned up.
10516 AddToWorklist(Token.getNode());
10518 // Don't add users to work list.
10519 return CombineTo(N, Token, false);
10523 // Try transforming N to an indexed store.
10524 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10525 return SDValue(N, 0);
10527 // FIXME: is there such a thing as a truncating indexed store?
10528 if (ST->isTruncatingStore() && ST->isUnindexed() &&
10529 Value.getValueType().isInteger()) {
10530 // See if we can simplify the input to this truncstore with knowledge that
10531 // only the low bits are being used. For example:
10532 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
10534 GetDemandedBits(Value,
10535 APInt::getLowBitsSet(
10536 Value.getValueType().getScalarType().getSizeInBits(),
10537 ST->getMemoryVT().getScalarType().getSizeInBits()));
10538 AddToWorklist(Value.getNode());
10539 if (Shorter.getNode())
10540 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10541 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10543 // Otherwise, see if we can simplify the operation with
10544 // SimplifyDemandedBits, which only works if the value has a single use.
10545 if (SimplifyDemandedBits(Value,
10546 APInt::getLowBitsSet(
10547 Value.getValueType().getScalarType().getSizeInBits(),
10548 ST->getMemoryVT().getScalarType().getSizeInBits())))
10549 return SDValue(N, 0);
10552 // If this is a load followed by a store to the same location, then the store
10554 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10555 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10556 ST->isUnindexed() && !ST->isVolatile() &&
10557 // There can't be any side effects between the load and store, such as
10558 // a call or store.
10559 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10560 // The store is dead, remove it.
10565 // If this is a store followed by a store with the same value to the same
10566 // location, then the store is dead/noop.
10567 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10568 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10569 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10570 ST1->isUnindexed() && !ST1->isVolatile()) {
10571 // The store is dead, remove it.
10576 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10577 // truncating store. We can do this even if this is already a truncstore.
10578 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10579 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10580 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10581 ST->getMemoryVT())) {
10582 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10583 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10586 // Only perform this optimization before the types are legal, because we
10587 // don't want to perform this optimization on every DAGCombine invocation.
10589 bool EverChanged = false;
10592 // There can be multiple store sequences on the same chain.
10593 // Keep trying to merge store sequences until we are unable to do so
10594 // or until we merge the last store on the chain.
10595 bool Changed = MergeConsecutiveStores(ST);
10596 EverChanged |= Changed;
10597 if (!Changed) break;
10598 } while (ST->getOpcode() != ISD::DELETED_NODE);
10601 return SDValue(N, 0);
10604 return ReduceLoadOpStoreWidth(N);
10607 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10608 SDValue InVec = N->getOperand(0);
10609 SDValue InVal = N->getOperand(1);
10610 SDValue EltNo = N->getOperand(2);
10613 // If the inserted element is an UNDEF, just use the input vector.
10614 if (InVal.getOpcode() == ISD::UNDEF)
10617 EVT VT = InVec.getValueType();
10619 // If we can't generate a legal BUILD_VECTOR, exit
10620 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10623 // Check that we know which element is being inserted
10624 if (!isa<ConstantSDNode>(EltNo))
10626 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10628 // Canonicalize insert_vector_elt dag nodes.
10630 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10631 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10633 // Do this only if the child insert_vector node has one use; also
10634 // do this only if indices are both constants and Idx1 < Idx0.
10635 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10636 && isa<ConstantSDNode>(InVec.getOperand(2))) {
10637 unsigned OtherElt =
10638 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10639 if (Elt < OtherElt) {
10641 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10642 InVec.getOperand(0), InVal, EltNo);
10643 AddToWorklist(NewOp.getNode());
10644 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10645 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10649 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10650 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
10651 // vector elements.
10652 SmallVector<SDValue, 8> Ops;
10653 // Do not combine these two vectors if the output vector will not replace
10654 // the input vector.
10655 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10656 Ops.append(InVec.getNode()->op_begin(),
10657 InVec.getNode()->op_end());
10658 } else if (InVec.getOpcode() == ISD::UNDEF) {
10659 unsigned NElts = VT.getVectorNumElements();
10660 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10665 // Insert the element
10666 if (Elt < Ops.size()) {
10667 // All the operands of BUILD_VECTOR must have the same type;
10668 // we enforce that here.
10669 EVT OpVT = Ops[0].getValueType();
10670 if (InVal.getValueType() != OpVT)
10671 InVal = OpVT.bitsGT(InVal.getValueType()) ?
10672 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10673 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10677 // Return the new vector
10678 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10681 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10682 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10683 EVT ResultVT = EVE->getValueType(0);
10684 EVT VecEltVT = InVecVT.getVectorElementType();
10685 unsigned Align = OriginalLoad->getAlignment();
10686 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10687 VecEltVT.getTypeForEVT(*DAG.getContext()));
10689 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10694 SDValue NewPtr = OriginalLoad->getBasePtr();
10696 EVT PtrType = NewPtr.getValueType();
10697 MachinePointerInfo MPI;
10698 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10699 int Elt = ConstEltNo->getZExtValue();
10700 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10701 if (TLI.isBigEndian())
10702 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10703 Offset = DAG.getConstant(PtrOff, PtrType);
10704 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10706 Offset = DAG.getNode(
10707 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10708 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10709 if (TLI.isBigEndian())
10710 Offset = DAG.getNode(
10711 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10712 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10713 MPI = OriginalLoad->getPointerInfo();
10715 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10717 // The replacement we need to do here is a little tricky: we need to
10718 // replace an extractelement of a load with a load.
10719 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10720 // Note that this replacement assumes that the extractvalue is the only
10721 // use of the load; that's okay because we don't want to perform this
10722 // transformation in other cases anyway.
10725 if (ResultVT.bitsGT(VecEltVT)) {
10726 // If the result type of vextract is wider than the load, then issue an
10727 // extending load instead.
10728 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10732 Load = DAG.getExtLoad(
10733 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10734 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10735 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10736 Chain = Load.getValue(1);
10738 Load = DAG.getLoad(
10739 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10740 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10741 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10742 Chain = Load.getValue(1);
10743 if (ResultVT.bitsLT(VecEltVT))
10744 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10746 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10748 WorklistRemover DeadNodes(*this);
10749 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10750 SDValue To[] = { Load, Chain };
10751 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10752 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10753 // worklist explicitly as well.
10754 AddToWorklist(Load.getNode());
10755 AddUsersToWorklist(Load.getNode()); // Add users too
10756 // Make sure to revisit this node to clean it up; it will usually be dead.
10757 AddToWorklist(EVE);
10759 return SDValue(EVE, 0);
10762 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10763 // (vextract (scalar_to_vector val, 0) -> val
10764 SDValue InVec = N->getOperand(0);
10765 EVT VT = InVec.getValueType();
10766 EVT NVT = N->getValueType(0);
10768 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10769 // Check if the result type doesn't match the inserted element type. A
10770 // SCALAR_TO_VECTOR may truncate the inserted element and the
10771 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10772 SDValue InOp = InVec.getOperand(0);
10773 if (InOp.getValueType() != NVT) {
10774 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10775 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10780 SDValue EltNo = N->getOperand(1);
10781 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10783 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10784 // We only perform this optimization before the op legalization phase because
10785 // we may introduce new vector instructions which are not backed by TD
10786 // patterns. For example on AVX, extracting elements from a wide vector
10787 // without using extract_subvector. However, if we can find an underlying
10788 // scalar value, then we can always use that.
10789 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10791 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10792 int NumElem = VT.getVectorNumElements();
10793 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10794 // Find the new index to extract from.
10795 int OrigElt = SVOp->getMaskElt(Elt);
10797 // Extracting an undef index is undef.
10799 return DAG.getUNDEF(NVT);
10801 // Select the right vector half to extract from.
10803 if (OrigElt < NumElem) {
10804 SVInVec = InVec->getOperand(0);
10806 SVInVec = InVec->getOperand(1);
10807 OrigElt -= NumElem;
10810 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10811 SDValue InOp = SVInVec.getOperand(OrigElt);
10812 if (InOp.getValueType() != NVT) {
10813 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10814 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10820 // FIXME: We should handle recursing on other vector shuffles and
10821 // scalar_to_vector here as well.
10823 if (!LegalOperations) {
10824 EVT IndexTy = TLI.getVectorIdxTy();
10825 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10826 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10830 bool BCNumEltsChanged = false;
10831 EVT ExtVT = VT.getVectorElementType();
10834 // If the result of load has to be truncated, then it's not necessarily
10836 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10839 if (InVec.getOpcode() == ISD::BITCAST) {
10840 // Don't duplicate a load with other uses.
10841 if (!InVec.hasOneUse())
10844 EVT BCVT = InVec.getOperand(0).getValueType();
10845 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10847 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10848 BCNumEltsChanged = true;
10849 InVec = InVec.getOperand(0);
10850 ExtVT = BCVT.getVectorElementType();
10853 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10854 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10855 ISD::isNormalLoad(InVec.getNode()) &&
10856 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10857 SDValue Index = N->getOperand(1);
10858 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10859 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10863 // Perform only after legalization to ensure build_vector / vector_shuffle
10864 // optimizations have already been done.
10865 if (!LegalOperations) return SDValue();
10867 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10868 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10869 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10872 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10874 LoadSDNode *LN0 = nullptr;
10875 const ShuffleVectorSDNode *SVN = nullptr;
10876 if (ISD::isNormalLoad(InVec.getNode())) {
10877 LN0 = cast<LoadSDNode>(InVec);
10878 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10879 InVec.getOperand(0).getValueType() == ExtVT &&
10880 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10881 // Don't duplicate a load with other uses.
10882 if (!InVec.hasOneUse())
10885 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10886 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10887 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10889 // (load $addr+1*size)
10891 // Don't duplicate a load with other uses.
10892 if (!InVec.hasOneUse())
10895 // If the bit convert changed the number of elements, it is unsafe
10896 // to examine the mask.
10897 if (BCNumEltsChanged)
10900 // Select the input vector, guarding against out of range extract vector.
10901 unsigned NumElems = VT.getVectorNumElements();
10902 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10903 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10905 if (InVec.getOpcode() == ISD::BITCAST) {
10906 // Don't duplicate a load with other uses.
10907 if (!InVec.hasOneUse())
10910 InVec = InVec.getOperand(0);
10912 if (ISD::isNormalLoad(InVec.getNode())) {
10913 LN0 = cast<LoadSDNode>(InVec);
10914 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10915 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10919 // Make sure we found a non-volatile load and the extractelement is
10921 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10924 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10926 return DAG.getUNDEF(LVT);
10928 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10934 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10935 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10936 // We perform this optimization post type-legalization because
10937 // the type-legalizer often scalarizes integer-promoted vectors.
10938 // Performing this optimization before may create bit-casts which
10939 // will be type-legalized to complex code sequences.
10940 // We perform this optimization only before the operation legalizer because we
10941 // may introduce illegal operations.
10942 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10945 unsigned NumInScalars = N->getNumOperands();
10947 EVT VT = N->getValueType(0);
10949 // Check to see if this is a BUILD_VECTOR of a bunch of values
10950 // which come from any_extend or zero_extend nodes. If so, we can create
10951 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10952 // optimizations. We do not handle sign-extend because we can't fill the sign
10954 EVT SourceType = MVT::Other;
10955 bool AllAnyExt = true;
10957 for (unsigned i = 0; i != NumInScalars; ++i) {
10958 SDValue In = N->getOperand(i);
10959 // Ignore undef inputs.
10960 if (In.getOpcode() == ISD::UNDEF) continue;
10962 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10963 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10965 // Abort if the element is not an extension.
10966 if (!ZeroExt && !AnyExt) {
10967 SourceType = MVT::Other;
10971 // The input is a ZeroExt or AnyExt. Check the original type.
10972 EVT InTy = In.getOperand(0).getValueType();
10974 // Check that all of the widened source types are the same.
10975 if (SourceType == MVT::Other)
10978 else if (InTy != SourceType) {
10979 // Multiple income types. Abort.
10980 SourceType = MVT::Other;
10984 // Check if all of the extends are ANY_EXTENDs.
10985 AllAnyExt &= AnyExt;
10988 // In order to have valid types, all of the inputs must be extended from the
10989 // same source type and all of the inputs must be any or zero extend.
10990 // Scalar sizes must be a power of two.
10991 EVT OutScalarTy = VT.getScalarType();
10992 bool ValidTypes = SourceType != MVT::Other &&
10993 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10994 isPowerOf2_32(SourceType.getSizeInBits());
10996 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10997 // turn into a single shuffle instruction.
11001 bool isLE = TLI.isLittleEndian();
11002 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11003 assert(ElemRatio > 1 && "Invalid element size ratio");
11004 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11005 DAG.getConstant(0, SourceType);
11007 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11008 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11010 // Populate the new build_vector
11011 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11012 SDValue Cast = N->getOperand(i);
11013 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11014 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11015 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11017 if (Cast.getOpcode() == ISD::UNDEF)
11018 In = DAG.getUNDEF(SourceType);
11020 In = Cast->getOperand(0);
11021 unsigned Index = isLE ? (i * ElemRatio) :
11022 (i * ElemRatio + (ElemRatio - 1));
11024 assert(Index < Ops.size() && "Invalid index");
11028 // The type of the new BUILD_VECTOR node.
11029 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11030 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11031 "Invalid vector size");
11032 // Check if the new vector type is legal.
11033 if (!isTypeLegal(VecVT)) return SDValue();
11035 // Make the new BUILD_VECTOR.
11036 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11038 // The new BUILD_VECTOR node has the potential to be further optimized.
11039 AddToWorklist(BV.getNode());
11040 // Bitcast to the desired type.
11041 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11044 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11045 EVT VT = N->getValueType(0);
11047 unsigned NumInScalars = N->getNumOperands();
11050 EVT SrcVT = MVT::Other;
11051 unsigned Opcode = ISD::DELETED_NODE;
11052 unsigned NumDefs = 0;
11054 for (unsigned i = 0; i != NumInScalars; ++i) {
11055 SDValue In = N->getOperand(i);
11056 unsigned Opc = In.getOpcode();
11058 if (Opc == ISD::UNDEF)
11061 // If all scalar values are floats and converted from integers.
11062 if (Opcode == ISD::DELETED_NODE &&
11063 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11070 EVT InVT = In.getOperand(0).getValueType();
11072 // If all scalar values are typed differently, bail out. It's chosen to
11073 // simplify BUILD_VECTOR of integer types.
11074 if (SrcVT == MVT::Other)
11081 // If the vector has just one element defined, it's not worth to fold it into
11082 // a vectorized one.
11086 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11087 && "Should only handle conversion from integer to float.");
11088 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11090 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11092 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11095 SmallVector<SDValue, 8> Opnds;
11096 for (unsigned i = 0; i != NumInScalars; ++i) {
11097 SDValue In = N->getOperand(i);
11099 if (In.getOpcode() == ISD::UNDEF)
11100 Opnds.push_back(DAG.getUNDEF(SrcVT));
11102 Opnds.push_back(In.getOperand(0));
11104 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11105 AddToWorklist(BV.getNode());
11107 return DAG.getNode(Opcode, dl, VT, BV);
11110 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11111 unsigned NumInScalars = N->getNumOperands();
11113 EVT VT = N->getValueType(0);
11115 // A vector built entirely of undefs is undef.
11116 if (ISD::allOperandsUndef(N))
11117 return DAG.getUNDEF(VT);
11119 SDValue V = reduceBuildVecExtToExtBuildVec(N);
11123 V = reduceBuildVecConvertToConvertBuildVec(N);
11127 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11128 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11129 // at most two distinct vectors, turn this into a shuffle node.
11131 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11132 if (!isTypeLegal(VT))
11135 // May only combine to shuffle after legalize if shuffle is legal.
11136 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11139 SDValue VecIn1, VecIn2;
11140 bool UsesZeroVector = false;
11141 for (unsigned i = 0; i != NumInScalars; ++i) {
11142 SDValue Op = N->getOperand(i);
11143 // Ignore undef inputs.
11144 if (Op.getOpcode() == ISD::UNDEF) continue;
11146 // See if we can combine this build_vector into a blend with a zero vector.
11147 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11148 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11149 (Op.getOpcode() == ISD::ConstantFP &&
11150 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11151 UsesZeroVector = true;
11155 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11156 // constant index, bail out.
11157 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11158 !isa<ConstantSDNode>(Op.getOperand(1))) {
11159 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11163 // We allow up to two distinct input vectors.
11164 SDValue ExtractedFromVec = Op.getOperand(0);
11165 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11168 if (!VecIn1.getNode()) {
11169 VecIn1 = ExtractedFromVec;
11170 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11171 VecIn2 = ExtractedFromVec;
11173 // Too many inputs.
11174 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11179 // If everything is good, we can make a shuffle operation.
11180 if (VecIn1.getNode()) {
11181 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11182 SmallVector<int, 8> Mask;
11183 for (unsigned i = 0; i != NumInScalars; ++i) {
11184 unsigned Opcode = N->getOperand(i).getOpcode();
11185 if (Opcode == ISD::UNDEF) {
11186 Mask.push_back(-1);
11190 // Operands can also be zero.
11191 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11192 assert(UsesZeroVector &&
11193 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11194 "Unexpected node found!");
11195 Mask.push_back(NumInScalars+i);
11199 // If extracting from the first vector, just use the index directly.
11200 SDValue Extract = N->getOperand(i);
11201 SDValue ExtVal = Extract.getOperand(1);
11202 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11203 if (Extract.getOperand(0) == VecIn1) {
11204 Mask.push_back(ExtIndex);
11208 // Otherwise, use InIdx + InputVecSize
11209 Mask.push_back(InNumElements + ExtIndex);
11212 // Avoid introducing illegal shuffles with zero.
11213 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11216 // We can't generate a shuffle node with mismatched input and output types.
11217 // Attempt to transform a single input vector to the correct type.
11218 if ((VT != VecIn1.getValueType())) {
11219 // If the input vector type has a different base type to the output
11220 // vector type, bail out.
11221 EVT VTElemType = VT.getVectorElementType();
11222 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11223 (VecIn2.getNode() &&
11224 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11227 // If the input vector is too small, widen it.
11228 // We only support widening of vectors which are half the size of the
11229 // output registers. For example XMM->YMM widening on X86 with AVX.
11230 EVT VecInT = VecIn1.getValueType();
11231 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11232 // If we only have one small input, widen it by adding undef values.
11233 if (!VecIn2.getNode())
11234 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11235 DAG.getUNDEF(VecIn1.getValueType()));
11236 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11237 // If we have two small inputs of the same type, try to concat them.
11238 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11239 VecIn2 = SDValue(nullptr, 0);
11242 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11243 // If the input vector is too large, try to split it.
11244 // We don't support having two input vectors that are too large.
11245 if (VecIn2.getNode())
11248 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11251 // Try to replace VecIn1 with two extract_subvectors
11252 // No need to update the masks, they should still be correct.
11253 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11254 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11255 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11256 DAG.getConstant(0, TLI.getVectorIdxTy()));
11257 UsesZeroVector = false;
11262 if (UsesZeroVector)
11263 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11264 DAG.getConstantFP(0.0, VT);
11266 // If VecIn2 is unused then change it to undef.
11267 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11269 // Check that we were able to transform all incoming values to the same
11271 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11272 VecIn1.getValueType() != VT)
11275 // Return the new VECTOR_SHUFFLE node.
11279 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11285 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11286 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11287 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
11288 // inputs come from at most two distinct vectors, turn this into a shuffle
11291 // If we only have one input vector, we don't need to do any concatenation.
11292 if (N->getNumOperands() == 1)
11293 return N->getOperand(0);
11295 // Check if all of the operands are undefs.
11296 EVT VT = N->getValueType(0);
11297 if (ISD::allOperandsUndef(N))
11298 return DAG.getUNDEF(VT);
11300 // Optimize concat_vectors where one of the vectors is undef.
11301 if (N->getNumOperands() == 2 &&
11302 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11303 SDValue In = N->getOperand(0);
11304 assert(In.getValueType().isVector() && "Must concat vectors");
11306 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11307 if (In->getOpcode() == ISD::BITCAST &&
11308 !In->getOperand(0)->getValueType(0).isVector()) {
11309 SDValue Scalar = In->getOperand(0);
11310 EVT SclTy = Scalar->getValueType(0);
11312 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11315 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11316 VT.getSizeInBits() / SclTy.getSizeInBits());
11317 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11320 SDLoc dl = SDLoc(N);
11321 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11322 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11326 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11327 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11328 if (N->getNumOperands() == 2 &&
11329 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
11330 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
11331 EVT VT = N->getValueType(0);
11332 SDValue N0 = N->getOperand(0);
11333 SDValue N1 = N->getOperand(1);
11334 SmallVector<SDValue, 8> Opnds;
11335 unsigned BuildVecNumElts = N0.getNumOperands();
11337 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
11338 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
11339 if (SclTy0.isFloatingPoint()) {
11340 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11341 Opnds.push_back(N0.getOperand(i));
11342 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11343 Opnds.push_back(N1.getOperand(i));
11345 // If BUILD_VECTOR are from built from integer, they may have different
11346 // operand types. Get the smaller type and truncate all operands to it.
11347 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
11348 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11349 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11350 N0.getOperand(i)));
11351 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11352 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11353 N1.getOperand(i)));
11356 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11359 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11360 // nodes often generate nop CONCAT_VECTOR nodes.
11361 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11362 // place the incoming vectors at the exact same location.
11363 SDValue SingleSource = SDValue();
11364 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11366 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11367 SDValue Op = N->getOperand(i);
11369 if (Op.getOpcode() == ISD::UNDEF)
11372 // Check if this is the identity extract:
11373 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11376 // Find the single incoming vector for the extract_subvector.
11377 if (SingleSource.getNode()) {
11378 if (Op.getOperand(0) != SingleSource)
11381 SingleSource = Op.getOperand(0);
11383 // Check the source type is the same as the type of the result.
11384 // If not, this concat may extend the vector, so we can not
11385 // optimize it away.
11386 if (SingleSource.getValueType() != N->getValueType(0))
11390 unsigned IdentityIndex = i * PartNumElem;
11391 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11392 // The extract index must be constant.
11396 // Check that we are reading from the identity index.
11397 if (CS->getZExtValue() != IdentityIndex)
11401 if (SingleSource.getNode())
11402 return SingleSource;
11407 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11408 EVT NVT = N->getValueType(0);
11409 SDValue V = N->getOperand(0);
11411 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11413 // (extract_subvec (concat V1, V2, ...), i)
11416 // Only operand 0 is checked as 'concat' assumes all inputs of the same
11418 if (V->getOperand(0).getValueType() != NVT)
11420 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11421 unsigned NumElems = NVT.getVectorNumElements();
11422 assert((Idx % NumElems) == 0 &&
11423 "IDX in concat is not a multiple of the result vector length.");
11424 return V->getOperand(Idx / NumElems);
11428 if (V->getOpcode() == ISD::BITCAST)
11429 V = V.getOperand(0);
11431 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11433 // Handle only simple case where vector being inserted and vector
11434 // being extracted are of same type, and are half size of larger vectors.
11435 EVT BigVT = V->getOperand(0).getValueType();
11436 EVT SmallVT = V->getOperand(1).getValueType();
11437 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11440 // Only handle cases where both indexes are constants with the same type.
11441 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11442 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11444 if (InsIdx && ExtIdx &&
11445 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11446 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11448 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11450 // indices are equal or bit offsets are equal => V1
11451 // otherwise => (extract_subvec V1, ExtIdx)
11452 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11453 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11454 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11455 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11456 DAG.getNode(ISD::BITCAST, dl,
11457 N->getOperand(0).getValueType(),
11458 V->getOperand(0)), N->getOperand(1));
11465 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11466 SDValue V, SelectionDAG &DAG) {
11468 EVT VT = V.getValueType();
11470 switch (V.getOpcode()) {
11474 case ISD::CONCAT_VECTORS: {
11475 EVT OpVT = V->getOperand(0).getValueType();
11476 int OpSize = OpVT.getVectorNumElements();
11477 SmallBitVector OpUsedElements(OpSize, false);
11478 bool FoundSimplification = false;
11479 SmallVector<SDValue, 4> NewOps;
11480 NewOps.reserve(V->getNumOperands());
11481 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11482 SDValue Op = V->getOperand(i);
11483 bool OpUsed = false;
11484 for (int j = 0; j < OpSize; ++j)
11485 if (UsedElements[i * OpSize + j]) {
11486 OpUsedElements[j] = true;
11490 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11491 : DAG.getUNDEF(OpVT));
11492 FoundSimplification |= Op == NewOps.back();
11493 OpUsedElements.reset();
11495 if (FoundSimplification)
11496 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11500 case ISD::INSERT_SUBVECTOR: {
11501 SDValue BaseV = V->getOperand(0);
11502 SDValue SubV = V->getOperand(1);
11503 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11507 int SubSize = SubV.getValueType().getVectorNumElements();
11508 int Idx = IdxN->getZExtValue();
11509 bool SubVectorUsed = false;
11510 SmallBitVector SubUsedElements(SubSize, false);
11511 for (int i = 0; i < SubSize; ++i)
11512 if (UsedElements[i + Idx]) {
11513 SubVectorUsed = true;
11514 SubUsedElements[i] = true;
11515 UsedElements[i + Idx] = false;
11518 // Now recurse on both the base and sub vectors.
11519 SDValue SimplifiedSubV =
11521 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11522 : DAG.getUNDEF(SubV.getValueType());
11523 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11524 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11525 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11526 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11532 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11533 SDValue N1, SelectionDAG &DAG) {
11534 EVT VT = SVN->getValueType(0);
11535 int NumElts = VT.getVectorNumElements();
11536 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11537 for (int M : SVN->getMask())
11538 if (M >= 0 && M < NumElts)
11539 N0UsedElements[M] = true;
11540 else if (M >= NumElts)
11541 N1UsedElements[M - NumElts] = true;
11543 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11544 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11545 if (S0 == N0 && S1 == N1)
11548 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11551 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11552 // or turn a shuffle of a single concat into simpler shuffle then concat.
11553 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11554 EVT VT = N->getValueType(0);
11555 unsigned NumElts = VT.getVectorNumElements();
11557 SDValue N0 = N->getOperand(0);
11558 SDValue N1 = N->getOperand(1);
11559 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11561 SmallVector<SDValue, 4> Ops;
11562 EVT ConcatVT = N0.getOperand(0).getValueType();
11563 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11564 unsigned NumConcats = NumElts / NumElemsPerConcat;
11566 // Special case: shuffle(concat(A,B)) can be more efficiently represented
11567 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11568 // half vector elements.
11569 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11570 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11571 SVN->getMask().end(), [](int i) { return i == -1; })) {
11572 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11573 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11574 N1 = DAG.getUNDEF(ConcatVT);
11575 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11578 // Look at every vector that's inserted. We're looking for exact
11579 // subvector-sized copies from a concatenated vector
11580 for (unsigned I = 0; I != NumConcats; ++I) {
11581 // Make sure we're dealing with a copy.
11582 unsigned Begin = I * NumElemsPerConcat;
11583 bool AllUndef = true, NoUndef = true;
11584 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11585 if (SVN->getMaskElt(J) >= 0)
11592 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11595 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11596 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11599 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11600 if (FirstElt < N0.getNumOperands())
11601 Ops.push_back(N0.getOperand(FirstElt));
11603 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11605 } else if (AllUndef) {
11606 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11607 } else { // Mixed with general masks and undefs, can't do optimization.
11612 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11615 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11616 EVT VT = N->getValueType(0);
11617 unsigned NumElts = VT.getVectorNumElements();
11619 SDValue N0 = N->getOperand(0);
11620 SDValue N1 = N->getOperand(1);
11622 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11624 // Canonicalize shuffle undef, undef -> undef
11625 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11626 return DAG.getUNDEF(VT);
11628 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11630 // Canonicalize shuffle v, v -> v, undef
11632 SmallVector<int, 8> NewMask;
11633 for (unsigned i = 0; i != NumElts; ++i) {
11634 int Idx = SVN->getMaskElt(i);
11635 if (Idx >= (int)NumElts) Idx -= NumElts;
11636 NewMask.push_back(Idx);
11638 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11642 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
11643 if (N0.getOpcode() == ISD::UNDEF) {
11644 SmallVector<int, 8> NewMask;
11645 for (unsigned i = 0; i != NumElts; ++i) {
11646 int Idx = SVN->getMaskElt(i);
11648 if (Idx >= (int)NumElts)
11651 Idx = -1; // remove reference to lhs
11653 NewMask.push_back(Idx);
11655 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11659 // Remove references to rhs if it is undef
11660 if (N1.getOpcode() == ISD::UNDEF) {
11661 bool Changed = false;
11662 SmallVector<int, 8> NewMask;
11663 for (unsigned i = 0; i != NumElts; ++i) {
11664 int Idx = SVN->getMaskElt(i);
11665 if (Idx >= (int)NumElts) {
11669 NewMask.push_back(Idx);
11672 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11675 // If it is a splat, check if the argument vector is another splat or a
11677 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11678 SDNode *V = N0.getNode();
11680 // If this is a bit convert that changes the element type of the vector but
11681 // not the number of vector elements, look through it. Be careful not to
11682 // look though conversions that change things like v4f32 to v2f64.
11683 if (V->getOpcode() == ISD::BITCAST) {
11684 SDValue ConvInput = V->getOperand(0);
11685 if (ConvInput.getValueType().isVector() &&
11686 ConvInput.getValueType().getVectorNumElements() == NumElts)
11687 V = ConvInput.getNode();
11690 if (V->getOpcode() == ISD::BUILD_VECTOR) {
11691 assert(V->getNumOperands() == NumElts &&
11692 "BUILD_VECTOR has wrong number of operands");
11694 bool AllSame = true;
11695 for (unsigned i = 0; i != NumElts; ++i) {
11696 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11697 Base = V->getOperand(i);
11701 // Splat of <u, u, u, u>, return <u, u, u, u>
11702 if (!Base.getNode())
11704 for (unsigned i = 0; i != NumElts; ++i) {
11705 if (V->getOperand(i) != Base) {
11710 // Splat of <x, x, x, x>, return <x, x, x, x>
11714 // If the splatted element is a constant, just build the vector out of
11715 // constants directly.
11716 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
11717 if (isa<ConstantSDNode>(Splatted) || isa<ConstantFPSDNode>(Splatted)) {
11718 SmallVector<SDValue, 8> Ops;
11719 for (unsigned i = 0; i != NumElts; ++i) {
11720 Ops.push_back(Splatted);
11722 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
11723 V->getValueType(0), Ops);
11725 // We may have jumped through bitcasts, so the type of the
11726 // BUILD_VECTOR may not match the type of the shuffle.
11727 if (V->getValueType(0) != VT)
11728 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
11734 // There are various patterns used to build up a vector from smaller vectors,
11735 // subvectors, or elements. Scan chains of these and replace unused insertions
11736 // or components with undef.
11737 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11740 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11741 Level < AfterLegalizeVectorOps &&
11742 (N1.getOpcode() == ISD::UNDEF ||
11743 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11744 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11745 SDValue V = partitionShuffleOfConcats(N, DAG);
11751 // Canonicalize shuffles according to rules:
11752 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11753 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11754 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11755 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
11756 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11757 TLI.isTypeLegal(VT)) {
11758 // The incoming shuffle must be of the same type as the result of the
11759 // current shuffle.
11760 assert(N1->getOperand(0).getValueType() == VT &&
11761 "Shuffle types don't match");
11763 SDValue SV0 = N1->getOperand(0);
11764 SDValue SV1 = N1->getOperand(1);
11765 bool HasSameOp0 = N0 == SV0;
11766 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11767 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11768 // Commute the operands of this shuffle so that next rule
11770 return DAG.getCommutedVectorShuffle(*SVN);
11773 // Try to fold according to rules:
11774 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11775 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11776 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11777 // Don't try to fold shuffles with illegal type.
11778 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11779 TLI.isTypeLegal(VT)) {
11780 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11782 // The incoming shuffle must be of the same type as the result of the
11783 // current shuffle.
11784 assert(OtherSV->getOperand(0).getValueType() == VT &&
11785 "Shuffle types don't match");
11788 SmallVector<int, 4> Mask;
11789 // Compute the combined shuffle mask for a shuffle with SV0 as the first
11790 // operand, and SV1 as the second operand.
11791 for (unsigned i = 0; i != NumElts; ++i) {
11792 int Idx = SVN->getMaskElt(i);
11794 // Propagate Undef.
11795 Mask.push_back(Idx);
11799 SDValue CurrentVec;
11800 if (Idx < (int)NumElts) {
11801 // This shuffle index refers to the inner shuffle N0. Lookup the inner
11802 // shuffle mask to identify which vector is actually referenced.
11803 Idx = OtherSV->getMaskElt(Idx);
11805 // Propagate Undef.
11806 Mask.push_back(Idx);
11810 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11811 : OtherSV->getOperand(1);
11813 // This shuffle index references an element within N1.
11817 // Simple case where 'CurrentVec' is UNDEF.
11818 if (CurrentVec.getOpcode() == ISD::UNDEF) {
11819 Mask.push_back(-1);
11823 // Canonicalize the shuffle index. We don't know yet if CurrentVec
11824 // will be the first or second operand of the combined shuffle.
11825 Idx = Idx % NumElts;
11826 if (!SV0.getNode() || SV0 == CurrentVec) {
11827 // Ok. CurrentVec is the left hand side.
11828 // Update the mask accordingly.
11830 Mask.push_back(Idx);
11834 // Bail out if we cannot convert the shuffle pair into a single shuffle.
11835 if (SV1.getNode() && SV1 != CurrentVec)
11838 // Ok. CurrentVec is the right hand side.
11839 // Update the mask accordingly.
11841 Mask.push_back(Idx + NumElts);
11844 // Check if all indices in Mask are Undef. In case, propagate Undef.
11845 bool isUndefMask = true;
11846 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11847 isUndefMask &= Mask[i] < 0;
11850 return DAG.getUNDEF(VT);
11852 if (!SV0.getNode())
11853 SV0 = DAG.getUNDEF(VT);
11854 if (!SV1.getNode())
11855 SV1 = DAG.getUNDEF(VT);
11857 // Avoid introducing shuffles with illegal mask.
11858 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11859 // Compute the commuted shuffle mask and test again.
11860 for (unsigned i = 0; i != NumElts; ++i) {
11864 else if (idx < (int)NumElts)
11865 Mask[i] = idx + NumElts;
11867 Mask[i] = idx - NumElts;
11870 if (!TLI.isShuffleMaskLegal(Mask, VT))
11873 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11874 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11875 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11876 std::swap(SV0, SV1);
11879 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11880 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11881 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11882 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11888 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11889 SDValue N0 = N->getOperand(0);
11890 SDValue N2 = N->getOperand(2);
11892 // If the input vector is a concatenation, and the insert replaces
11893 // one of the halves, we can optimize into a single concat_vectors.
11894 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11895 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11896 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11897 EVT VT = N->getValueType(0);
11899 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11900 // (concat_vectors Z, Y)
11902 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11903 N->getOperand(1), N0.getOperand(1));
11905 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11906 // (concat_vectors X, Z)
11907 if (InsIdx == VT.getVectorNumElements()/2)
11908 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11909 N0.getOperand(0), N->getOperand(1));
11915 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11916 /// with the destination vector and a zero vector.
11917 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11918 /// vector_shuffle V, Zero, <0, 4, 2, 4>
11919 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11920 EVT VT = N->getValueType(0);
11922 SDValue LHS = N->getOperand(0);
11923 SDValue RHS = N->getOperand(1);
11924 if (N->getOpcode() == ISD::AND) {
11925 if (RHS.getOpcode() == ISD::BITCAST)
11926 RHS = RHS.getOperand(0);
11927 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11928 SmallVector<int, 8> Indices;
11929 unsigned NumElts = RHS.getNumOperands();
11930 for (unsigned i = 0; i != NumElts; ++i) {
11931 SDValue Elt = RHS.getOperand(i);
11932 if (!isa<ConstantSDNode>(Elt))
11935 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11936 Indices.push_back(i);
11937 else if (cast<ConstantSDNode>(Elt)->isNullValue())
11938 Indices.push_back(NumElts+i);
11943 // Let's see if the target supports this vector_shuffle.
11944 EVT RVT = RHS.getValueType();
11945 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11948 // Return the new VECTOR_SHUFFLE node.
11949 EVT EltVT = RVT.getVectorElementType();
11950 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11951 DAG.getConstant(0, EltVT));
11952 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11953 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11954 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11955 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11962 /// Visit a binary vector operation, like ADD.
11963 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11964 assert(N->getValueType(0).isVector() &&
11965 "SimplifyVBinOp only works on vectors!");
11967 SDValue LHS = N->getOperand(0);
11968 SDValue RHS = N->getOperand(1);
11969 SDValue Shuffle = XformToShuffleWithZero(N);
11970 if (Shuffle.getNode()) return Shuffle;
11972 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11974 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11975 RHS.getOpcode() == ISD::BUILD_VECTOR) {
11976 // Check if both vectors are constants. If not bail out.
11977 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11978 cast<BuildVectorSDNode>(RHS)->isConstant()))
11981 SmallVector<SDValue, 8> Ops;
11982 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11983 SDValue LHSOp = LHS.getOperand(i);
11984 SDValue RHSOp = RHS.getOperand(i);
11986 // Can't fold divide by zero.
11987 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11988 N->getOpcode() == ISD::FDIV) {
11989 if ((RHSOp.getOpcode() == ISD::Constant &&
11990 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11991 (RHSOp.getOpcode() == ISD::ConstantFP &&
11992 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11996 EVT VT = LHSOp.getValueType();
11997 EVT RVT = RHSOp.getValueType();
11999 // Integer BUILD_VECTOR operands may have types larger than the element
12000 // size (e.g., when the element type is not legal). Prior to type
12001 // legalization, the types may not match between the two BUILD_VECTORS.
12002 // Truncate one of the operands to make them match.
12003 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12004 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12006 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12010 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12012 if (FoldOp.getOpcode() != ISD::UNDEF &&
12013 FoldOp.getOpcode() != ISD::Constant &&
12014 FoldOp.getOpcode() != ISD::ConstantFP)
12016 Ops.push_back(FoldOp);
12017 AddToWorklist(FoldOp.getNode());
12020 if (Ops.size() == LHS.getNumOperands())
12021 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12024 // Type legalization might introduce new shuffles in the DAG.
12025 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12026 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
12027 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12028 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12029 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12030 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12031 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12032 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12034 if (SVN0->getMask().equals(SVN1->getMask())) {
12035 EVT VT = N->getValueType(0);
12036 SDValue UndefVector = LHS.getOperand(1);
12037 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12038 LHS.getOperand(0), RHS.getOperand(0));
12039 AddUsersToWorklist(N);
12040 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12041 &SVN0->getMask()[0]);
12048 /// Visit a binary vector operation, like FABS/FNEG.
12049 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
12050 assert(N->getValueType(0).isVector() &&
12051 "SimplifyVUnaryOp only works on vectors!");
12053 SDValue N0 = N->getOperand(0);
12055 if (N0.getOpcode() != ISD::BUILD_VECTOR)
12058 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
12059 SmallVector<SDValue, 8> Ops;
12060 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
12061 SDValue Op = N0.getOperand(i);
12062 if (Op.getOpcode() != ISD::UNDEF &&
12063 Op.getOpcode() != ISD::ConstantFP)
12065 EVT EltVT = Op.getValueType();
12066 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
12067 if (FoldOp.getOpcode() != ISD::UNDEF &&
12068 FoldOp.getOpcode() != ISD::ConstantFP)
12070 Ops.push_back(FoldOp);
12071 AddToWorklist(FoldOp.getNode());
12074 if (Ops.size() != N0.getNumOperands())
12077 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
12080 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12081 SDValue N1, SDValue N2){
12082 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12084 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12085 cast<CondCodeSDNode>(N0.getOperand(2))->get());
12087 // If we got a simplified select_cc node back from SimplifySelectCC, then
12088 // break it down into a new SETCC node, and a new SELECT node, and then return
12089 // the SELECT node, since we were called with a SELECT node.
12090 if (SCC.getNode()) {
12091 // Check to see if we got a select_cc back (to turn into setcc/select).
12092 // Otherwise, just return whatever node we got back, like fabs.
12093 if (SCC.getOpcode() == ISD::SELECT_CC) {
12094 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12096 SCC.getOperand(0), SCC.getOperand(1),
12097 SCC.getOperand(4));
12098 AddToWorklist(SETCC.getNode());
12099 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12100 SCC.getOperand(2), SCC.getOperand(3));
12108 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12109 /// being selected between, see if we can simplify the select. Callers of this
12110 /// should assume that TheSelect is deleted if this returns true. As such, they
12111 /// should return the appropriate thing (e.g. the node) back to the top-level of
12112 /// the DAG combiner loop to avoid it being looked at.
12113 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12116 // Cannot simplify select with vector condition
12117 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12119 // If this is a select from two identical things, try to pull the operation
12120 // through the select.
12121 if (LHS.getOpcode() != RHS.getOpcode() ||
12122 !LHS.hasOneUse() || !RHS.hasOneUse())
12125 // If this is a load and the token chain is identical, replace the select
12126 // of two loads with a load through a select of the address to load from.
12127 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12128 // constants have been dropped into the constant pool.
12129 if (LHS.getOpcode() == ISD::LOAD) {
12130 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12131 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12133 // Token chains must be identical.
12134 if (LHS.getOperand(0) != RHS.getOperand(0) ||
12135 // Do not let this transformation reduce the number of volatile loads.
12136 LLD->isVolatile() || RLD->isVolatile() ||
12137 // If this is an EXTLOAD, the VT's must match.
12138 LLD->getMemoryVT() != RLD->getMemoryVT() ||
12139 // If this is an EXTLOAD, the kind of extension must match.
12140 (LLD->getExtensionType() != RLD->getExtensionType() &&
12141 // The only exception is if one of the extensions is anyext.
12142 LLD->getExtensionType() != ISD::EXTLOAD &&
12143 RLD->getExtensionType() != ISD::EXTLOAD) ||
12144 // FIXME: this discards src value information. This is
12145 // over-conservative. It would be beneficial to be able to remember
12146 // both potential memory locations. Since we are discarding
12147 // src value info, don't do the transformation if the memory
12148 // locations are not in the default address space.
12149 LLD->getPointerInfo().getAddrSpace() != 0 ||
12150 RLD->getPointerInfo().getAddrSpace() != 0 ||
12151 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12152 LLD->getBasePtr().getValueType()))
12155 // Check that the select condition doesn't reach either load. If so,
12156 // folding this will induce a cycle into the DAG. If not, this is safe to
12157 // xform, so create a select of the addresses.
12159 if (TheSelect->getOpcode() == ISD::SELECT) {
12160 SDNode *CondNode = TheSelect->getOperand(0).getNode();
12161 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12162 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12164 // The loads must not depend on one another.
12165 if (LLD->isPredecessorOf(RLD) ||
12166 RLD->isPredecessorOf(LLD))
12168 Addr = DAG.getSelect(SDLoc(TheSelect),
12169 LLD->getBasePtr().getValueType(),
12170 TheSelect->getOperand(0), LLD->getBasePtr(),
12171 RLD->getBasePtr());
12172 } else { // Otherwise SELECT_CC
12173 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12174 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12176 if ((LLD->hasAnyUseOfValue(1) &&
12177 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
12178 (RLD->hasAnyUseOfValue(1) &&
12179 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
12182 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
12183 LLD->getBasePtr().getValueType(),
12184 TheSelect->getOperand(0),
12185 TheSelect->getOperand(1),
12186 LLD->getBasePtr(), RLD->getBasePtr(),
12187 TheSelect->getOperand(4));
12191 // It is safe to replace the two loads if they have different alignments,
12192 // but the new load must be the minimum (most restrictive) alignment of the
12194 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
12195 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
12196 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12197 Load = DAG.getLoad(TheSelect->getValueType(0),
12199 // FIXME: Discards pointer and AA info.
12200 LLD->getChain(), Addr, MachinePointerInfo(),
12201 LLD->isVolatile(), LLD->isNonTemporal(),
12202 isInvariant, Alignment);
12204 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12205 RLD->getExtensionType() : LLD->getExtensionType(),
12207 TheSelect->getValueType(0),
12208 // FIXME: Discards pointer and AA info.
12209 LLD->getChain(), Addr, MachinePointerInfo(),
12210 LLD->getMemoryVT(), LLD->isVolatile(),
12211 LLD->isNonTemporal(), isInvariant, Alignment);
12214 // Users of the select now use the result of the load.
12215 CombineTo(TheSelect, Load);
12217 // Users of the old loads now use the new load's chain. We know the
12218 // old-load value is dead now.
12219 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12220 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12227 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12228 /// where 'cond' is the comparison specified by CC.
12229 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12230 SDValue N2, SDValue N3,
12231 ISD::CondCode CC, bool NotExtCompare) {
12232 // (x ? y : y) -> y.
12233 if (N2 == N3) return N2;
12235 EVT VT = N2.getValueType();
12236 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12237 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12238 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12240 // Determine if the condition we're dealing with is constant
12241 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12242 N0, N1, CC, DL, false);
12243 if (SCC.getNode()) AddToWorklist(SCC.getNode());
12244 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12246 // fold select_cc true, x, y -> x
12247 if (SCCC && !SCCC->isNullValue())
12249 // fold select_cc false, x, y -> y
12250 if (SCCC && SCCC->isNullValue())
12253 // Check to see if we can simplify the select into an fabs node
12254 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12255 // Allow either -0.0 or 0.0
12256 if (CFP->getValueAPF().isZero()) {
12257 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12258 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12259 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12260 N2 == N3.getOperand(0))
12261 return DAG.getNode(ISD::FABS, DL, VT, N0);
12263 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12264 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12265 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12266 N2.getOperand(0) == N3)
12267 return DAG.getNode(ISD::FABS, DL, VT, N3);
12271 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12272 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12273 // in it. This is a win when the constant is not otherwise available because
12274 // it replaces two constant pool loads with one. We only do this if the FP
12275 // type is known to be legal, because if it isn't, then we are before legalize
12276 // types an we want the other legalization to happen first (e.g. to avoid
12277 // messing with soft float) and if the ConstantFP is not legal, because if
12278 // it is legal, we may not need to store the FP constant in a constant pool.
12279 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12280 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12281 if (TLI.isTypeLegal(N2.getValueType()) &&
12282 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12283 TargetLowering::Legal &&
12284 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12285 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12286 // If both constants have multiple uses, then we won't need to do an
12287 // extra load, they are likely around in registers for other users.
12288 (TV->hasOneUse() || FV->hasOneUse())) {
12289 Constant *Elts[] = {
12290 const_cast<ConstantFP*>(FV->getConstantFPValue()),
12291 const_cast<ConstantFP*>(TV->getConstantFPValue())
12293 Type *FPTy = Elts[0]->getType();
12294 const DataLayout &TD = *TLI.getDataLayout();
12296 // Create a ConstantArray of the two constants.
12297 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12298 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12299 TD.getPrefTypeAlignment(FPTy));
12300 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12302 // Get the offsets to the 0 and 1 element of the array so that we can
12303 // select between them.
12304 SDValue Zero = DAG.getIntPtrConstant(0);
12305 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12306 SDValue One = DAG.getIntPtrConstant(EltSize);
12308 SDValue Cond = DAG.getSetCC(DL,
12309 getSetCCResultType(N0.getValueType()),
12311 AddToWorklist(Cond.getNode());
12312 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12314 AddToWorklist(CstOffset.getNode());
12315 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12317 AddToWorklist(CPIdx.getNode());
12318 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12319 MachinePointerInfo::getConstantPool(), false,
12320 false, false, Alignment);
12325 // Check to see if we can perform the "gzip trick", transforming
12326 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12327 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12328 (N1C->isNullValue() || // (a < 0) ? b : 0
12329 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
12330 EVT XType = N0.getValueType();
12331 EVT AType = N2.getValueType();
12332 if (XType.bitsGE(AType)) {
12333 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12334 // single-bit constant.
12335 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12336 unsigned ShCtV = N2C->getAPIntValue().logBase2();
12337 ShCtV = XType.getSizeInBits()-ShCtV-1;
12338 SDValue ShCt = DAG.getConstant(ShCtV,
12339 getShiftAmountTy(N0.getValueType()));
12340 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12342 AddToWorklist(Shift.getNode());
12344 if (XType.bitsGT(AType)) {
12345 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12346 AddToWorklist(Shift.getNode());
12349 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12352 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12354 DAG.getConstant(XType.getSizeInBits()-1,
12355 getShiftAmountTy(N0.getValueType())));
12356 AddToWorklist(Shift.getNode());
12358 if (XType.bitsGT(AType)) {
12359 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12360 AddToWorklist(Shift.getNode());
12363 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12367 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12368 // where y is has a single bit set.
12369 // A plaintext description would be, we can turn the SELECT_CC into an AND
12370 // when the condition can be materialized as an all-ones register. Any
12371 // single bit-test can be materialized as an all-ones register with
12372 // shift-left and shift-right-arith.
12373 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12374 N0->getValueType(0) == VT &&
12375 N1C && N1C->isNullValue() &&
12376 N2C && N2C->isNullValue()) {
12377 SDValue AndLHS = N0->getOperand(0);
12378 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12379 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12380 // Shift the tested bit over the sign bit.
12381 APInt AndMask = ConstAndRHS->getAPIntValue();
12383 DAG.getConstant(AndMask.countLeadingZeros(),
12384 getShiftAmountTy(AndLHS.getValueType()));
12385 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12387 // Now arithmetic right shift it all the way over, so the result is either
12388 // all-ones, or zero.
12390 DAG.getConstant(AndMask.getBitWidth()-1,
12391 getShiftAmountTy(Shl.getValueType()));
12392 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12394 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12398 // fold select C, 16, 0 -> shl C, 4
12399 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12400 TLI.getBooleanContents(N0.getValueType()) ==
12401 TargetLowering::ZeroOrOneBooleanContent) {
12403 // If the caller doesn't want us to simplify this into a zext of a compare,
12405 if (NotExtCompare && N2C->getAPIntValue() == 1)
12408 // Get a SetCC of the condition
12409 // NOTE: Don't create a SETCC if it's not legal on this target.
12410 if (!LegalOperations ||
12411 TLI.isOperationLegal(ISD::SETCC,
12412 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12414 // cast from setcc result type to select result type
12416 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12418 if (N2.getValueType().bitsLT(SCC.getValueType()))
12419 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12420 N2.getValueType());
12422 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12423 N2.getValueType(), SCC);
12425 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12426 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12427 N2.getValueType(), SCC);
12430 AddToWorklist(SCC.getNode());
12431 AddToWorklist(Temp.getNode());
12433 if (N2C->getAPIntValue() == 1)
12436 // shl setcc result by log2 n2c
12437 return DAG.getNode(
12438 ISD::SHL, DL, N2.getValueType(), Temp,
12439 DAG.getConstant(N2C->getAPIntValue().logBase2(),
12440 getShiftAmountTy(Temp.getValueType())));
12444 // Check to see if this is the equivalent of setcc
12445 // FIXME: Turn all of these into setcc if setcc if setcc is legal
12446 // otherwise, go ahead with the folds.
12447 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12448 EVT XType = N0.getValueType();
12449 if (!LegalOperations ||
12450 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12451 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12452 if (Res.getValueType() != VT)
12453 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12457 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12458 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12459 (!LegalOperations ||
12460 TLI.isOperationLegal(ISD::CTLZ, XType))) {
12461 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12462 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12463 DAG.getConstant(Log2_32(XType.getSizeInBits()),
12464 getShiftAmountTy(Ctlz.getValueType())));
12466 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12467 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12468 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12469 XType, DAG.getConstant(0, XType), N0);
12470 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12471 return DAG.getNode(ISD::SRL, DL, XType,
12472 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12473 DAG.getConstant(XType.getSizeInBits()-1,
12474 getShiftAmountTy(XType)));
12476 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12477 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12478 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12479 DAG.getConstant(XType.getSizeInBits()-1,
12480 getShiftAmountTy(N0.getValueType())));
12481 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12485 // Check to see if this is an integer abs.
12486 // select_cc setg[te] X, 0, X, -X ->
12487 // select_cc setgt X, -1, X, -X ->
12488 // select_cc setl[te] X, 0, -X, X ->
12489 // select_cc setlt X, 1, -X, X ->
12490 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12492 ConstantSDNode *SubC = nullptr;
12493 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12494 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12495 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12496 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12497 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12498 (N1C->isOne() && CC == ISD::SETLT)) &&
12499 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12500 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12502 EVT XType = N0.getValueType();
12503 if (SubC && SubC->isNullValue() && XType.isInteger()) {
12504 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12506 DAG.getConstant(XType.getSizeInBits()-1,
12507 getShiftAmountTy(N0.getValueType())));
12508 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12510 AddToWorklist(Shift.getNode());
12511 AddToWorklist(Add.getNode());
12512 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12519 /// This is a stub for TargetLowering::SimplifySetCC.
12520 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12521 SDValue N1, ISD::CondCode Cond,
12522 SDLoc DL, bool foldBooleans) {
12523 TargetLowering::DAGCombinerInfo
12524 DagCombineInfo(DAG, Level, false, this);
12525 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12528 /// Given an ISD::SDIV node expressing a divide by constant, return
12529 /// a DAG expression to select that will generate the same value by multiplying
12530 /// by a magic number.
12531 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12532 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12533 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12537 // Avoid division by zero.
12538 if (!C->getAPIntValue())
12541 std::vector<SDNode*> Built;
12543 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12545 for (SDNode *N : Built)
12550 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12551 /// DAG expression that will generate the same value by right shifting.
12552 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12553 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12557 // Avoid division by zero.
12558 if (!C->getAPIntValue())
12561 std::vector<SDNode *> Built;
12562 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12564 for (SDNode *N : Built)
12569 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12570 /// expression that will generate the same value by multiplying by a magic
12572 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12573 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12574 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12578 // Avoid division by zero.
12579 if (!C->getAPIntValue())
12582 std::vector<SDNode*> Built;
12584 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12586 for (SDNode *N : Built)
12591 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12592 if (Level >= AfterLegalizeDAG)
12595 // Expose the DAG combiner to the target combiner implementations.
12596 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12598 unsigned Iterations = 0;
12599 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12601 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12602 // For the reciprocal, we need to find the zero of the function:
12603 // F(X) = A X - 1 [which has a zero at X = 1/A]
12605 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12606 // does not require additional intermediate precision]
12607 EVT VT = Op.getValueType();
12609 SDValue FPOne = DAG.getConstantFP(1.0, VT);
12611 AddToWorklist(Est.getNode());
12613 // Newton iterations: Est = Est + Est (1 - Arg * Est)
12614 for (unsigned i = 0; i < Iterations; ++i) {
12615 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12616 AddToWorklist(NewEst.getNode());
12618 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12619 AddToWorklist(NewEst.getNode());
12621 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12622 AddToWorklist(NewEst.getNode());
12624 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12625 AddToWorklist(Est.getNode());
12634 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12635 /// For the reciprocal sqrt, we need to find the zero of the function:
12636 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12638 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12639 /// As a result, we precompute A/2 prior to the iteration loop.
12640 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12641 unsigned Iterations) {
12642 EVT VT = Arg.getValueType();
12644 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12646 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12647 // this entire sequence requires only one FP constant.
12648 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12649 AddToWorklist(HalfArg.getNode());
12651 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12652 AddToWorklist(HalfArg.getNode());
12654 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12655 for (unsigned i = 0; i < Iterations; ++i) {
12656 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12657 AddToWorklist(NewEst.getNode());
12659 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12660 AddToWorklist(NewEst.getNode());
12662 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12663 AddToWorklist(NewEst.getNode());
12665 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12666 AddToWorklist(Est.getNode());
12671 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12672 /// For the reciprocal sqrt, we need to find the zero of the function:
12673 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12675 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12676 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12677 unsigned Iterations) {
12678 EVT VT = Arg.getValueType();
12680 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12681 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12683 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12684 for (unsigned i = 0; i < Iterations; ++i) {
12685 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12686 AddToWorklist(HalfEst.getNode());
12688 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12689 AddToWorklist(Est.getNode());
12691 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12692 AddToWorklist(Est.getNode());
12694 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12695 AddToWorklist(Est.getNode());
12697 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12698 AddToWorklist(Est.getNode());
12703 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12704 if (Level >= AfterLegalizeDAG)
12707 // Expose the DAG combiner to the target combiner implementations.
12708 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12709 unsigned Iterations = 0;
12710 bool UseOneConstNR = false;
12711 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12712 AddToWorklist(Est.getNode());
12714 Est = UseOneConstNR ?
12715 BuildRsqrtNROneConst(Op, Est, Iterations) :
12716 BuildRsqrtNRTwoConst(Op, Est, Iterations);
12724 /// Return true if base is a frame index, which is known not to alias with
12725 /// anything but itself. Provides base object and offset as results.
12726 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12727 const GlobalValue *&GV, const void *&CV) {
12728 // Assume it is a primitive operation.
12729 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12731 // If it's an adding a simple constant then integrate the offset.
12732 if (Base.getOpcode() == ISD::ADD) {
12733 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12734 Base = Base.getOperand(0);
12735 Offset += C->getZExtValue();
12739 // Return the underlying GlobalValue, and update the Offset. Return false
12740 // for GlobalAddressSDNode since the same GlobalAddress may be represented
12741 // by multiple nodes with different offsets.
12742 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12743 GV = G->getGlobal();
12744 Offset += G->getOffset();
12748 // Return the underlying Constant value, and update the Offset. Return false
12749 // for ConstantSDNodes since the same constant pool entry may be represented
12750 // by multiple nodes with different offsets.
12751 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12752 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12753 : (const void *)C->getConstVal();
12754 Offset += C->getOffset();
12757 // If it's any of the following then it can't alias with anything but itself.
12758 return isa<FrameIndexSDNode>(Base);
12761 /// Return true if there is any possibility that the two addresses overlap.
12762 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12763 // If they are the same then they must be aliases.
12764 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12766 // If they are both volatile then they cannot be reordered.
12767 if (Op0->isVolatile() && Op1->isVolatile()) return true;
12769 // Gather base node and offset information.
12770 SDValue Base1, Base2;
12771 int64_t Offset1, Offset2;
12772 const GlobalValue *GV1, *GV2;
12773 const void *CV1, *CV2;
12774 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12775 Base1, Offset1, GV1, CV1);
12776 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12777 Base2, Offset2, GV2, CV2);
12779 // If they have a same base address then check to see if they overlap.
12780 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12781 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12782 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12784 // It is possible for different frame indices to alias each other, mostly
12785 // when tail call optimization reuses return address slots for arguments.
12786 // To catch this case, look up the actual index of frame indices to compute
12787 // the real alias relationship.
12788 if (isFrameIndex1 && isFrameIndex2) {
12789 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12790 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12791 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12792 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12793 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12796 // Otherwise, if we know what the bases are, and they aren't identical, then
12797 // we know they cannot alias.
12798 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12801 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12802 // compared to the size and offset of the access, we may be able to prove they
12803 // do not alias. This check is conservative for now to catch cases created by
12804 // splitting vector types.
12805 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12806 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12807 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12808 Op1->getMemoryVT().getSizeInBits() >> 3) &&
12809 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12810 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12811 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12813 // There is no overlap between these relatively aligned accesses of similar
12814 // size, return no alias.
12815 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12816 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12820 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12822 : DAG.getSubtarget().useAA();
12824 if (CombinerAAOnlyFunc.getNumOccurrences() &&
12825 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12829 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12830 // Use alias analysis information.
12831 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12832 Op1->getSrcValueOffset());
12833 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12834 Op0->getSrcValueOffset() - MinOffset;
12835 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12836 Op1->getSrcValueOffset() - MinOffset;
12837 AliasAnalysis::AliasResult AAResult =
12838 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12840 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12841 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12843 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12844 if (AAResult == AliasAnalysis::NoAlias)
12848 // Otherwise we have to assume they alias.
12852 /// Walk up chain skipping non-aliasing memory nodes,
12853 /// looking for aliasing nodes and adding them to the Aliases vector.
12854 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12855 SmallVectorImpl<SDValue> &Aliases) {
12856 SmallVector<SDValue, 8> Chains; // List of chains to visit.
12857 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
12859 // Get alias information for node.
12860 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12863 Chains.push_back(OriginalChain);
12864 unsigned Depth = 0;
12866 // Look at each chain and determine if it is an alias. If so, add it to the
12867 // aliases list. If not, then continue up the chain looking for the next
12869 while (!Chains.empty()) {
12870 SDValue Chain = Chains.back();
12873 // For TokenFactor nodes, look at each operand and only continue up the
12874 // chain until we find two aliases. If we've seen two aliases, assume we'll
12875 // find more and revert to original chain since the xform is unlikely to be
12878 // FIXME: The depth check could be made to return the last non-aliasing
12879 // chain we found before we hit a tokenfactor rather than the original
12881 if (Depth > 6 || Aliases.size() == 2) {
12883 Aliases.push_back(OriginalChain);
12887 // Don't bother if we've been before.
12888 if (!Visited.insert(Chain.getNode()).second)
12891 switch (Chain.getOpcode()) {
12892 case ISD::EntryToken:
12893 // Entry token is ideal chain operand, but handled in FindBetterChain.
12898 // Get alias information for Chain.
12899 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12900 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12902 // If chain is alias then stop here.
12903 if (!(IsLoad && IsOpLoad) &&
12904 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12905 Aliases.push_back(Chain);
12907 // Look further up the chain.
12908 Chains.push_back(Chain.getOperand(0));
12914 case ISD::TokenFactor:
12915 // We have to check each of the operands of the token factor for "small"
12916 // token factors, so we queue them up. Adding the operands to the queue
12917 // (stack) in reverse order maintains the original order and increases the
12918 // likelihood that getNode will find a matching token factor (CSE.)
12919 if (Chain.getNumOperands() > 16) {
12920 Aliases.push_back(Chain);
12923 for (unsigned n = Chain.getNumOperands(); n;)
12924 Chains.push_back(Chain.getOperand(--n));
12929 // For all other instructions we will just have to take what we can get.
12930 Aliases.push_back(Chain);
12935 // We need to be careful here to also search for aliases through the
12936 // value operand of a store, etc. Consider the following situation:
12938 // L1 = load Token1, %52
12939 // S1 = store Token1, L1, %51
12940 // L2 = load Token1, %52+8
12941 // S2 = store Token1, L2, %51+8
12942 // Token2 = Token(S1, S2)
12943 // L3 = load Token2, %53
12944 // S3 = store Token2, L3, %52
12945 // L4 = load Token2, %53+8
12946 // S4 = store Token2, L4, %52+8
12947 // If we search for aliases of S3 (which loads address %52), and we look
12948 // only through the chain, then we'll miss the trivial dependence on L1
12949 // (which also loads from %52). We then might change all loads and
12950 // stores to use Token1 as their chain operand, which could result in
12951 // copying %53 into %52 before copying %52 into %51 (which should
12954 // The problem is, however, that searching for such data dependencies
12955 // can become expensive, and the cost is not directly related to the
12956 // chain depth. Instead, we'll rule out such configurations here by
12957 // insisting that we've visited all chain users (except for users
12958 // of the original chain, which is not necessary). When doing this,
12959 // we need to look through nodes we don't care about (otherwise, things
12960 // like register copies will interfere with trivial cases).
12962 SmallVector<const SDNode *, 16> Worklist;
12963 for (const SDNode *N : Visited)
12964 if (N != OriginalChain.getNode())
12965 Worklist.push_back(N);
12967 while (!Worklist.empty()) {
12968 const SDNode *M = Worklist.pop_back_val();
12970 // We have already visited M, and want to make sure we've visited any uses
12971 // of M that we care about. For uses that we've not visisted, and don't
12972 // care about, queue them to the worklist.
12974 for (SDNode::use_iterator UI = M->use_begin(),
12975 UIE = M->use_end(); UI != UIE; ++UI)
12976 if (UI.getUse().getValueType() == MVT::Other &&
12977 Visited.insert(*UI).second) {
12978 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12979 // We've not visited this use, and we care about it (it could have an
12980 // ordering dependency with the original node).
12982 Aliases.push_back(OriginalChain);
12986 // We've not visited this use, but we don't care about it. Mark it as
12987 // visited and enqueue it to the worklist.
12988 Worklist.push_back(*UI);
12993 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12994 /// (aliasing node.)
12995 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12996 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
12998 // Accumulate all the aliases to this node.
12999 GatherAllAliases(N, OldChain, Aliases);
13001 // If no operands then chain to entry token.
13002 if (Aliases.size() == 0)
13003 return DAG.getEntryNode();
13005 // If a single operand then chain to it. We don't need to revisit it.
13006 if (Aliases.size() == 1)
13009 // Construct a custom tailored token factor.
13010 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13013 /// This is the entry point for the file.
13014 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13015 CodeGenOpt::Level OptLevel) {
13016 /// This is the main entry point to this class.
13017 DAGCombiner(*this, AA, OptLevel).Run(Level);