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 visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250 SDValue visitOR(SDNode *N);
251 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252 SDValue visitXOR(SDNode *N);
253 SDValue SimplifyVBinOp(SDNode *N);
254 SDValue visitSHL(SDNode *N);
255 SDValue visitSRA(SDNode *N);
256 SDValue visitSRL(SDNode *N);
257 SDValue visitRotate(SDNode *N);
258 SDValue visitCTLZ(SDNode *N);
259 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
260 SDValue visitCTTZ(SDNode *N);
261 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
262 SDValue visitCTPOP(SDNode *N);
263 SDValue visitSELECT(SDNode *N);
264 SDValue visitVSELECT(SDNode *N);
265 SDValue visitSELECT_CC(SDNode *N);
266 SDValue visitSETCC(SDNode *N);
267 SDValue visitSIGN_EXTEND(SDNode *N);
268 SDValue visitZERO_EXTEND(SDNode *N);
269 SDValue visitANY_EXTEND(SDNode *N);
270 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271 SDValue visitTRUNCATE(SDNode *N);
272 SDValue visitBITCAST(SDNode *N);
273 SDValue visitBUILD_PAIR(SDNode *N);
274 SDValue visitFADD(SDNode *N);
275 SDValue visitFSUB(SDNode *N);
276 SDValue visitFMUL(SDNode *N);
277 SDValue visitFMA(SDNode *N);
278 SDValue visitFDIV(SDNode *N);
279 SDValue visitFREM(SDNode *N);
280 SDValue visitFSQRT(SDNode *N);
281 SDValue visitFCOPYSIGN(SDNode *N);
282 SDValue visitSINT_TO_FP(SDNode *N);
283 SDValue visitUINT_TO_FP(SDNode *N);
284 SDValue visitFP_TO_SINT(SDNode *N);
285 SDValue visitFP_TO_UINT(SDNode *N);
286 SDValue visitFP_ROUND(SDNode *N);
287 SDValue visitFP_ROUND_INREG(SDNode *N);
288 SDValue visitFP_EXTEND(SDNode *N);
289 SDValue visitFNEG(SDNode *N);
290 SDValue visitFABS(SDNode *N);
291 SDValue visitFCEIL(SDNode *N);
292 SDValue visitFTRUNC(SDNode *N);
293 SDValue visitFFLOOR(SDNode *N);
294 SDValue visitFMINNUM(SDNode *N);
295 SDValue visitFMAXNUM(SDNode *N);
296 SDValue visitBRCOND(SDNode *N);
297 SDValue visitBR_CC(SDNode *N);
298 SDValue visitLOAD(SDNode *N);
299 SDValue visitSTORE(SDNode *N);
300 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302 SDValue visitBUILD_VECTOR(SDNode *N);
303 SDValue visitCONCAT_VECTORS(SDNode *N);
304 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
305 SDValue visitVECTOR_SHUFFLE(SDNode *N);
306 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
307 SDValue visitINSERT_SUBVECTOR(SDNode *N);
308 SDValue visitMLOAD(SDNode *N);
309 SDValue visitMSTORE(SDNode *N);
311 SDValue XformToShuffleWithZero(SDNode *N);
312 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
314 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
316 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
317 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
318 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
319 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
320 SDValue N3, ISD::CondCode CC,
321 bool NotExtCompare = false);
322 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
323 SDLoc DL, bool foldBooleans = true);
325 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
327 bool isOneUseSetCC(SDValue N) const;
329 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
331 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
332 SDValue CombineExtLoad(SDNode *N);
333 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
334 SDValue BuildSDIV(SDNode *N);
335 SDValue BuildSDIVPow2(SDNode *N);
336 SDValue BuildUDIV(SDNode *N);
337 SDValue BuildReciprocalEstimate(SDValue Op);
338 SDValue BuildRsqrtEstimate(SDValue Op);
339 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
340 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
341 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
342 bool DemandHighBits = true);
343 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
344 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
345 SDValue InnerPos, SDValue InnerNeg,
346 unsigned PosOpcode, unsigned NegOpcode,
348 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
349 SDValue ReduceLoadWidth(SDNode *N);
350 SDValue ReduceLoadOpStoreWidth(SDNode *N);
351 SDValue TransformFPLoadStorePair(SDNode *N);
352 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
353 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
355 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
357 /// Walk up chain skipping non-aliasing memory nodes,
358 /// looking for aliasing nodes and adding them to the Aliases vector.
359 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
360 SmallVectorImpl<SDValue> &Aliases);
362 /// Return true if there is any possibility that the two addresses overlap.
363 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
365 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
366 /// chain (aliasing node.)
367 SDValue FindBetterChain(SDNode *N, SDValue Chain);
369 /// Holds a pointer to an LSBaseSDNode as well as information on where it
370 /// is located in a sequence of memory operations connected by a chain.
372 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
373 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
374 // Ptr to the mem node.
375 LSBaseSDNode *MemNode;
376 // Offset from the base ptr.
377 int64_t OffsetFromBase;
378 // What is the sequence number of this mem node.
379 // Lowest mem operand in the DAG starts at zero.
380 unsigned SequenceNum;
383 /// This is a helper function for MergeConsecutiveStores. When the source
384 /// elements of the consecutive stores are all constants or all extracted
385 /// vector elements, try to merge them into one larger store.
386 /// \return True if a merged store was created.
387 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
388 EVT MemVT, unsigned NumElem,
389 bool IsConstantSrc, bool UseVector);
391 /// Merge consecutive store operations into a wide store.
392 /// This optimization uses wide integers or vectors when possible.
393 /// \return True if some memory operations were changed.
394 bool MergeConsecutiveStores(StoreSDNode *N);
396 /// \brief Try to transform a truncation where C is a constant:
397 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
399 /// \p N needs to be a truncation and its first operand an AND. Other
400 /// requirements are checked by the function (e.g. that trunc is
401 /// single-use) and if missed an empty SDValue is returned.
402 SDValue distributeTruncateThroughAnd(SDNode *N);
405 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
406 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
407 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
408 auto *F = DAG.getMachineFunction().getFunction();
409 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
410 F->hasFnAttribute(Attribute::MinSize);
413 /// Runs the dag combiner on all nodes in the work list
414 void Run(CombineLevel AtLevel);
416 SelectionDAG &getDAG() const { return DAG; }
418 /// Returns a type large enough to hold any valid shift amount - before type
419 /// legalization these can be huge.
420 EVT getShiftAmountTy(EVT LHSTy) {
421 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
422 if (LHSTy.isVector())
424 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
425 : TLI.getPointerTy();
428 /// This method returns true if we are running before type legalization or
429 /// if the specified VT is legal.
430 bool isTypeLegal(const EVT &VT) {
431 if (!LegalTypes) return true;
432 return TLI.isTypeLegal(VT);
435 /// Convenience wrapper around TargetLowering::getSetCCResultType
436 EVT getSetCCResultType(EVT VT) const {
437 return TLI.getSetCCResultType(*DAG.getContext(), VT);
444 /// This class is a DAGUpdateListener that removes any deleted
445 /// nodes from the worklist.
446 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
449 explicit WorklistRemover(DAGCombiner &dc)
450 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
452 void NodeDeleted(SDNode *N, SDNode *E) override {
453 DC.removeFromWorklist(N);
458 //===----------------------------------------------------------------------===//
459 // TargetLowering::DAGCombinerInfo implementation
460 //===----------------------------------------------------------------------===//
462 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
463 ((DAGCombiner*)DC)->AddToWorklist(N);
466 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
467 ((DAGCombiner*)DC)->removeFromWorklist(N);
470 SDValue TargetLowering::DAGCombinerInfo::
471 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
472 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
475 SDValue TargetLowering::DAGCombinerInfo::
476 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
477 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
481 SDValue TargetLowering::DAGCombinerInfo::
482 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
483 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
486 void TargetLowering::DAGCombinerInfo::
487 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
488 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
491 //===----------------------------------------------------------------------===//
493 //===----------------------------------------------------------------------===//
495 void DAGCombiner::deleteAndRecombine(SDNode *N) {
496 removeFromWorklist(N);
498 // If the operands of this node are only used by the node, they will now be
499 // dead. Make sure to re-visit them and recursively delete dead nodes.
500 for (const SDValue &Op : N->ops())
501 // For an operand generating multiple values, one of the values may
502 // become dead allowing further simplification (e.g. split index
503 // arithmetic from an indexed load).
504 if (Op->hasOneUse() || Op->getNumValues() > 1)
505 AddToWorklist(Op.getNode());
510 /// Return 1 if we can compute the negated form of the specified expression for
511 /// the same cost as the expression itself, or 2 if we can compute the negated
512 /// form more cheaply than the expression itself.
513 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
514 const TargetLowering &TLI,
515 const TargetOptions *Options,
516 unsigned Depth = 0) {
517 // fneg is removable even if it has multiple uses.
518 if (Op.getOpcode() == ISD::FNEG) return 2;
520 // Don't allow anything with multiple uses.
521 if (!Op.hasOneUse()) return 0;
523 // Don't recurse exponentially.
524 if (Depth > 6) return 0;
526 switch (Op.getOpcode()) {
527 default: return false;
528 case ISD::ConstantFP:
529 // Don't invert constant FP values after legalize. The negated constant
530 // isn't necessarily legal.
531 return LegalOperations ? 0 : 1;
533 // FIXME: determine better conditions for this xform.
534 if (!Options->UnsafeFPMath) return 0;
536 // After operation legalization, it might not be legal to create new FSUBs.
537 if (LegalOperations &&
538 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
541 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
542 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
545 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
546 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
549 // We can't turn -(A-B) into B-A when we honor signed zeros.
550 if (!Options->UnsafeFPMath) return 0;
552 // fold (fneg (fsub A, B)) -> (fsub B, A)
557 if (Options->HonorSignDependentRoundingFPMath()) return 0;
559 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
560 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
564 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
570 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
575 /// If isNegatibleForFree returns true, return the newly negated expression.
576 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
577 bool LegalOperations, unsigned Depth = 0) {
578 const TargetOptions &Options = DAG.getTarget().Options;
579 // fneg is removable even if it has multiple uses.
580 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
582 // Don't allow anything with multiple uses.
583 assert(Op.hasOneUse() && "Unknown reuse!");
585 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
586 switch (Op.getOpcode()) {
587 default: llvm_unreachable("Unknown code");
588 case ISD::ConstantFP: {
589 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
591 return DAG.getConstantFP(V, Op.getValueType());
594 // FIXME: determine better conditions for this xform.
595 assert(Options.UnsafeFPMath);
597 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
598 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
599 DAG.getTargetLoweringInfo(), &Options, Depth+1))
600 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
601 GetNegatedExpression(Op.getOperand(0), DAG,
602 LegalOperations, Depth+1),
604 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
605 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
606 GetNegatedExpression(Op.getOperand(1), DAG,
607 LegalOperations, Depth+1),
610 // We can't turn -(A-B) into B-A when we honor signed zeros.
611 assert(Options.UnsafeFPMath);
613 // fold (fneg (fsub 0, B)) -> B
614 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
615 if (N0CFP->getValueAPF().isZero())
616 return Op.getOperand(1);
618 // fold (fneg (fsub A, B)) -> (fsub B, A)
619 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
620 Op.getOperand(1), Op.getOperand(0));
624 assert(!Options.HonorSignDependentRoundingFPMath());
626 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
627 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
628 DAG.getTargetLoweringInfo(), &Options, Depth+1))
629 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
630 GetNegatedExpression(Op.getOperand(0), DAG,
631 LegalOperations, Depth+1),
634 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
635 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
637 GetNegatedExpression(Op.getOperand(1), DAG,
638 LegalOperations, Depth+1));
642 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
643 GetNegatedExpression(Op.getOperand(0), DAG,
644 LegalOperations, Depth+1));
646 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
647 GetNegatedExpression(Op.getOperand(0), DAG,
648 LegalOperations, Depth+1),
653 // Return true if this node is a setcc, or is a select_cc
654 // that selects between the target values used for true and false, making it
655 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
656 // the appropriate nodes based on the type of node we are checking. This
657 // simplifies life a bit for the callers.
658 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
660 if (N.getOpcode() == ISD::SETCC) {
661 LHS = N.getOperand(0);
662 RHS = N.getOperand(1);
663 CC = N.getOperand(2);
667 if (N.getOpcode() != ISD::SELECT_CC ||
668 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
669 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
672 if (TLI.getBooleanContents(N.getValueType()) ==
673 TargetLowering::UndefinedBooleanContent)
676 LHS = N.getOperand(0);
677 RHS = N.getOperand(1);
678 CC = N.getOperand(4);
682 /// Return true if this is a SetCC-equivalent operation with only one use.
683 /// If this is true, it allows the users to invert the operation for free when
684 /// it is profitable to do so.
685 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
687 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
692 /// Returns true if N is a BUILD_VECTOR node whose
693 /// elements are all the same constant or undefined.
694 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
695 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
700 unsigned SplatBitSize;
702 EVT EltVT = N->getValueType(0).getVectorElementType();
703 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
705 EltVT.getSizeInBits() >= SplatBitSize);
708 // \brief Returns the SDNode if it is a constant BuildVector or constant.
709 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
710 if (isa<ConstantSDNode>(N))
712 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
713 if (BV && BV->isConstant())
718 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
719 if (isa<ConstantSDNode>(N))
721 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
726 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
727 if (isa<ConstantFPSDNode>(N))
729 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
734 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
736 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
737 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
740 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
741 BitVector UndefElements;
742 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
744 // BuildVectors can truncate their operands. Ignore that case here.
745 // FIXME: We blindly ignore splats which include undef which is overly
747 if (CN && UndefElements.none() &&
748 CN->getValueType(0) == N.getValueType().getScalarType())
755 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
757 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
758 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
761 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
762 BitVector UndefElements;
763 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
765 if (CN && UndefElements.none())
772 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
773 SDValue N0, SDValue N1) {
774 EVT VT = N0.getValueType();
775 if (N0.getOpcode() == Opc) {
776 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
777 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
778 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
779 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
780 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
783 if (N0.hasOneUse()) {
784 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
786 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
787 if (!OpNode.getNode())
789 AddToWorklist(OpNode.getNode());
790 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
795 if (N1.getOpcode() == Opc) {
796 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
797 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
798 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
799 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
800 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
803 if (N1.hasOneUse()) {
804 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
806 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
807 if (!OpNode.getNode())
809 AddToWorklist(OpNode.getNode());
810 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
818 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
820 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
822 DEBUG(dbgs() << "\nReplacing.1 ";
824 dbgs() << "\nWith: ";
825 To[0].getNode()->dump(&DAG);
826 dbgs() << " and " << NumTo-1 << " other values\n");
827 for (unsigned i = 0, e = NumTo; i != e; ++i)
828 assert((!To[i].getNode() ||
829 N->getValueType(i) == To[i].getValueType()) &&
830 "Cannot combine value to value of different type!");
832 WorklistRemover DeadNodes(*this);
833 DAG.ReplaceAllUsesWith(N, To);
835 // Push the new nodes and any users onto the worklist
836 for (unsigned i = 0, e = NumTo; i != e; ++i) {
837 if (To[i].getNode()) {
838 AddToWorklist(To[i].getNode());
839 AddUsersToWorklist(To[i].getNode());
844 // Finally, if the node is now dead, remove it from the graph. The node
845 // may not be dead if the replacement process recursively simplified to
846 // something else needing this node.
848 deleteAndRecombine(N);
849 return SDValue(N, 0);
853 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
854 // Replace all uses. If any nodes become isomorphic to other nodes and
855 // are deleted, make sure to remove them from our worklist.
856 WorklistRemover DeadNodes(*this);
857 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
859 // Push the new node and any (possibly new) users onto the worklist.
860 AddToWorklist(TLO.New.getNode());
861 AddUsersToWorklist(TLO.New.getNode());
863 // Finally, if the node is now dead, remove it from the graph. The node
864 // may not be dead if the replacement process recursively simplified to
865 // something else needing this node.
866 if (TLO.Old.getNode()->use_empty())
867 deleteAndRecombine(TLO.Old.getNode());
870 /// Check the specified integer node value to see if it can be simplified or if
871 /// things it uses can be simplified by bit propagation. If so, return true.
872 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
873 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
874 APInt KnownZero, KnownOne;
875 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
879 AddToWorklist(Op.getNode());
881 // Replace the old value with the new one.
883 DEBUG(dbgs() << "\nReplacing.2 ";
884 TLO.Old.getNode()->dump(&DAG);
885 dbgs() << "\nWith: ";
886 TLO.New.getNode()->dump(&DAG);
889 CommitTargetLoweringOpt(TLO);
893 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
895 EVT VT = Load->getValueType(0);
896 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
898 DEBUG(dbgs() << "\nReplacing.9 ";
900 dbgs() << "\nWith: ";
901 Trunc.getNode()->dump(&DAG);
903 WorklistRemover DeadNodes(*this);
904 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
905 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
906 deleteAndRecombine(Load);
907 AddToWorklist(Trunc.getNode());
910 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
913 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
914 EVT MemVT = LD->getMemoryVT();
915 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
916 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
918 : LD->getExtensionType();
920 return DAG.getExtLoad(ExtType, dl, PVT,
921 LD->getChain(), LD->getBasePtr(),
922 MemVT, LD->getMemOperand());
925 unsigned Opc = Op.getOpcode();
928 case ISD::AssertSext:
929 return DAG.getNode(ISD::AssertSext, dl, PVT,
930 SExtPromoteOperand(Op.getOperand(0), PVT),
932 case ISD::AssertZext:
933 return DAG.getNode(ISD::AssertZext, dl, PVT,
934 ZExtPromoteOperand(Op.getOperand(0), PVT),
936 case ISD::Constant: {
938 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
939 return DAG.getNode(ExtOpc, dl, PVT, Op);
943 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
945 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
948 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
949 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 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.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
962 DAG.getValueType(OldVT));
965 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
966 EVT OldVT = Op.getValueType();
968 bool Replace = false;
969 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
970 if (!NewOp.getNode())
972 AddToWorklist(NewOp.getNode());
975 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
976 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
979 /// Promote the specified integer binary operation if the target indicates it is
980 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
981 /// i32 since i16 instructions are longer.
982 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
983 if (!LegalOperations)
986 EVT VT = Op.getValueType();
987 if (VT.isVector() || !VT.isInteger())
990 // If operation type is 'undesirable', e.g. i16 on x86, consider
992 unsigned Opc = Op.getOpcode();
993 if (TLI.isTypeDesirableForOp(Opc, VT))
997 // Consult target whether it is a good idea to promote this operation and
998 // what's the right type to promote it to.
999 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1000 assert(PVT != VT && "Don't know what type to promote to!");
1002 bool Replace0 = false;
1003 SDValue N0 = Op.getOperand(0);
1004 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1008 bool Replace1 = false;
1009 SDValue N1 = Op.getOperand(1);
1014 NN1 = PromoteOperand(N1, PVT, Replace1);
1019 AddToWorklist(NN0.getNode());
1021 AddToWorklist(NN1.getNode());
1024 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1026 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1028 DEBUG(dbgs() << "\nPromoting ";
1029 Op.getNode()->dump(&DAG));
1031 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1032 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1037 /// Promote the specified integer shift operation if the target indicates it is
1038 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1039 /// i32 since i16 instructions are longer.
1040 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1041 if (!LegalOperations)
1044 EVT VT = Op.getValueType();
1045 if (VT.isVector() || !VT.isInteger())
1048 // If operation type is 'undesirable', e.g. i16 on x86, consider
1050 unsigned Opc = Op.getOpcode();
1051 if (TLI.isTypeDesirableForOp(Opc, VT))
1055 // Consult target whether it is a good idea to promote this operation and
1056 // what's the right type to promote it to.
1057 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1058 assert(PVT != VT && "Don't know what type to promote to!");
1060 bool Replace = false;
1061 SDValue N0 = Op.getOperand(0);
1062 if (Opc == ISD::SRA)
1063 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1064 else if (Opc == ISD::SRL)
1065 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1067 N0 = PromoteOperand(N0, PVT, Replace);
1071 AddToWorklist(N0.getNode());
1073 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1075 DEBUG(dbgs() << "\nPromoting ";
1076 Op.getNode()->dump(&DAG));
1078 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1079 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1084 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1085 if (!LegalOperations)
1088 EVT VT = Op.getValueType();
1089 if (VT.isVector() || !VT.isInteger())
1092 // If operation type is 'undesirable', e.g. i16 on x86, consider
1094 unsigned Opc = Op.getOpcode();
1095 if (TLI.isTypeDesirableForOp(Opc, VT))
1099 // Consult target whether it is a good idea to promote this operation and
1100 // what's the right type to promote it to.
1101 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1102 assert(PVT != VT && "Don't know what type to promote to!");
1103 // fold (aext (aext x)) -> (aext x)
1104 // fold (aext (zext x)) -> (zext x)
1105 // fold (aext (sext x)) -> (sext x)
1106 DEBUG(dbgs() << "\nPromoting ";
1107 Op.getNode()->dump(&DAG));
1108 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1113 bool DAGCombiner::PromoteLoad(SDValue Op) {
1114 if (!LegalOperations)
1117 EVT VT = Op.getValueType();
1118 if (VT.isVector() || !VT.isInteger())
1121 // If operation type is 'undesirable', e.g. i16 on x86, consider
1123 unsigned Opc = Op.getOpcode();
1124 if (TLI.isTypeDesirableForOp(Opc, VT))
1128 // Consult target whether it is a good idea to promote this operation and
1129 // what's the right type to promote it to.
1130 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1131 assert(PVT != VT && "Don't know what type to promote to!");
1134 SDNode *N = Op.getNode();
1135 LoadSDNode *LD = cast<LoadSDNode>(N);
1136 EVT MemVT = LD->getMemoryVT();
1137 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1138 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1140 : LD->getExtensionType();
1141 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1142 LD->getChain(), LD->getBasePtr(),
1143 MemVT, LD->getMemOperand());
1144 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1146 DEBUG(dbgs() << "\nPromoting ";
1149 Result.getNode()->dump(&DAG);
1151 WorklistRemover DeadNodes(*this);
1152 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1153 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1154 deleteAndRecombine(N);
1155 AddToWorklist(Result.getNode());
1161 /// \brief Recursively delete a node which has no uses and any operands for
1162 /// which it is the only use.
1164 /// Note that this both deletes the nodes and removes them from the worklist.
1165 /// It also adds any nodes who have had a user deleted to the worklist as they
1166 /// may now have only one use and subject to other combines.
1167 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1168 if (!N->use_empty())
1171 SmallSetVector<SDNode *, 16> Nodes;
1174 N = Nodes.pop_back_val();
1178 if (N->use_empty()) {
1179 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1180 Nodes.insert(N->getOperand(i).getNode());
1182 removeFromWorklist(N);
1187 } while (!Nodes.empty());
1191 //===----------------------------------------------------------------------===//
1192 // Main DAG Combiner implementation
1193 //===----------------------------------------------------------------------===//
1195 void DAGCombiner::Run(CombineLevel AtLevel) {
1196 // set the instance variables, so that the various visit routines may use it.
1198 LegalOperations = Level >= AfterLegalizeVectorOps;
1199 LegalTypes = Level >= AfterLegalizeTypes;
1201 // Add all the dag nodes to the worklist.
1202 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1203 E = DAG.allnodes_end(); I != E; ++I)
1206 // Create a dummy node (which is not added to allnodes), that adds a reference
1207 // to the root node, preventing it from being deleted, and tracking any
1208 // changes of the root.
1209 HandleSDNode Dummy(DAG.getRoot());
1211 // while the worklist isn't empty, find a node and
1212 // try and combine it.
1213 while (!WorklistMap.empty()) {
1215 // The Worklist holds the SDNodes in order, but it may contain null entries.
1217 N = Worklist.pop_back_val();
1220 bool GoodWorklistEntry = WorklistMap.erase(N);
1221 (void)GoodWorklistEntry;
1222 assert(GoodWorklistEntry &&
1223 "Found a worklist entry without a corresponding map entry!");
1225 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1226 // N is deleted from the DAG, since they too may now be dead or may have a
1227 // reduced number of uses, allowing other xforms.
1228 if (recursivelyDeleteUnusedNodes(N))
1231 WorklistRemover DeadNodes(*this);
1233 // If this combine is running after legalizing the DAG, re-legalize any
1234 // nodes pulled off the worklist.
1235 if (Level == AfterLegalizeDAG) {
1236 SmallSetVector<SDNode *, 16> UpdatedNodes;
1237 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1239 for (SDNode *LN : UpdatedNodes) {
1241 AddUsersToWorklist(LN);
1247 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1249 // Add any operands of the new node which have not yet been combined to the
1250 // worklist as well. Because the worklist uniques things already, this
1251 // won't repeatedly process the same operand.
1252 CombinedNodes.insert(N);
1253 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1254 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1255 AddToWorklist(N->getOperand(i).getNode());
1257 SDValue RV = combine(N);
1264 // If we get back the same node we passed in, rather than a new node or
1265 // zero, we know that the node must have defined multiple values and
1266 // CombineTo was used. Since CombineTo takes care of the worklist
1267 // mechanics for us, we have no work to do in this case.
1268 if (RV.getNode() == N)
1271 assert(N->getOpcode() != ISD::DELETED_NODE &&
1272 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1273 "Node was deleted but visit returned new node!");
1275 DEBUG(dbgs() << " ... into: ";
1276 RV.getNode()->dump(&DAG));
1278 // Transfer debug value.
1279 DAG.TransferDbgValues(SDValue(N, 0), RV);
1280 if (N->getNumValues() == RV.getNode()->getNumValues())
1281 DAG.ReplaceAllUsesWith(N, RV.getNode());
1283 assert(N->getValueType(0) == RV.getValueType() &&
1284 N->getNumValues() == 1 && "Type mismatch");
1286 DAG.ReplaceAllUsesWith(N, &OpV);
1289 // Push the new node and any users onto the worklist
1290 AddToWorklist(RV.getNode());
1291 AddUsersToWorklist(RV.getNode());
1293 // Finally, if the node is now dead, remove it from the graph. The node
1294 // may not be dead if the replacement process recursively simplified to
1295 // something else needing this node. This will also take care of adding any
1296 // operands which have lost a user to the worklist.
1297 recursivelyDeleteUnusedNodes(N);
1300 // If the root changed (e.g. it was a dead load, update the root).
1301 DAG.setRoot(Dummy.getValue());
1302 DAG.RemoveDeadNodes();
1305 SDValue DAGCombiner::visit(SDNode *N) {
1306 switch (N->getOpcode()) {
1308 case ISD::TokenFactor: return visitTokenFactor(N);
1309 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1310 case ISD::ADD: return visitADD(N);
1311 case ISD::SUB: return visitSUB(N);
1312 case ISD::ADDC: return visitADDC(N);
1313 case ISD::SUBC: return visitSUBC(N);
1314 case ISD::ADDE: return visitADDE(N);
1315 case ISD::SUBE: return visitSUBE(N);
1316 case ISD::MUL: return visitMUL(N);
1317 case ISD::SDIV: return visitSDIV(N);
1318 case ISD::UDIV: return visitUDIV(N);
1319 case ISD::SREM: return visitSREM(N);
1320 case ISD::UREM: return visitUREM(N);
1321 case ISD::MULHU: return visitMULHU(N);
1322 case ISD::MULHS: return visitMULHS(N);
1323 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1324 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1325 case ISD::SMULO: return visitSMULO(N);
1326 case ISD::UMULO: return visitUMULO(N);
1327 case ISD::SDIVREM: return visitSDIVREM(N);
1328 case ISD::UDIVREM: return visitUDIVREM(N);
1329 case ISD::AND: return visitAND(N);
1330 case ISD::OR: return visitOR(N);
1331 case ISD::XOR: return visitXOR(N);
1332 case ISD::SHL: return visitSHL(N);
1333 case ISD::SRA: return visitSRA(N);
1334 case ISD::SRL: return visitSRL(N);
1336 case ISD::ROTL: return visitRotate(N);
1337 case ISD::CTLZ: return visitCTLZ(N);
1338 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1339 case ISD::CTTZ: return visitCTTZ(N);
1340 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1341 case ISD::CTPOP: return visitCTPOP(N);
1342 case ISD::SELECT: return visitSELECT(N);
1343 case ISD::VSELECT: return visitVSELECT(N);
1344 case ISD::SELECT_CC: return visitSELECT_CC(N);
1345 case ISD::SETCC: return visitSETCC(N);
1346 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1347 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1348 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1349 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1350 case ISD::TRUNCATE: return visitTRUNCATE(N);
1351 case ISD::BITCAST: return visitBITCAST(N);
1352 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1353 case ISD::FADD: return visitFADD(N);
1354 case ISD::FSUB: return visitFSUB(N);
1355 case ISD::FMUL: return visitFMUL(N);
1356 case ISD::FMA: return visitFMA(N);
1357 case ISD::FDIV: return visitFDIV(N);
1358 case ISD::FREM: return visitFREM(N);
1359 case ISD::FSQRT: return visitFSQRT(N);
1360 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1361 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1362 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1363 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1364 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1365 case ISD::FP_ROUND: return visitFP_ROUND(N);
1366 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1367 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1368 case ISD::FNEG: return visitFNEG(N);
1369 case ISD::FABS: return visitFABS(N);
1370 case ISD::FFLOOR: return visitFFLOOR(N);
1371 case ISD::FMINNUM: return visitFMINNUM(N);
1372 case ISD::FMAXNUM: return visitFMAXNUM(N);
1373 case ISD::FCEIL: return visitFCEIL(N);
1374 case ISD::FTRUNC: return visitFTRUNC(N);
1375 case ISD::BRCOND: return visitBRCOND(N);
1376 case ISD::BR_CC: return visitBR_CC(N);
1377 case ISD::LOAD: return visitLOAD(N);
1378 case ISD::STORE: return visitSTORE(N);
1379 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1380 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1381 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1382 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1383 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1384 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1385 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1386 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1387 case ISD::MLOAD: return visitMLOAD(N);
1388 case ISD::MSTORE: return visitMSTORE(N);
1393 SDValue DAGCombiner::combine(SDNode *N) {
1394 SDValue RV = visit(N);
1396 // If nothing happened, try a target-specific DAG combine.
1397 if (!RV.getNode()) {
1398 assert(N->getOpcode() != ISD::DELETED_NODE &&
1399 "Node was deleted but visit returned NULL!");
1401 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1402 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1404 // Expose the DAG combiner to the target combiner impls.
1405 TargetLowering::DAGCombinerInfo
1406 DagCombineInfo(DAG, Level, false, this);
1408 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1412 // If nothing happened still, try promoting the operation.
1413 if (!RV.getNode()) {
1414 switch (N->getOpcode()) {
1422 RV = PromoteIntBinOp(SDValue(N, 0));
1427 RV = PromoteIntShiftOp(SDValue(N, 0));
1429 case ISD::SIGN_EXTEND:
1430 case ISD::ZERO_EXTEND:
1431 case ISD::ANY_EXTEND:
1432 RV = PromoteExtend(SDValue(N, 0));
1435 if (PromoteLoad(SDValue(N, 0)))
1441 // If N is a commutative binary node, try commuting it to enable more
1443 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1444 N->getNumValues() == 1) {
1445 SDValue N0 = N->getOperand(0);
1446 SDValue N1 = N->getOperand(1);
1448 // Constant operands are canonicalized to RHS.
1449 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1450 SDValue Ops[] = {N1, N0};
1452 if (const BinaryWithFlagsSDNode *BinNode =
1453 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1454 CSENode = DAG.getNodeIfExists(
1455 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1456 BinNode->hasNoSignedWrap(), BinNode->isExact());
1458 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1461 return SDValue(CSENode, 0);
1468 /// Given a node, return its input chain if it has one, otherwise return a null
1470 static SDValue getInputChainForNode(SDNode *N) {
1471 if (unsigned NumOps = N->getNumOperands()) {
1472 if (N->getOperand(0).getValueType() == MVT::Other)
1473 return N->getOperand(0);
1474 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1475 return N->getOperand(NumOps-1);
1476 for (unsigned i = 1; i < NumOps-1; ++i)
1477 if (N->getOperand(i).getValueType() == MVT::Other)
1478 return N->getOperand(i);
1483 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1484 // If N has two operands, where one has an input chain equal to the other,
1485 // the 'other' chain is redundant.
1486 if (N->getNumOperands() == 2) {
1487 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1488 return N->getOperand(0);
1489 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1490 return N->getOperand(1);
1493 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1494 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1495 SmallPtrSet<SDNode*, 16> SeenOps;
1496 bool Changed = false; // If we should replace this token factor.
1498 // Start out with this token factor.
1501 // Iterate through token factors. The TFs grows when new token factors are
1503 for (unsigned i = 0; i < TFs.size(); ++i) {
1504 SDNode *TF = TFs[i];
1506 // Check each of the operands.
1507 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1508 SDValue Op = TF->getOperand(i);
1510 switch (Op.getOpcode()) {
1511 case ISD::EntryToken:
1512 // Entry tokens don't need to be added to the list. They are
1517 case ISD::TokenFactor:
1518 if (Op.hasOneUse() &&
1519 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1520 // Queue up for processing.
1521 TFs.push_back(Op.getNode());
1522 // Clean up in case the token factor is removed.
1523 AddToWorklist(Op.getNode());
1530 // Only add if it isn't already in the list.
1531 if (SeenOps.insert(Op.getNode()).second)
1542 // If we've changed things around then replace token factor.
1545 // The entry token is the only possible outcome.
1546 Result = DAG.getEntryNode();
1548 // New and improved token factor.
1549 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1552 // Add users to worklist if AA is enabled, since it may introduce
1553 // a lot of new chained token factors while removing memory deps.
1554 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1555 : DAG.getSubtarget().useAA();
1556 return CombineTo(N, Result, UseAA /*add to worklist*/);
1562 /// MERGE_VALUES can always be eliminated.
1563 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1564 WorklistRemover DeadNodes(*this);
1565 // Replacing results may cause a different MERGE_VALUES to suddenly
1566 // be CSE'd with N, and carry its uses with it. Iterate until no
1567 // uses remain, to ensure that the node can be safely deleted.
1568 // First add the users of this node to the work list so that they
1569 // can be tried again once they have new operands.
1570 AddUsersToWorklist(N);
1572 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1573 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1574 } while (!N->use_empty());
1575 deleteAndRecombine(N);
1576 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1579 SDValue DAGCombiner::visitADD(SDNode *N) {
1580 SDValue N0 = N->getOperand(0);
1581 SDValue N1 = N->getOperand(1);
1582 EVT VT = N0.getValueType();
1585 if (VT.isVector()) {
1586 SDValue FoldedVOp = SimplifyVBinOp(N);
1587 if (FoldedVOp.getNode()) return FoldedVOp;
1589 // fold (add x, 0) -> x, vector edition
1590 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1592 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1596 // fold (add x, undef) -> undef
1597 if (N0.getOpcode() == ISD::UNDEF)
1599 if (N1.getOpcode() == ISD::UNDEF)
1601 // fold (add c1, c2) -> c1+c2
1602 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1603 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1605 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1606 // canonicalize constant to RHS
1608 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1609 // fold (add x, 0) -> x
1610 if (N1C && N1C->isNullValue())
1612 // fold (add Sym, c) -> Sym+c
1613 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1614 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1615 GA->getOpcode() == ISD::GlobalAddress)
1616 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1618 (uint64_t)N1C->getSExtValue());
1619 // fold ((c1-A)+c2) -> (c1+c2)-A
1620 if (N1C && N0.getOpcode() == ISD::SUB)
1621 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1622 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1623 DAG.getConstant(N1C->getAPIntValue()+
1624 N0C->getAPIntValue(), VT),
1627 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1630 // fold ((0-A) + B) -> B-A
1631 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1632 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1633 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1634 // fold (A + (0-B)) -> A-B
1635 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1636 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1637 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1638 // fold (A+(B-A)) -> B
1639 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1640 return N1.getOperand(0);
1641 // fold ((B-A)+A) -> B
1642 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1643 return N0.getOperand(0);
1644 // fold (A+(B-(A+C))) to (B-C)
1645 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1646 N0 == N1.getOperand(1).getOperand(0))
1647 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1648 N1.getOperand(1).getOperand(1));
1649 // fold (A+(B-(C+A))) to (B-C)
1650 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1651 N0 == N1.getOperand(1).getOperand(1))
1652 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1653 N1.getOperand(1).getOperand(0));
1654 // fold (A+((B-A)+or-C)) to (B+or-C)
1655 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1656 N1.getOperand(0).getOpcode() == ISD::SUB &&
1657 N0 == N1.getOperand(0).getOperand(1))
1658 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1659 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1661 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1662 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1663 SDValue N00 = N0.getOperand(0);
1664 SDValue N01 = N0.getOperand(1);
1665 SDValue N10 = N1.getOperand(0);
1666 SDValue N11 = N1.getOperand(1);
1668 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1669 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1670 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1671 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1674 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1675 return SDValue(N, 0);
1677 // fold (a+b) -> (a|b) iff a and b share no bits.
1678 if (VT.isInteger() && !VT.isVector()) {
1679 APInt LHSZero, LHSOne;
1680 APInt RHSZero, RHSOne;
1681 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1683 if (LHSZero.getBoolValue()) {
1684 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1686 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1687 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1688 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1689 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1690 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1695 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1696 if (N1.getOpcode() == ISD::SHL &&
1697 N1.getOperand(0).getOpcode() == ISD::SUB)
1698 if (ConstantSDNode *C =
1699 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1700 if (C->getAPIntValue() == 0)
1701 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1702 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1703 N1.getOperand(0).getOperand(1),
1705 if (N0.getOpcode() == ISD::SHL &&
1706 N0.getOperand(0).getOpcode() == ISD::SUB)
1707 if (ConstantSDNode *C =
1708 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1709 if (C->getAPIntValue() == 0)
1710 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1711 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1712 N0.getOperand(0).getOperand(1),
1715 if (N1.getOpcode() == ISD::AND) {
1716 SDValue AndOp0 = N1.getOperand(0);
1717 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1718 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1719 unsigned DestBits = VT.getScalarType().getSizeInBits();
1721 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1722 // and similar xforms where the inner op is either ~0 or 0.
1723 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1725 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1729 // add (sext i1), X -> sub X, (zext i1)
1730 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1731 N0.getOperand(0).getValueType() == MVT::i1 &&
1732 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1734 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1735 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1738 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1739 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1740 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1741 if (TN->getVT() == MVT::i1) {
1743 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1744 DAG.getConstant(1, VT));
1745 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1752 SDValue DAGCombiner::visitADDC(SDNode *N) {
1753 SDValue N0 = N->getOperand(0);
1754 SDValue N1 = N->getOperand(1);
1755 EVT VT = N0.getValueType();
1757 // If the flag result is dead, turn this into an ADD.
1758 if (!N->hasAnyUseOfValue(1))
1759 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1760 DAG.getNode(ISD::CARRY_FALSE,
1761 SDLoc(N), MVT::Glue));
1763 // canonicalize constant to RHS.
1764 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1765 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1767 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1769 // fold (addc x, 0) -> x + no carry out
1770 if (N1C && N1C->isNullValue())
1771 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1772 SDLoc(N), MVT::Glue));
1774 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1775 APInt LHSZero, LHSOne;
1776 APInt RHSZero, RHSOne;
1777 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1779 if (LHSZero.getBoolValue()) {
1780 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1782 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1783 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1784 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1785 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1786 DAG.getNode(ISD::CARRY_FALSE,
1787 SDLoc(N), MVT::Glue));
1793 SDValue DAGCombiner::visitADDE(SDNode *N) {
1794 SDValue N0 = N->getOperand(0);
1795 SDValue N1 = N->getOperand(1);
1796 SDValue CarryIn = N->getOperand(2);
1798 // canonicalize constant to RHS
1799 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1800 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1802 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1805 // fold (adde x, y, false) -> (addc x, y)
1806 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1807 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1812 // Since it may not be valid to emit a fold to zero for vector initializers
1813 // check if we can before folding.
1814 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1816 bool LegalOperations, bool LegalTypes) {
1818 return DAG.getConstant(0, VT);
1819 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1820 return DAG.getConstant(0, VT);
1824 SDValue DAGCombiner::visitSUB(SDNode *N) {
1825 SDValue N0 = N->getOperand(0);
1826 SDValue N1 = N->getOperand(1);
1827 EVT VT = N0.getValueType();
1830 if (VT.isVector()) {
1831 SDValue FoldedVOp = SimplifyVBinOp(N);
1832 if (FoldedVOp.getNode()) return FoldedVOp;
1834 // fold (sub x, 0) -> x, vector edition
1835 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1839 // fold (sub x, x) -> 0
1840 // FIXME: Refactor this and xor and other similar operations together.
1842 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1843 // fold (sub c1, c2) -> c1-c2
1844 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1845 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1847 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1848 // fold (sub x, c) -> (add x, -c)
1850 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1851 DAG.getConstant(-N1C->getAPIntValue(), VT));
1852 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1853 if (N0C && N0C->isAllOnesValue())
1854 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1855 // fold A-(A-B) -> B
1856 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1857 return N1.getOperand(1);
1858 // fold (A+B)-A -> B
1859 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1860 return N0.getOperand(1);
1861 // fold (A+B)-B -> A
1862 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1863 return N0.getOperand(0);
1864 // fold C2-(A+C1) -> (C2-C1)-A
1865 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1866 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1867 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1868 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1870 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1873 // fold ((A+(B+or-C))-B) -> A+or-C
1874 if (N0.getOpcode() == ISD::ADD &&
1875 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1876 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1877 N0.getOperand(1).getOperand(0) == N1)
1878 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1879 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1880 // fold ((A+(C+B))-B) -> A+C
1881 if (N0.getOpcode() == ISD::ADD &&
1882 N0.getOperand(1).getOpcode() == ISD::ADD &&
1883 N0.getOperand(1).getOperand(1) == N1)
1884 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1885 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1886 // fold ((A-(B-C))-C) -> A-B
1887 if (N0.getOpcode() == ISD::SUB &&
1888 N0.getOperand(1).getOpcode() == ISD::SUB &&
1889 N0.getOperand(1).getOperand(1) == N1)
1890 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1891 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1893 // If either operand of a sub is undef, the result is undef
1894 if (N0.getOpcode() == ISD::UNDEF)
1896 if (N1.getOpcode() == ISD::UNDEF)
1899 // If the relocation model supports it, consider symbol offsets.
1900 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1901 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1902 // fold (sub Sym, c) -> Sym-c
1903 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1904 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1906 (uint64_t)N1C->getSExtValue());
1907 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1908 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1909 if (GA->getGlobal() == GB->getGlobal())
1910 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1914 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1915 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1916 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1917 if (TN->getVT() == MVT::i1) {
1919 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1920 DAG.getConstant(1, VT));
1921 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1928 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1929 SDValue N0 = N->getOperand(0);
1930 SDValue N1 = N->getOperand(1);
1931 EVT VT = N0.getValueType();
1933 // If the flag result is dead, turn this into an SUB.
1934 if (!N->hasAnyUseOfValue(1))
1935 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1936 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1939 // fold (subc x, x) -> 0 + no borrow
1941 return CombineTo(N, DAG.getConstant(0, VT),
1942 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1945 // fold (subc x, 0) -> x + no borrow
1946 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1947 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1948 if (N1C && N1C->isNullValue())
1949 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1952 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1953 if (N0C && N0C->isAllOnesValue())
1954 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1955 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1961 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1962 SDValue N0 = N->getOperand(0);
1963 SDValue N1 = N->getOperand(1);
1964 SDValue CarryIn = N->getOperand(2);
1966 // fold (sube x, y, false) -> (subc x, y)
1967 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1968 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1973 SDValue DAGCombiner::visitMUL(SDNode *N) {
1974 SDValue N0 = N->getOperand(0);
1975 SDValue N1 = N->getOperand(1);
1976 EVT VT = N0.getValueType();
1978 // fold (mul x, undef) -> 0
1979 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1980 return DAG.getConstant(0, VT);
1982 bool N0IsConst = false;
1983 bool N1IsConst = false;
1984 APInt ConstValue0, ConstValue1;
1986 if (VT.isVector()) {
1987 SDValue FoldedVOp = SimplifyVBinOp(N);
1988 if (FoldedVOp.getNode()) return FoldedVOp;
1990 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1991 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1993 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1994 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1996 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1997 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
2001 // fold (mul c1, c2) -> c1*c2
2002 if (N0IsConst && N1IsConst)
2003 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
2005 // canonicalize constant to RHS
2006 if (N0IsConst && !N1IsConst)
2007 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2008 // fold (mul x, 0) -> 0
2009 if (N1IsConst && ConstValue1 == 0)
2011 // We require a splat of the entire scalar bit width for non-contiguous
2014 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2015 // fold (mul x, 1) -> x
2016 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2018 // fold (mul x, -1) -> 0-x
2019 if (N1IsConst && ConstValue1.isAllOnesValue())
2020 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2021 DAG.getConstant(0, VT), N0);
2022 // fold (mul x, (1 << c)) -> x << c
2023 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
2024 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2025 DAG.getConstant(ConstValue1.logBase2(),
2026 getShiftAmountTy(N0.getValueType())));
2027 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2028 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2029 unsigned Log2Val = (-ConstValue1).logBase2();
2030 // FIXME: If the input is something that is easily negated (e.g. a
2031 // single-use add), we should put the negate there.
2032 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2033 DAG.getConstant(0, VT),
2034 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2035 DAG.getConstant(Log2Val,
2036 getShiftAmountTy(N0.getValueType()))));
2040 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2041 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2042 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2043 isa<ConstantSDNode>(N0.getOperand(1)))) {
2044 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2045 N1, N0.getOperand(1));
2046 AddToWorklist(C3.getNode());
2047 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2048 N0.getOperand(0), C3);
2051 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2054 SDValue Sh(nullptr,0), Y(nullptr,0);
2055 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2056 if (N0.getOpcode() == ISD::SHL &&
2057 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2058 isa<ConstantSDNode>(N0.getOperand(1))) &&
2059 N0.getNode()->hasOneUse()) {
2061 } else if (N1.getOpcode() == ISD::SHL &&
2062 isa<ConstantSDNode>(N1.getOperand(1)) &&
2063 N1.getNode()->hasOneUse()) {
2068 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2069 Sh.getOperand(0), Y);
2070 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2071 Mul, Sh.getOperand(1));
2075 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2076 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2077 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2078 isa<ConstantSDNode>(N0.getOperand(1))))
2079 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2080 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2081 N0.getOperand(0), N1),
2082 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2083 N0.getOperand(1), N1));
2086 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2093 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2094 SDValue N0 = N->getOperand(0);
2095 SDValue N1 = N->getOperand(1);
2096 EVT VT = N->getValueType(0);
2099 if (VT.isVector()) {
2100 SDValue FoldedVOp = SimplifyVBinOp(N);
2101 if (FoldedVOp.getNode()) return FoldedVOp;
2104 // fold (sdiv c1, c2) -> c1/c2
2105 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2106 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2107 if (N0C && N1C && !N1C->isNullValue())
2108 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2109 // fold (sdiv X, 1) -> X
2110 if (N1C && N1C->getAPIntValue() == 1LL)
2112 // fold (sdiv X, -1) -> 0-X
2113 if (N1C && N1C->isAllOnesValue())
2114 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2115 DAG.getConstant(0, VT), N0);
2116 // If we know the sign bits of both operands are zero, strength reduce to a
2117 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2118 if (!VT.isVector()) {
2119 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2120 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2124 // fold (sdiv X, pow2) -> simple ops after legalize
2125 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2126 (-N1C->getAPIntValue()).isPowerOf2())) {
2127 // If dividing by powers of two is cheap, then don't perform the following
2129 if (TLI.isPow2SDivCheap())
2132 // Target-specific implementation of sdiv x, pow2.
2133 SDValue Res = BuildSDIVPow2(N);
2137 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2139 // Splat the sign bit into the register
2141 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2142 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2143 getShiftAmountTy(N0.getValueType())));
2144 AddToWorklist(SGN.getNode());
2146 // Add (N0 < 0) ? abs2 - 1 : 0;
2148 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2149 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2150 getShiftAmountTy(SGN.getValueType())));
2151 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2152 AddToWorklist(SRL.getNode());
2153 AddToWorklist(ADD.getNode()); // Divide by pow2
2154 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2155 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2157 // If we're dividing by a positive value, we're done. Otherwise, we must
2158 // negate the result.
2159 if (N1C->getAPIntValue().isNonNegative())
2162 AddToWorklist(SRA.getNode());
2163 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2166 // if integer divide is expensive and we satisfy the requirements, emit an
2167 // alternate sequence.
2168 if (N1C && !TLI.isIntDivCheap()) {
2169 SDValue Op = BuildSDIV(N);
2170 if (Op.getNode()) return Op;
2174 if (N0.getOpcode() == ISD::UNDEF)
2175 return DAG.getConstant(0, VT);
2176 // X / undef -> undef
2177 if (N1.getOpcode() == ISD::UNDEF)
2183 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2184 SDValue N0 = N->getOperand(0);
2185 SDValue N1 = N->getOperand(1);
2186 EVT VT = N->getValueType(0);
2189 if (VT.isVector()) {
2190 SDValue FoldedVOp = SimplifyVBinOp(N);
2191 if (FoldedVOp.getNode()) return FoldedVOp;
2194 // fold (udiv c1, c2) -> c1/c2
2195 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2196 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2197 if (N0C && N1C && !N1C->isNullValue())
2198 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2199 // fold (udiv x, (1 << c)) -> x >>u c
2200 if (N1C && N1C->getAPIntValue().isPowerOf2())
2201 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2202 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2203 getShiftAmountTy(N0.getValueType())));
2204 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2205 if (N1.getOpcode() == ISD::SHL) {
2206 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2207 if (SHC->getAPIntValue().isPowerOf2()) {
2208 EVT ADDVT = N1.getOperand(1).getValueType();
2209 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2211 DAG.getConstant(SHC->getAPIntValue()
2214 AddToWorklist(Add.getNode());
2215 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2219 // fold (udiv x, c) -> alternate
2220 if (N1C && !TLI.isIntDivCheap()) {
2221 SDValue Op = BuildUDIV(N);
2222 if (Op.getNode()) return Op;
2226 if (N0.getOpcode() == ISD::UNDEF)
2227 return DAG.getConstant(0, VT);
2228 // X / undef -> undef
2229 if (N1.getOpcode() == ISD::UNDEF)
2235 SDValue DAGCombiner::visitSREM(SDNode *N) {
2236 SDValue N0 = N->getOperand(0);
2237 SDValue N1 = N->getOperand(1);
2238 EVT VT = N->getValueType(0);
2240 // fold (srem c1, c2) -> c1%c2
2241 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2242 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2243 if (N0C && N1C && !N1C->isNullValue())
2244 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2245 // If we know the sign bits of both operands are zero, strength reduce to a
2246 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2247 if (!VT.isVector()) {
2248 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2249 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2252 // If X/C can be simplified by the division-by-constant logic, lower
2253 // X%C to the equivalent of X-X/C*C.
2254 if (N1C && !N1C->isNullValue()) {
2255 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2256 AddToWorklist(Div.getNode());
2257 SDValue OptimizedDiv = combine(Div.getNode());
2258 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2259 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2261 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2262 AddToWorklist(Mul.getNode());
2268 if (N0.getOpcode() == ISD::UNDEF)
2269 return DAG.getConstant(0, VT);
2270 // X % undef -> undef
2271 if (N1.getOpcode() == ISD::UNDEF)
2277 SDValue DAGCombiner::visitUREM(SDNode *N) {
2278 SDValue N0 = N->getOperand(0);
2279 SDValue N1 = N->getOperand(1);
2280 EVT VT = N->getValueType(0);
2282 // fold (urem c1, c2) -> c1%c2
2283 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2284 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2285 if (N0C && N1C && !N1C->isNullValue())
2286 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2287 // fold (urem x, pow2) -> (and x, pow2-1)
2288 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2289 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2290 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2291 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2292 if (N1.getOpcode() == ISD::SHL) {
2293 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2294 if (SHC->getAPIntValue().isPowerOf2()) {
2296 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2297 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2299 AddToWorklist(Add.getNode());
2300 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2305 // If X/C can be simplified by the division-by-constant logic, lower
2306 // X%C to the equivalent of X-X/C*C.
2307 if (N1C && !N1C->isNullValue()) {
2308 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2309 AddToWorklist(Div.getNode());
2310 SDValue OptimizedDiv = combine(Div.getNode());
2311 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2312 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2314 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2315 AddToWorklist(Mul.getNode());
2321 if (N0.getOpcode() == ISD::UNDEF)
2322 return DAG.getConstant(0, VT);
2323 // X % undef -> undef
2324 if (N1.getOpcode() == ISD::UNDEF)
2330 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2331 SDValue N0 = N->getOperand(0);
2332 SDValue N1 = N->getOperand(1);
2333 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2334 EVT VT = N->getValueType(0);
2337 // fold (mulhs x, 0) -> 0
2338 if (N1C && N1C->isNullValue())
2340 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2341 if (N1C && N1C->getAPIntValue() == 1)
2342 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2343 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2344 getShiftAmountTy(N0.getValueType())));
2345 // fold (mulhs x, undef) -> 0
2346 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2347 return DAG.getConstant(0, VT);
2349 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2351 if (VT.isSimple() && !VT.isVector()) {
2352 MVT Simple = VT.getSimpleVT();
2353 unsigned SimpleSize = Simple.getSizeInBits();
2354 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2355 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2356 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2357 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2358 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2359 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2360 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2361 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2368 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2369 SDValue N0 = N->getOperand(0);
2370 SDValue N1 = N->getOperand(1);
2371 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2372 EVT VT = N->getValueType(0);
2375 // fold (mulhu x, 0) -> 0
2376 if (N1C && N1C->isNullValue())
2378 // fold (mulhu x, 1) -> 0
2379 if (N1C && N1C->getAPIntValue() == 1)
2380 return DAG.getConstant(0, N0.getValueType());
2381 // fold (mulhu x, undef) -> 0
2382 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2383 return DAG.getConstant(0, VT);
2385 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2387 if (VT.isSimple() && !VT.isVector()) {
2388 MVT Simple = VT.getSimpleVT();
2389 unsigned SimpleSize = Simple.getSizeInBits();
2390 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2391 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2392 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2393 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2394 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2395 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2396 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2397 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2404 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2405 /// give the opcodes for the two computations that are being performed. Return
2406 /// true if a simplification was made.
2407 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2409 // If the high half is not needed, just compute the low half.
2410 bool HiExists = N->hasAnyUseOfValue(1);
2412 (!LegalOperations ||
2413 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2414 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2415 return CombineTo(N, Res, Res);
2418 // If the low half is not needed, just compute the high half.
2419 bool LoExists = N->hasAnyUseOfValue(0);
2421 (!LegalOperations ||
2422 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2423 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2424 return CombineTo(N, Res, Res);
2427 // If both halves are used, return as it is.
2428 if (LoExists && HiExists)
2431 // If the two computed results can be simplified separately, separate them.
2433 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2434 AddToWorklist(Lo.getNode());
2435 SDValue LoOpt = combine(Lo.getNode());
2436 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2437 (!LegalOperations ||
2438 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2439 return CombineTo(N, LoOpt, LoOpt);
2443 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2444 AddToWorklist(Hi.getNode());
2445 SDValue HiOpt = combine(Hi.getNode());
2446 if (HiOpt.getNode() && HiOpt != Hi &&
2447 (!LegalOperations ||
2448 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2449 return CombineTo(N, HiOpt, HiOpt);
2455 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2456 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2457 if (Res.getNode()) return Res;
2459 EVT VT = N->getValueType(0);
2462 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2464 if (VT.isSimple() && !VT.isVector()) {
2465 MVT Simple = VT.getSimpleVT();
2466 unsigned SimpleSize = Simple.getSizeInBits();
2467 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2468 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2469 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2470 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2471 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2472 // Compute the high part as N1.
2473 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2474 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2475 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2476 // Compute the low part as N0.
2477 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2478 return CombineTo(N, Lo, Hi);
2485 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2486 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2487 if (Res.getNode()) return Res;
2489 EVT VT = N->getValueType(0);
2492 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2494 if (VT.isSimple() && !VT.isVector()) {
2495 MVT Simple = VT.getSimpleVT();
2496 unsigned SimpleSize = Simple.getSizeInBits();
2497 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2498 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2499 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2500 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2501 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2502 // Compute the high part as N1.
2503 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2504 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2505 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2506 // Compute the low part as N0.
2507 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2508 return CombineTo(N, Lo, Hi);
2515 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2516 // (smulo x, 2) -> (saddo x, x)
2517 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2518 if (C2->getAPIntValue() == 2)
2519 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2520 N->getOperand(0), N->getOperand(0));
2525 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2526 // (umulo x, 2) -> (uaddo x, x)
2527 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2528 if (C2->getAPIntValue() == 2)
2529 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2530 N->getOperand(0), N->getOperand(0));
2535 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2536 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2537 if (Res.getNode()) return Res;
2542 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2543 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2544 if (Res.getNode()) return Res;
2549 /// If this is a binary operator with two operands of the same opcode, try to
2551 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2552 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2553 EVT VT = N0.getValueType();
2554 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2556 // Bail early if none of these transforms apply.
2557 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2559 // For each of OP in AND/OR/XOR:
2560 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2561 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2562 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2563 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2564 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2566 // do not sink logical op inside of a vector extend, since it may combine
2568 EVT Op0VT = N0.getOperand(0).getValueType();
2569 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2570 N0.getOpcode() == ISD::SIGN_EXTEND ||
2571 N0.getOpcode() == ISD::BSWAP ||
2572 // Avoid infinite looping with PromoteIntBinOp.
2573 (N0.getOpcode() == ISD::ANY_EXTEND &&
2574 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2575 (N0.getOpcode() == ISD::TRUNCATE &&
2576 (!TLI.isZExtFree(VT, Op0VT) ||
2577 !TLI.isTruncateFree(Op0VT, VT)) &&
2578 TLI.isTypeLegal(Op0VT))) &&
2580 Op0VT == N1.getOperand(0).getValueType() &&
2581 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2582 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2583 N0.getOperand(0).getValueType(),
2584 N0.getOperand(0), N1.getOperand(0));
2585 AddToWorklist(ORNode.getNode());
2586 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2589 // For each of OP in SHL/SRL/SRA/AND...
2590 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2591 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2592 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2593 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2594 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2595 N0.getOperand(1) == N1.getOperand(1)) {
2596 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2597 N0.getOperand(0).getValueType(),
2598 N0.getOperand(0), N1.getOperand(0));
2599 AddToWorklist(ORNode.getNode());
2600 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2601 ORNode, N0.getOperand(1));
2604 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2605 // Only perform this optimization after type legalization and before
2606 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2607 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2608 // we don't want to undo this promotion.
2609 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2611 if ((N0.getOpcode() == ISD::BITCAST ||
2612 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2613 Level == AfterLegalizeTypes) {
2614 SDValue In0 = N0.getOperand(0);
2615 SDValue In1 = N1.getOperand(0);
2616 EVT In0Ty = In0.getValueType();
2617 EVT In1Ty = In1.getValueType();
2619 // If both incoming values are integers, and the original types are the
2621 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2622 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2623 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2624 AddToWorklist(Op.getNode());
2629 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2630 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2631 // If both shuffles use the same mask, and both shuffle within a single
2632 // vector, then it is worthwhile to move the swizzle after the operation.
2633 // The type-legalizer generates this pattern when loading illegal
2634 // vector types from memory. In many cases this allows additional shuffle
2636 // There are other cases where moving the shuffle after the xor/and/or
2637 // is profitable even if shuffles don't perform a swizzle.
2638 // If both shuffles use the same mask, and both shuffles have the same first
2639 // or second operand, then it might still be profitable to move the shuffle
2640 // after the xor/and/or operation.
2641 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2642 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2643 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2645 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2646 "Inputs to shuffles are not the same type");
2648 // Check that both shuffles use the same mask. The masks are known to be of
2649 // the same length because the result vector type is the same.
2650 // Check also that shuffles have only one use to avoid introducing extra
2652 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2653 SVN0->getMask().equals(SVN1->getMask())) {
2654 SDValue ShOp = N0->getOperand(1);
2656 // Don't try to fold this node if it requires introducing a
2657 // build vector of all zeros that might be illegal at this stage.
2658 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2660 ShOp = DAG.getConstant(0, VT);
2665 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2666 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2667 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2668 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2669 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2670 N0->getOperand(0), N1->getOperand(0));
2671 AddToWorklist(NewNode.getNode());
2672 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2673 &SVN0->getMask()[0]);
2676 // Don't try to fold this node if it requires introducing a
2677 // build vector of all zeros that might be illegal at this stage.
2678 ShOp = N0->getOperand(0);
2679 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2681 ShOp = DAG.getConstant(0, VT);
2686 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2687 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2688 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2689 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2690 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2691 N0->getOperand(1), N1->getOperand(1));
2692 AddToWorklist(NewNode.getNode());
2693 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2694 &SVN0->getMask()[0]);
2702 /// This contains all DAGCombine rules which reduce two values combined by
2703 /// an And operation to a single value. This makes them reusable in the context
2704 /// of visitSELECT(). Rules involving constants are not included as
2705 /// visitSELECT() already handles those cases.
2706 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2707 SDNode *LocReference) {
2708 EVT VT = N1.getValueType();
2710 // fold (and x, undef) -> 0
2711 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2712 return DAG.getConstant(0, VT);
2713 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2714 SDValue LL, LR, RL, RR, CC0, CC1;
2715 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2716 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2717 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2719 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2720 LL.getValueType().isInteger()) {
2721 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2722 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2723 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2724 LR.getValueType(), LL, RL);
2725 AddToWorklist(ORNode.getNode());
2726 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2728 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2729 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2730 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2731 LR.getValueType(), LL, RL);
2732 AddToWorklist(ANDNode.getNode());
2733 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2735 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2736 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2737 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2738 LR.getValueType(), LL, RL);
2739 AddToWorklist(ORNode.getNode());
2740 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2743 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2744 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2745 Op0 == Op1 && LL.getValueType().isInteger() &&
2746 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2747 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2748 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2749 cast<ConstantSDNode>(RR)->isNullValue()))) {
2750 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2751 LL, DAG.getConstant(1, LL.getValueType()));
2752 AddToWorklist(ADDNode.getNode());
2753 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2754 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2756 // canonicalize equivalent to ll == rl
2757 if (LL == RR && LR == RL) {
2758 Op1 = ISD::getSetCCSwappedOperands(Op1);
2761 if (LL == RL && LR == RR) {
2762 bool isInteger = LL.getValueType().isInteger();
2763 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2764 if (Result != ISD::SETCC_INVALID &&
2765 (!LegalOperations ||
2766 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2767 TLI.isOperationLegal(ISD::SETCC,
2768 getSetCCResultType(N0.getSimpleValueType())))))
2769 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2774 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2775 VT.getSizeInBits() <= 64) {
2776 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2777 APInt ADDC = ADDI->getAPIntValue();
2778 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2779 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2780 // immediate for an add, but it is legal if its top c2 bits are set,
2781 // transform the ADD so the immediate doesn't need to be materialized
2783 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2784 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2785 SRLI->getZExtValue());
2786 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2788 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2790 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2791 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2792 CombineTo(N0.getNode(), NewAdd);
2793 // Return N so it doesn't get rechecked!
2794 return SDValue(LocReference, 0);
2805 SDValue DAGCombiner::visitAND(SDNode *N) {
2806 SDValue N0 = N->getOperand(0);
2807 SDValue N1 = N->getOperand(1);
2808 EVT VT = N1.getValueType();
2811 if (VT.isVector()) {
2812 SDValue FoldedVOp = SimplifyVBinOp(N);
2813 if (FoldedVOp.getNode()) return FoldedVOp;
2815 // fold (and x, 0) -> 0, vector edition
2816 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2817 // do not return N0, because undef node may exist in N0
2818 return DAG.getConstant(
2819 APInt::getNullValue(
2820 N0.getValueType().getScalarType().getSizeInBits()),
2822 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2823 // do not return N1, because undef node may exist in N1
2824 return DAG.getConstant(
2825 APInt::getNullValue(
2826 N1.getValueType().getScalarType().getSizeInBits()),
2829 // fold (and x, -1) -> x, vector edition
2830 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2832 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2836 // fold (and c1, c2) -> c1&c2
2837 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2838 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2840 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2841 // canonicalize constant to RHS
2843 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2844 // fold (and x, -1) -> x
2845 if (N1C && N1C->isAllOnesValue())
2847 // if (and x, c) is known to be zero, return 0
2848 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2849 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2850 APInt::getAllOnesValue(BitWidth)))
2851 return DAG.getConstant(0, VT);
2853 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2856 // fold (and (or x, C), D) -> D if (C & D) == D
2857 if (N1C && N0.getOpcode() == ISD::OR)
2858 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2859 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2861 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2862 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2863 SDValue N0Op0 = N0.getOperand(0);
2864 APInt Mask = ~N1C->getAPIntValue();
2865 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2866 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2867 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2868 N0.getValueType(), N0Op0);
2870 // Replace uses of the AND with uses of the Zero extend node.
2873 // We actually want to replace all uses of the any_extend with the
2874 // zero_extend, to avoid duplicating things. This will later cause this
2875 // AND to be folded.
2876 CombineTo(N0.getNode(), Zext);
2877 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2880 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2881 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2882 // already be zero by virtue of the width of the base type of the load.
2884 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2886 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2887 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2888 N0.getOpcode() == ISD::LOAD) {
2889 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2890 N0 : N0.getOperand(0) );
2892 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2893 // This can be a pure constant or a vector splat, in which case we treat the
2894 // vector as a scalar and use the splat value.
2895 APInt Constant = APInt::getNullValue(1);
2896 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2897 Constant = C->getAPIntValue();
2898 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2899 APInt SplatValue, SplatUndef;
2900 unsigned SplatBitSize;
2902 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2903 SplatBitSize, HasAnyUndefs);
2905 // Undef bits can contribute to a possible optimisation if set, so
2907 SplatValue |= SplatUndef;
2909 // The splat value may be something like "0x00FFFFFF", which means 0 for
2910 // the first vector value and FF for the rest, repeating. We need a mask
2911 // that will apply equally to all members of the vector, so AND all the
2912 // lanes of the constant together.
2913 EVT VT = Vector->getValueType(0);
2914 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2916 // If the splat value has been compressed to a bitlength lower
2917 // than the size of the vector lane, we need to re-expand it to
2919 if (BitWidth > SplatBitSize)
2920 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2921 SplatBitSize < BitWidth;
2922 SplatBitSize = SplatBitSize * 2)
2923 SplatValue |= SplatValue.shl(SplatBitSize);
2925 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2926 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2927 if (SplatBitSize % BitWidth == 0) {
2928 Constant = APInt::getAllOnesValue(BitWidth);
2929 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2930 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2935 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2936 // actually legal and isn't going to get expanded, else this is a false
2938 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2939 Load->getValueType(0),
2940 Load->getMemoryVT());
2942 // Resize the constant to the same size as the original memory access before
2943 // extension. If it is still the AllOnesValue then this AND is completely
2946 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2949 switch (Load->getExtensionType()) {
2950 default: B = false; break;
2951 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2953 case ISD::NON_EXTLOAD: B = true; break;
2956 if (B && Constant.isAllOnesValue()) {
2957 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2958 // preserve semantics once we get rid of the AND.
2959 SDValue NewLoad(Load, 0);
2960 if (Load->getExtensionType() == ISD::EXTLOAD) {
2961 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2962 Load->getValueType(0), SDLoc(Load),
2963 Load->getChain(), Load->getBasePtr(),
2964 Load->getOffset(), Load->getMemoryVT(),
2965 Load->getMemOperand());
2966 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2967 if (Load->getNumValues() == 3) {
2968 // PRE/POST_INC loads have 3 values.
2969 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2970 NewLoad.getValue(2) };
2971 CombineTo(Load, To, 3, true);
2973 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2977 // Fold the AND away, taking care not to fold to the old load node if we
2979 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2981 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2985 // fold (and (load x), 255) -> (zextload x, i8)
2986 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2987 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2988 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2989 (N0.getOpcode() == ISD::ANY_EXTEND &&
2990 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2991 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2992 LoadSDNode *LN0 = HasAnyExt
2993 ? cast<LoadSDNode>(N0.getOperand(0))
2994 : cast<LoadSDNode>(N0);
2995 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2996 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2997 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2998 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2999 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3000 EVT LoadedVT = LN0->getMemoryVT();
3001 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3003 if (ExtVT == LoadedVT &&
3004 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3008 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3009 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3010 LN0->getMemOperand());
3012 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3013 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3016 // Do not change the width of a volatile load.
3017 // Do not generate loads of non-round integer types since these can
3018 // be expensive (and would be wrong if the type is not byte sized).
3019 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3020 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3022 EVT PtrType = LN0->getOperand(1).getValueType();
3024 unsigned Alignment = LN0->getAlignment();
3025 SDValue NewPtr = LN0->getBasePtr();
3027 // For big endian targets, we need to add an offset to the pointer
3028 // to load the correct bytes. For little endian systems, we merely
3029 // need to read fewer bytes from the same pointer.
3030 if (TLI.isBigEndian()) {
3031 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3032 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3033 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3034 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3035 NewPtr, DAG.getConstant(PtrOff, PtrType));
3036 Alignment = MinAlign(Alignment, PtrOff);
3039 AddToWorklist(NewPtr.getNode());
3042 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3043 LN0->getChain(), NewPtr,
3044 LN0->getPointerInfo(),
3045 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3046 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3048 CombineTo(LN0, Load, Load.getValue(1));
3049 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3055 if (SDValue Combined = visitANDLike(N0, N1, N))
3058 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3059 if (N0.getOpcode() == N1.getOpcode()) {
3060 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3061 if (Tmp.getNode()) return Tmp;
3064 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3065 // fold (and (sra)) -> (and (srl)) when possible.
3066 if (!VT.isVector() &&
3067 SimplifyDemandedBits(SDValue(N, 0)))
3068 return SDValue(N, 0);
3070 // fold (zext_inreg (extload x)) -> (zextload x)
3071 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3072 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3073 EVT MemVT = LN0->getMemoryVT();
3074 // If we zero all the possible extended bits, then we can turn this into
3075 // a zextload if we are running before legalize or the operation is legal.
3076 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3077 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3078 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3079 ((!LegalOperations && !LN0->isVolatile()) ||
3080 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3081 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3082 LN0->getChain(), LN0->getBasePtr(),
3083 MemVT, LN0->getMemOperand());
3085 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3086 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3089 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3090 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3092 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3093 EVT MemVT = LN0->getMemoryVT();
3094 // If we zero all the possible extended bits, then we can turn this into
3095 // a zextload if we are running before legalize or the operation is legal.
3096 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3097 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3098 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3099 ((!LegalOperations && !LN0->isVolatile()) ||
3100 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3101 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3102 LN0->getChain(), LN0->getBasePtr(),
3103 MemVT, LN0->getMemOperand());
3105 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3106 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3109 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3110 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3111 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3112 N0.getOperand(1), false);
3113 if (BSwap.getNode())
3120 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3121 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3122 bool DemandHighBits) {
3123 if (!LegalOperations)
3126 EVT VT = N->getValueType(0);
3127 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3129 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3132 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3133 bool LookPassAnd0 = false;
3134 bool LookPassAnd1 = false;
3135 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3137 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3139 if (N0.getOpcode() == ISD::AND) {
3140 if (!N0.getNode()->hasOneUse())
3142 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3143 if (!N01C || N01C->getZExtValue() != 0xFF00)
3145 N0 = N0.getOperand(0);
3146 LookPassAnd0 = true;
3149 if (N1.getOpcode() == ISD::AND) {
3150 if (!N1.getNode()->hasOneUse())
3152 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3153 if (!N11C || N11C->getZExtValue() != 0xFF)
3155 N1 = N1.getOperand(0);
3156 LookPassAnd1 = true;
3159 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3161 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3163 if (!N0.getNode()->hasOneUse() ||
3164 !N1.getNode()->hasOneUse())
3167 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3168 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3171 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3174 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3175 SDValue N00 = N0->getOperand(0);
3176 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3177 if (!N00.getNode()->hasOneUse())
3179 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3180 if (!N001C || N001C->getZExtValue() != 0xFF)
3182 N00 = N00.getOperand(0);
3183 LookPassAnd0 = true;
3186 SDValue N10 = N1->getOperand(0);
3187 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3188 if (!N10.getNode()->hasOneUse())
3190 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3191 if (!N101C || N101C->getZExtValue() != 0xFF00)
3193 N10 = N10.getOperand(0);
3194 LookPassAnd1 = true;
3200 // Make sure everything beyond the low halfword gets set to zero since the SRL
3201 // 16 will clear the top bits.
3202 unsigned OpSizeInBits = VT.getSizeInBits();
3203 if (DemandHighBits && OpSizeInBits > 16) {
3204 // If the left-shift isn't masked out then the only way this is a bswap is
3205 // if all bits beyond the low 8 are 0. In that case the entire pattern
3206 // reduces to a left shift anyway: leave it for other parts of the combiner.
3210 // However, if the right shift isn't masked out then it might be because
3211 // it's not needed. See if we can spot that too.
3212 if (!LookPassAnd1 &&
3213 !DAG.MaskedValueIsZero(
3214 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3218 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3219 if (OpSizeInBits > 16)
3220 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3221 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3225 /// Return true if the specified node is an element that makes up a 32-bit
3226 /// packed halfword byteswap.
3227 /// ((x & 0x000000ff) << 8) |
3228 /// ((x & 0x0000ff00) >> 8) |
3229 /// ((x & 0x00ff0000) << 8) |
3230 /// ((x & 0xff000000) >> 8)
3231 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3232 if (!N.getNode()->hasOneUse())
3235 unsigned Opc = N.getOpcode();
3236 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3239 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3244 switch (N1C->getZExtValue()) {
3247 case 0xFF: Num = 0; break;
3248 case 0xFF00: Num = 1; break;
3249 case 0xFF0000: Num = 2; break;
3250 case 0xFF000000: Num = 3; break;
3253 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3254 SDValue N0 = N.getOperand(0);
3255 if (Opc == ISD::AND) {
3256 if (Num == 0 || Num == 2) {
3258 // (x >> 8) & 0xff0000
3259 if (N0.getOpcode() != ISD::SRL)
3261 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3262 if (!C || C->getZExtValue() != 8)
3265 // (x << 8) & 0xff00
3266 // (x << 8) & 0xff000000
3267 if (N0.getOpcode() != ISD::SHL)
3269 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3270 if (!C || C->getZExtValue() != 8)
3273 } else if (Opc == ISD::SHL) {
3275 // (x & 0xff0000) << 8
3276 if (Num != 0 && Num != 2)
3278 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3279 if (!C || C->getZExtValue() != 8)
3281 } else { // Opc == ISD::SRL
3282 // (x & 0xff00) >> 8
3283 // (x & 0xff000000) >> 8
3284 if (Num != 1 && Num != 3)
3286 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3287 if (!C || C->getZExtValue() != 8)
3294 Parts[Num] = N0.getOperand(0).getNode();
3298 /// Match a 32-bit packed halfword bswap. That is
3299 /// ((x & 0x000000ff) << 8) |
3300 /// ((x & 0x0000ff00) >> 8) |
3301 /// ((x & 0x00ff0000) << 8) |
3302 /// ((x & 0xff000000) >> 8)
3303 /// => (rotl (bswap x), 16)
3304 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3305 if (!LegalOperations)
3308 EVT VT = N->getValueType(0);
3311 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3315 // (or (or (and), (and)), (or (and), (and)))
3316 // (or (or (or (and), (and)), (and)), (and))
3317 if (N0.getOpcode() != ISD::OR)
3319 SDValue N00 = N0.getOperand(0);
3320 SDValue N01 = N0.getOperand(1);
3321 SDNode *Parts[4] = {};
3323 if (N1.getOpcode() == ISD::OR &&
3324 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3325 // (or (or (and), (and)), (or (and), (and)))
3326 SDValue N000 = N00.getOperand(0);
3327 if (!isBSwapHWordElement(N000, Parts))
3330 SDValue N001 = N00.getOperand(1);
3331 if (!isBSwapHWordElement(N001, Parts))
3333 SDValue N010 = N01.getOperand(0);
3334 if (!isBSwapHWordElement(N010, Parts))
3336 SDValue N011 = N01.getOperand(1);
3337 if (!isBSwapHWordElement(N011, Parts))
3340 // (or (or (or (and), (and)), (and)), (and))
3341 if (!isBSwapHWordElement(N1, Parts))
3343 if (!isBSwapHWordElement(N01, Parts))
3345 if (N00.getOpcode() != ISD::OR)
3347 SDValue N000 = N00.getOperand(0);
3348 if (!isBSwapHWordElement(N000, Parts))
3350 SDValue N001 = N00.getOperand(1);
3351 if (!isBSwapHWordElement(N001, Parts))
3355 // Make sure the parts are all coming from the same node.
3356 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3359 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3360 SDValue(Parts[0],0));
3362 // Result of the bswap should be rotated by 16. If it's not legal, then
3363 // do (x << 16) | (x >> 16).
3364 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3365 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3366 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3367 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3368 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3369 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3370 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3371 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3374 /// This contains all DAGCombine rules which reduce two values combined by
3375 /// an Or operation to a single value \see visitANDLike().
3376 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3377 EVT VT = N1.getValueType();
3378 // fold (or x, undef) -> -1
3379 if (!LegalOperations &&
3380 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3381 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3382 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3384 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3385 SDValue LL, LR, RL, RR, CC0, CC1;
3386 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3387 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3388 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3390 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3391 LL.getValueType().isInteger()) {
3392 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3393 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3394 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3395 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3396 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3397 LR.getValueType(), LL, RL);
3398 AddToWorklist(ORNode.getNode());
3399 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3401 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3402 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3403 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3404 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3405 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3406 LR.getValueType(), LL, RL);
3407 AddToWorklist(ANDNode.getNode());
3408 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3411 // canonicalize equivalent to ll == rl
3412 if (LL == RR && LR == RL) {
3413 Op1 = ISD::getSetCCSwappedOperands(Op1);
3416 if (LL == RL && LR == RR) {
3417 bool isInteger = LL.getValueType().isInteger();
3418 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3419 if (Result != ISD::SETCC_INVALID &&
3420 (!LegalOperations ||
3421 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3422 TLI.isOperationLegal(ISD::SETCC,
3423 getSetCCResultType(N0.getValueType())))))
3424 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3429 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3430 if (N0.getOpcode() == ISD::AND &&
3431 N1.getOpcode() == ISD::AND &&
3432 N0.getOperand(1).getOpcode() == ISD::Constant &&
3433 N1.getOperand(1).getOpcode() == ISD::Constant &&
3434 // Don't increase # computations.
3435 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3436 // We can only do this xform if we know that bits from X that are set in C2
3437 // but not in C1 are already zero. Likewise for Y.
3438 const APInt &LHSMask =
3439 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3440 const APInt &RHSMask =
3441 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3443 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3444 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3445 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3446 N0.getOperand(0), N1.getOperand(0));
3447 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X,
3448 DAG.getConstant(LHSMask | RHSMask, VT));
3452 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3453 if (N0.getOpcode() == ISD::AND &&
3454 N1.getOpcode() == ISD::AND &&
3455 N0.getOperand(0) == N1.getOperand(0) &&
3456 // Don't increase # computations.
3457 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3458 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3459 N0.getOperand(1), N1.getOperand(1));
3460 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3466 SDValue DAGCombiner::visitOR(SDNode *N) {
3467 SDValue N0 = N->getOperand(0);
3468 SDValue N1 = N->getOperand(1);
3469 EVT VT = N1.getValueType();
3472 if (VT.isVector()) {
3473 SDValue FoldedVOp = SimplifyVBinOp(N);
3474 if (FoldedVOp.getNode()) return FoldedVOp;
3476 // fold (or x, 0) -> x, vector edition
3477 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3479 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3482 // fold (or x, -1) -> -1, vector edition
3483 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3484 // do not return N0, because undef node may exist in N0
3485 return DAG.getConstant(
3486 APInt::getAllOnesValue(
3487 N0.getValueType().getScalarType().getSizeInBits()),
3489 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3490 // do not return N1, because undef node may exist in N1
3491 return DAG.getConstant(
3492 APInt::getAllOnesValue(
3493 N1.getValueType().getScalarType().getSizeInBits()),
3496 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3497 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3498 // Do this only if the resulting shuffle is legal.
3499 if (isa<ShuffleVectorSDNode>(N0) &&
3500 isa<ShuffleVectorSDNode>(N1) &&
3501 // Avoid folding a node with illegal type.
3502 TLI.isTypeLegal(VT) &&
3503 N0->getOperand(1) == N1->getOperand(1) &&
3504 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3505 bool CanFold = true;
3506 unsigned NumElts = VT.getVectorNumElements();
3507 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3508 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3509 // We construct two shuffle masks:
3510 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3511 // and N1 as the second operand.
3512 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3513 // and N0 as the second operand.
3514 // We do this because OR is commutable and therefore there might be
3515 // two ways to fold this node into a shuffle.
3516 SmallVector<int,4> Mask1;
3517 SmallVector<int,4> Mask2;
3519 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3520 int M0 = SV0->getMaskElt(i);
3521 int M1 = SV1->getMaskElt(i);
3523 // Both shuffle indexes are undef. Propagate Undef.
3524 if (M0 < 0 && M1 < 0) {
3525 Mask1.push_back(M0);
3526 Mask2.push_back(M0);
3530 if (M0 < 0 || M1 < 0 ||
3531 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3532 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3537 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3538 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3542 // Fold this sequence only if the resulting shuffle is 'legal'.
3543 if (TLI.isShuffleMaskLegal(Mask1, VT))
3544 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3545 N1->getOperand(0), &Mask1[0]);
3546 if (TLI.isShuffleMaskLegal(Mask2, VT))
3547 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3548 N0->getOperand(0), &Mask2[0]);
3553 // fold (or c1, c2) -> c1|c2
3554 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3555 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3557 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3558 // canonicalize constant to RHS
3560 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3561 // fold (or x, 0) -> x
3562 if (N1C && N1C->isNullValue())
3564 // fold (or x, -1) -> -1
3565 if (N1C && N1C->isAllOnesValue())
3567 // fold (or x, c) -> c iff (x & ~c) == 0
3568 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3571 if (SDValue Combined = visitORLike(N0, N1, N))
3574 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3575 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3576 if (BSwap.getNode())
3578 BSwap = MatchBSwapHWordLow(N, N0, N1);
3579 if (BSwap.getNode())
3583 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3586 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3587 // iff (c1 & c2) == 0.
3588 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3589 isa<ConstantSDNode>(N0.getOperand(1))) {
3590 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3591 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3592 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3594 ISD::AND, SDLoc(N), VT,
3595 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3599 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3600 if (N0.getOpcode() == N1.getOpcode()) {
3601 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3602 if (Tmp.getNode()) return Tmp;
3605 // See if this is some rotate idiom.
3606 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3607 return SDValue(Rot, 0);
3609 // Simplify the operands using demanded-bits information.
3610 if (!VT.isVector() &&
3611 SimplifyDemandedBits(SDValue(N, 0)))
3612 return SDValue(N, 0);
3617 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3618 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3619 if (Op.getOpcode() == ISD::AND) {
3620 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3621 Mask = Op.getOperand(1);
3622 Op = Op.getOperand(0);
3628 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3636 // Return true if we can prove that, whenever Neg and Pos are both in the
3637 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3638 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3640 // (or (shift1 X, Neg), (shift2 X, Pos))
3642 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3643 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3644 // to consider shift amounts with defined behavior.
3645 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3646 // If OpSize is a power of 2 then:
3648 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3649 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3651 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3652 // for the stronger condition:
3654 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3656 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3657 // we can just replace Neg with Neg' for the rest of the function.
3659 // In other cases we check for the even stronger condition:
3661 // Neg == OpSize - Pos [B]
3663 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3664 // behavior if Pos == 0 (and consequently Neg == OpSize).
3666 // We could actually use [A] whenever OpSize is a power of 2, but the
3667 // only extra cases that it would match are those uninteresting ones
3668 // where Neg and Pos are never in range at the same time. E.g. for
3669 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3670 // as well as (sub 32, Pos), but:
3672 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3674 // always invokes undefined behavior for 32-bit X.
3676 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3677 unsigned MaskLoBits = 0;
3678 if (Neg.getOpcode() == ISD::AND &&
3679 isPowerOf2_64(OpSize) &&
3680 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3681 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3682 Neg = Neg.getOperand(0);
3683 MaskLoBits = Log2_64(OpSize);
3686 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3687 if (Neg.getOpcode() != ISD::SUB)
3689 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3692 SDValue NegOp1 = Neg.getOperand(1);
3694 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3695 // Pos'. The truncation is redundant for the purpose of the equality.
3697 Pos.getOpcode() == ISD::AND &&
3698 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3699 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3700 Pos = Pos.getOperand(0);
3702 // The condition we need is now:
3704 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3706 // If NegOp1 == Pos then we need:
3708 // OpSize & Mask == NegC & Mask
3710 // (because "x & Mask" is a truncation and distributes through subtraction).
3713 Width = NegC->getAPIntValue();
3714 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3715 // Then the condition we want to prove becomes:
3717 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3719 // which, again because "x & Mask" is a truncation, becomes:
3721 // NegC & Mask == (OpSize - PosC) & Mask
3722 // OpSize & Mask == (NegC + PosC) & Mask
3723 else if (Pos.getOpcode() == ISD::ADD &&
3724 Pos.getOperand(0) == NegOp1 &&
3725 Pos.getOperand(1).getOpcode() == ISD::Constant)
3726 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3727 NegC->getAPIntValue());
3731 // Now we just need to check that OpSize & Mask == Width & Mask.
3733 // Opsize & Mask is 0 since Mask is Opsize - 1.
3734 return Width.getLoBits(MaskLoBits) == 0;
3735 return Width == OpSize;
3738 // A subroutine of MatchRotate used once we have found an OR of two opposite
3739 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3740 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3741 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3742 // Neg with outer conversions stripped away.
3743 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3744 SDValue Neg, SDValue InnerPos,
3745 SDValue InnerNeg, unsigned PosOpcode,
3746 unsigned NegOpcode, SDLoc DL) {
3747 // fold (or (shl x, (*ext y)),
3748 // (srl x, (*ext (sub 32, y)))) ->
3749 // (rotl x, y) or (rotr x, (sub 32, y))
3751 // fold (or (shl x, (*ext (sub 32, y))),
3752 // (srl x, (*ext y))) ->
3753 // (rotr x, y) or (rotl x, (sub 32, y))
3754 EVT VT = Shifted.getValueType();
3755 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3756 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3757 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3758 HasPos ? Pos : Neg).getNode();
3764 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3765 // idioms for rotate, and if the target supports rotation instructions, generate
3767 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3768 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3769 EVT VT = LHS.getValueType();
3770 if (!TLI.isTypeLegal(VT)) return nullptr;
3772 // The target must have at least one rotate flavor.
3773 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3774 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3775 if (!HasROTL && !HasROTR) return nullptr;
3777 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3778 SDValue LHSShift; // The shift.
3779 SDValue LHSMask; // AND value if any.
3780 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3781 return nullptr; // Not part of a rotate.
3783 SDValue RHSShift; // The shift.
3784 SDValue RHSMask; // AND value if any.
3785 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3786 return nullptr; // Not part of a rotate.
3788 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3789 return nullptr; // Not shifting the same value.
3791 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3792 return nullptr; // Shifts must disagree.
3794 // Canonicalize shl to left side in a shl/srl pair.
3795 if (RHSShift.getOpcode() == ISD::SHL) {
3796 std::swap(LHS, RHS);
3797 std::swap(LHSShift, RHSShift);
3798 std::swap(LHSMask , RHSMask );
3801 unsigned OpSizeInBits = VT.getSizeInBits();
3802 SDValue LHSShiftArg = LHSShift.getOperand(0);
3803 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3804 SDValue RHSShiftArg = RHSShift.getOperand(0);
3805 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3807 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3808 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3809 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3810 RHSShiftAmt.getOpcode() == ISD::Constant) {
3811 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3812 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3813 if ((LShVal + RShVal) != OpSizeInBits)
3816 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3817 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3819 // If there is an AND of either shifted operand, apply it to the result.
3820 if (LHSMask.getNode() || RHSMask.getNode()) {
3821 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3823 if (LHSMask.getNode()) {
3824 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3825 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3827 if (RHSMask.getNode()) {
3828 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3829 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3832 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3835 return Rot.getNode();
3838 // If there is a mask here, and we have a variable shift, we can't be sure
3839 // that we're masking out the right stuff.
3840 if (LHSMask.getNode() || RHSMask.getNode())
3843 // If the shift amount is sign/zext/any-extended just peel it off.
3844 SDValue LExtOp0 = LHSShiftAmt;
3845 SDValue RExtOp0 = RHSShiftAmt;
3846 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3847 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3848 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3849 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3850 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3851 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3852 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3853 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3854 LExtOp0 = LHSShiftAmt.getOperand(0);
3855 RExtOp0 = RHSShiftAmt.getOperand(0);
3858 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3859 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3863 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3864 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3871 SDValue DAGCombiner::visitXOR(SDNode *N) {
3872 SDValue N0 = N->getOperand(0);
3873 SDValue N1 = N->getOperand(1);
3874 EVT VT = N0.getValueType();
3877 if (VT.isVector()) {
3878 SDValue FoldedVOp = SimplifyVBinOp(N);
3879 if (FoldedVOp.getNode()) return FoldedVOp;
3881 // fold (xor x, 0) -> x, vector edition
3882 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3884 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3888 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3889 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3890 return DAG.getConstant(0, VT);
3891 // fold (xor x, undef) -> undef
3892 if (N0.getOpcode() == ISD::UNDEF)
3894 if (N1.getOpcode() == ISD::UNDEF)
3896 // fold (xor c1, c2) -> c1^c2
3897 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3898 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3900 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3901 // canonicalize constant to RHS
3903 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3904 // fold (xor x, 0) -> x
3905 if (N1C && N1C->isNullValue())
3908 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3912 // fold !(x cc y) -> (x !cc y)
3913 SDValue LHS, RHS, CC;
3914 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3915 bool isInt = LHS.getValueType().isInteger();
3916 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3919 if (!LegalOperations ||
3920 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3921 switch (N0.getOpcode()) {
3923 llvm_unreachable("Unhandled SetCC Equivalent!");
3925 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3926 case ISD::SELECT_CC:
3927 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3928 N0.getOperand(3), NotCC);
3933 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3934 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3935 N0.getNode()->hasOneUse() &&
3936 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3937 SDValue V = N0.getOperand(0);
3938 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3939 DAG.getConstant(1, V.getValueType()));
3940 AddToWorklist(V.getNode());
3941 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3944 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3945 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3946 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3947 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3948 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3949 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3950 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3951 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3952 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3953 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3956 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3957 if (N1C && N1C->isAllOnesValue() &&
3958 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3959 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3960 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3961 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3962 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3963 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3964 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3965 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3968 // fold (xor (and x, y), y) -> (and (not x), y)
3969 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3970 N0->getOperand(1) == N1) {
3971 SDValue X = N0->getOperand(0);
3972 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3973 AddToWorklist(NotX.getNode());
3974 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3976 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3977 if (N1C && N0.getOpcode() == ISD::XOR) {
3978 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3979 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3981 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3982 DAG.getConstant(N1C->getAPIntValue() ^
3983 N00C->getAPIntValue(), VT));
3985 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3986 DAG.getConstant(N1C->getAPIntValue() ^
3987 N01C->getAPIntValue(), VT));
3989 // fold (xor x, x) -> 0
3991 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3993 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
3994 // Here is a concrete example of this equivalence:
3996 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
3997 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4001 // i16 ~1 == 0b1111111111111110
4002 // i16 rol(~1, 14) == 0b1011111111111111
4004 // Some additional tips to help conceptualize this transform:
4005 // - Try to see the operation as placing a single zero in a value of all ones.
4006 // - There exists no value for x which would allow the result to contain zero.
4007 // - Values of x larger than the bitwidth are undefined and do not require a
4008 // consistent result.
4009 // - Pushing the zero left requires shifting one bits in from the right.
4010 // A rotate left of ~1 is a nice way of achieving the desired result.
4011 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4012 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4013 if (N0.getOpcode() == ISD::SHL)
4014 if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4015 if (N1C->isAllOnesValue() && ShlLHS->isOne())
4016 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, DAG.getConstant(~1, VT),
4019 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4020 if (N0.getOpcode() == N1.getOpcode()) {
4021 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4022 if (Tmp.getNode()) return Tmp;
4025 // Simplify the expression using non-local knowledge.
4026 if (!VT.isVector() &&
4027 SimplifyDemandedBits(SDValue(N, 0)))
4028 return SDValue(N, 0);
4033 /// Handle transforms common to the three shifts, when the shift amount is a
4035 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4036 // We can't and shouldn't fold opaque constants.
4037 if (Amt->isOpaque())
4040 SDNode *LHS = N->getOperand(0).getNode();
4041 if (!LHS->hasOneUse()) return SDValue();
4043 // We want to pull some binops through shifts, so that we have (and (shift))
4044 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4045 // thing happens with address calculations, so it's important to canonicalize
4047 bool HighBitSet = false; // Can we transform this if the high bit is set?
4049 switch (LHS->getOpcode()) {
4050 default: return SDValue();
4053 HighBitSet = false; // We can only transform sra if the high bit is clear.
4056 HighBitSet = true; // We can only transform sra if the high bit is set.
4059 if (N->getOpcode() != ISD::SHL)
4060 return SDValue(); // only shl(add) not sr[al](add).
4061 HighBitSet = false; // We can only transform sra if the high bit is clear.
4065 // We require the RHS of the binop to be a constant and not opaque as well.
4066 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4067 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4069 // FIXME: disable this unless the input to the binop is a shift by a constant.
4070 // If it is not a shift, it pessimizes some common cases like:
4072 // void foo(int *X, int i) { X[i & 1235] = 1; }
4073 // int bar(int *X, int i) { return X[i & 255]; }
4074 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4075 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4076 BinOpLHSVal->getOpcode() != ISD::SRA &&
4077 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4078 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4081 EVT VT = N->getValueType(0);
4083 // If this is a signed shift right, and the high bit is modified by the
4084 // logical operation, do not perform the transformation. The highBitSet
4085 // boolean indicates the value of the high bit of the constant which would
4086 // cause it to be modified for this operation.
4087 if (N->getOpcode() == ISD::SRA) {
4088 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4089 if (BinOpRHSSignSet != HighBitSet)
4093 if (!TLI.isDesirableToCommuteWithShift(LHS))
4096 // Fold the constants, shifting the binop RHS by the shift amount.
4097 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4099 LHS->getOperand(1), N->getOperand(1));
4100 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4102 // Create the new shift.
4103 SDValue NewShift = DAG.getNode(N->getOpcode(),
4104 SDLoc(LHS->getOperand(0)),
4105 VT, LHS->getOperand(0), N->getOperand(1));
4107 // Create the new binop.
4108 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4111 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4112 assert(N->getOpcode() == ISD::TRUNCATE);
4113 assert(N->getOperand(0).getOpcode() == ISD::AND);
4115 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4116 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4117 SDValue N01 = N->getOperand(0).getOperand(1);
4119 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4120 EVT TruncVT = N->getValueType(0);
4121 SDValue N00 = N->getOperand(0).getOperand(0);
4122 APInt TruncC = N01C->getAPIntValue();
4123 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4125 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4126 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4127 DAG.getConstant(TruncC, TruncVT));
4134 SDValue DAGCombiner::visitRotate(SDNode *N) {
4135 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4136 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4137 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4138 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4139 if (NewOp1.getNode())
4140 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4141 N->getOperand(0), NewOp1);
4146 SDValue DAGCombiner::visitSHL(SDNode *N) {
4147 SDValue N0 = N->getOperand(0);
4148 SDValue N1 = N->getOperand(1);
4149 EVT VT = N0.getValueType();
4150 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4153 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4154 if (VT.isVector()) {
4155 SDValue FoldedVOp = SimplifyVBinOp(N);
4156 if (FoldedVOp.getNode()) return FoldedVOp;
4158 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4159 // If setcc produces all-one true value then:
4160 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4161 if (N1CV && N1CV->isConstant()) {
4162 if (N0.getOpcode() == ISD::AND) {
4163 SDValue N00 = N0->getOperand(0);
4164 SDValue N01 = N0->getOperand(1);
4165 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4167 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4168 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4169 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4170 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
4171 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4174 N1C = isConstOrConstSplat(N1);
4179 // fold (shl c1, c2) -> c1<<c2
4180 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4182 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4183 // fold (shl 0, x) -> 0
4184 if (N0C && N0C->isNullValue())
4186 // fold (shl x, c >= size(x)) -> undef
4187 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4188 return DAG.getUNDEF(VT);
4189 // fold (shl x, 0) -> x
4190 if (N1C && N1C->isNullValue())
4192 // fold (shl undef, x) -> 0
4193 if (N0.getOpcode() == ISD::UNDEF)
4194 return DAG.getConstant(0, VT);
4195 // if (shl x, c) is known to be zero, return 0
4196 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4197 APInt::getAllOnesValue(OpSizeInBits)))
4198 return DAG.getConstant(0, VT);
4199 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4200 if (N1.getOpcode() == ISD::TRUNCATE &&
4201 N1.getOperand(0).getOpcode() == ISD::AND) {
4202 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4203 if (NewOp1.getNode())
4204 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4207 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4208 return SDValue(N, 0);
4210 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4211 if (N1C && N0.getOpcode() == ISD::SHL) {
4212 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4213 uint64_t c1 = N0C1->getZExtValue();
4214 uint64_t c2 = N1C->getZExtValue();
4215 if (c1 + c2 >= OpSizeInBits)
4216 return DAG.getConstant(0, VT);
4217 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4218 DAG.getConstant(c1 + c2, N1.getValueType()));
4222 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4223 // For this to be valid, the second form must not preserve any of the bits
4224 // that are shifted out by the inner shift in the first form. This means
4225 // the outer shift size must be >= the number of bits added by the ext.
4226 // As a corollary, we don't care what kind of ext it is.
4227 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4228 N0.getOpcode() == ISD::ANY_EXTEND ||
4229 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4230 N0.getOperand(0).getOpcode() == ISD::SHL) {
4231 SDValue N0Op0 = N0.getOperand(0);
4232 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4233 uint64_t c1 = N0Op0C1->getZExtValue();
4234 uint64_t c2 = N1C->getZExtValue();
4235 EVT InnerShiftVT = N0Op0.getValueType();
4236 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4237 if (c2 >= OpSizeInBits - InnerShiftSize) {
4238 if (c1 + c2 >= OpSizeInBits)
4239 return DAG.getConstant(0, VT);
4240 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4241 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4242 N0Op0->getOperand(0)),
4243 DAG.getConstant(c1 + c2, N1.getValueType()));
4248 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4249 // Only fold this if the inner zext has no other uses to avoid increasing
4250 // the total number of instructions.
4251 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4252 N0.getOperand(0).getOpcode() == ISD::SRL) {
4253 SDValue N0Op0 = N0.getOperand(0);
4254 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4255 uint64_t c1 = N0Op0C1->getZExtValue();
4256 if (c1 < VT.getScalarSizeInBits()) {
4257 uint64_t c2 = N1C->getZExtValue();
4259 SDValue NewOp0 = N0.getOperand(0);
4260 EVT CountVT = NewOp0.getOperand(1).getValueType();
4261 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4262 NewOp0, DAG.getConstant(c2, CountVT));
4263 AddToWorklist(NewSHL.getNode());
4264 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4270 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4271 // (and (srl x, (sub c1, c2), MASK)
4272 // Only fold this if the inner shift has no other uses -- if it does, folding
4273 // this will increase the total number of instructions.
4274 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4275 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4276 uint64_t c1 = N0C1->getZExtValue();
4277 if (c1 < OpSizeInBits) {
4278 uint64_t c2 = N1C->getZExtValue();
4279 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4282 Mask = Mask.shl(c2 - c1);
4283 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4284 DAG.getConstant(c2 - c1, N1.getValueType()));
4286 Mask = Mask.lshr(c1 - c2);
4287 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4288 DAG.getConstant(c1 - c2, N1.getValueType()));
4290 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4291 DAG.getConstant(Mask, VT));
4295 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4296 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4297 unsigned BitSize = VT.getScalarSizeInBits();
4298 SDValue HiBitsMask =
4299 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4300 BitSize - N1C->getZExtValue()), VT);
4301 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4305 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4306 // Variant of version done on multiply, except mul by a power of 2 is turned
4309 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4310 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4311 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4312 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4313 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4314 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4318 SDValue NewSHL = visitShiftByConstant(N, N1C);
4319 if (NewSHL.getNode())
4326 SDValue DAGCombiner::visitSRA(SDNode *N) {
4327 SDValue N0 = N->getOperand(0);
4328 SDValue N1 = N->getOperand(1);
4329 EVT VT = N0.getValueType();
4330 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4333 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4334 if (VT.isVector()) {
4335 SDValue FoldedVOp = SimplifyVBinOp(N);
4336 if (FoldedVOp.getNode()) return FoldedVOp;
4338 N1C = isConstOrConstSplat(N1);
4341 // fold (sra c1, c2) -> (sra c1, c2)
4342 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4344 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4345 // fold (sra 0, x) -> 0
4346 if (N0C && N0C->isNullValue())
4348 // fold (sra -1, x) -> -1
4349 if (N0C && N0C->isAllOnesValue())
4351 // fold (sra x, (setge c, size(x))) -> undef
4352 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4353 return DAG.getUNDEF(VT);
4354 // fold (sra x, 0) -> x
4355 if (N1C && N1C->isNullValue())
4357 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4359 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4360 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4361 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4363 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4364 ExtVT, VT.getVectorNumElements());
4365 if ((!LegalOperations ||
4366 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4367 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4368 N0.getOperand(0), DAG.getValueType(ExtVT));
4371 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4372 if (N1C && N0.getOpcode() == ISD::SRA) {
4373 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4374 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4375 if (Sum >= OpSizeInBits)
4376 Sum = OpSizeInBits - 1;
4377 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4378 DAG.getConstant(Sum, N1.getValueType()));
4382 // fold (sra (shl X, m), (sub result_size, n))
4383 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4384 // result_size - n != m.
4385 // If truncate is free for the target sext(shl) is likely to result in better
4387 if (N0.getOpcode() == ISD::SHL && N1C) {
4388 // Get the two constanst of the shifts, CN0 = m, CN = n.
4389 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4391 LLVMContext &Ctx = *DAG.getContext();
4392 // Determine what the truncate's result bitsize and type would be.
4393 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4396 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4398 // Determine the residual right-shift amount.
4399 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4401 // If the shift is not a no-op (in which case this should be just a sign
4402 // extend already), the truncated to type is legal, sign_extend is legal
4403 // on that type, and the truncate to that type is both legal and free,
4404 // perform the transform.
4405 if ((ShiftAmt > 0) &&
4406 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4407 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4408 TLI.isTruncateFree(VT, TruncVT)) {
4410 SDValue Amt = DAG.getConstant(ShiftAmt,
4411 getShiftAmountTy(N0.getOperand(0).getValueType()));
4412 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4413 N0.getOperand(0), Amt);
4414 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4416 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4417 N->getValueType(0), Trunc);
4422 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4423 if (N1.getOpcode() == ISD::TRUNCATE &&
4424 N1.getOperand(0).getOpcode() == ISD::AND) {
4425 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4426 if (NewOp1.getNode())
4427 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4430 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4431 // if c1 is equal to the number of bits the trunc removes
4432 if (N0.getOpcode() == ISD::TRUNCATE &&
4433 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4434 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4435 N0.getOperand(0).hasOneUse() &&
4436 N0.getOperand(0).getOperand(1).hasOneUse() &&
4438 SDValue N0Op0 = N0.getOperand(0);
4439 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4440 unsigned LargeShiftVal = LargeShift->getZExtValue();
4441 EVT LargeVT = N0Op0.getValueType();
4443 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4445 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4446 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4447 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4448 N0Op0.getOperand(0), Amt);
4449 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4454 // Simplify, based on bits shifted out of the LHS.
4455 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4456 return SDValue(N, 0);
4459 // If the sign bit is known to be zero, switch this to a SRL.
4460 if (DAG.SignBitIsZero(N0))
4461 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4464 SDValue NewSRA = visitShiftByConstant(N, N1C);
4465 if (NewSRA.getNode())
4472 SDValue DAGCombiner::visitSRL(SDNode *N) {
4473 SDValue N0 = N->getOperand(0);
4474 SDValue N1 = N->getOperand(1);
4475 EVT VT = N0.getValueType();
4476 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4479 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4480 if (VT.isVector()) {
4481 SDValue FoldedVOp = SimplifyVBinOp(N);
4482 if (FoldedVOp.getNode()) return FoldedVOp;
4484 N1C = isConstOrConstSplat(N1);
4487 // fold (srl c1, c2) -> c1 >>u c2
4488 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4490 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4491 // fold (srl 0, x) -> 0
4492 if (N0C && N0C->isNullValue())
4494 // fold (srl x, c >= size(x)) -> undef
4495 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4496 return DAG.getUNDEF(VT);
4497 // fold (srl x, 0) -> x
4498 if (N1C && N1C->isNullValue())
4500 // if (srl x, c) is known to be zero, return 0
4501 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4502 APInt::getAllOnesValue(OpSizeInBits)))
4503 return DAG.getConstant(0, VT);
4505 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4506 if (N1C && N0.getOpcode() == ISD::SRL) {
4507 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4508 uint64_t c1 = N01C->getZExtValue();
4509 uint64_t c2 = N1C->getZExtValue();
4510 if (c1 + c2 >= OpSizeInBits)
4511 return DAG.getConstant(0, VT);
4512 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4513 DAG.getConstant(c1 + c2, N1.getValueType()));
4517 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4518 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4519 N0.getOperand(0).getOpcode() == ISD::SRL &&
4520 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4522 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4523 uint64_t c2 = N1C->getZExtValue();
4524 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4525 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4526 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4527 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4528 if (c1 + OpSizeInBits == InnerShiftSize) {
4529 if (c1 + c2 >= InnerShiftSize)
4530 return DAG.getConstant(0, VT);
4531 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4532 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4533 N0.getOperand(0)->getOperand(0),
4534 DAG.getConstant(c1 + c2, ShiftCountVT)));
4538 // fold (srl (shl x, c), c) -> (and x, cst2)
4539 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4540 unsigned BitSize = N0.getScalarValueSizeInBits();
4541 if (BitSize <= 64) {
4542 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4543 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4544 DAG.getConstant(~0ULL >> ShAmt, VT));
4548 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4549 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4550 // Shifting in all undef bits?
4551 EVT SmallVT = N0.getOperand(0).getValueType();
4552 unsigned BitSize = SmallVT.getScalarSizeInBits();
4553 if (N1C->getZExtValue() >= BitSize)
4554 return DAG.getUNDEF(VT);
4556 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4557 uint64_t ShiftAmt = N1C->getZExtValue();
4558 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4560 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4561 AddToWorklist(SmallShift.getNode());
4562 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4563 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4564 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4565 DAG.getConstant(Mask, VT));
4569 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4570 // bit, which is unmodified by sra.
4571 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4572 if (N0.getOpcode() == ISD::SRA)
4573 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4576 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4577 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4578 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4579 APInt KnownZero, KnownOne;
4580 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4582 // If any of the input bits are KnownOne, then the input couldn't be all
4583 // zeros, thus the result of the srl will always be zero.
4584 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4586 // If all of the bits input the to ctlz node are known to be zero, then
4587 // the result of the ctlz is "32" and the result of the shift is one.
4588 APInt UnknownBits = ~KnownZero;
4589 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4591 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4592 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4593 // Okay, we know that only that the single bit specified by UnknownBits
4594 // could be set on input to the CTLZ node. If this bit is set, the SRL
4595 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4596 // to an SRL/XOR pair, which is likely to simplify more.
4597 unsigned ShAmt = UnknownBits.countTrailingZeros();
4598 SDValue Op = N0.getOperand(0);
4601 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4602 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4603 AddToWorklist(Op.getNode());
4606 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4607 Op, DAG.getConstant(1, VT));
4611 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4612 if (N1.getOpcode() == ISD::TRUNCATE &&
4613 N1.getOperand(0).getOpcode() == ISD::AND) {
4614 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4615 if (NewOp1.getNode())
4616 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4619 // fold operands of srl based on knowledge that the low bits are not
4621 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4622 return SDValue(N, 0);
4625 SDValue NewSRL = visitShiftByConstant(N, N1C);
4626 if (NewSRL.getNode())
4630 // Attempt to convert a srl of a load into a narrower zero-extending load.
4631 SDValue NarrowLoad = ReduceLoadWidth(N);
4632 if (NarrowLoad.getNode())
4635 // Here is a common situation. We want to optimize:
4638 // %b = and i32 %a, 2
4639 // %c = srl i32 %b, 1
4640 // brcond i32 %c ...
4646 // %c = setcc eq %b, 0
4649 // However when after the source operand of SRL is optimized into AND, the SRL
4650 // itself may not be optimized further. Look for it and add the BRCOND into
4652 if (N->hasOneUse()) {
4653 SDNode *Use = *N->use_begin();
4654 if (Use->getOpcode() == ISD::BRCOND)
4656 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4657 // Also look pass the truncate.
4658 Use = *Use->use_begin();
4659 if (Use->getOpcode() == ISD::BRCOND)
4667 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4668 SDValue N0 = N->getOperand(0);
4669 EVT VT = N->getValueType(0);
4671 // fold (ctlz c1) -> c2
4672 if (isa<ConstantSDNode>(N0))
4673 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4677 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4678 SDValue N0 = N->getOperand(0);
4679 EVT VT = N->getValueType(0);
4681 // fold (ctlz_zero_undef c1) -> c2
4682 if (isa<ConstantSDNode>(N0))
4683 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4687 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4688 SDValue N0 = N->getOperand(0);
4689 EVT VT = N->getValueType(0);
4691 // fold (cttz c1) -> c2
4692 if (isa<ConstantSDNode>(N0))
4693 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4697 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4698 SDValue N0 = N->getOperand(0);
4699 EVT VT = N->getValueType(0);
4701 // fold (cttz_zero_undef c1) -> c2
4702 if (isa<ConstantSDNode>(N0))
4703 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4707 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4708 SDValue N0 = N->getOperand(0);
4709 EVT VT = N->getValueType(0);
4711 // fold (ctpop c1) -> c2
4712 if (isa<ConstantSDNode>(N0))
4713 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4718 /// \brief Generate Min/Max node
4719 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4720 SDValue True, SDValue False,
4721 ISD::CondCode CC, const TargetLowering &TLI,
4722 SelectionDAG &DAG) {
4723 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4733 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4734 if (TLI.isOperationLegal(Opcode, VT))
4735 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4744 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4745 if (TLI.isOperationLegal(Opcode, VT))
4746 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4754 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4755 SDValue N0 = N->getOperand(0);
4756 SDValue N1 = N->getOperand(1);
4757 SDValue N2 = N->getOperand(2);
4758 EVT VT = N->getValueType(0);
4759 EVT VT0 = N0.getValueType();
4761 // fold (select C, X, X) -> X
4764 // fold (select true, X, Y) -> X
4765 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4766 if (N0C && !N0C->isNullValue())
4768 // fold (select false, X, Y) -> Y
4769 if (N0C && N0C->isNullValue())
4771 // fold (select C, 1, X) -> (or C, X)
4772 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4773 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4774 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4775 // fold (select C, 0, 1) -> (xor C, 1)
4776 // We can't do this reliably if integer based booleans have different contents
4777 // to floating point based booleans. This is because we can't tell whether we
4778 // have an integer-based boolean or a floating-point-based boolean unless we
4779 // can find the SETCC that produced it and inspect its operands. This is
4780 // fairly easy if C is the SETCC node, but it can potentially be
4781 // undiscoverable (or not reasonably discoverable). For example, it could be
4782 // in another basic block or it could require searching a complicated
4784 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4785 if (VT.isInteger() &&
4786 (VT0 == MVT::i1 || (VT0.isInteger() &&
4787 TLI.getBooleanContents(false, false) ==
4788 TLI.getBooleanContents(false, true) &&
4789 TLI.getBooleanContents(false, false) ==
4790 TargetLowering::ZeroOrOneBooleanContent)) &&
4791 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4794 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4795 N0, DAG.getConstant(1, VT0));
4796 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4797 N0, DAG.getConstant(1, VT0));
4798 AddToWorklist(XORNode.getNode());
4800 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4801 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4803 // fold (select C, 0, X) -> (and (not C), X)
4804 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4805 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4806 AddToWorklist(NOTNode.getNode());
4807 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4809 // fold (select C, X, 1) -> (or (not C), X)
4810 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4811 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4812 AddToWorklist(NOTNode.getNode());
4813 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4815 // fold (select C, X, 0) -> (and C, X)
4816 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4817 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4818 // fold (select X, X, Y) -> (or X, Y)
4819 // fold (select X, 1, Y) -> (or X, Y)
4820 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4821 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4822 // fold (select X, Y, X) -> (and X, Y)
4823 // fold (select X, Y, 0) -> (and X, Y)
4824 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4825 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4827 // If we can fold this based on the true/false value, do so.
4828 if (SimplifySelectOps(N, N1, N2))
4829 return SDValue(N, 0); // Don't revisit N.
4831 // fold selects based on a setcc into other things, such as min/max/abs
4832 if (N0.getOpcode() == ISD::SETCC) {
4833 // select x, y (fcmp lt x, y) -> fminnum x, y
4834 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4836 // This is OK if we don't care about what happens if either operand is a
4840 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4841 // no signed zeros as well as no nans.
4842 const TargetOptions &Options = DAG.getTarget().Options;
4843 if (Options.UnsafeFPMath &&
4844 VT.isFloatingPoint() && N0.hasOneUse() &&
4845 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4846 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4849 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4850 N1, N2, CC, TLI, DAG);
4855 if ((!LegalOperations &&
4856 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4857 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4858 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4859 N0.getOperand(0), N0.getOperand(1),
4860 N1, N2, N0.getOperand(2));
4861 return SimplifySelect(SDLoc(N), N0, N1, N2);
4864 if (VT0 == MVT::i1) {
4865 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4866 // select (and Cond0, Cond1), X, Y
4867 // -> select Cond0, (select Cond1, X, Y), Y
4868 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4869 SDValue Cond0 = N0->getOperand(0);
4870 SDValue Cond1 = N0->getOperand(1);
4871 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4872 N1.getValueType(), Cond1, N1, N2);
4873 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4876 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4877 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4878 SDValue Cond0 = N0->getOperand(0);
4879 SDValue Cond1 = N0->getOperand(1);
4880 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4881 N1.getValueType(), Cond1, N1, N2);
4882 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4887 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4888 if (N1->getOpcode() == ISD::SELECT) {
4889 SDValue N1_0 = N1->getOperand(0);
4890 SDValue N1_1 = N1->getOperand(1);
4891 SDValue N1_2 = N1->getOperand(2);
4893 // Create the actual and node if we can generate good code for it.
4894 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4895 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4897 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4900 // Otherwise see if we can optimize the "and" to a better pattern.
4901 if (SDValue Combined = visitANDLike(N0, N1_0, N))
4902 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4906 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4907 if (N2->getOpcode() == ISD::SELECT) {
4908 SDValue N2_0 = N2->getOperand(0);
4909 SDValue N2_1 = N2->getOperand(1);
4910 SDValue N2_2 = N2->getOperand(2);
4912 // Create the actual or node if we can generate good code for it.
4913 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4914 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4916 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4919 // Otherwise see if we can optimize to a better pattern.
4920 if (SDValue Combined = visitORLike(N0, N2_0, N))
4921 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4931 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4934 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4936 // Split the inputs.
4937 SDValue Lo, Hi, LL, LH, RL, RH;
4938 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4939 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4941 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4942 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4944 return std::make_pair(Lo, Hi);
4947 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4948 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4949 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4951 SDValue Cond = N->getOperand(0);
4952 SDValue LHS = N->getOperand(1);
4953 SDValue RHS = N->getOperand(2);
4954 EVT VT = N->getValueType(0);
4955 int NumElems = VT.getVectorNumElements();
4956 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4957 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4958 Cond.getOpcode() == ISD::BUILD_VECTOR);
4960 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4961 // binary ones here.
4962 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4965 // We're sure we have an even number of elements due to the
4966 // concat_vectors we have as arguments to vselect.
4967 // Skip BV elements until we find one that's not an UNDEF
4968 // After we find an UNDEF element, keep looping until we get to half the
4969 // length of the BV and see if all the non-undef nodes are the same.
4970 ConstantSDNode *BottomHalf = nullptr;
4971 for (int i = 0; i < NumElems / 2; ++i) {
4972 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4975 if (BottomHalf == nullptr)
4976 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4977 else if (Cond->getOperand(i).getNode() != BottomHalf)
4981 // Do the same for the second half of the BuildVector
4982 ConstantSDNode *TopHalf = nullptr;
4983 for (int i = NumElems / 2; i < NumElems; ++i) {
4984 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4987 if (TopHalf == nullptr)
4988 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4989 else if (Cond->getOperand(i).getNode() != TopHalf)
4993 assert(TopHalf && BottomHalf &&
4994 "One half of the selector was all UNDEFs and the other was all the "
4995 "same value. This should have been addressed before this function.");
4997 ISD::CONCAT_VECTORS, dl, VT,
4998 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4999 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5002 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5004 if (Level >= AfterLegalizeTypes)
5007 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5008 SDValue Mask = MST->getMask();
5009 SDValue Data = MST->getValue();
5012 // If the MSTORE data type requires splitting and the mask is provided by a
5013 // SETCC, then split both nodes and its operands before legalization. This
5014 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5015 // and enables future optimizations (e.g. min/max pattern matching on X86).
5016 if (Mask.getOpcode() == ISD::SETCC) {
5018 // Check if any splitting is required.
5019 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5020 TargetLowering::TypeSplitVector)
5023 SDValue MaskLo, MaskHi, Lo, Hi;
5024 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5027 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5029 SDValue Chain = MST->getChain();
5030 SDValue Ptr = MST->getBasePtr();
5032 EVT MemoryVT = MST->getMemoryVT();
5033 unsigned Alignment = MST->getOriginalAlignment();
5035 // if Alignment is equal to the vector size,
5036 // take the half of it for the second part
5037 unsigned SecondHalfAlignment =
5038 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5039 Alignment/2 : Alignment;
5041 EVT LoMemVT, HiMemVT;
5042 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5044 SDValue DataLo, DataHi;
5045 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5047 MachineMemOperand *MMO = DAG.getMachineFunction().
5048 getMachineMemOperand(MST->getPointerInfo(),
5049 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5050 Alignment, MST->getAAInfo(), MST->getRanges());
5052 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5053 MST->isTruncatingStore());
5055 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5056 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5057 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5059 MMO = DAG.getMachineFunction().
5060 getMachineMemOperand(MST->getPointerInfo(),
5061 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5062 SecondHalfAlignment, MST->getAAInfo(),
5065 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5066 MST->isTruncatingStore());
5068 AddToWorklist(Lo.getNode());
5069 AddToWorklist(Hi.getNode());
5071 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5076 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5078 if (Level >= AfterLegalizeTypes)
5081 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5082 SDValue Mask = MLD->getMask();
5085 // If the MLOAD result requires splitting and the mask is provided by a
5086 // SETCC, then split both nodes and its operands before legalization. This
5087 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5088 // and enables future optimizations (e.g. min/max pattern matching on X86).
5090 if (Mask.getOpcode() == ISD::SETCC) {
5091 EVT VT = N->getValueType(0);
5093 // Check if any splitting is required.
5094 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5095 TargetLowering::TypeSplitVector)
5098 SDValue MaskLo, MaskHi, Lo, Hi;
5099 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5101 SDValue Src0 = MLD->getSrc0();
5102 SDValue Src0Lo, Src0Hi;
5103 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5106 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5108 SDValue Chain = MLD->getChain();
5109 SDValue Ptr = MLD->getBasePtr();
5110 EVT MemoryVT = MLD->getMemoryVT();
5111 unsigned Alignment = MLD->getOriginalAlignment();
5113 // if Alignment is equal to the vector size,
5114 // take the half of it for the second part
5115 unsigned SecondHalfAlignment =
5116 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5117 Alignment/2 : Alignment;
5119 EVT LoMemVT, HiMemVT;
5120 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5122 MachineMemOperand *MMO = DAG.getMachineFunction().
5123 getMachineMemOperand(MLD->getPointerInfo(),
5124 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5125 Alignment, MLD->getAAInfo(), MLD->getRanges());
5127 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5130 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5131 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5132 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5134 MMO = DAG.getMachineFunction().
5135 getMachineMemOperand(MLD->getPointerInfo(),
5136 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5137 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5139 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5142 AddToWorklist(Lo.getNode());
5143 AddToWorklist(Hi.getNode());
5145 // Build a factor node to remember that this load is independent of the
5147 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5150 // Legalized the chain result - switch anything that used the old chain to
5152 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5154 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5156 SDValue RetOps[] = { LoadRes, Chain };
5157 return DAG.getMergeValues(RetOps, DL);
5162 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5163 SDValue N0 = N->getOperand(0);
5164 SDValue N1 = N->getOperand(1);
5165 SDValue N2 = N->getOperand(2);
5168 // Canonicalize integer abs.
5169 // vselect (setg[te] X, 0), X, -X ->
5170 // vselect (setgt X, -1), X, -X ->
5171 // vselect (setl[te] X, 0), -X, X ->
5172 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5173 if (N0.getOpcode() == ISD::SETCC) {
5174 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5175 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5177 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5179 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5180 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5181 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5182 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5183 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5184 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5185 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5188 EVT VT = LHS.getValueType();
5189 SDValue Shift = DAG.getNode(
5190 ISD::SRA, DL, VT, LHS,
5191 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5192 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5193 AddToWorklist(Shift.getNode());
5194 AddToWorklist(Add.getNode());
5195 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5199 // If the VSELECT result requires splitting and the mask is provided by a
5200 // SETCC, then split both nodes and its operands before legalization. This
5201 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5202 // and enables future optimizations (e.g. min/max pattern matching on X86).
5203 if (N0.getOpcode() == ISD::SETCC) {
5204 EVT VT = N->getValueType(0);
5206 // Check if any splitting is required.
5207 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5208 TargetLowering::TypeSplitVector)
5211 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5212 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5213 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5214 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5216 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5217 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5219 // Add the new VSELECT nodes to the work list in case they need to be split
5221 AddToWorklist(Lo.getNode());
5222 AddToWorklist(Hi.getNode());
5224 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5227 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5228 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5230 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5231 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5234 // The ConvertSelectToConcatVector function is assuming both the above
5235 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5237 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5238 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5239 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5240 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5248 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5249 SDValue N0 = N->getOperand(0);
5250 SDValue N1 = N->getOperand(1);
5251 SDValue N2 = N->getOperand(2);
5252 SDValue N3 = N->getOperand(3);
5253 SDValue N4 = N->getOperand(4);
5254 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5256 // fold select_cc lhs, rhs, x, x, cc -> x
5260 // Determine if the condition we're dealing with is constant
5261 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5262 N0, N1, CC, SDLoc(N), false);
5263 if (SCC.getNode()) {
5264 AddToWorklist(SCC.getNode());
5266 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5267 if (!SCCC->isNullValue())
5268 return N2; // cond always true -> true val
5270 return N3; // cond always false -> false val
5271 } else if (SCC->getOpcode() == ISD::UNDEF) {
5272 // When the condition is UNDEF, just return the first operand. This is
5273 // coherent the DAG creation, no setcc node is created in this case
5275 } else if (SCC.getOpcode() == ISD::SETCC) {
5276 // Fold to a simpler select_cc
5277 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5278 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5283 // If we can fold this based on the true/false value, do so.
5284 if (SimplifySelectOps(N, N2, N3))
5285 return SDValue(N, 0); // Don't revisit N.
5287 // fold select_cc into other things, such as min/max/abs
5288 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5291 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5292 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5293 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5297 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5298 // dag node into a ConstantSDNode or a build_vector of constants.
5299 // This function is called by the DAGCombiner when visiting sext/zext/aext
5300 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5301 // Vector extends are not folded if operations are legal; this is to
5302 // avoid introducing illegal build_vector dag nodes.
5303 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5304 SelectionDAG &DAG, bool LegalTypes,
5305 bool LegalOperations) {
5306 unsigned Opcode = N->getOpcode();
5307 SDValue N0 = N->getOperand(0);
5308 EVT VT = N->getValueType(0);
5310 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5311 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5313 // fold (sext c1) -> c1
5314 // fold (zext c1) -> c1
5315 // fold (aext c1) -> c1
5316 if (isa<ConstantSDNode>(N0))
5317 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5319 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5320 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5321 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5322 EVT SVT = VT.getScalarType();
5323 if (!(VT.isVector() &&
5324 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5325 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5328 // We can fold this node into a build_vector.
5329 unsigned VTBits = SVT.getSizeInBits();
5330 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5331 unsigned ShAmt = VTBits - EVTBits;
5332 SmallVector<SDValue, 8> Elts;
5333 unsigned NumElts = N0->getNumOperands();
5336 for (unsigned i=0; i != NumElts; ++i) {
5337 SDValue Op = N0->getOperand(i);
5338 if (Op->getOpcode() == ISD::UNDEF) {
5339 Elts.push_back(DAG.getUNDEF(SVT));
5343 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5344 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5345 if (Opcode == ISD::SIGN_EXTEND)
5346 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5349 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5353 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5356 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5357 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5358 // transformation. Returns true if extension are possible and the above
5359 // mentioned transformation is profitable.
5360 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5362 SmallVectorImpl<SDNode *> &ExtendNodes,
5363 const TargetLowering &TLI) {
5364 bool HasCopyToRegUses = false;
5365 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5366 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5367 UE = N0.getNode()->use_end();
5372 if (UI.getUse().getResNo() != N0.getResNo())
5374 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5375 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5376 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5377 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5378 // Sign bits will be lost after a zext.
5381 for (unsigned i = 0; i != 2; ++i) {
5382 SDValue UseOp = User->getOperand(i);
5385 if (!isa<ConstantSDNode>(UseOp))
5390 ExtendNodes.push_back(User);
5393 // If truncates aren't free and there are users we can't
5394 // extend, it isn't worthwhile.
5397 // Remember if this value is live-out.
5398 if (User->getOpcode() == ISD::CopyToReg)
5399 HasCopyToRegUses = true;
5402 if (HasCopyToRegUses) {
5403 bool BothLiveOut = false;
5404 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5406 SDUse &Use = UI.getUse();
5407 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5413 // Both unextended and extended values are live out. There had better be
5414 // a good reason for the transformation.
5415 return ExtendNodes.size();
5420 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5421 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5422 ISD::NodeType ExtType) {
5423 // Extend SetCC uses if necessary.
5424 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5425 SDNode *SetCC = SetCCs[i];
5426 SmallVector<SDValue, 4> Ops;
5428 for (unsigned j = 0; j != 2; ++j) {
5429 SDValue SOp = SetCC->getOperand(j);
5431 Ops.push_back(ExtLoad);
5433 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5436 Ops.push_back(SetCC->getOperand(2));
5437 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5441 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5442 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5443 SDValue N0 = N->getOperand(0);
5444 EVT DstVT = N->getValueType(0);
5445 EVT SrcVT = N0.getValueType();
5447 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5448 N->getOpcode() == ISD::ZERO_EXTEND) &&
5449 "Unexpected node type (not an extend)!");
5451 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5452 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5453 // (v8i32 (sext (v8i16 (load x))))
5455 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5456 // (v4i32 (sextload (x + 16)))))
5457 // Where uses of the original load, i.e.:
5459 // are replaced with:
5461 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5462 // (v4i32 (sextload (x + 16)))))))
5464 // This combine is only applicable to illegal, but splittable, vectors.
5465 // All legal types, and illegal non-vector types, are handled elsewhere.
5466 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5468 if (N0->getOpcode() != ISD::LOAD)
5471 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5473 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5474 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5475 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5478 SmallVector<SDNode *, 4> SetCCs;
5479 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5482 ISD::LoadExtType ExtType =
5483 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5485 // Try to split the vector types to get down to legal types.
5486 EVT SplitSrcVT = SrcVT;
5487 EVT SplitDstVT = DstVT;
5488 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5489 SplitSrcVT.getVectorNumElements() > 1) {
5490 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5491 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5494 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5498 const unsigned NumSplits =
5499 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5500 const unsigned Stride = SplitSrcVT.getStoreSize();
5501 SmallVector<SDValue, 4> Loads;
5502 SmallVector<SDValue, 4> Chains;
5504 SDValue BasePtr = LN0->getBasePtr();
5505 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5506 const unsigned Offset = Idx * Stride;
5507 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5509 SDValue SplitLoad = DAG.getExtLoad(
5510 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5511 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5512 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5513 Align, LN0->getAAInfo());
5515 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5516 DAG.getConstant(Stride, BasePtr.getValueType()));
5518 Loads.push_back(SplitLoad.getValue(0));
5519 Chains.push_back(SplitLoad.getValue(1));
5522 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5523 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5525 CombineTo(N, NewValue);
5527 // Replace uses of the original load (before extension)
5528 // with a truncate of the concatenated sextloaded vectors.
5530 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5531 CombineTo(N0.getNode(), Trunc, NewChain);
5532 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5533 (ISD::NodeType)N->getOpcode());
5534 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5537 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5538 SDValue N0 = N->getOperand(0);
5539 EVT VT = N->getValueType(0);
5541 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5543 return SDValue(Res, 0);
5545 // fold (sext (sext x)) -> (sext x)
5546 // fold (sext (aext x)) -> (sext x)
5547 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5548 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5551 if (N0.getOpcode() == ISD::TRUNCATE) {
5552 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5553 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5554 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5555 if (NarrowLoad.getNode()) {
5556 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5557 if (NarrowLoad.getNode() != N0.getNode()) {
5558 CombineTo(N0.getNode(), NarrowLoad);
5559 // CombineTo deleted the truncate, if needed, but not what's under it.
5562 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5565 // See if the value being truncated is already sign extended. If so, just
5566 // eliminate the trunc/sext pair.
5567 SDValue Op = N0.getOperand(0);
5568 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5569 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5570 unsigned DestBits = VT.getScalarType().getSizeInBits();
5571 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5573 if (OpBits == DestBits) {
5574 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5575 // bits, it is already ready.
5576 if (NumSignBits > DestBits-MidBits)
5578 } else if (OpBits < DestBits) {
5579 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5580 // bits, just sext from i32.
5581 if (NumSignBits > OpBits-MidBits)
5582 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5584 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5585 // bits, just truncate to i32.
5586 if (NumSignBits > OpBits-MidBits)
5587 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5590 // fold (sext (truncate x)) -> (sextinreg x).
5591 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5592 N0.getValueType())) {
5593 if (OpBits < DestBits)
5594 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5595 else if (OpBits > DestBits)
5596 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5597 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5598 DAG.getValueType(N0.getValueType()));
5602 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5603 // Only generate vector extloads when 1) they're legal, and 2) they are
5604 // deemed desirable by the target.
5605 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5606 ((!LegalOperations && !VT.isVector() &&
5607 !cast<LoadSDNode>(N0)->isVolatile()) ||
5608 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5609 bool DoXform = true;
5610 SmallVector<SDNode*, 4> SetCCs;
5611 if (!N0.hasOneUse())
5612 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5614 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5616 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5617 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5619 LN0->getBasePtr(), N0.getValueType(),
5620 LN0->getMemOperand());
5621 CombineTo(N, ExtLoad);
5622 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5623 N0.getValueType(), ExtLoad);
5624 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5625 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5627 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5631 // fold (sext (load x)) to multiple smaller sextloads.
5632 // Only on illegal but splittable vectors.
5633 if (SDValue ExtLoad = CombineExtLoad(N))
5636 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5637 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5638 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5639 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5640 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5641 EVT MemVT = LN0->getMemoryVT();
5642 if ((!LegalOperations && !LN0->isVolatile()) ||
5643 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5644 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5646 LN0->getBasePtr(), MemVT,
5647 LN0->getMemOperand());
5648 CombineTo(N, ExtLoad);
5649 CombineTo(N0.getNode(),
5650 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5651 N0.getValueType(), ExtLoad),
5652 ExtLoad.getValue(1));
5653 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5657 // fold (sext (and/or/xor (load x), cst)) ->
5658 // (and/or/xor (sextload x), (sext cst))
5659 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5660 N0.getOpcode() == ISD::XOR) &&
5661 isa<LoadSDNode>(N0.getOperand(0)) &&
5662 N0.getOperand(1).getOpcode() == ISD::Constant &&
5663 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5664 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5665 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5666 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5667 bool DoXform = true;
5668 SmallVector<SDNode*, 4> SetCCs;
5669 if (!N0.hasOneUse())
5670 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5673 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5674 LN0->getChain(), LN0->getBasePtr(),
5676 LN0->getMemOperand());
5677 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5678 Mask = Mask.sext(VT.getSizeInBits());
5679 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5680 ExtLoad, DAG.getConstant(Mask, VT));
5681 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5682 SDLoc(N0.getOperand(0)),
5683 N0.getOperand(0).getValueType(), ExtLoad);
5685 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5686 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5688 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5693 if (N0.getOpcode() == ISD::SETCC) {
5694 EVT N0VT = N0.getOperand(0).getValueType();
5695 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5696 // Only do this before legalize for now.
5697 if (VT.isVector() && !LegalOperations &&
5698 TLI.getBooleanContents(N0VT) ==
5699 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5700 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5701 // of the same size as the compared operands. Only optimize sext(setcc())
5702 // if this is the case.
5703 EVT SVT = getSetCCResultType(N0VT);
5705 // We know that the # elements of the results is the same as the
5706 // # elements of the compare (and the # elements of the compare result
5707 // for that matter). Check to see that they are the same size. If so,
5708 // we know that the element size of the sext'd result matches the
5709 // element size of the compare operands.
5710 if (VT.getSizeInBits() == SVT.getSizeInBits())
5711 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5713 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5715 // If the desired elements are smaller or larger than the source
5716 // elements we can use a matching integer vector type and then
5717 // truncate/sign extend
5718 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5719 if (SVT == MatchingVectorType) {
5720 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5721 N0.getOperand(0), N0.getOperand(1),
5722 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5723 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5727 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5728 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5730 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5732 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5733 NegOne, DAG.getConstant(0, VT),
5734 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5735 if (SCC.getNode()) return SCC;
5737 if (!VT.isVector()) {
5738 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5739 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5741 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5742 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5743 N0.getOperand(0), N0.getOperand(1), CC);
5744 return DAG.getSelect(DL, VT, SetCC,
5745 NegOne, DAG.getConstant(0, VT));
5750 // fold (sext x) -> (zext x) if the sign bit is known zero.
5751 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5752 DAG.SignBitIsZero(N0))
5753 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5758 // isTruncateOf - If N is a truncate of some other value, return true, record
5759 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5760 // This function computes KnownZero to avoid a duplicated call to
5761 // computeKnownBits in the caller.
5762 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5765 if (N->getOpcode() == ISD::TRUNCATE) {
5766 Op = N->getOperand(0);
5767 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5771 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5772 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5775 SDValue Op0 = N->getOperand(0);
5776 SDValue Op1 = N->getOperand(1);
5777 assert(Op0.getValueType() == Op1.getValueType());
5779 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5780 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5781 if (COp0 && COp0->isNullValue())
5783 else if (COp1 && COp1->isNullValue())
5788 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5790 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5796 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5797 SDValue N0 = N->getOperand(0);
5798 EVT VT = N->getValueType(0);
5800 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5802 return SDValue(Res, 0);
5804 // fold (zext (zext x)) -> (zext x)
5805 // fold (zext (aext x)) -> (zext x)
5806 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5807 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5810 // fold (zext (truncate x)) -> (zext x) or
5811 // (zext (truncate x)) -> (truncate x)
5812 // This is valid when the truncated bits of x are already zero.
5813 // FIXME: We should extend this to work for vectors too.
5816 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5817 APInt TruncatedBits =
5818 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5819 APInt(Op.getValueSizeInBits(), 0) :
5820 APInt::getBitsSet(Op.getValueSizeInBits(),
5821 N0.getValueSizeInBits(),
5822 std::min(Op.getValueSizeInBits(),
5823 VT.getSizeInBits()));
5824 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5825 if (VT.bitsGT(Op.getValueType()))
5826 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5827 if (VT.bitsLT(Op.getValueType()))
5828 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5834 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5835 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5836 if (N0.getOpcode() == ISD::TRUNCATE) {
5837 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5838 if (NarrowLoad.getNode()) {
5839 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5840 if (NarrowLoad.getNode() != N0.getNode()) {
5841 CombineTo(N0.getNode(), NarrowLoad);
5842 // CombineTo deleted the truncate, if needed, but not what's under it.
5845 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5849 // fold (zext (truncate x)) -> (and x, mask)
5850 if (N0.getOpcode() == ISD::TRUNCATE &&
5851 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5853 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5854 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5855 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5856 if (NarrowLoad.getNode()) {
5857 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5858 if (NarrowLoad.getNode() != N0.getNode()) {
5859 CombineTo(N0.getNode(), NarrowLoad);
5860 // CombineTo deleted the truncate, if needed, but not what's under it.
5863 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5866 SDValue Op = N0.getOperand(0);
5867 if (Op.getValueType().bitsLT(VT)) {
5868 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5869 AddToWorklist(Op.getNode());
5870 } else if (Op.getValueType().bitsGT(VT)) {
5871 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5872 AddToWorklist(Op.getNode());
5874 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5875 N0.getValueType().getScalarType());
5878 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5879 // if either of the casts is not free.
5880 if (N0.getOpcode() == ISD::AND &&
5881 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5882 N0.getOperand(1).getOpcode() == ISD::Constant &&
5883 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5884 N0.getValueType()) ||
5885 !TLI.isZExtFree(N0.getValueType(), VT))) {
5886 SDValue X = N0.getOperand(0).getOperand(0);
5887 if (X.getValueType().bitsLT(VT)) {
5888 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5889 } else if (X.getValueType().bitsGT(VT)) {
5890 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5892 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5893 Mask = Mask.zext(VT.getSizeInBits());
5894 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5895 X, DAG.getConstant(Mask, VT));
5898 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5899 // Only generate vector extloads when 1) they're legal, and 2) they are
5900 // deemed desirable by the target.
5901 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5902 ((!LegalOperations && !VT.isVector() &&
5903 !cast<LoadSDNode>(N0)->isVolatile()) ||
5904 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5905 bool DoXform = true;
5906 SmallVector<SDNode*, 4> SetCCs;
5907 if (!N0.hasOneUse())
5908 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5910 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5912 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5913 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5915 LN0->getBasePtr(), N0.getValueType(),
5916 LN0->getMemOperand());
5917 CombineTo(N, ExtLoad);
5918 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5919 N0.getValueType(), ExtLoad);
5920 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5922 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5924 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5928 // fold (zext (load x)) to multiple smaller zextloads.
5929 // Only on illegal but splittable vectors.
5930 if (SDValue ExtLoad = CombineExtLoad(N))
5933 // fold (zext (and/or/xor (load x), cst)) ->
5934 // (and/or/xor (zextload x), (zext cst))
5935 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5936 N0.getOpcode() == ISD::XOR) &&
5937 isa<LoadSDNode>(N0.getOperand(0)) &&
5938 N0.getOperand(1).getOpcode() == ISD::Constant &&
5939 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5940 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5941 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5942 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5943 bool DoXform = true;
5944 SmallVector<SDNode*, 4> SetCCs;
5945 if (!N0.hasOneUse())
5946 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5949 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5950 LN0->getChain(), LN0->getBasePtr(),
5952 LN0->getMemOperand());
5953 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5954 Mask = Mask.zext(VT.getSizeInBits());
5955 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5956 ExtLoad, DAG.getConstant(Mask, VT));
5957 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5958 SDLoc(N0.getOperand(0)),
5959 N0.getOperand(0).getValueType(), ExtLoad);
5961 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5962 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5964 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5969 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5970 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5971 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5972 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5973 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5974 EVT MemVT = LN0->getMemoryVT();
5975 if ((!LegalOperations && !LN0->isVolatile()) ||
5976 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5977 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5979 LN0->getBasePtr(), MemVT,
5980 LN0->getMemOperand());
5981 CombineTo(N, ExtLoad);
5982 CombineTo(N0.getNode(),
5983 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5985 ExtLoad.getValue(1));
5986 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5990 if (N0.getOpcode() == ISD::SETCC) {
5991 if (!LegalOperations && VT.isVector() &&
5992 N0.getValueType().getVectorElementType() == MVT::i1) {
5993 EVT N0VT = N0.getOperand(0).getValueType();
5994 if (getSetCCResultType(N0VT) == N0.getValueType())
5997 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5998 // Only do this before legalize for now.
5999 EVT EltVT = VT.getVectorElementType();
6000 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6001 DAG.getConstant(1, EltVT));
6002 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6003 // We know that the # elements of the results is the same as the
6004 // # elements of the compare (and the # elements of the compare result
6005 // for that matter). Check to see that they are the same size. If so,
6006 // we know that the element size of the sext'd result matches the
6007 // element size of the compare operands.
6008 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6009 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6011 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6012 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
6015 // If the desired elements are smaller or larger than the source
6016 // elements we can use a matching integer vector type and then
6017 // truncate/sign extend
6018 EVT MatchingElementType =
6019 EVT::getIntegerVT(*DAG.getContext(),
6020 N0VT.getScalarType().getSizeInBits());
6021 EVT MatchingVectorType =
6022 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6023 N0VT.getVectorNumElements());
6025 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6027 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6028 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6029 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
6030 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
6033 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6035 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6036 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6037 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6038 if (SCC.getNode()) return SCC;
6041 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6042 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6043 isa<ConstantSDNode>(N0.getOperand(1)) &&
6044 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6046 SDValue ShAmt = N0.getOperand(1);
6047 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6048 if (N0.getOpcode() == ISD::SHL) {
6049 SDValue InnerZExt = N0.getOperand(0);
6050 // If the original shl may be shifting out bits, do not perform this
6052 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6053 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6054 if (ShAmtVal > KnownZeroBits)
6060 // Ensure that the shift amount is wide enough for the shifted value.
6061 if (VT.getSizeInBits() >= 256)
6062 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6064 return DAG.getNode(N0.getOpcode(), DL, VT,
6065 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6072 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6073 SDValue N0 = N->getOperand(0);
6074 EVT VT = N->getValueType(0);
6076 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6078 return SDValue(Res, 0);
6080 // fold (aext (aext x)) -> (aext x)
6081 // fold (aext (zext x)) -> (zext x)
6082 // fold (aext (sext x)) -> (sext x)
6083 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6084 N0.getOpcode() == ISD::ZERO_EXTEND ||
6085 N0.getOpcode() == ISD::SIGN_EXTEND)
6086 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6088 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6089 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6090 if (N0.getOpcode() == ISD::TRUNCATE) {
6091 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6092 if (NarrowLoad.getNode()) {
6093 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6094 if (NarrowLoad.getNode() != N0.getNode()) {
6095 CombineTo(N0.getNode(), NarrowLoad);
6096 // CombineTo deleted the truncate, if needed, but not what's under it.
6099 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6103 // fold (aext (truncate x))
6104 if (N0.getOpcode() == ISD::TRUNCATE) {
6105 SDValue TruncOp = N0.getOperand(0);
6106 if (TruncOp.getValueType() == VT)
6107 return TruncOp; // x iff x size == zext size.
6108 if (TruncOp.getValueType().bitsGT(VT))
6109 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6110 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6113 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6114 // if the trunc is not free.
6115 if (N0.getOpcode() == ISD::AND &&
6116 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6117 N0.getOperand(1).getOpcode() == ISD::Constant &&
6118 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6119 N0.getValueType())) {
6120 SDValue X = N0.getOperand(0).getOperand(0);
6121 if (X.getValueType().bitsLT(VT)) {
6122 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6123 } else if (X.getValueType().bitsGT(VT)) {
6124 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6126 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6127 Mask = Mask.zext(VT.getSizeInBits());
6128 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6129 X, DAG.getConstant(Mask, VT));
6132 // fold (aext (load x)) -> (aext (truncate (extload x)))
6133 // None of the supported targets knows how to perform load and any_ext
6134 // on vectors in one instruction. We only perform this transformation on
6136 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6137 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6138 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6139 bool DoXform = true;
6140 SmallVector<SDNode*, 4> SetCCs;
6141 if (!N0.hasOneUse())
6142 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6144 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6145 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6147 LN0->getBasePtr(), N0.getValueType(),
6148 LN0->getMemOperand());
6149 CombineTo(N, ExtLoad);
6150 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6151 N0.getValueType(), ExtLoad);
6152 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6153 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6155 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6159 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6160 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6161 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6162 if (N0.getOpcode() == ISD::LOAD &&
6163 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6165 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6166 ISD::LoadExtType ExtType = LN0->getExtensionType();
6167 EVT MemVT = LN0->getMemoryVT();
6168 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6169 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6170 VT, LN0->getChain(), LN0->getBasePtr(),
6171 MemVT, LN0->getMemOperand());
6172 CombineTo(N, ExtLoad);
6173 CombineTo(N0.getNode(),
6174 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6175 N0.getValueType(), ExtLoad),
6176 ExtLoad.getValue(1));
6177 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6181 if (N0.getOpcode() == ISD::SETCC) {
6183 // aext(setcc) -> vsetcc
6184 // aext(setcc) -> truncate(vsetcc)
6185 // aext(setcc) -> aext(vsetcc)
6186 // Only do this before legalize for now.
6187 if (VT.isVector() && !LegalOperations) {
6188 EVT N0VT = N0.getOperand(0).getValueType();
6189 // We know that the # elements of the results is the same as the
6190 // # elements of the compare (and the # elements of the compare result
6191 // for that matter). Check to see that they are the same size. If so,
6192 // we know that the element size of the sext'd result matches the
6193 // element size of the compare operands.
6194 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6195 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6197 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6198 // If the desired elements are smaller or larger than the source
6199 // elements we can use a matching integer vector type and then
6200 // truncate/any extend
6202 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6204 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6206 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6207 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6211 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6213 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
6214 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
6215 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6223 /// See if the specified operand can be simplified with the knowledge that only
6224 /// the bits specified by Mask are used. If so, return the simpler operand,
6225 /// otherwise return a null SDValue.
6226 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6227 switch (V.getOpcode()) {
6229 case ISD::Constant: {
6230 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6231 assert(CV && "Const value should be ConstSDNode.");
6232 const APInt &CVal = CV->getAPIntValue();
6233 APInt NewVal = CVal & Mask;
6235 return DAG.getConstant(NewVal, V.getValueType());
6240 // If the LHS or RHS don't contribute bits to the or, drop them.
6241 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6242 return V.getOperand(1);
6243 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6244 return V.getOperand(0);
6247 // Only look at single-use SRLs.
6248 if (!V.getNode()->hasOneUse())
6250 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6251 // See if we can recursively simplify the LHS.
6252 unsigned Amt = RHSC->getZExtValue();
6254 // Watch out for shift count overflow though.
6255 if (Amt >= Mask.getBitWidth()) break;
6256 APInt NewMask = Mask << Amt;
6257 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6258 if (SimplifyLHS.getNode())
6259 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6260 SimplifyLHS, V.getOperand(1));
6266 /// If the result of a wider load is shifted to right of N bits and then
6267 /// truncated to a narrower type and where N is a multiple of number of bits of
6268 /// the narrower type, transform it to a narrower load from address + N / num of
6269 /// bits of new type. If the result is to be extended, also fold the extension
6270 /// to form a extending load.
6271 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6272 unsigned Opc = N->getOpcode();
6274 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6275 SDValue N0 = N->getOperand(0);
6276 EVT VT = N->getValueType(0);
6279 // This transformation isn't valid for vector loads.
6283 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6285 if (Opc == ISD::SIGN_EXTEND_INREG) {
6286 ExtType = ISD::SEXTLOAD;
6287 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6288 } else if (Opc == ISD::SRL) {
6289 // Another special-case: SRL is basically zero-extending a narrower value.
6290 ExtType = ISD::ZEXTLOAD;
6292 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6293 if (!N01) return SDValue();
6294 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6295 VT.getSizeInBits() - N01->getZExtValue());
6297 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6300 unsigned EVTBits = ExtVT.getSizeInBits();
6302 // Do not generate loads of non-round integer types since these can
6303 // be expensive (and would be wrong if the type is not byte sized).
6304 if (!ExtVT.isRound())
6308 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6309 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6310 ShAmt = N01->getZExtValue();
6311 // Is the shift amount a multiple of size of VT?
6312 if ((ShAmt & (EVTBits-1)) == 0) {
6313 N0 = N0.getOperand(0);
6314 // Is the load width a multiple of size of VT?
6315 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6319 // At this point, we must have a load or else we can't do the transform.
6320 if (!isa<LoadSDNode>(N0)) return SDValue();
6322 // Because a SRL must be assumed to *need* to zero-extend the high bits
6323 // (as opposed to anyext the high bits), we can't combine the zextload
6324 // lowering of SRL and an sextload.
6325 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6328 // If the shift amount is larger than the input type then we're not
6329 // accessing any of the loaded bytes. If the load was a zextload/extload
6330 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6331 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6336 // If the load is shifted left (and the result isn't shifted back right),
6337 // we can fold the truncate through the shift.
6338 unsigned ShLeftAmt = 0;
6339 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6340 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6341 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6342 ShLeftAmt = N01->getZExtValue();
6343 N0 = N0.getOperand(0);
6347 // If we haven't found a load, we can't narrow it. Don't transform one with
6348 // multiple uses, this would require adding a new load.
6349 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6352 // Don't change the width of a volatile load.
6353 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6354 if (LN0->isVolatile())
6357 // Verify that we are actually reducing a load width here.
6358 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6361 // For the transform to be legal, the load must produce only two values
6362 // (the value loaded and the chain). Don't transform a pre-increment
6363 // load, for example, which produces an extra value. Otherwise the
6364 // transformation is not equivalent, and the downstream logic to replace
6365 // uses gets things wrong.
6366 if (LN0->getNumValues() > 2)
6369 // If the load that we're shrinking is an extload and we're not just
6370 // discarding the extension we can't simply shrink the load. Bail.
6371 // TODO: It would be possible to merge the extensions in some cases.
6372 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6373 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6376 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6379 EVT PtrType = N0.getOperand(1).getValueType();
6381 if (PtrType == MVT::Untyped || PtrType.isExtended())
6382 // It's not possible to generate a constant of extended or untyped type.
6385 // For big endian targets, we need to adjust the offset to the pointer to
6386 // load the correct bytes.
6387 if (TLI.isBigEndian()) {
6388 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6389 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6390 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6393 uint64_t PtrOff = ShAmt / 8;
6394 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6395 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6396 PtrType, LN0->getBasePtr(),
6397 DAG.getConstant(PtrOff, PtrType));
6398 AddToWorklist(NewPtr.getNode());
6401 if (ExtType == ISD::NON_EXTLOAD)
6402 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6403 LN0->getPointerInfo().getWithOffset(PtrOff),
6404 LN0->isVolatile(), LN0->isNonTemporal(),
6405 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6407 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6408 LN0->getPointerInfo().getWithOffset(PtrOff),
6409 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6410 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6412 // Replace the old load's chain with the new load's chain.
6413 WorklistRemover DeadNodes(*this);
6414 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6416 // Shift the result left, if we've swallowed a left shift.
6417 SDValue Result = Load;
6418 if (ShLeftAmt != 0) {
6419 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6420 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6422 // If the shift amount is as large as the result size (but, presumably,
6423 // no larger than the source) then the useful bits of the result are
6424 // zero; we can't simply return the shortened shift, because the result
6425 // of that operation is undefined.
6426 if (ShLeftAmt >= VT.getSizeInBits())
6427 Result = DAG.getConstant(0, VT);
6429 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6430 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6433 // Return the new loaded value.
6437 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6438 SDValue N0 = N->getOperand(0);
6439 SDValue N1 = N->getOperand(1);
6440 EVT VT = N->getValueType(0);
6441 EVT EVT = cast<VTSDNode>(N1)->getVT();
6442 unsigned VTBits = VT.getScalarType().getSizeInBits();
6443 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6445 // fold (sext_in_reg c1) -> c1
6446 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6447 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6449 // If the input is already sign extended, just drop the extension.
6450 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6453 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6454 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6455 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6456 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6457 N0.getOperand(0), N1);
6459 // fold (sext_in_reg (sext x)) -> (sext x)
6460 // fold (sext_in_reg (aext x)) -> (sext x)
6461 // if x is small enough.
6462 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6463 SDValue N00 = N0.getOperand(0);
6464 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6465 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6466 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6469 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6470 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6471 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6473 // fold operands of sext_in_reg based on knowledge that the top bits are not
6475 if (SimplifyDemandedBits(SDValue(N, 0)))
6476 return SDValue(N, 0);
6478 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6479 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6480 SDValue NarrowLoad = ReduceLoadWidth(N);
6481 if (NarrowLoad.getNode())
6484 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6485 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6486 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6487 if (N0.getOpcode() == ISD::SRL) {
6488 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6489 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6490 // We can turn this into an SRA iff the input to the SRL is already sign
6492 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6493 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6494 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6495 N0.getOperand(0), N0.getOperand(1));
6499 // fold (sext_inreg (extload x)) -> (sextload x)
6500 if (ISD::isEXTLoad(N0.getNode()) &&
6501 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6502 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6503 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6504 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6505 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6506 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6508 LN0->getBasePtr(), EVT,
6509 LN0->getMemOperand());
6510 CombineTo(N, ExtLoad);
6511 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6512 AddToWorklist(ExtLoad.getNode());
6513 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6515 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6516 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6518 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6519 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6520 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6521 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6522 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6524 LN0->getBasePtr(), EVT,
6525 LN0->getMemOperand());
6526 CombineTo(N, ExtLoad);
6527 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6528 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6531 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6532 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6533 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6534 N0.getOperand(1), false);
6535 if (BSwap.getNode())
6536 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6540 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6541 // into a build_vector.
6542 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6543 SmallVector<SDValue, 8> Elts;
6544 unsigned NumElts = N0->getNumOperands();
6545 unsigned ShAmt = VTBits - EVTBits;
6547 for (unsigned i = 0; i != NumElts; ++i) {
6548 SDValue Op = N0->getOperand(i);
6549 if (Op->getOpcode() == ISD::UNDEF) {
6554 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6555 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6556 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6557 Op.getValueType()));
6560 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6566 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6567 SDValue N0 = N->getOperand(0);
6568 EVT VT = N->getValueType(0);
6569 bool isLE = TLI.isLittleEndian();
6572 if (N0.getValueType() == N->getValueType(0))
6574 // fold (truncate c1) -> c1
6575 if (isConstantIntBuildVectorOrConstantInt(N0))
6576 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6577 // fold (truncate (truncate x)) -> (truncate x)
6578 if (N0.getOpcode() == ISD::TRUNCATE)
6579 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6580 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6581 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6582 N0.getOpcode() == ISD::SIGN_EXTEND ||
6583 N0.getOpcode() == ISD::ANY_EXTEND) {
6584 if (N0.getOperand(0).getValueType().bitsLT(VT))
6585 // if the source is smaller than the dest, we still need an extend
6586 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6588 if (N0.getOperand(0).getValueType().bitsGT(VT))
6589 // if the source is larger than the dest, than we just need the truncate
6590 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6591 // if the source and dest are the same type, we can drop both the extend
6592 // and the truncate.
6593 return N0.getOperand(0);
6596 // Fold extract-and-trunc into a narrow extract. For example:
6597 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6598 // i32 y = TRUNCATE(i64 x)
6600 // v16i8 b = BITCAST (v2i64 val)
6601 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6603 // Note: We only run this optimization after type legalization (which often
6604 // creates this pattern) and before operation legalization after which
6605 // we need to be more careful about the vector instructions that we generate.
6606 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6607 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6609 EVT VecTy = N0.getOperand(0).getValueType();
6610 EVT ExTy = N0.getValueType();
6611 EVT TrTy = N->getValueType(0);
6613 unsigned NumElem = VecTy.getVectorNumElements();
6614 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6616 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6617 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6619 SDValue EltNo = N0->getOperand(1);
6620 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6621 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6622 EVT IndexTy = TLI.getVectorIdxTy();
6623 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6625 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6626 NVT, N0.getOperand(0));
6628 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6630 DAG.getConstant(Index, IndexTy));
6634 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6635 if (N0.getOpcode() == ISD::SELECT) {
6636 EVT SrcVT = N0.getValueType();
6637 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6638 TLI.isTruncateFree(SrcVT, VT)) {
6640 SDValue Cond = N0.getOperand(0);
6641 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6642 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6643 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6647 // Fold a series of buildvector, bitcast, and truncate if possible.
6649 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6650 // (2xi32 (buildvector x, y)).
6651 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6652 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6653 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6654 N0.getOperand(0).hasOneUse()) {
6656 SDValue BuildVect = N0.getOperand(0);
6657 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6658 EVT TruncVecEltTy = VT.getVectorElementType();
6660 // Check that the element types match.
6661 if (BuildVectEltTy == TruncVecEltTy) {
6662 // Now we only need to compute the offset of the truncated elements.
6663 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6664 unsigned TruncVecNumElts = VT.getVectorNumElements();
6665 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6667 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6668 "Invalid number of elements");
6670 SmallVector<SDValue, 8> Opnds;
6671 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6672 Opnds.push_back(BuildVect.getOperand(i));
6674 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6678 // See if we can simplify the input to this truncate through knowledge that
6679 // only the low bits are being used.
6680 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6681 // Currently we only perform this optimization on scalars because vectors
6682 // may have different active low bits.
6683 if (!VT.isVector()) {
6685 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6686 VT.getSizeInBits()));
6687 if (Shorter.getNode())
6688 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6690 // fold (truncate (load x)) -> (smaller load x)
6691 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6692 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6693 SDValue Reduced = ReduceLoadWidth(N);
6694 if (Reduced.getNode())
6696 // Handle the case where the load remains an extending load even
6697 // after truncation.
6698 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6699 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6700 if (!LN0->isVolatile() &&
6701 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6702 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6703 VT, LN0->getChain(), LN0->getBasePtr(),
6705 LN0->getMemOperand());
6706 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6711 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6712 // where ... are all 'undef'.
6713 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6714 SmallVector<EVT, 8> VTs;
6717 unsigned NumDefs = 0;
6719 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6720 SDValue X = N0.getOperand(i);
6721 if (X.getOpcode() != ISD::UNDEF) {
6726 // Stop if more than one members are non-undef.
6729 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6730 VT.getVectorElementType(),
6731 X.getValueType().getVectorNumElements()));
6735 return DAG.getUNDEF(VT);
6738 assert(V.getNode() && "The single defined operand is empty!");
6739 SmallVector<SDValue, 8> Opnds;
6740 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6742 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6745 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6746 AddToWorklist(NV.getNode());
6747 Opnds.push_back(NV);
6749 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6753 // Simplify the operands using demanded-bits information.
6754 if (!VT.isVector() &&
6755 SimplifyDemandedBits(SDValue(N, 0)))
6756 return SDValue(N, 0);
6761 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6762 SDValue Elt = N->getOperand(i);
6763 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6764 return Elt.getNode();
6765 return Elt.getOperand(Elt.getResNo()).getNode();
6768 /// build_pair (load, load) -> load
6769 /// if load locations are consecutive.
6770 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6771 assert(N->getOpcode() == ISD::BUILD_PAIR);
6773 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6774 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6775 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6776 LD1->getAddressSpace() != LD2->getAddressSpace())
6778 EVT LD1VT = LD1->getValueType(0);
6780 if (ISD::isNON_EXTLoad(LD2) &&
6782 // If both are volatile this would reduce the number of volatile loads.
6783 // If one is volatile it might be ok, but play conservative and bail out.
6784 !LD1->isVolatile() &&
6785 !LD2->isVolatile() &&
6786 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6787 unsigned Align = LD1->getAlignment();
6788 unsigned NewAlign = TLI.getDataLayout()->
6789 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6791 if (NewAlign <= Align &&
6792 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6793 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6794 LD1->getBasePtr(), LD1->getPointerInfo(),
6795 false, false, false, Align);
6801 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6802 SDValue N0 = N->getOperand(0);
6803 EVT VT = N->getValueType(0);
6805 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6806 // Only do this before legalize, since afterward the target may be depending
6807 // on the bitconvert.
6808 // First check to see if this is all constant.
6810 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6812 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6814 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6815 assert(!DestEltVT.isVector() &&
6816 "Element type of vector ValueType must not be vector!");
6818 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6821 // If the input is a constant, let getNode fold it.
6822 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6823 // If we can't allow illegal operations, we need to check that this is just
6824 // a fp -> int or int -> conversion and that the resulting operation will
6826 if (!LegalOperations ||
6827 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6828 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6829 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6830 TLI.isOperationLegal(ISD::Constant, VT)))
6831 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6834 // (conv (conv x, t1), t2) -> (conv x, t2)
6835 if (N0.getOpcode() == ISD::BITCAST)
6836 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6839 // fold (conv (load x)) -> (load (conv*)x)
6840 // If the resultant load doesn't need a higher alignment than the original!
6841 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6842 // Do not change the width of a volatile load.
6843 !cast<LoadSDNode>(N0)->isVolatile() &&
6844 // Do not remove the cast if the types differ in endian layout.
6845 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6846 TLI.hasBigEndianPartOrdering(VT) &&
6847 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6848 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6849 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6850 unsigned Align = TLI.getDataLayout()->
6851 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6852 unsigned OrigAlign = LN0->getAlignment();
6854 if (Align <= OrigAlign) {
6855 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6856 LN0->getBasePtr(), LN0->getPointerInfo(),
6857 LN0->isVolatile(), LN0->isNonTemporal(),
6858 LN0->isInvariant(), OrigAlign,
6860 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6865 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6866 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6867 // This often reduces constant pool loads.
6868 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6869 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6870 N0.getNode()->hasOneUse() && VT.isInteger() &&
6871 !VT.isVector() && !N0.getValueType().isVector()) {
6872 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6874 AddToWorklist(NewConv.getNode());
6876 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6877 if (N0.getOpcode() == ISD::FNEG)
6878 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6879 NewConv, DAG.getConstant(SignBit, VT));
6880 assert(N0.getOpcode() == ISD::FABS);
6881 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6882 NewConv, DAG.getConstant(~SignBit, VT));
6885 // fold (bitconvert (fcopysign cst, x)) ->
6886 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6887 // Note that we don't handle (copysign x, cst) because this can always be
6888 // folded to an fneg or fabs.
6889 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6890 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6891 VT.isInteger() && !VT.isVector()) {
6892 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6893 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6894 if (isTypeLegal(IntXVT)) {
6895 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6896 IntXVT, N0.getOperand(1));
6897 AddToWorklist(X.getNode());
6899 // If X has a different width than the result/lhs, sext it or truncate it.
6900 unsigned VTWidth = VT.getSizeInBits();
6901 if (OrigXWidth < VTWidth) {
6902 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6903 AddToWorklist(X.getNode());
6904 } else if (OrigXWidth > VTWidth) {
6905 // To get the sign bit in the right place, we have to shift it right
6906 // before truncating.
6907 X = DAG.getNode(ISD::SRL, SDLoc(X),
6908 X.getValueType(), X,
6909 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6910 AddToWorklist(X.getNode());
6911 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6912 AddToWorklist(X.getNode());
6915 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6916 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6917 X, DAG.getConstant(SignBit, VT));
6918 AddToWorklist(X.getNode());
6920 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6921 VT, N0.getOperand(0));
6922 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6923 Cst, DAG.getConstant(~SignBit, VT));
6924 AddToWorklist(Cst.getNode());
6926 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6930 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6931 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6932 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6933 if (CombineLD.getNode())
6940 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6941 EVT VT = N->getValueType(0);
6942 return CombineConsecutiveLoads(N, VT);
6945 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6946 /// operands. DstEltVT indicates the destination element value type.
6947 SDValue DAGCombiner::
6948 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6949 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6951 // If this is already the right type, we're done.
6952 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6954 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6955 unsigned DstBitSize = DstEltVT.getSizeInBits();
6957 // If this is a conversion of N elements of one type to N elements of another
6958 // type, convert each element. This handles FP<->INT cases.
6959 if (SrcBitSize == DstBitSize) {
6960 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6961 BV->getValueType(0).getVectorNumElements());
6963 // Due to the FP element handling below calling this routine recursively,
6964 // we can end up with a scalar-to-vector node here.
6965 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6966 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6967 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6968 DstEltVT, BV->getOperand(0)));
6970 SmallVector<SDValue, 8> Ops;
6971 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6972 SDValue Op = BV->getOperand(i);
6973 // If the vector element type is not legal, the BUILD_VECTOR operands
6974 // are promoted and implicitly truncated. Make that explicit here.
6975 if (Op.getValueType() != SrcEltVT)
6976 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6977 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6979 AddToWorklist(Ops.back().getNode());
6981 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6984 // Otherwise, we're growing or shrinking the elements. To avoid having to
6985 // handle annoying details of growing/shrinking FP values, we convert them to
6987 if (SrcEltVT.isFloatingPoint()) {
6988 // Convert the input float vector to a int vector where the elements are the
6990 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6991 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6995 // Now we know the input is an integer vector. If the output is a FP type,
6996 // convert to integer first, then to FP of the right size.
6997 if (DstEltVT.isFloatingPoint()) {
6998 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6999 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7001 // Next, convert to FP elements of the same size.
7002 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7005 // Okay, we know the src/dst types are both integers of differing types.
7006 // Handling growing first.
7007 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7008 if (SrcBitSize < DstBitSize) {
7009 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7011 SmallVector<SDValue, 8> Ops;
7012 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7013 i += NumInputsPerOutput) {
7014 bool isLE = TLI.isLittleEndian();
7015 APInt NewBits = APInt(DstBitSize, 0);
7016 bool EltIsUndef = true;
7017 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7018 // Shift the previously computed bits over.
7019 NewBits <<= SrcBitSize;
7020 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7021 if (Op.getOpcode() == ISD::UNDEF) continue;
7024 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7025 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7029 Ops.push_back(DAG.getUNDEF(DstEltVT));
7031 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
7034 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7035 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7038 // Finally, this must be the case where we are shrinking elements: each input
7039 // turns into multiple outputs.
7040 bool isS2V = ISD::isScalarToVector(BV);
7041 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7042 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7043 NumOutputsPerInput*BV->getNumOperands());
7044 SmallVector<SDValue, 8> Ops;
7046 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7047 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7048 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7052 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7053 getAPIntValue().zextOrTrunc(SrcBitSize);
7055 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7056 APInt ThisVal = OpVal.trunc(DstBitSize);
7057 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
7058 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
7059 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
7060 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7062 OpVal = OpVal.lshr(DstBitSize);
7065 // For big endian targets, swap the order of the pieces of each element.
7066 if (TLI.isBigEndian())
7067 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7070 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7073 // Attempt different variants of (fadd (fmul a, b), c) -> fma or fmad
7074 static SDValue performFaddFmulCombines(unsigned FusedOpcode,
7077 const TargetLowering &TLI,
7078 SelectionDAG &DAG) {
7079 SDValue N0 = N->getOperand(0);
7080 SDValue N1 = N->getOperand(1);
7081 EVT VT = N->getValueType(0);
7083 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7084 if (N0.getOpcode() == ISD::FMUL &&
7085 (Aggressive || N0->hasOneUse())) {
7086 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7087 N0.getOperand(0), N0.getOperand(1), N1);
7090 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7091 // Note: Commutes FADD operands.
7092 if (N1.getOpcode() == ISD::FMUL &&
7093 (Aggressive || N1->hasOneUse())) {
7094 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7095 N1.getOperand(0), N1.getOperand(1), N0);
7098 // More folding opportunities when target permits.
7100 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7101 if (N0.getOpcode() == ISD::FMA &&
7102 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7103 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7104 N0.getOperand(0), N0.getOperand(1),
7105 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7106 N0.getOperand(2).getOperand(0),
7107 N0.getOperand(2).getOperand(1),
7111 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7112 if (N1->getOpcode() == ISD::FMA &&
7113 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7114 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7115 N1.getOperand(0), N1.getOperand(1),
7116 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7117 N1.getOperand(2).getOperand(0),
7118 N1.getOperand(2).getOperand(1),
7126 static SDValue performFsubFmulCombines(unsigned FusedOpcode,
7129 const TargetLowering &TLI,
7130 SelectionDAG &DAG) {
7131 SDValue N0 = N->getOperand(0);
7132 SDValue N1 = N->getOperand(1);
7133 EVT VT = N->getValueType(0);
7137 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7138 if (N0.getOpcode() == ISD::FMUL &&
7139 (Aggressive || N0->hasOneUse())) {
7140 return DAG.getNode(FusedOpcode, SL, VT,
7141 N0.getOperand(0), N0.getOperand(1),
7142 DAG.getNode(ISD::FNEG, SL, VT, N1));
7145 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7146 // Note: Commutes FSUB operands.
7147 if (N1.getOpcode() == ISD::FMUL &&
7148 (Aggressive || N1->hasOneUse()))
7149 return DAG.getNode(FusedOpcode, SL, VT,
7150 DAG.getNode(ISD::FNEG, SL, VT,
7152 N1.getOperand(1), N0);
7154 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7155 if (N0.getOpcode() == ISD::FNEG &&
7156 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7157 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7158 SDValue N00 = N0.getOperand(0).getOperand(0);
7159 SDValue N01 = N0.getOperand(0).getOperand(1);
7160 return DAG.getNode(FusedOpcode, SL, VT,
7161 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7162 DAG.getNode(ISD::FNEG, SL, VT, N1));
7165 // More folding opportunities when target permits.
7167 // fold (fsub (fma x, y, (fmul u, v)), z)
7168 // -> (fma x, y (fma u, v, (fneg z)))
7169 if (N0.getOpcode() == FusedOpcode &&
7170 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7171 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7172 N0.getOperand(0), N0.getOperand(1),
7173 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7174 N0.getOperand(2).getOperand(0),
7175 N0.getOperand(2).getOperand(1),
7176 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7180 // fold (fsub x, (fma y, z, (fmul u, v)))
7181 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7182 if (N1.getOpcode() == FusedOpcode &&
7183 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7184 SDValue N20 = N1.getOperand(2).getOperand(0);
7185 SDValue N21 = N1.getOperand(2).getOperand(1);
7186 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7187 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7190 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7191 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7200 SDValue DAGCombiner::visitFADD(SDNode *N) {
7201 SDValue N0 = N->getOperand(0);
7202 SDValue N1 = N->getOperand(1);
7203 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7204 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7205 EVT VT = N->getValueType(0);
7206 const TargetOptions &Options = DAG.getTarget().Options;
7209 if (VT.isVector()) {
7210 SDValue FoldedVOp = SimplifyVBinOp(N);
7211 if (FoldedVOp.getNode()) return FoldedVOp;
7214 // fold (fadd c1, c2) -> c1 + c2
7216 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
7218 // canonicalize constant to RHS
7219 if (N0CFP && !N1CFP)
7220 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7222 // fold (fadd A, (fneg B)) -> (fsub A, B)
7223 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7224 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7225 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
7226 GetNegatedExpression(N1, DAG, LegalOperations));
7228 // fold (fadd (fneg A), B) -> (fsub B, A)
7229 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7230 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7231 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
7232 GetNegatedExpression(N0, DAG, LegalOperations));
7234 // If 'unsafe math' is enabled, fold lots of things.
7235 if (Options.UnsafeFPMath) {
7236 // No FP constant should be created after legalization as Instruction
7237 // Selection pass has a hard time dealing with FP constants.
7238 bool AllowNewConst = (Level < AfterLegalizeDAG);
7240 // fold (fadd A, 0) -> A
7241 if (N1CFP && N1CFP->getValueAPF().isZero())
7244 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7245 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7246 isa<ConstantFPSDNode>(N0.getOperand(1)))
7247 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7248 DAG.getNode(ISD::FADD, SDLoc(N), VT,
7249 N0.getOperand(1), N1));
7251 // If allowed, fold (fadd (fneg x), x) -> 0.0
7252 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7253 return DAG.getConstantFP(0.0, VT);
7255 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7256 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7257 return DAG.getConstantFP(0.0, VT);
7259 // We can fold chains of FADD's of the same value into multiplications.
7260 // This transform is not safe in general because we are reducing the number
7261 // of rounding steps.
7262 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7263 if (N0.getOpcode() == ISD::FMUL) {
7264 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7265 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7267 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7268 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7269 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7271 DAG.getConstantFP(1.0, VT));
7272 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7275 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7276 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7277 N1.getOperand(0) == N1.getOperand(1) &&
7278 N0.getOperand(0) == N1.getOperand(0)) {
7279 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7281 DAG.getConstantFP(2.0, VT));
7282 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7283 N0.getOperand(0), NewCFP);
7287 if (N1.getOpcode() == ISD::FMUL) {
7288 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7289 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7291 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7292 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7293 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7295 DAG.getConstantFP(1.0, VT));
7296 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7299 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7300 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7301 N0.getOperand(0) == N0.getOperand(1) &&
7302 N1.getOperand(0) == N0.getOperand(0)) {
7303 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7305 DAG.getConstantFP(2.0, VT));
7306 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7310 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7311 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7312 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7313 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7314 (N0.getOperand(0) == N1))
7315 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7316 N1, DAG.getConstantFP(3.0, VT));
7319 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7320 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7321 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7322 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7323 N1.getOperand(0) == N0)
7324 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7325 N0, DAG.getConstantFP(3.0, VT));
7328 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7329 if (AllowNewConst &&
7330 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7331 N0.getOperand(0) == N0.getOperand(1) &&
7332 N1.getOperand(0) == N1.getOperand(1) &&
7333 N0.getOperand(0) == N1.getOperand(0))
7334 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7335 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
7337 } // enable-unsafe-fp-math
7339 if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7340 // Assume if there is an fmad instruction that it should be aggressively
7342 if (SDValue Fused = performFaddFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7346 // FADD -> FMA combines:
7347 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7348 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7349 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7351 if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7352 // Don't form FMA if we are preferring FMAD.
7354 = performFaddFmulCombines(ISD::FMA,
7355 TLI.enableAggressiveFMAFusion(VT),
7361 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7362 // to combine into FMA, arrange such nodes accordingly.
7363 if (TLI.isFPExtFree(VT)) {
7365 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7366 if (N0.getOpcode() == ISD::FP_EXTEND) {
7367 SDValue N00 = N0.getOperand(0);
7368 if (N00.getOpcode() == ISD::FMUL)
7369 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7370 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7372 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7373 N00.getOperand(1)), N1);
7376 // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
7377 // Note: Commutes FADD operands.
7378 if (N1.getOpcode() == ISD::FP_EXTEND) {
7379 SDValue N10 = N1.getOperand(0);
7380 if (N10.getOpcode() == ISD::FMUL)
7381 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7382 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7384 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7385 N10.getOperand(1)), N0);
7393 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7394 SDValue N0 = N->getOperand(0);
7395 SDValue N1 = N->getOperand(1);
7396 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7397 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7398 EVT VT = N->getValueType(0);
7400 const TargetOptions &Options = DAG.getTarget().Options;
7403 if (VT.isVector()) {
7404 SDValue FoldedVOp = SimplifyVBinOp(N);
7405 if (FoldedVOp.getNode()) return FoldedVOp;
7408 // fold (fsub c1, c2) -> c1-c2
7410 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7412 // fold (fsub A, (fneg B)) -> (fadd A, B)
7413 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7414 return DAG.getNode(ISD::FADD, dl, VT, N0,
7415 GetNegatedExpression(N1, DAG, LegalOperations));
7417 // If 'unsafe math' is enabled, fold lots of things.
7418 if (Options.UnsafeFPMath) {
7420 if (N1CFP && N1CFP->getValueAPF().isZero())
7423 // (fsub 0, B) -> -B
7424 if (N0CFP && N0CFP->getValueAPF().isZero()) {
7425 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7426 return GetNegatedExpression(N1, DAG, LegalOperations);
7427 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7428 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7431 // (fsub x, x) -> 0.0
7433 return DAG.getConstantFP(0.0f, VT);
7435 // (fsub x, (fadd x, y)) -> (fneg y)
7436 // (fsub x, (fadd y, x)) -> (fneg y)
7437 if (N1.getOpcode() == ISD::FADD) {
7438 SDValue N10 = N1->getOperand(0);
7439 SDValue N11 = N1->getOperand(1);
7441 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7442 return GetNegatedExpression(N11, DAG, LegalOperations);
7444 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7445 return GetNegatedExpression(N10, DAG, LegalOperations);
7449 if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7450 // Assume if there is an fmad instruction that it should be aggressively
7452 if (SDValue Fused = performFsubFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7456 // FSUB -> FMA combines:
7457 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7458 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7459 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7461 if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7462 // Don't form FMA if we are preferring FMAD.
7465 = performFsubFmulCombines(ISD::FMA,
7466 TLI.enableAggressiveFMAFusion(VT),
7472 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7473 // to combine into FMA, arrange such nodes accordingly.
7474 if (TLI.isFPExtFree(VT)) {
7475 // fold (fsub (fpext (fmul x, y)), z)
7476 // -> (fma (fpext x), (fpext y), (fneg z))
7477 if (N0.getOpcode() == ISD::FP_EXTEND) {
7478 SDValue N00 = N0.getOperand(0);
7479 if (N00.getOpcode() == ISD::FMUL)
7480 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7481 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7483 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7485 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7488 // fold (fsub x, (fpext (fmul y, z)))
7489 // -> (fma (fneg (fpext y)), (fpext z), x)
7490 // Note: Commutes FSUB operands.
7491 if (N1.getOpcode() == ISD::FP_EXTEND) {
7492 SDValue N10 = N1.getOperand(0);
7493 if (N10.getOpcode() == ISD::FMUL)
7494 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7495 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7496 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7497 VT, N10.getOperand(0))),
7498 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7503 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7504 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7505 if (N0.getOpcode() == ISD::FP_EXTEND) {
7506 SDValue N00 = N0.getOperand(0);
7507 if (N00.getOpcode() == ISD::FNEG) {
7508 SDValue N000 = N00.getOperand(0);
7509 if (N000.getOpcode() == ISD::FMUL) {
7510 return DAG.getNode(ISD::FMA, dl, VT,
7511 DAG.getNode(ISD::FNEG, dl, VT,
7512 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7513 VT, N000.getOperand(0))),
7514 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7515 N000.getOperand(1)),
7516 DAG.getNode(ISD::FNEG, dl, VT, N1));
7521 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7522 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7523 if (N0.getOpcode() == ISD::FNEG) {
7524 SDValue N00 = N0.getOperand(0);
7525 if (N00.getOpcode() == ISD::FP_EXTEND) {
7526 SDValue N000 = N00.getOperand(0);
7527 if (N000.getOpcode() == ISD::FMUL) {
7528 return DAG.getNode(ISD::FMA, dl, VT,
7529 DAG.getNode(ISD::FNEG, dl, VT,
7530 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7531 VT, N000.getOperand(0))),
7532 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7533 N000.getOperand(1)),
7534 DAG.getNode(ISD::FNEG, dl, VT, N1));
7544 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7545 SDValue N0 = N->getOperand(0);
7546 SDValue N1 = N->getOperand(1);
7547 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7548 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7549 EVT VT = N->getValueType(0);
7550 const TargetOptions &Options = DAG.getTarget().Options;
7553 if (VT.isVector()) {
7554 // This just handles C1 * C2 for vectors. Other vector folds are below.
7555 SDValue FoldedVOp = SimplifyVBinOp(N);
7556 if (FoldedVOp.getNode())
7558 // Canonicalize vector constant to RHS.
7559 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7560 N1.getOpcode() != ISD::BUILD_VECTOR)
7561 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7562 if (BV0->isConstant())
7563 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7566 // fold (fmul c1, c2) -> c1*c2
7568 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7570 // canonicalize constant to RHS
7571 if (N0CFP && !N1CFP)
7572 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7574 // fold (fmul A, 1.0) -> A
7575 if (N1CFP && N1CFP->isExactlyValue(1.0))
7578 if (Options.UnsafeFPMath) {
7579 // fold (fmul A, 0) -> 0
7580 if (N1CFP && N1CFP->getValueAPF().isZero())
7583 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7584 if (N0.getOpcode() == ISD::FMUL) {
7585 // Fold scalars or any vector constants (not just splats).
7586 // This fold is done in general by InstCombine, but extra fmul insts
7587 // may have been generated during lowering.
7588 SDValue N00 = N0.getOperand(0);
7589 SDValue N01 = N0.getOperand(1);
7590 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7591 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7592 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7594 // Check 1: Make sure that the first operand of the inner multiply is NOT
7595 // a constant. Otherwise, we may induce infinite looping.
7596 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7597 // Check 2: Make sure that the second operand of the inner multiply and
7598 // the second operand of the outer multiply are constants.
7599 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7600 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7602 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7603 return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7608 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7609 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7610 // during an early run of DAGCombiner can prevent folding with fmuls
7611 // inserted during lowering.
7612 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7614 const SDValue Two = DAG.getConstantFP(2.0, VT);
7615 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7616 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7620 // fold (fmul X, 2.0) -> (fadd X, X)
7621 if (N1CFP && N1CFP->isExactlyValue(+2.0))
7622 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7624 // fold (fmul X, -1.0) -> (fneg X)
7625 if (N1CFP && N1CFP->isExactlyValue(-1.0))
7626 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7627 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7629 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7630 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7631 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7632 // Both can be negated for free, check to see if at least one is cheaper
7634 if (LHSNeg == 2 || RHSNeg == 2)
7635 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7636 GetNegatedExpression(N0, DAG, LegalOperations),
7637 GetNegatedExpression(N1, DAG, LegalOperations));
7644 SDValue DAGCombiner::visitFMA(SDNode *N) {
7645 SDValue N0 = N->getOperand(0);
7646 SDValue N1 = N->getOperand(1);
7647 SDValue N2 = N->getOperand(2);
7648 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7649 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7650 EVT VT = N->getValueType(0);
7652 const TargetOptions &Options = DAG.getTarget().Options;
7654 // Constant fold FMA.
7655 if (isa<ConstantFPSDNode>(N0) &&
7656 isa<ConstantFPSDNode>(N1) &&
7657 isa<ConstantFPSDNode>(N2)) {
7658 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7661 if (Options.UnsafeFPMath) {
7662 if (N0CFP && N0CFP->isZero())
7664 if (N1CFP && N1CFP->isZero())
7667 if (N0CFP && N0CFP->isExactlyValue(1.0))
7668 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7669 if (N1CFP && N1CFP->isExactlyValue(1.0))
7670 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7672 // Canonicalize (fma c, x, y) -> (fma x, c, y)
7673 if (N0CFP && !N1CFP)
7674 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7676 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7677 if (Options.UnsafeFPMath && N1CFP &&
7678 N2.getOpcode() == ISD::FMUL &&
7679 N0 == N2.getOperand(0) &&
7680 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7681 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7682 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7686 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7687 if (Options.UnsafeFPMath &&
7688 N0.getOpcode() == ISD::FMUL && N1CFP &&
7689 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7690 return DAG.getNode(ISD::FMA, dl, VT,
7692 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7696 // (fma x, 1, y) -> (fadd x, y)
7697 // (fma x, -1, y) -> (fadd (fneg x), y)
7699 if (N1CFP->isExactlyValue(1.0))
7700 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7702 if (N1CFP->isExactlyValue(-1.0) &&
7703 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7704 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7705 AddToWorklist(RHSNeg.getNode());
7706 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7710 // (fma x, c, x) -> (fmul x, (c+1))
7711 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7712 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7713 DAG.getNode(ISD::FADD, dl, VT,
7714 N1, DAG.getConstantFP(1.0, VT)));
7716 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7717 if (Options.UnsafeFPMath && N1CFP &&
7718 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7719 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7720 DAG.getNode(ISD::FADD, dl, VT,
7721 N1, DAG.getConstantFP(-1.0, VT)));
7727 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7728 SDValue N0 = N->getOperand(0);
7729 SDValue N1 = N->getOperand(1);
7730 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7731 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7732 EVT VT = N->getValueType(0);
7734 const TargetOptions &Options = DAG.getTarget().Options;
7737 if (VT.isVector()) {
7738 SDValue FoldedVOp = SimplifyVBinOp(N);
7739 if (FoldedVOp.getNode()) return FoldedVOp;
7742 // fold (fdiv c1, c2) -> c1/c2
7744 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7746 if (Options.UnsafeFPMath) {
7747 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7749 // Compute the reciprocal 1.0 / c2.
7750 APFloat N1APF = N1CFP->getValueAPF();
7751 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7752 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7753 // Only do the transform if the reciprocal is a legal fp immediate that
7754 // isn't too nasty (eg NaN, denormal, ...).
7755 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7756 (!LegalOperations ||
7757 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7758 // backend)... we should handle this gracefully after Legalize.
7759 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7760 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7761 TLI.isFPImmLegal(Recip, VT)))
7762 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7763 DAG.getConstantFP(Recip, VT));
7766 // If this FDIV is part of a reciprocal square root, it may be folded
7767 // into a target-specific square root estimate instruction.
7768 if (N1.getOpcode() == ISD::FSQRT) {
7769 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7770 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7772 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7773 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7774 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7775 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7776 AddToWorklist(RV.getNode());
7777 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7779 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7780 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7781 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7782 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7783 AddToWorklist(RV.getNode());
7784 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7786 } else if (N1.getOpcode() == ISD::FMUL) {
7787 // Look through an FMUL. Even though this won't remove the FDIV directly,
7788 // it's still worthwhile to get rid of the FSQRT if possible.
7791 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7792 SqrtOp = N1.getOperand(0);
7793 OtherOp = N1.getOperand(1);
7794 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7795 SqrtOp = N1.getOperand(1);
7796 OtherOp = N1.getOperand(0);
7798 if (SqrtOp.getNode()) {
7799 // We found a FSQRT, so try to make this fold:
7800 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7801 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7802 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7803 AddToWorklist(RV.getNode());
7804 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7809 // Fold into a reciprocal estimate and multiply instead of a real divide.
7810 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7811 AddToWorklist(RV.getNode());
7812 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7816 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7817 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7818 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7819 // Both can be negated for free, check to see if at least one is cheaper
7821 if (LHSNeg == 2 || RHSNeg == 2)
7822 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7823 GetNegatedExpression(N0, DAG, LegalOperations),
7824 GetNegatedExpression(N1, DAG, LegalOperations));
7828 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7830 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7831 // Notice that this is not always beneficial. One reason is different target
7832 // may have different costs for FDIV and FMUL, so sometimes the cost of two
7833 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7834 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7835 if (Options.UnsafeFPMath) {
7836 // Skip if current node is a reciprocal.
7837 if (N0CFP && N0CFP->isExactlyValue(1.0))
7840 SmallVector<SDNode *, 4> Users;
7841 // Find all FDIV users of the same divisor.
7842 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7843 UE = N1.getNode()->use_end();
7845 SDNode *User = UI.getUse().getUser();
7846 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7847 Users.push_back(User);
7850 if (TLI.combineRepeatedFPDivisors(Users.size())) {
7851 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7852 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7854 // Dividend / Divisor -> Dividend * Reciprocal
7855 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7856 if ((*I)->getOperand(0) != FPOne) {
7857 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7858 (*I)->getOperand(0), Reciprocal);
7859 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7869 SDValue DAGCombiner::visitFREM(SDNode *N) {
7870 SDValue N0 = N->getOperand(0);
7871 SDValue N1 = N->getOperand(1);
7872 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7873 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7874 EVT VT = N->getValueType(0);
7876 // fold (frem c1, c2) -> fmod(c1,c2)
7878 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7883 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7884 if (DAG.getTarget().Options.UnsafeFPMath &&
7885 !TLI.isFsqrtCheap()) {
7886 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7887 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7888 EVT VT = RV.getValueType();
7889 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7890 AddToWorklist(RV.getNode());
7892 // Unfortunately, RV is now NaN if the input was exactly 0.
7893 // Select out this case and force the answer to 0.
7894 SDValue Zero = DAG.getConstantFP(0.0, VT);
7896 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7897 N->getOperand(0), Zero, ISD::SETEQ);
7898 AddToWorklist(ZeroCmp.getNode());
7899 AddToWorklist(RV.getNode());
7901 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7902 SDLoc(N), VT, ZeroCmp, Zero, RV);
7909 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7910 SDValue N0 = N->getOperand(0);
7911 SDValue N1 = N->getOperand(1);
7912 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7913 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7914 EVT VT = N->getValueType(0);
7916 if (N0CFP && N1CFP) // Constant fold
7917 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7920 const APFloat& V = N1CFP->getValueAPF();
7921 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7922 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7923 if (!V.isNegative()) {
7924 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7925 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7927 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7928 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7929 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7933 // copysign(fabs(x), y) -> copysign(x, y)
7934 // copysign(fneg(x), y) -> copysign(x, y)
7935 // copysign(copysign(x,z), y) -> copysign(x, y)
7936 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7937 N0.getOpcode() == ISD::FCOPYSIGN)
7938 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7939 N0.getOperand(0), N1);
7941 // copysign(x, abs(y)) -> abs(x)
7942 if (N1.getOpcode() == ISD::FABS)
7943 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7945 // copysign(x, copysign(y,z)) -> copysign(x, z)
7946 if (N1.getOpcode() == ISD::FCOPYSIGN)
7947 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7948 N0, N1.getOperand(1));
7950 // copysign(x, fp_extend(y)) -> copysign(x, y)
7951 // copysign(x, fp_round(y)) -> copysign(x, y)
7952 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7953 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7954 N0, N1.getOperand(0));
7959 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7960 SDValue N0 = N->getOperand(0);
7961 EVT VT = N->getValueType(0);
7962 EVT OpVT = N0.getValueType();
7964 // fold (sint_to_fp c1) -> c1fp
7965 if (isConstantIntBuildVectorOrConstantInt(N0) &&
7966 // ...but only if the target supports immediate floating-point values
7967 (!LegalOperations ||
7968 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7969 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7971 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7972 // but UINT_TO_FP is legal on this target, try to convert.
7973 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7974 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7975 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7976 if (DAG.SignBitIsZero(N0))
7977 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7980 // The next optimizations are desirable only if SELECT_CC can be lowered.
7981 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7982 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7983 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7985 (!LegalOperations ||
7986 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7988 { N0.getOperand(0), N0.getOperand(1),
7989 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7991 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7994 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7995 // (select_cc x, y, 1.0, 0.0,, cc)
7996 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7997 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7998 (!LegalOperations ||
7999 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8001 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8002 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
8003 N0.getOperand(0).getOperand(2) };
8004 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8011 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8012 SDValue N0 = N->getOperand(0);
8013 EVT VT = N->getValueType(0);
8014 EVT OpVT = N0.getValueType();
8016 // fold (uint_to_fp c1) -> c1fp
8017 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8018 // ...but only if the target supports immediate floating-point values
8019 (!LegalOperations ||
8020 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8021 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8023 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8024 // but SINT_TO_FP is legal on this target, try to convert.
8025 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8026 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8027 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8028 if (DAG.SignBitIsZero(N0))
8029 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8032 // The next optimizations are desirable only if SELECT_CC can be lowered.
8033 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8034 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8036 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8037 (!LegalOperations ||
8038 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8040 { N0.getOperand(0), N0.getOperand(1),
8041 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
8043 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
8050 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8051 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8052 SDValue N0 = N->getOperand(0);
8053 EVT VT = N->getValueType(0);
8055 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8058 SDValue Src = N0.getOperand(0);
8059 EVT SrcVT = Src.getValueType();
8060 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8061 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8063 // We can safely assume the conversion won't overflow the output range,
8064 // because (for example) (uint8_t)18293.f is undefined behavior.
8066 // Since we can assume the conversion won't overflow, our decision as to
8067 // whether the input will fit in the float should depend on the minimum
8068 // of the input range and output range.
8070 // This means this is also safe for a signed input and unsigned output, since
8071 // a negative input would lead to undefined behavior.
8072 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8073 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8074 unsigned ActualSize = std::min(InputSize, OutputSize);
8075 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8077 // We can only fold away the float conversion if the input range can be
8078 // represented exactly in the float range.
8079 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8080 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8081 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8083 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8085 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8086 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8089 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8094 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8095 SDValue N0 = N->getOperand(0);
8096 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8097 EVT VT = N->getValueType(0);
8099 // fold (fp_to_sint c1fp) -> c1
8101 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8103 return FoldIntToFPToInt(N, DAG);
8106 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8107 SDValue N0 = N->getOperand(0);
8108 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8109 EVT VT = N->getValueType(0);
8111 // fold (fp_to_uint c1fp) -> c1
8113 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8115 return FoldIntToFPToInt(N, DAG);
8118 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8119 SDValue N0 = N->getOperand(0);
8120 SDValue N1 = N->getOperand(1);
8121 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8122 EVT VT = N->getValueType(0);
8124 // fold (fp_round c1fp) -> c1fp
8126 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8128 // fold (fp_round (fp_extend x)) -> x
8129 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8130 return N0.getOperand(0);
8132 // fold (fp_round (fp_round x)) -> (fp_round x)
8133 if (N0.getOpcode() == ISD::FP_ROUND) {
8134 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8135 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8136 // If the first fp_round isn't a value preserving truncation, it might
8137 // introduce a tie in the second fp_round, that wouldn't occur in the
8138 // single-step fp_round we want to fold to.
8139 // In other words, double rounding isn't the same as rounding.
8140 // Also, this is a value preserving truncation iff both fp_round's are.
8141 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
8142 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
8143 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
8146 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8147 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8148 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8149 N0.getOperand(0), N1);
8150 AddToWorklist(Tmp.getNode());
8151 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8152 Tmp, N0.getOperand(1));
8158 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8159 SDValue N0 = N->getOperand(0);
8160 EVT VT = N->getValueType(0);
8161 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8162 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8164 // fold (fp_round_inreg c1fp) -> c1fp
8165 if (N0CFP && isTypeLegal(EVT)) {
8166 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
8167 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
8173 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8174 SDValue N0 = N->getOperand(0);
8175 EVT VT = N->getValueType(0);
8177 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8178 if (N->hasOneUse() &&
8179 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8182 // fold (fp_extend c1fp) -> c1fp
8183 if (isConstantFPBuildVectorOrConstantFP(N0))
8184 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8186 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8188 if (N0.getOpcode() == ISD::FP_ROUND
8189 && N0.getNode()->getConstantOperandVal(1) == 1) {
8190 SDValue In = N0.getOperand(0);
8191 if (In.getValueType() == VT) return In;
8192 if (VT.bitsLT(In.getValueType()))
8193 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8194 In, N0.getOperand(1));
8195 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8198 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8199 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8200 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8201 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8202 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8204 LN0->getBasePtr(), N0.getValueType(),
8205 LN0->getMemOperand());
8206 CombineTo(N, ExtLoad);
8207 CombineTo(N0.getNode(),
8208 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8209 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
8210 ExtLoad.getValue(1));
8211 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8217 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8218 SDValue N0 = N->getOperand(0);
8219 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8220 EVT VT = N->getValueType(0);
8222 // fold (fceil c1) -> fceil(c1)
8224 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8229 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8230 SDValue N0 = N->getOperand(0);
8231 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8232 EVT VT = N->getValueType(0);
8234 // fold (ftrunc c1) -> ftrunc(c1)
8236 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8241 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8242 SDValue N0 = N->getOperand(0);
8243 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8244 EVT VT = N->getValueType(0);
8246 // fold (ffloor c1) -> ffloor(c1)
8248 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8253 // FIXME: FNEG and FABS have a lot in common; refactor.
8254 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8255 SDValue N0 = N->getOperand(0);
8256 EVT VT = N->getValueType(0);
8258 // Constant fold FNEG.
8259 if (isConstantFPBuildVectorOrConstantFP(N0))
8260 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8262 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8263 &DAG.getTarget().Options))
8264 return GetNegatedExpression(N0, DAG, LegalOperations);
8266 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8267 // constant pool values.
8268 if (!TLI.isFNegFree(VT) &&
8269 N0.getOpcode() == ISD::BITCAST &&
8270 N0.getNode()->hasOneUse()) {
8271 SDValue Int = N0.getOperand(0);
8272 EVT IntVT = Int.getValueType();
8273 if (IntVT.isInteger() && !IntVT.isVector()) {
8275 if (N0.getValueType().isVector()) {
8276 // For a vector, get a mask such as 0x80... per scalar element
8278 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8279 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8281 // For a scalar, just generate 0x80...
8282 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8284 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
8285 DAG.getConstant(SignMask, IntVT));
8286 AddToWorklist(Int.getNode());
8287 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8291 // (fneg (fmul c, x)) -> (fmul -c, x)
8292 if (N0.getOpcode() == ISD::FMUL) {
8293 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8295 APFloat CVal = CFP1->getValueAPF();
8297 if (Level >= AfterLegalizeDAG &&
8298 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8299 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8301 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8302 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8309 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8310 SDValue N0 = N->getOperand(0);
8311 SDValue N1 = N->getOperand(1);
8312 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8313 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8315 if (N0CFP && N1CFP) {
8316 const APFloat &C0 = N0CFP->getValueAPF();
8317 const APFloat &C1 = N1CFP->getValueAPF();
8318 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8322 EVT VT = N->getValueType(0);
8323 // Canonicalize to constant on RHS.
8324 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8330 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8331 SDValue N0 = N->getOperand(0);
8332 SDValue N1 = N->getOperand(1);
8333 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8334 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8336 if (N0CFP && N1CFP) {
8337 const APFloat &C0 = N0CFP->getValueAPF();
8338 const APFloat &C1 = N1CFP->getValueAPF();
8339 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8343 EVT VT = N->getValueType(0);
8344 // Canonicalize to constant on RHS.
8345 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8351 SDValue DAGCombiner::visitFABS(SDNode *N) {
8352 SDValue N0 = N->getOperand(0);
8353 EVT VT = N->getValueType(0);
8355 // fold (fabs c1) -> fabs(c1)
8356 if (isConstantFPBuildVectorOrConstantFP(N0))
8357 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8359 // fold (fabs (fabs x)) -> (fabs x)
8360 if (N0.getOpcode() == ISD::FABS)
8361 return N->getOperand(0);
8363 // fold (fabs (fneg x)) -> (fabs x)
8364 // fold (fabs (fcopysign x, y)) -> (fabs x)
8365 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8366 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8368 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8369 // constant pool values.
8370 if (!TLI.isFAbsFree(VT) &&
8371 N0.getOpcode() == ISD::BITCAST &&
8372 N0.getNode()->hasOneUse()) {
8373 SDValue Int = N0.getOperand(0);
8374 EVT IntVT = Int.getValueType();
8375 if (IntVT.isInteger() && !IntVT.isVector()) {
8377 if (N0.getValueType().isVector()) {
8378 // For a vector, get a mask such as 0x7f... per scalar element
8380 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8381 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8383 // For a scalar, just generate 0x7f...
8384 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8386 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8387 DAG.getConstant(SignMask, IntVT));
8388 AddToWorklist(Int.getNode());
8389 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8396 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8397 SDValue Chain = N->getOperand(0);
8398 SDValue N1 = N->getOperand(1);
8399 SDValue N2 = N->getOperand(2);
8401 // If N is a constant we could fold this into a fallthrough or unconditional
8402 // branch. However that doesn't happen very often in normal code, because
8403 // Instcombine/SimplifyCFG should have handled the available opportunities.
8404 // If we did this folding here, it would be necessary to update the
8405 // MachineBasicBlock CFG, which is awkward.
8407 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8409 if (N1.getOpcode() == ISD::SETCC &&
8410 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8411 N1.getOperand(0).getValueType())) {
8412 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8413 Chain, N1.getOperand(2),
8414 N1.getOperand(0), N1.getOperand(1), N2);
8417 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8418 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8419 (N1.getOperand(0).hasOneUse() &&
8420 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8421 SDNode *Trunc = nullptr;
8422 if (N1.getOpcode() == ISD::TRUNCATE) {
8423 // Look pass the truncate.
8424 Trunc = N1.getNode();
8425 N1 = N1.getOperand(0);
8428 // Match this pattern so that we can generate simpler code:
8431 // %b = and i32 %a, 2
8432 // %c = srl i32 %b, 1
8433 // brcond i32 %c ...
8438 // %b = and i32 %a, 2
8439 // %c = setcc eq %b, 0
8442 // This applies only when the AND constant value has one bit set and the
8443 // SRL constant is equal to the log2 of the AND constant. The back-end is
8444 // smart enough to convert the result into a TEST/JMP sequence.
8445 SDValue Op0 = N1.getOperand(0);
8446 SDValue Op1 = N1.getOperand(1);
8448 if (Op0.getOpcode() == ISD::AND &&
8449 Op1.getOpcode() == ISD::Constant) {
8450 SDValue AndOp1 = Op0.getOperand(1);
8452 if (AndOp1.getOpcode() == ISD::Constant) {
8453 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8455 if (AndConst.isPowerOf2() &&
8456 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8458 DAG.getSetCC(SDLoc(N),
8459 getSetCCResultType(Op0.getValueType()),
8460 Op0, DAG.getConstant(0, Op0.getValueType()),
8463 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8464 MVT::Other, Chain, SetCC, N2);
8465 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8466 // will convert it back to (X & C1) >> C2.
8467 CombineTo(N, NewBRCond, false);
8468 // Truncate is dead.
8470 deleteAndRecombine(Trunc);
8471 // Replace the uses of SRL with SETCC
8472 WorklistRemover DeadNodes(*this);
8473 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8474 deleteAndRecombine(N1.getNode());
8475 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8481 // Restore N1 if the above transformation doesn't match.
8482 N1 = N->getOperand(1);
8485 // Transform br(xor(x, y)) -> br(x != y)
8486 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8487 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8488 SDNode *TheXor = N1.getNode();
8489 SDValue Op0 = TheXor->getOperand(0);
8490 SDValue Op1 = TheXor->getOperand(1);
8491 if (Op0.getOpcode() == Op1.getOpcode()) {
8492 // Avoid missing important xor optimizations.
8493 SDValue Tmp = visitXOR(TheXor);
8494 if (Tmp.getNode()) {
8495 if (Tmp.getNode() != TheXor) {
8496 DEBUG(dbgs() << "\nReplacing.8 ";
8498 dbgs() << "\nWith: ";
8499 Tmp.getNode()->dump(&DAG);
8501 WorklistRemover DeadNodes(*this);
8502 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8503 deleteAndRecombine(TheXor);
8504 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8505 MVT::Other, Chain, Tmp, N2);
8508 // visitXOR has changed XOR's operands or replaced the XOR completely,
8510 return SDValue(N, 0);
8514 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8516 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8517 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8518 Op0.getOpcode() == ISD::XOR) {
8519 TheXor = Op0.getNode();
8523 EVT SetCCVT = N1.getValueType();
8525 SetCCVT = getSetCCResultType(SetCCVT);
8526 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8529 Equal ? ISD::SETEQ : ISD::SETNE);
8530 // Replace the uses of XOR with SETCC
8531 WorklistRemover DeadNodes(*this);
8532 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8533 deleteAndRecombine(N1.getNode());
8534 return DAG.getNode(ISD::BRCOND, SDLoc(N),
8535 MVT::Other, Chain, SetCC, N2);
8542 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8544 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8545 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8546 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8548 // If N is a constant we could fold this into a fallthrough or unconditional
8549 // branch. However that doesn't happen very often in normal code, because
8550 // Instcombine/SimplifyCFG should have handled the available opportunities.
8551 // If we did this folding here, it would be necessary to update the
8552 // MachineBasicBlock CFG, which is awkward.
8554 // Use SimplifySetCC to simplify SETCC's.
8555 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8556 CondLHS, CondRHS, CC->get(), SDLoc(N),
8558 if (Simp.getNode()) AddToWorklist(Simp.getNode());
8560 // fold to a simpler setcc
8561 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8562 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8563 N->getOperand(0), Simp.getOperand(2),
8564 Simp.getOperand(0), Simp.getOperand(1),
8570 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8571 /// and that N may be folded in the load / store addressing mode.
8572 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8574 const TargetLowering &TLI) {
8576 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
8577 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8579 VT = Use->getValueType(0);
8580 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
8581 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8583 VT = ST->getValue().getValueType();
8587 TargetLowering::AddrMode AM;
8588 if (N->getOpcode() == ISD::ADD) {
8589 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8592 AM.BaseOffs = Offset->getSExtValue();
8596 } else if (N->getOpcode() == ISD::SUB) {
8597 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8600 AM.BaseOffs = -Offset->getSExtValue();
8607 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8610 /// Try turning a load/store into a pre-indexed load/store when the base
8611 /// pointer is an add or subtract and it has other uses besides the load/store.
8612 /// After the transformation, the new indexed load/store has effectively folded
8613 /// the add/subtract in and all of its other uses are redirected to the
8615 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8616 if (Level < AfterLegalizeDAG)
8622 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8623 if (LD->isIndexed())
8625 VT = LD->getMemoryVT();
8626 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8627 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8629 Ptr = LD->getBasePtr();
8630 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8631 if (ST->isIndexed())
8633 VT = ST->getMemoryVT();
8634 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8635 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8637 Ptr = ST->getBasePtr();
8643 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8644 // out. There is no reason to make this a preinc/predec.
8645 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8646 Ptr.getNode()->hasOneUse())
8649 // Ask the target to do addressing mode selection.
8652 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8653 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8656 // Backends without true r+i pre-indexed forms may need to pass a
8657 // constant base with a variable offset so that constant coercion
8658 // will work with the patterns in canonical form.
8659 bool Swapped = false;
8660 if (isa<ConstantSDNode>(BasePtr)) {
8661 std::swap(BasePtr, Offset);
8665 // Don't create a indexed load / store with zero offset.
8666 if (isa<ConstantSDNode>(Offset) &&
8667 cast<ConstantSDNode>(Offset)->isNullValue())
8670 // Try turning it into a pre-indexed load / store except when:
8671 // 1) The new base ptr is a frame index.
8672 // 2) If N is a store and the new base ptr is either the same as or is a
8673 // predecessor of the value being stored.
8674 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8675 // that would create a cycle.
8676 // 4) All uses are load / store ops that use it as old base ptr.
8678 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8679 // (plus the implicit offset) to a register to preinc anyway.
8680 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8685 SDValue Val = cast<StoreSDNode>(N)->getValue();
8686 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8690 // If the offset is a constant, there may be other adds of constants that
8691 // can be folded with this one. We should do this to avoid having to keep
8692 // a copy of the original base pointer.
8693 SmallVector<SDNode *, 16> OtherUses;
8694 if (isa<ConstantSDNode>(Offset))
8695 for (SDNode *Use : BasePtr.getNode()->uses()) {
8696 if (Use == Ptr.getNode())
8699 if (Use->isPredecessorOf(N))
8702 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8707 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8708 if (Op1.getNode() == BasePtr.getNode())
8709 std::swap(Op0, Op1);
8710 assert(Op0.getNode() == BasePtr.getNode() &&
8711 "Use of ADD/SUB but not an operand");
8713 if (!isa<ConstantSDNode>(Op1)) {
8718 // FIXME: In some cases, we can be smarter about this.
8719 if (Op1.getValueType() != Offset.getValueType()) {
8724 OtherUses.push_back(Use);
8728 std::swap(BasePtr, Offset);
8730 // Now check for #3 and #4.
8731 bool RealUse = false;
8733 // Caches for hasPredecessorHelper
8734 SmallPtrSet<const SDNode *, 32> Visited;
8735 SmallVector<const SDNode *, 16> Worklist;
8737 for (SDNode *Use : Ptr.getNode()->uses()) {
8740 if (N->hasPredecessorHelper(Use, Visited, Worklist))
8743 // If Ptr may be folded in addressing mode of other use, then it's
8744 // not profitable to do this transformation.
8745 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8754 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8755 BasePtr, Offset, AM);
8757 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8758 BasePtr, Offset, AM);
8761 DEBUG(dbgs() << "\nReplacing.4 ";
8763 dbgs() << "\nWith: ";
8764 Result.getNode()->dump(&DAG);
8766 WorklistRemover DeadNodes(*this);
8768 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8769 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8771 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8774 // Finally, since the node is now dead, remove it from the graph.
8775 deleteAndRecombine(N);
8778 std::swap(BasePtr, Offset);
8780 // Replace other uses of BasePtr that can be updated to use Ptr
8781 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8782 unsigned OffsetIdx = 1;
8783 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8785 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8786 BasePtr.getNode() && "Expected BasePtr operand");
8788 // We need to replace ptr0 in the following expression:
8789 // x0 * offset0 + y0 * ptr0 = t0
8791 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8793 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8794 // indexed load/store and the expresion that needs to be re-written.
8796 // Therefore, we have:
8797 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8799 ConstantSDNode *CN =
8800 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8802 APInt Offset0 = CN->getAPIntValue();
8803 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8805 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8806 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8807 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8808 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8810 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8812 APInt CNV = Offset0;
8813 if (X0 < 0) CNV = -CNV;
8814 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8815 else CNV = CNV - Offset1;
8817 // We can now generate the new expression.
8818 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8819 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8821 SDValue NewUse = DAG.getNode(Opcode,
8822 SDLoc(OtherUses[i]),
8823 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8824 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8825 deleteAndRecombine(OtherUses[i]);
8828 // Replace the uses of Ptr with uses of the updated base value.
8829 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8830 deleteAndRecombine(Ptr.getNode());
8835 /// Try to combine a load/store with a add/sub of the base pointer node into a
8836 /// post-indexed load/store. The transformation folded the add/subtract into the
8837 /// new indexed load/store effectively and all of its uses are redirected to the
8839 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8840 if (Level < AfterLegalizeDAG)
8846 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8847 if (LD->isIndexed())
8849 VT = LD->getMemoryVT();
8850 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8851 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8853 Ptr = LD->getBasePtr();
8854 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8855 if (ST->isIndexed())
8857 VT = ST->getMemoryVT();
8858 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8859 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8861 Ptr = ST->getBasePtr();
8867 if (Ptr.getNode()->hasOneUse())
8870 for (SDNode *Op : Ptr.getNode()->uses()) {
8872 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8877 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8878 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8879 // Don't create a indexed load / store with zero offset.
8880 if (isa<ConstantSDNode>(Offset) &&
8881 cast<ConstantSDNode>(Offset)->isNullValue())
8884 // Try turning it into a post-indexed load / store except when
8885 // 1) All uses are load / store ops that use it as base ptr (and
8886 // it may be folded as addressing mmode).
8887 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8888 // nor a successor of N. Otherwise, if Op is folded that would
8891 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8895 bool TryNext = false;
8896 for (SDNode *Use : BasePtr.getNode()->uses()) {
8897 if (Use == Ptr.getNode())
8900 // If all the uses are load / store addresses, then don't do the
8902 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8903 bool RealUse = false;
8904 for (SDNode *UseUse : Use->uses()) {
8905 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8920 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8921 SDValue Result = isLoad
8922 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8923 BasePtr, Offset, AM)
8924 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8925 BasePtr, Offset, AM);
8928 DEBUG(dbgs() << "\nReplacing.5 ";
8930 dbgs() << "\nWith: ";
8931 Result.getNode()->dump(&DAG);
8933 WorklistRemover DeadNodes(*this);
8935 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8936 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8938 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8941 // Finally, since the node is now dead, remove it from the graph.
8942 deleteAndRecombine(N);
8944 // Replace the uses of Use with uses of the updated base value.
8945 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8946 Result.getValue(isLoad ? 1 : 0));
8947 deleteAndRecombine(Op);
8956 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8957 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8958 ISD::MemIndexedMode AM = LD->getAddressingMode();
8959 assert(AM != ISD::UNINDEXED);
8960 SDValue BP = LD->getOperand(1);
8961 SDValue Inc = LD->getOperand(2);
8963 // Some backends use TargetConstants for load offsets, but don't expect
8964 // TargetConstants in general ADD nodes. We can convert these constants into
8965 // regular Constants (if the constant is not opaque).
8966 assert((Inc.getOpcode() != ISD::TargetConstant ||
8967 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8968 "Cannot split out indexing using opaque target constants");
8969 if (Inc.getOpcode() == ISD::TargetConstant) {
8970 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8971 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8972 ConstInc->getValueType(0));
8976 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8977 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8980 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8981 LoadSDNode *LD = cast<LoadSDNode>(N);
8982 SDValue Chain = LD->getChain();
8983 SDValue Ptr = LD->getBasePtr();
8985 // If load is not volatile and there are no uses of the loaded value (and
8986 // the updated indexed value in case of indexed loads), change uses of the
8987 // chain value into uses of the chain input (i.e. delete the dead load).
8988 if (!LD->isVolatile()) {
8989 if (N->getValueType(1) == MVT::Other) {
8991 if (!N->hasAnyUseOfValue(0)) {
8992 // It's not safe to use the two value CombineTo variant here. e.g.
8993 // v1, chain2 = load chain1, loc
8994 // v2, chain3 = load chain2, loc
8996 // Now we replace use of chain2 with chain1. This makes the second load
8997 // isomorphic to the one we are deleting, and thus makes this load live.
8998 DEBUG(dbgs() << "\nReplacing.6 ";
9000 dbgs() << "\nWith chain: ";
9001 Chain.getNode()->dump(&DAG);
9003 WorklistRemover DeadNodes(*this);
9004 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9007 deleteAndRecombine(N);
9009 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9013 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9015 // If this load has an opaque TargetConstant offset, then we cannot split
9016 // the indexing into an add/sub directly (that TargetConstant may not be
9017 // valid for a different type of node, and we cannot convert an opaque
9018 // target constant into a regular constant).
9019 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9020 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9022 if (!N->hasAnyUseOfValue(0) &&
9023 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9024 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9026 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9027 Index = SplitIndexingFromLoad(LD);
9028 // Try to fold the base pointer arithmetic into subsequent loads and
9030 AddUsersToWorklist(N);
9032 Index = DAG.getUNDEF(N->getValueType(1));
9033 DEBUG(dbgs() << "\nReplacing.7 ";
9035 dbgs() << "\nWith: ";
9036 Undef.getNode()->dump(&DAG);
9037 dbgs() << " and 2 other values\n");
9038 WorklistRemover DeadNodes(*this);
9039 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9040 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9041 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9042 deleteAndRecombine(N);
9043 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9048 // If this load is directly stored, replace the load value with the stored
9050 // TODO: Handle store large -> read small portion.
9051 // TODO: Handle TRUNCSTORE/LOADEXT
9052 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9053 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9054 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9055 if (PrevST->getBasePtr() == Ptr &&
9056 PrevST->getValue().getValueType() == N->getValueType(0))
9057 return CombineTo(N, Chain.getOperand(1), Chain);
9061 // Try to infer better alignment information than the load already has.
9062 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9063 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9064 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9066 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9067 LD->getValueType(0),
9068 Chain, Ptr, LD->getPointerInfo(),
9070 LD->isVolatile(), LD->isNonTemporal(),
9071 LD->isInvariant(), Align, LD->getAAInfo());
9072 if (NewLoad.getNode() != N)
9073 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9078 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9079 : DAG.getSubtarget().useAA();
9081 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9082 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9085 if (UseAA && LD->isUnindexed()) {
9086 // Walk up chain skipping non-aliasing memory nodes.
9087 SDValue BetterChain = FindBetterChain(N, Chain);
9089 // If there is a better chain.
9090 if (Chain != BetterChain) {
9093 // Replace the chain to void dependency.
9094 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9095 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9096 BetterChain, Ptr, LD->getMemOperand());
9098 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9099 LD->getValueType(0),
9100 BetterChain, Ptr, LD->getMemoryVT(),
9101 LD->getMemOperand());
9104 // Create token factor to keep old chain connected.
9105 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9106 MVT::Other, Chain, ReplLoad.getValue(1));
9108 // Make sure the new and old chains are cleaned up.
9109 AddToWorklist(Token.getNode());
9111 // Replace uses with load result and token factor. Don't add users
9113 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9117 // Try transforming N to an indexed load.
9118 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9119 return SDValue(N, 0);
9121 // Try to slice up N to more direct loads if the slices are mapped to
9122 // different register banks or pairing can take place.
9124 return SDValue(N, 0);
9130 /// \brief Helper structure used to slice a load in smaller loads.
9131 /// Basically a slice is obtained from the following sequence:
9132 /// Origin = load Ty1, Base
9133 /// Shift = srl Ty1 Origin, CstTy Amount
9134 /// Inst = trunc Shift to Ty2
9136 /// Then, it will be rewriten into:
9137 /// Slice = load SliceTy, Base + SliceOffset
9138 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9140 /// SliceTy is deduced from the number of bits that are actually used to
9142 struct LoadedSlice {
9143 /// \brief Helper structure used to compute the cost of a slice.
9145 /// Are we optimizing for code size.
9150 unsigned CrossRegisterBanksCopies;
9154 Cost(bool ForCodeSize = false)
9155 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9156 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9158 /// \brief Get the cost of one isolated slice.
9159 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9160 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9161 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9162 EVT TruncType = LS.Inst->getValueType(0);
9163 EVT LoadedType = LS.getLoadedType();
9164 if (TruncType != LoadedType &&
9165 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9169 /// \brief Account for slicing gain in the current cost.
9170 /// Slicing provide a few gains like removing a shift or a
9171 /// truncate. This method allows to grow the cost of the original
9172 /// load with the gain from this slice.
9173 void addSliceGain(const LoadedSlice &LS) {
9174 // Each slice saves a truncate.
9175 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9176 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9177 LS.Inst->getOperand(0).getValueType()))
9179 // If there is a shift amount, this slice gets rid of it.
9182 // If this slice can merge a cross register bank copy, account for it.
9183 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9184 ++CrossRegisterBanksCopies;
9187 Cost &operator+=(const Cost &RHS) {
9189 Truncates += RHS.Truncates;
9190 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9196 bool operator==(const Cost &RHS) const {
9197 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9198 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9199 ZExts == RHS.ZExts && Shift == RHS.Shift;
9202 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9204 bool operator<(const Cost &RHS) const {
9205 // Assume cross register banks copies are as expensive as loads.
9206 // FIXME: Do we want some more target hooks?
9207 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9208 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9209 // Unless we are optimizing for code size, consider the
9210 // expensive operation first.
9211 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9212 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9213 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9214 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9217 bool operator>(const Cost &RHS) const { return RHS < *this; }
9219 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9221 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9223 // The last instruction that represent the slice. This should be a
9224 // truncate instruction.
9226 // The original load instruction.
9228 // The right shift amount in bits from the original load.
9230 // The DAG from which Origin came from.
9231 // This is used to get some contextual information about legal types, etc.
9234 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9235 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9236 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9238 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9239 /// \return Result is \p BitWidth and has used bits set to 1 and
9240 /// not used bits set to 0.
9241 APInt getUsedBits() const {
9242 // Reproduce the trunc(lshr) sequence:
9243 // - Start from the truncated value.
9244 // - Zero extend to the desired bit width.
9246 assert(Origin && "No original load to compare against.");
9247 unsigned BitWidth = Origin->getValueSizeInBits(0);
9248 assert(Inst && "This slice is not bound to an instruction");
9249 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9250 "Extracted slice is bigger than the whole type!");
9251 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9252 UsedBits.setAllBits();
9253 UsedBits = UsedBits.zext(BitWidth);
9258 /// \brief Get the size of the slice to be loaded in bytes.
9259 unsigned getLoadedSize() const {
9260 unsigned SliceSize = getUsedBits().countPopulation();
9261 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9262 return SliceSize / 8;
9265 /// \brief Get the type that will be loaded for this slice.
9266 /// Note: This may not be the final type for the slice.
9267 EVT getLoadedType() const {
9268 assert(DAG && "Missing context");
9269 LLVMContext &Ctxt = *DAG->getContext();
9270 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9273 /// \brief Get the alignment of the load used for this slice.
9274 unsigned getAlignment() const {
9275 unsigned Alignment = Origin->getAlignment();
9276 unsigned Offset = getOffsetFromBase();
9278 Alignment = MinAlign(Alignment, Alignment + Offset);
9282 /// \brief Check if this slice can be rewritten with legal operations.
9283 bool isLegal() const {
9284 // An invalid slice is not legal.
9285 if (!Origin || !Inst || !DAG)
9288 // Offsets are for indexed load only, we do not handle that.
9289 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9292 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9294 // Check that the type is legal.
9295 EVT SliceType = getLoadedType();
9296 if (!TLI.isTypeLegal(SliceType))
9299 // Check that the load is legal for this type.
9300 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9303 // Check that the offset can be computed.
9304 // 1. Check its type.
9305 EVT PtrType = Origin->getBasePtr().getValueType();
9306 if (PtrType == MVT::Untyped || PtrType.isExtended())
9309 // 2. Check that it fits in the immediate.
9310 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9313 // 3. Check that the computation is legal.
9314 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9317 // Check that the zext is legal if it needs one.
9318 EVT TruncateType = Inst->getValueType(0);
9319 if (TruncateType != SliceType &&
9320 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9326 /// \brief Get the offset in bytes of this slice in the original chunk of
9328 /// \pre DAG != nullptr.
9329 uint64_t getOffsetFromBase() const {
9330 assert(DAG && "Missing context.");
9332 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9333 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9334 uint64_t Offset = Shift / 8;
9335 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9336 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9337 "The size of the original loaded type is not a multiple of a"
9339 // If Offset is bigger than TySizeInBytes, it means we are loading all
9340 // zeros. This should have been optimized before in the process.
9341 assert(TySizeInBytes > Offset &&
9342 "Invalid shift amount for given loaded size");
9344 Offset = TySizeInBytes - Offset - getLoadedSize();
9348 /// \brief Generate the sequence of instructions to load the slice
9349 /// represented by this object and redirect the uses of this slice to
9350 /// this new sequence of instructions.
9351 /// \pre this->Inst && this->Origin are valid Instructions and this
9352 /// object passed the legal check: LoadedSlice::isLegal returned true.
9353 /// \return The last instruction of the sequence used to load the slice.
9354 SDValue loadSlice() const {
9355 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9356 const SDValue &OldBaseAddr = Origin->getBasePtr();
9357 SDValue BaseAddr = OldBaseAddr;
9358 // Get the offset in that chunk of bytes w.r.t. the endianess.
9359 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9360 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9362 // BaseAddr = BaseAddr + Offset.
9363 EVT ArithType = BaseAddr.getValueType();
9364 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9365 DAG->getConstant(Offset, ArithType));
9368 // Create the type of the loaded slice according to its size.
9369 EVT SliceType = getLoadedType();
9371 // Create the load for the slice.
9372 SDValue LastInst = DAG->getLoad(
9373 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9374 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9375 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9376 // If the final type is not the same as the loaded type, this means that
9377 // we have to pad with zero. Create a zero extend for that.
9378 EVT FinalType = Inst->getValueType(0);
9379 if (SliceType != FinalType)
9381 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9385 /// \brief Check if this slice can be merged with an expensive cross register
9386 /// bank copy. E.g.,
9388 /// f = bitcast i32 i to float
9389 bool canMergeExpensiveCrossRegisterBankCopy() const {
9390 if (!Inst || !Inst->hasOneUse())
9392 SDNode *Use = *Inst->use_begin();
9393 if (Use->getOpcode() != ISD::BITCAST)
9395 assert(DAG && "Missing context");
9396 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9397 EVT ResVT = Use->getValueType(0);
9398 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9399 const TargetRegisterClass *ArgRC =
9400 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9401 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9404 // At this point, we know that we perform a cross-register-bank copy.
9405 // Check if it is expensive.
9406 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9407 // Assume bitcasts are cheap, unless both register classes do not
9408 // explicitly share a common sub class.
9409 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9412 // Check if it will be merged with the load.
9413 // 1. Check the alignment constraint.
9414 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9415 ResVT.getTypeForEVT(*DAG->getContext()));
9417 if (RequiredAlignment > getAlignment())
9420 // 2. Check that the load is a legal operation for that type.
9421 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9424 // 3. Check that we do not have a zext in the way.
9425 if (Inst->getValueType(0) != getLoadedType())
9433 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9434 /// \p UsedBits looks like 0..0 1..1 0..0.
9435 static bool areUsedBitsDense(const APInt &UsedBits) {
9436 // If all the bits are one, this is dense!
9437 if (UsedBits.isAllOnesValue())
9440 // Get rid of the unused bits on the right.
9441 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9442 // Get rid of the unused bits on the left.
9443 if (NarrowedUsedBits.countLeadingZeros())
9444 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9445 // Check that the chunk of bits is completely used.
9446 return NarrowedUsedBits.isAllOnesValue();
9449 /// \brief Check whether or not \p First and \p Second are next to each other
9450 /// in memory. This means that there is no hole between the bits loaded
9451 /// by \p First and the bits loaded by \p Second.
9452 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9453 const LoadedSlice &Second) {
9454 assert(First.Origin == Second.Origin && First.Origin &&
9455 "Unable to match different memory origins.");
9456 APInt UsedBits = First.getUsedBits();
9457 assert((UsedBits & Second.getUsedBits()) == 0 &&
9458 "Slices are not supposed to overlap.");
9459 UsedBits |= Second.getUsedBits();
9460 return areUsedBitsDense(UsedBits);
9463 /// \brief Adjust the \p GlobalLSCost according to the target
9464 /// paring capabilities and the layout of the slices.
9465 /// \pre \p GlobalLSCost should account for at least as many loads as
9466 /// there is in the slices in \p LoadedSlices.
9467 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9468 LoadedSlice::Cost &GlobalLSCost) {
9469 unsigned NumberOfSlices = LoadedSlices.size();
9470 // If there is less than 2 elements, no pairing is possible.
9471 if (NumberOfSlices < 2)
9474 // Sort the slices so that elements that are likely to be next to each
9475 // other in memory are next to each other in the list.
9476 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9477 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9478 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9479 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9481 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9482 // First (resp. Second) is the first (resp. Second) potentially candidate
9483 // to be placed in a paired load.
9484 const LoadedSlice *First = nullptr;
9485 const LoadedSlice *Second = nullptr;
9486 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9487 // Set the beginning of the pair.
9490 Second = &LoadedSlices[CurrSlice];
9492 // If First is NULL, it means we start a new pair.
9493 // Get to the next slice.
9497 EVT LoadedType = First->getLoadedType();
9499 // If the types of the slices are different, we cannot pair them.
9500 if (LoadedType != Second->getLoadedType())
9503 // Check if the target supplies paired loads for this type.
9504 unsigned RequiredAlignment = 0;
9505 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9506 // move to the next pair, this type is hopeless.
9510 // Check if we meet the alignment requirement.
9511 if (RequiredAlignment > First->getAlignment())
9514 // Check that both loads are next to each other in memory.
9515 if (!areSlicesNextToEachOther(*First, *Second))
9518 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9519 --GlobalLSCost.Loads;
9520 // Move to the next pair.
9525 /// \brief Check the profitability of all involved LoadedSlice.
9526 /// Currently, it is considered profitable if there is exactly two
9527 /// involved slices (1) which are (2) next to each other in memory, and
9528 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9530 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9531 /// the elements themselves.
9533 /// FIXME: When the cost model will be mature enough, we can relax
9534 /// constraints (1) and (2).
9535 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9536 const APInt &UsedBits, bool ForCodeSize) {
9537 unsigned NumberOfSlices = LoadedSlices.size();
9538 if (StressLoadSlicing)
9539 return NumberOfSlices > 1;
9542 if (NumberOfSlices != 2)
9546 if (!areUsedBitsDense(UsedBits))
9550 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9551 // The original code has one big load.
9553 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9554 const LoadedSlice &LS = LoadedSlices[CurrSlice];
9555 // Accumulate the cost of all the slices.
9556 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9557 GlobalSlicingCost += SliceCost;
9559 // Account as cost in the original configuration the gain obtained
9560 // with the current slices.
9561 OrigCost.addSliceGain(LS);
9564 // If the target supports paired load, adjust the cost accordingly.
9565 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9566 return OrigCost > GlobalSlicingCost;
9569 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9570 /// operations, split it in the various pieces being extracted.
9572 /// This sort of thing is introduced by SROA.
9573 /// This slicing takes care not to insert overlapping loads.
9574 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9575 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9576 if (Level < AfterLegalizeDAG)
9579 LoadSDNode *LD = cast<LoadSDNode>(N);
9580 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9581 !LD->getValueType(0).isInteger())
9584 // Keep track of already used bits to detect overlapping values.
9585 // In that case, we will just abort the transformation.
9586 APInt UsedBits(LD->getValueSizeInBits(0), 0);
9588 SmallVector<LoadedSlice, 4> LoadedSlices;
9590 // Check if this load is used as several smaller chunks of bits.
9591 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9592 // of computation for each trunc.
9593 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9594 UI != UIEnd; ++UI) {
9595 // Skip the uses of the chain.
9596 if (UI.getUse().getResNo() != 0)
9602 // Check if this is a trunc(lshr).
9603 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9604 isa<ConstantSDNode>(User->getOperand(1))) {
9605 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9606 User = *User->use_begin();
9609 // At this point, User is a Truncate, iff we encountered, trunc or
9611 if (User->getOpcode() != ISD::TRUNCATE)
9614 // The width of the type must be a power of 2 and greater than 8-bits.
9615 // Otherwise the load cannot be represented in LLVM IR.
9616 // Moreover, if we shifted with a non-8-bits multiple, the slice
9617 // will be across several bytes. We do not support that.
9618 unsigned Width = User->getValueSizeInBits(0);
9619 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9622 // Build the slice for this chain of computations.
9623 LoadedSlice LS(User, LD, Shift, &DAG);
9624 APInt CurrentUsedBits = LS.getUsedBits();
9626 // Check if this slice overlaps with another.
9627 if ((CurrentUsedBits & UsedBits) != 0)
9629 // Update the bits used globally.
9630 UsedBits |= CurrentUsedBits;
9632 // Check if the new slice would be legal.
9636 // Record the slice.
9637 LoadedSlices.push_back(LS);
9640 // Abort slicing if it does not seem to be profitable.
9641 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9646 // Rewrite each chain to use an independent load.
9647 // By construction, each chain can be represented by a unique load.
9649 // Prepare the argument for the new token factor for all the slices.
9650 SmallVector<SDValue, 8> ArgChains;
9651 for (SmallVectorImpl<LoadedSlice>::const_iterator
9652 LSIt = LoadedSlices.begin(),
9653 LSItEnd = LoadedSlices.end();
9654 LSIt != LSItEnd; ++LSIt) {
9655 SDValue SliceInst = LSIt->loadSlice();
9656 CombineTo(LSIt->Inst, SliceInst, true);
9657 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9658 SliceInst = SliceInst.getOperand(0);
9659 assert(SliceInst->getOpcode() == ISD::LOAD &&
9660 "It takes more than a zext to get to the loaded slice!!");
9661 ArgChains.push_back(SliceInst.getValue(1));
9664 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9666 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9670 /// Check to see if V is (and load (ptr), imm), where the load is having
9671 /// specific bytes cleared out. If so, return the byte size being masked out
9672 /// and the shift amount.
9673 static std::pair<unsigned, unsigned>
9674 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9675 std::pair<unsigned, unsigned> Result(0, 0);
9677 // Check for the structure we're looking for.
9678 if (V->getOpcode() != ISD::AND ||
9679 !isa<ConstantSDNode>(V->getOperand(1)) ||
9680 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9683 // Check the chain and pointer.
9684 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9685 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
9687 // The store should be chained directly to the load or be an operand of a
9689 if (LD == Chain.getNode())
9691 else if (Chain->getOpcode() != ISD::TokenFactor)
9692 return Result; // Fail.
9695 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9696 if (Chain->getOperand(i).getNode() == LD) {
9700 if (!isOk) return Result;
9703 // This only handles simple types.
9704 if (V.getValueType() != MVT::i16 &&
9705 V.getValueType() != MVT::i32 &&
9706 V.getValueType() != MVT::i64)
9709 // Check the constant mask. Invert it so that the bits being masked out are
9710 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9711 // follow the sign bit for uniformity.
9712 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9713 unsigned NotMaskLZ = countLeadingZeros(NotMask);
9714 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
9715 unsigned NotMaskTZ = countTrailingZeros(NotMask);
9716 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9717 if (NotMaskLZ == 64) return Result; // All zero mask.
9719 // See if we have a continuous run of bits. If so, we have 0*1+0*
9720 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
9723 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9724 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9725 NotMaskLZ -= 64-V.getValueSizeInBits();
9727 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9728 switch (MaskedBytes) {
9732 default: return Result; // All one mask, or 5-byte mask.
9735 // Verify that the first bit starts at a multiple of mask so that the access
9736 // is aligned the same as the access width.
9737 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9739 Result.first = MaskedBytes;
9740 Result.second = NotMaskTZ/8;
9745 /// Check to see if IVal is something that provides a value as specified by
9746 /// MaskInfo. If so, replace the specified store with a narrower store of
9749 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9750 SDValue IVal, StoreSDNode *St,
9752 unsigned NumBytes = MaskInfo.first;
9753 unsigned ByteShift = MaskInfo.second;
9754 SelectionDAG &DAG = DC->getDAG();
9756 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9757 // that uses this. If not, this is not a replacement.
9758 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9759 ByteShift*8, (ByteShift+NumBytes)*8);
9760 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9762 // Check that it is legal on the target to do this. It is legal if the new
9763 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9765 MVT VT = MVT::getIntegerVT(NumBytes*8);
9766 if (!DC->isTypeLegal(VT))
9769 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9770 // shifted by ByteShift and truncated down to NumBytes.
9772 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9773 DAG.getConstant(ByteShift*8,
9774 DC->getShiftAmountTy(IVal.getValueType())));
9776 // Figure out the offset for the store and the alignment of the access.
9778 unsigned NewAlign = St->getAlignment();
9780 if (DAG.getTargetLoweringInfo().isLittleEndian())
9781 StOffset = ByteShift;
9783 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9785 SDValue Ptr = St->getBasePtr();
9787 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9788 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9789 NewAlign = MinAlign(NewAlign, StOffset);
9792 // Truncate down to the new size.
9793 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9796 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9797 St->getPointerInfo().getWithOffset(StOffset),
9798 false, false, NewAlign).getNode();
9802 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9803 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9804 /// narrowing the load and store if it would end up being a win for performance
9806 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9807 StoreSDNode *ST = cast<StoreSDNode>(N);
9808 if (ST->isVolatile())
9811 SDValue Chain = ST->getChain();
9812 SDValue Value = ST->getValue();
9813 SDValue Ptr = ST->getBasePtr();
9814 EVT VT = Value.getValueType();
9816 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9819 unsigned Opc = Value.getOpcode();
9821 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9822 // is a byte mask indicating a consecutive number of bytes, check to see if
9823 // Y is known to provide just those bytes. If so, we try to replace the
9824 // load + replace + store sequence with a single (narrower) store, which makes
9826 if (Opc == ISD::OR) {
9827 std::pair<unsigned, unsigned> MaskedLoad;
9828 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9829 if (MaskedLoad.first)
9830 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9831 Value.getOperand(1), ST,this))
9832 return SDValue(NewST, 0);
9834 // Or is commutative, so try swapping X and Y.
9835 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9836 if (MaskedLoad.first)
9837 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9838 Value.getOperand(0), ST,this))
9839 return SDValue(NewST, 0);
9842 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9843 Value.getOperand(1).getOpcode() != ISD::Constant)
9846 SDValue N0 = Value.getOperand(0);
9847 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9848 Chain == SDValue(N0.getNode(), 1)) {
9849 LoadSDNode *LD = cast<LoadSDNode>(N0);
9850 if (LD->getBasePtr() != Ptr ||
9851 LD->getPointerInfo().getAddrSpace() !=
9852 ST->getPointerInfo().getAddrSpace())
9855 // Find the type to narrow it the load / op / store to.
9856 SDValue N1 = Value.getOperand(1);
9857 unsigned BitWidth = N1.getValueSizeInBits();
9858 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9859 if (Opc == ISD::AND)
9860 Imm ^= APInt::getAllOnesValue(BitWidth);
9861 if (Imm == 0 || Imm.isAllOnesValue())
9863 unsigned ShAmt = Imm.countTrailingZeros();
9864 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9865 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9866 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9867 // The narrowing should be profitable, the load/store operation should be
9868 // legal (or custom) and the store size should be equal to the NewVT width.
9869 while (NewBW < BitWidth &&
9870 (NewVT.getStoreSizeInBits() != NewBW ||
9871 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
9872 !TLI.isNarrowingProfitable(VT, NewVT))) {
9873 NewBW = NextPowerOf2(NewBW);
9874 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9876 if (NewBW >= BitWidth)
9879 // If the lsb changed does not start at the type bitwidth boundary,
9880 // start at the previous one.
9882 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9883 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9884 std::min(BitWidth, ShAmt + NewBW));
9885 if ((Imm & Mask) == Imm) {
9886 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9887 if (Opc == ISD::AND)
9888 NewImm ^= APInt::getAllOnesValue(NewBW);
9889 uint64_t PtrOff = ShAmt / 8;
9890 // For big endian targets, we need to adjust the offset to the pointer to
9891 // load the correct bytes.
9892 if (TLI.isBigEndian())
9893 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9895 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9896 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9897 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9900 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9901 Ptr.getValueType(), Ptr,
9902 DAG.getConstant(PtrOff, Ptr.getValueType()));
9903 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9904 LD->getChain(), NewPtr,
9905 LD->getPointerInfo().getWithOffset(PtrOff),
9906 LD->isVolatile(), LD->isNonTemporal(),
9907 LD->isInvariant(), NewAlign,
9909 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9910 DAG.getConstant(NewImm, NewVT));
9911 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9913 ST->getPointerInfo().getWithOffset(PtrOff),
9914 false, false, NewAlign);
9916 AddToWorklist(NewPtr.getNode());
9917 AddToWorklist(NewLD.getNode());
9918 AddToWorklist(NewVal.getNode());
9919 WorklistRemover DeadNodes(*this);
9920 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9929 /// For a given floating point load / store pair, if the load value isn't used
9930 /// by any other operations, then consider transforming the pair to integer
9931 /// load / store operations if the target deems the transformation profitable.
9932 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9933 StoreSDNode *ST = cast<StoreSDNode>(N);
9934 SDValue Chain = ST->getChain();
9935 SDValue Value = ST->getValue();
9936 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9937 Value.hasOneUse() &&
9938 Chain == SDValue(Value.getNode(), 1)) {
9939 LoadSDNode *LD = cast<LoadSDNode>(Value);
9940 EVT VT = LD->getMemoryVT();
9941 if (!VT.isFloatingPoint() ||
9942 VT != ST->getMemoryVT() ||
9943 LD->isNonTemporal() ||
9944 ST->isNonTemporal() ||
9945 LD->getPointerInfo().getAddrSpace() != 0 ||
9946 ST->getPointerInfo().getAddrSpace() != 0)
9949 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9950 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9951 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9952 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9953 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9956 unsigned LDAlign = LD->getAlignment();
9957 unsigned STAlign = ST->getAlignment();
9958 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9959 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9960 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9963 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9964 LD->getChain(), LD->getBasePtr(),
9965 LD->getPointerInfo(),
9966 false, false, false, LDAlign);
9968 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9969 NewLD, ST->getBasePtr(),
9970 ST->getPointerInfo(),
9971 false, false, STAlign);
9973 AddToWorklist(NewLD.getNode());
9974 AddToWorklist(NewST.getNode());
9975 WorklistRemover DeadNodes(*this);
9976 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9985 /// Helper struct to parse and store a memory address as base + index + offset.
9986 /// We ignore sign extensions when it is safe to do so.
9987 /// The following two expressions are not equivalent. To differentiate we need
9988 /// to store whether there was a sign extension involved in the index
9990 /// (load (i64 add (i64 copyfromreg %c)
9991 /// (i64 signextend (add (i8 load %index)
9995 /// (load (i64 add (i64 copyfromreg %c)
9996 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9998 struct BaseIndexOffset {
10002 bool IsIndexSignExt;
10004 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10006 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10007 bool IsIndexSignExt) :
10008 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10010 bool equalBaseIndex(const BaseIndexOffset &Other) {
10011 return Other.Base == Base && Other.Index == Index &&
10012 Other.IsIndexSignExt == IsIndexSignExt;
10015 /// Parses tree in Ptr for base, index, offset addresses.
10016 static BaseIndexOffset match(SDValue Ptr) {
10017 bool IsIndexSignExt = false;
10019 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10020 // instruction, then it could be just the BASE or everything else we don't
10021 // know how to handle. Just use Ptr as BASE and give up.
10022 if (Ptr->getOpcode() != ISD::ADD)
10023 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10025 // We know that we have at least an ADD instruction. Try to pattern match
10026 // the simple case of BASE + OFFSET.
10027 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10028 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10029 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10033 // Inside a loop the current BASE pointer is calculated using an ADD and a
10034 // MUL instruction. In this case Ptr is the actual BASE pointer.
10035 // (i64 add (i64 %array_ptr)
10036 // (i64 mul (i64 %induction_var)
10037 // (i64 %element_size)))
10038 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10039 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10041 // Look at Base + Index + Offset cases.
10042 SDValue Base = Ptr->getOperand(0);
10043 SDValue IndexOffset = Ptr->getOperand(1);
10045 // Skip signextends.
10046 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10047 IndexOffset = IndexOffset->getOperand(0);
10048 IsIndexSignExt = true;
10051 // Either the case of Base + Index (no offset) or something else.
10052 if (IndexOffset->getOpcode() != ISD::ADD)
10053 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10055 // Now we have the case of Base + Index + offset.
10056 SDValue Index = IndexOffset->getOperand(0);
10057 SDValue Offset = IndexOffset->getOperand(1);
10059 if (!isa<ConstantSDNode>(Offset))
10060 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10062 // Ignore signextends.
10063 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10064 Index = Index->getOperand(0);
10065 IsIndexSignExt = true;
10066 } else IsIndexSignExt = false;
10068 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10069 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10074 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10075 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10076 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10077 // Make sure we have something to merge.
10081 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10082 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10083 unsigned EarliestNodeUsed = 0;
10085 for (unsigned i=0; i < NumElem; ++i) {
10086 // Find a chain for the new wide-store operand. Notice that some
10087 // of the store nodes that we found may not be selected for inclusion
10088 // in the wide store. The chain we use needs to be the chain of the
10089 // earliest store node which is *used* and replaced by the wide store.
10090 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10091 EarliestNodeUsed = i;
10094 // The earliest Node in the DAG.
10095 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10096 SDLoc DL(StoreNodes[0].MemNode);
10100 // Find a legal type for the vector store.
10101 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10102 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10103 if (IsConstantSrc) {
10104 // A vector store with a constant source implies that the constant is
10105 // zero; we only handle merging stores of constant zeros because the zero
10106 // can be materialized without a load.
10107 // It may be beneficial to loosen this restriction to allow non-zero
10109 StoredVal = DAG.getConstant(0, Ty);
10111 SmallVector<SDValue, 8> Ops;
10112 for (unsigned i = 0; i < NumElem ; ++i) {
10113 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10114 SDValue Val = St->getValue();
10115 // All of the operands of a BUILD_VECTOR must have the same type.
10116 if (Val.getValueType() != MemVT)
10118 Ops.push_back(Val);
10121 // Build the extracted vector elements back into a vector.
10122 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10125 // We should always use a vector store when merging extracted vector
10126 // elements, so this path implies a store of constants.
10127 assert(IsConstantSrc && "Merged vector elements should use vector store");
10129 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10130 APInt StoreInt(StoreBW, 0);
10132 // Construct a single integer constant which is made of the smaller
10133 // constant inputs.
10134 bool IsLE = TLI.isLittleEndian();
10135 for (unsigned i = 0; i < NumElem ; ++i) {
10136 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10137 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10138 SDValue Val = St->getValue();
10139 StoreInt <<= ElementSizeBytes*8;
10140 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10141 StoreInt |= C->getAPIntValue().zext(StoreBW);
10142 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10143 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10145 llvm_unreachable("Invalid constant element type");
10149 // Create the new Load and Store operations.
10150 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10151 StoredVal = DAG.getConstant(StoreInt, StoreTy);
10154 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
10155 FirstInChain->getBasePtr(),
10156 FirstInChain->getPointerInfo(),
10158 FirstInChain->getAlignment());
10160 // Replace the first store with the new store
10161 CombineTo(EarliestOp, NewStore);
10162 // Erase all other stores.
10163 for (unsigned i = 0; i < NumElem ; ++i) {
10164 if (StoreNodes[i].MemNode == EarliestOp)
10166 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10167 // ReplaceAllUsesWith will replace all uses that existed when it was
10168 // called, but graph optimizations may cause new ones to appear. For
10169 // example, the case in pr14333 looks like
10171 // St's chain -> St -> another store -> X
10173 // And the only difference from St to the other store is the chain.
10174 // When we change it's chain to be St's chain they become identical,
10175 // get CSEed and the net result is that X is now a use of St.
10176 // Since we know that St is redundant, just iterate.
10177 while (!St->use_empty())
10178 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10179 deleteAndRecombine(St);
10185 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10186 if (OptLevel == CodeGenOpt::None)
10189 EVT MemVT = St->getMemoryVT();
10190 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10191 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10192 Attribute::NoImplicitFloat);
10194 // Don't merge vectors into wider inputs.
10195 if (MemVT.isVector() || !MemVT.isSimple())
10198 // Perform an early exit check. Do not bother looking at stored values that
10199 // are not constants, loads, or extracted vector elements.
10200 SDValue StoredVal = St->getValue();
10201 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10202 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10203 isa<ConstantFPSDNode>(StoredVal);
10204 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10206 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10209 // Only look at ends of store sequences.
10210 SDValue Chain = SDValue(St, 0);
10211 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10214 // This holds the base pointer, index, and the offset in bytes from the base
10216 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10218 // We must have a base and an offset.
10219 if (!BasePtr.Base.getNode())
10222 // Do not handle stores to undef base pointers.
10223 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10226 // Save the LoadSDNodes that we find in the chain.
10227 // We need to make sure that these nodes do not interfere with
10228 // any of the store nodes.
10229 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10231 // Save the StoreSDNodes that we find in the chain.
10232 SmallVector<MemOpLink, 8> StoreNodes;
10234 // Walk up the chain and look for nodes with offsets from the same
10235 // base pointer. Stop when reaching an instruction with a different kind
10236 // or instruction which has a different base pointer.
10238 StoreSDNode *Index = St;
10240 // If the chain has more than one use, then we can't reorder the mem ops.
10241 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10244 // Find the base pointer and offset for this memory node.
10245 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10247 // Check that the base pointer is the same as the original one.
10248 if (!Ptr.equalBaseIndex(BasePtr))
10251 // Check that the alignment is the same.
10252 if (Index->getAlignment() != St->getAlignment())
10255 // The memory operands must not be volatile.
10256 if (Index->isVolatile() || Index->isIndexed())
10260 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10261 if (St->isTruncatingStore())
10264 // The stored memory type must be the same.
10265 if (Index->getMemoryVT() != MemVT)
10268 // We do not allow unaligned stores because we want to prevent overriding
10270 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10273 // We found a potential memory operand to merge.
10274 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10276 // Find the next memory operand in the chain. If the next operand in the
10277 // chain is a store then move up and continue the scan with the next
10278 // memory operand. If the next operand is a load save it and use alias
10279 // information to check if it interferes with anything.
10280 SDNode *NextInChain = Index->getChain().getNode();
10282 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10283 // We found a store node. Use it for the next iteration.
10286 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10287 if (Ldn->isVolatile()) {
10292 // Save the load node for later. Continue the scan.
10293 AliasLoadNodes.push_back(Ldn);
10294 NextInChain = Ldn->getChain().getNode();
10303 // Check if there is anything to merge.
10304 if (StoreNodes.size() < 2)
10307 // Sort the memory operands according to their distance from the base pointer.
10308 std::sort(StoreNodes.begin(), StoreNodes.end(),
10309 [](MemOpLink LHS, MemOpLink RHS) {
10310 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10311 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10312 LHS.SequenceNum > RHS.SequenceNum);
10315 // Scan the memory operations on the chain and find the first non-consecutive
10316 // store memory address.
10317 unsigned LastConsecutiveStore = 0;
10318 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10319 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10321 // Check that the addresses are consecutive starting from the second
10322 // element in the list of stores.
10324 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10325 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10329 bool Alias = false;
10330 // Check if this store interferes with any of the loads that we found.
10331 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10332 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10336 // We found a load that alias with this store. Stop the sequence.
10340 // Mark this node as useful.
10341 LastConsecutiveStore = i;
10344 // The node with the lowest store address.
10345 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10347 // Store the constants into memory as one consecutive store.
10348 if (IsConstantSrc) {
10349 unsigned LastLegalType = 0;
10350 unsigned LastLegalVectorType = 0;
10351 bool NonZero = false;
10352 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10353 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10354 SDValue StoredVal = St->getValue();
10356 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10357 NonZero |= !C->isNullValue();
10358 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10359 NonZero |= !C->getConstantFPValue()->isNullValue();
10365 // Find a legal type for the constant store.
10366 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10367 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10368 if (TLI.isTypeLegal(StoreTy))
10369 LastLegalType = i+1;
10370 // Or check whether a truncstore is legal.
10371 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10372 TargetLowering::TypePromoteInteger) {
10373 EVT LegalizedStoredValueTy =
10374 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10375 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10376 LastLegalType = i+1;
10379 // Find a legal type for the vector store.
10380 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10381 if (TLI.isTypeLegal(Ty))
10382 LastLegalVectorType = i + 1;
10385 // We only use vectors if the constant is known to be zero and the
10386 // function is not marked with the noimplicitfloat attribute.
10387 if (NonZero || NoVectors)
10388 LastLegalVectorType = 0;
10390 // Check if we found a legal integer type to store.
10391 if (LastLegalType == 0 && LastLegalVectorType == 0)
10394 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10395 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10397 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10401 // When extracting multiple vector elements, try to store them
10402 // in one vector store rather than a sequence of scalar stores.
10403 if (IsExtractVecEltSrc) {
10404 unsigned NumElem = 0;
10405 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10406 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10407 SDValue StoredVal = St->getValue();
10408 // This restriction could be loosened.
10409 // Bail out if any stored values are not elements extracted from a vector.
10410 // It should be possible to handle mixed sources, but load sources need
10411 // more careful handling (see the block of code below that handles
10412 // consecutive loads).
10413 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10416 // Find a legal type for the vector store.
10417 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10418 if (TLI.isTypeLegal(Ty))
10422 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10426 // Below we handle the case of multiple consecutive stores that
10427 // come from multiple consecutive loads. We merge them into a single
10428 // wide load and a single wide store.
10430 // Look for load nodes which are used by the stored values.
10431 SmallVector<MemOpLink, 8> LoadNodes;
10433 // Find acceptable loads. Loads need to have the same chain (token factor),
10434 // must not be zext, volatile, indexed, and they must be consecutive.
10435 BaseIndexOffset LdBasePtr;
10436 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10437 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10438 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10441 // Loads must only have one use.
10442 if (!Ld->hasNUsesOfValue(1, 0))
10445 // Check that the alignment is the same as the stores.
10446 if (Ld->getAlignment() != St->getAlignment())
10449 // The memory operands must not be volatile.
10450 if (Ld->isVolatile() || Ld->isIndexed())
10453 // We do not accept ext loads.
10454 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10457 // The stored memory type must be the same.
10458 if (Ld->getMemoryVT() != MemVT)
10461 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10462 // If this is not the first ptr that we check.
10463 if (LdBasePtr.Base.getNode()) {
10464 // The base ptr must be the same.
10465 if (!LdPtr.equalBaseIndex(LdBasePtr))
10468 // Check that all other base pointers are the same as this one.
10472 // We found a potential memory operand to merge.
10473 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10476 if (LoadNodes.size() < 2)
10479 // If we have load/store pair instructions and we only have two values,
10481 unsigned RequiredAlignment;
10482 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10483 St->getAlignment() >= RequiredAlignment)
10486 // Scan the memory operations on the chain and find the first non-consecutive
10487 // load memory address. These variables hold the index in the store node
10489 unsigned LastConsecutiveLoad = 0;
10490 // This variable refers to the size and not index in the array.
10491 unsigned LastLegalVectorType = 0;
10492 unsigned LastLegalIntegerType = 0;
10493 StartAddress = LoadNodes[0].OffsetFromBase;
10494 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10495 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10496 // All loads much share the same chain.
10497 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10500 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10501 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10503 LastConsecutiveLoad = i;
10505 // Find a legal type for the vector store.
10506 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10507 if (TLI.isTypeLegal(StoreTy))
10508 LastLegalVectorType = i + 1;
10510 // Find a legal type for the integer store.
10511 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10512 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10513 if (TLI.isTypeLegal(StoreTy))
10514 LastLegalIntegerType = i + 1;
10515 // Or check whether a truncstore and extload is legal.
10516 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10517 TargetLowering::TypePromoteInteger) {
10518 EVT LegalizedStoredValueTy =
10519 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10520 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10521 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10522 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10523 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10524 LastLegalIntegerType = i+1;
10528 // Only use vector types if the vector type is larger than the integer type.
10529 // If they are the same, use integers.
10530 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10531 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10533 // We add +1 here because the LastXXX variables refer to location while
10534 // the NumElem refers to array/index size.
10535 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10536 NumElem = std::min(LastLegalType, NumElem);
10541 // The earliest Node in the DAG.
10542 unsigned EarliestNodeUsed = 0;
10543 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10544 for (unsigned i=1; i<NumElem; ++i) {
10545 // Find a chain for the new wide-store operand. Notice that some
10546 // of the store nodes that we found may not be selected for inclusion
10547 // in the wide store. The chain we use needs to be the chain of the
10548 // earliest store node which is *used* and replaced by the wide store.
10549 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10550 EarliestNodeUsed = i;
10553 // Find if it is better to use vectors or integers to load and store
10557 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10559 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10560 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10563 SDLoc LoadDL(LoadNodes[0].MemNode);
10564 SDLoc StoreDL(StoreNodes[0].MemNode);
10566 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10567 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10568 FirstLoad->getChain(),
10569 FirstLoad->getBasePtr(),
10570 FirstLoad->getPointerInfo(),
10571 false, false, false,
10572 FirstLoad->getAlignment());
10574 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10575 FirstInChain->getBasePtr(),
10576 FirstInChain->getPointerInfo(), false, false,
10577 FirstInChain->getAlignment());
10579 // Replace one of the loads with the new load.
10580 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10581 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10582 SDValue(NewLoad.getNode(), 1));
10584 // Remove the rest of the load chains.
10585 for (unsigned i = 1; i < NumElem ; ++i) {
10586 // Replace all chain users of the old load nodes with the chain of the new
10588 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10589 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10592 // Replace the first store with the new store.
10593 CombineTo(EarliestOp, NewStore);
10594 // Erase all other stores.
10595 for (unsigned i = 0; i < NumElem ; ++i) {
10596 // Remove all Store nodes.
10597 if (StoreNodes[i].MemNode == EarliestOp)
10599 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10600 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10601 deleteAndRecombine(St);
10607 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10608 StoreSDNode *ST = cast<StoreSDNode>(N);
10609 SDValue Chain = ST->getChain();
10610 SDValue Value = ST->getValue();
10611 SDValue Ptr = ST->getBasePtr();
10613 // If this is a store of a bit convert, store the input value if the
10614 // resultant store does not need a higher alignment than the original.
10615 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10616 ST->isUnindexed()) {
10617 unsigned OrigAlign = ST->getAlignment();
10618 EVT SVT = Value.getOperand(0).getValueType();
10619 unsigned Align = TLI.getDataLayout()->
10620 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10621 if (Align <= OrigAlign &&
10622 ((!LegalOperations && !ST->isVolatile()) ||
10623 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10624 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10625 Ptr, ST->getPointerInfo(), ST->isVolatile(),
10626 ST->isNonTemporal(), OrigAlign,
10630 // Turn 'store undef, Ptr' -> nothing.
10631 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10634 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10635 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10636 // NOTE: If the original store is volatile, this transform must not increase
10637 // the number of stores. For example, on x86-32 an f64 can be stored in one
10638 // processor operation but an i64 (which is not legal) requires two. So the
10639 // transform should not be done in this case.
10640 if (Value.getOpcode() != ISD::TargetConstantFP) {
10642 switch (CFP->getSimpleValueType(0).SimpleTy) {
10643 default: llvm_unreachable("Unknown FP type");
10644 case MVT::f16: // We don't do this for these yet.
10650 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10651 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10652 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10653 bitcastToAPInt().getZExtValue(), MVT::i32);
10654 return DAG.getStore(Chain, SDLoc(N), Tmp,
10655 Ptr, ST->getMemOperand());
10659 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10660 !ST->isVolatile()) ||
10661 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10662 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10663 getZExtValue(), MVT::i64);
10664 return DAG.getStore(Chain, SDLoc(N), Tmp,
10665 Ptr, ST->getMemOperand());
10668 if (!ST->isVolatile() &&
10669 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10670 // Many FP stores are not made apparent until after legalize, e.g. for
10671 // argument passing. Since this is so common, custom legalize the
10672 // 64-bit integer store into two 32-bit stores.
10673 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10674 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10675 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10676 if (TLI.isBigEndian()) std::swap(Lo, Hi);
10678 unsigned Alignment = ST->getAlignment();
10679 bool isVolatile = ST->isVolatile();
10680 bool isNonTemporal = ST->isNonTemporal();
10681 AAMDNodes AAInfo = ST->getAAInfo();
10683 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10684 Ptr, ST->getPointerInfo(),
10685 isVolatile, isNonTemporal,
10686 ST->getAlignment(), AAInfo);
10687 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10688 DAG.getConstant(4, Ptr.getValueType()));
10689 Alignment = MinAlign(Alignment, 4U);
10690 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10691 Ptr, ST->getPointerInfo().getWithOffset(4),
10692 isVolatile, isNonTemporal,
10693 Alignment, AAInfo);
10694 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10703 // Try to infer better alignment information than the store already has.
10704 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10705 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10706 if (Align > ST->getAlignment()) {
10708 DAG.getTruncStore(Chain, SDLoc(N), Value,
10709 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10710 ST->isVolatile(), ST->isNonTemporal(), Align,
10712 if (NewStore.getNode() != N)
10713 return CombineTo(ST, NewStore, true);
10718 // Try transforming a pair floating point load / store ops to integer
10719 // load / store ops.
10720 SDValue NewST = TransformFPLoadStorePair(N);
10721 if (NewST.getNode())
10724 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10725 : DAG.getSubtarget().useAA();
10727 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10728 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10731 if (UseAA && ST->isUnindexed()) {
10732 // Walk up chain skipping non-aliasing memory nodes.
10733 SDValue BetterChain = FindBetterChain(N, Chain);
10735 // If there is a better chain.
10736 if (Chain != BetterChain) {
10739 // Replace the chain to avoid dependency.
10740 if (ST->isTruncatingStore()) {
10741 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10742 ST->getMemoryVT(), ST->getMemOperand());
10744 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10745 ST->getMemOperand());
10748 // Create token to keep both nodes around.
10749 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10750 MVT::Other, Chain, ReplStore);
10752 // Make sure the new and old chains are cleaned up.
10753 AddToWorklist(Token.getNode());
10755 // Don't add users to work list.
10756 return CombineTo(N, Token, false);
10760 // Try transforming N to an indexed store.
10761 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10762 return SDValue(N, 0);
10764 // FIXME: is there such a thing as a truncating indexed store?
10765 if (ST->isTruncatingStore() && ST->isUnindexed() &&
10766 Value.getValueType().isInteger()) {
10767 // See if we can simplify the input to this truncstore with knowledge that
10768 // only the low bits are being used. For example:
10769 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
10771 GetDemandedBits(Value,
10772 APInt::getLowBitsSet(
10773 Value.getValueType().getScalarType().getSizeInBits(),
10774 ST->getMemoryVT().getScalarType().getSizeInBits()));
10775 AddToWorklist(Value.getNode());
10776 if (Shorter.getNode())
10777 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10778 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10780 // Otherwise, see if we can simplify the operation with
10781 // SimplifyDemandedBits, which only works if the value has a single use.
10782 if (SimplifyDemandedBits(Value,
10783 APInt::getLowBitsSet(
10784 Value.getValueType().getScalarType().getSizeInBits(),
10785 ST->getMemoryVT().getScalarType().getSizeInBits())))
10786 return SDValue(N, 0);
10789 // If this is a load followed by a store to the same location, then the store
10791 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10792 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10793 ST->isUnindexed() && !ST->isVolatile() &&
10794 // There can't be any side effects between the load and store, such as
10795 // a call or store.
10796 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10797 // The store is dead, remove it.
10802 // If this is a store followed by a store with the same value to the same
10803 // location, then the store is dead/noop.
10804 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10805 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10806 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10807 ST1->isUnindexed() && !ST1->isVolatile()) {
10808 // The store is dead, remove it.
10813 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10814 // truncating store. We can do this even if this is already a truncstore.
10815 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10816 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10817 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10818 ST->getMemoryVT())) {
10819 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10820 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10823 // Only perform this optimization before the types are legal, because we
10824 // don't want to perform this optimization on every DAGCombine invocation.
10826 bool EverChanged = false;
10829 // There can be multiple store sequences on the same chain.
10830 // Keep trying to merge store sequences until we are unable to do so
10831 // or until we merge the last store on the chain.
10832 bool Changed = MergeConsecutiveStores(ST);
10833 EverChanged |= Changed;
10834 if (!Changed) break;
10835 } while (ST->getOpcode() != ISD::DELETED_NODE);
10838 return SDValue(N, 0);
10841 return ReduceLoadOpStoreWidth(N);
10844 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10845 SDValue InVec = N->getOperand(0);
10846 SDValue InVal = N->getOperand(1);
10847 SDValue EltNo = N->getOperand(2);
10850 // If the inserted element is an UNDEF, just use the input vector.
10851 if (InVal.getOpcode() == ISD::UNDEF)
10854 EVT VT = InVec.getValueType();
10856 // If we can't generate a legal BUILD_VECTOR, exit
10857 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10860 // Check that we know which element is being inserted
10861 if (!isa<ConstantSDNode>(EltNo))
10863 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10865 // Canonicalize insert_vector_elt dag nodes.
10867 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10868 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10870 // Do this only if the child insert_vector node has one use; also
10871 // do this only if indices are both constants and Idx1 < Idx0.
10872 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10873 && isa<ConstantSDNode>(InVec.getOperand(2))) {
10874 unsigned OtherElt =
10875 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10876 if (Elt < OtherElt) {
10878 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10879 InVec.getOperand(0), InVal, EltNo);
10880 AddToWorklist(NewOp.getNode());
10881 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10882 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10886 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10887 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
10888 // vector elements.
10889 SmallVector<SDValue, 8> Ops;
10890 // Do not combine these two vectors if the output vector will not replace
10891 // the input vector.
10892 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10893 Ops.append(InVec.getNode()->op_begin(),
10894 InVec.getNode()->op_end());
10895 } else if (InVec.getOpcode() == ISD::UNDEF) {
10896 unsigned NElts = VT.getVectorNumElements();
10897 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10902 // Insert the element
10903 if (Elt < Ops.size()) {
10904 // All the operands of BUILD_VECTOR must have the same type;
10905 // we enforce that here.
10906 EVT OpVT = Ops[0].getValueType();
10907 if (InVal.getValueType() != OpVT)
10908 InVal = OpVT.bitsGT(InVal.getValueType()) ?
10909 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10910 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10914 // Return the new vector
10915 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10918 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10919 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10920 EVT ResultVT = EVE->getValueType(0);
10921 EVT VecEltVT = InVecVT.getVectorElementType();
10922 unsigned Align = OriginalLoad->getAlignment();
10923 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10924 VecEltVT.getTypeForEVT(*DAG.getContext()));
10926 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10931 SDValue NewPtr = OriginalLoad->getBasePtr();
10933 EVT PtrType = NewPtr.getValueType();
10934 MachinePointerInfo MPI;
10935 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10936 int Elt = ConstEltNo->getZExtValue();
10937 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10938 if (TLI.isBigEndian())
10939 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10940 Offset = DAG.getConstant(PtrOff, PtrType);
10941 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10943 Offset = DAG.getNode(
10944 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10945 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10946 if (TLI.isBigEndian())
10947 Offset = DAG.getNode(
10948 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10949 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10950 MPI = OriginalLoad->getPointerInfo();
10952 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10954 // The replacement we need to do here is a little tricky: we need to
10955 // replace an extractelement of a load with a load.
10956 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10957 // Note that this replacement assumes that the extractvalue is the only
10958 // use of the load; that's okay because we don't want to perform this
10959 // transformation in other cases anyway.
10962 if (ResultVT.bitsGT(VecEltVT)) {
10963 // If the result type of vextract is wider than the load, then issue an
10964 // extending load instead.
10965 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10969 Load = DAG.getExtLoad(
10970 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10971 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10972 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10973 Chain = Load.getValue(1);
10975 Load = DAG.getLoad(
10976 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10977 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10978 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10979 Chain = Load.getValue(1);
10980 if (ResultVT.bitsLT(VecEltVT))
10981 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10983 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10985 WorklistRemover DeadNodes(*this);
10986 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10987 SDValue To[] = { Load, Chain };
10988 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10989 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10990 // worklist explicitly as well.
10991 AddToWorklist(Load.getNode());
10992 AddUsersToWorklist(Load.getNode()); // Add users too
10993 // Make sure to revisit this node to clean it up; it will usually be dead.
10994 AddToWorklist(EVE);
10996 return SDValue(EVE, 0);
10999 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11000 // (vextract (scalar_to_vector val, 0) -> val
11001 SDValue InVec = N->getOperand(0);
11002 EVT VT = InVec.getValueType();
11003 EVT NVT = N->getValueType(0);
11005 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11006 // Check if the result type doesn't match the inserted element type. A
11007 // SCALAR_TO_VECTOR may truncate the inserted element and the
11008 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11009 SDValue InOp = InVec.getOperand(0);
11010 if (InOp.getValueType() != NVT) {
11011 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11012 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11017 SDValue EltNo = N->getOperand(1);
11018 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11020 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11021 // We only perform this optimization before the op legalization phase because
11022 // we may introduce new vector instructions which are not backed by TD
11023 // patterns. For example on AVX, extracting elements from a wide vector
11024 // without using extract_subvector. However, if we can find an underlying
11025 // scalar value, then we can always use that.
11026 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11028 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11029 int NumElem = VT.getVectorNumElements();
11030 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11031 // Find the new index to extract from.
11032 int OrigElt = SVOp->getMaskElt(Elt);
11034 // Extracting an undef index is undef.
11036 return DAG.getUNDEF(NVT);
11038 // Select the right vector half to extract from.
11040 if (OrigElt < NumElem) {
11041 SVInVec = InVec->getOperand(0);
11043 SVInVec = InVec->getOperand(1);
11044 OrigElt -= NumElem;
11047 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11048 SDValue InOp = SVInVec.getOperand(OrigElt);
11049 if (InOp.getValueType() != NVT) {
11050 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11051 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11057 // FIXME: We should handle recursing on other vector shuffles and
11058 // scalar_to_vector here as well.
11060 if (!LegalOperations) {
11061 EVT IndexTy = TLI.getVectorIdxTy();
11062 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
11063 SVInVec, DAG.getConstant(OrigElt, IndexTy));
11067 bool BCNumEltsChanged = false;
11068 EVT ExtVT = VT.getVectorElementType();
11071 // If the result of load has to be truncated, then it's not necessarily
11073 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11076 if (InVec.getOpcode() == ISD::BITCAST) {
11077 // Don't duplicate a load with other uses.
11078 if (!InVec.hasOneUse())
11081 EVT BCVT = InVec.getOperand(0).getValueType();
11082 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11084 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11085 BCNumEltsChanged = true;
11086 InVec = InVec.getOperand(0);
11087 ExtVT = BCVT.getVectorElementType();
11090 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11091 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11092 ISD::isNormalLoad(InVec.getNode()) &&
11093 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11094 SDValue Index = N->getOperand(1);
11095 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11096 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11100 // Perform only after legalization to ensure build_vector / vector_shuffle
11101 // optimizations have already been done.
11102 if (!LegalOperations) return SDValue();
11104 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11105 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11106 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11109 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11111 LoadSDNode *LN0 = nullptr;
11112 const ShuffleVectorSDNode *SVN = nullptr;
11113 if (ISD::isNormalLoad(InVec.getNode())) {
11114 LN0 = cast<LoadSDNode>(InVec);
11115 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11116 InVec.getOperand(0).getValueType() == ExtVT &&
11117 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11118 // Don't duplicate a load with other uses.
11119 if (!InVec.hasOneUse())
11122 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11123 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11124 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11126 // (load $addr+1*size)
11128 // Don't duplicate a load with other uses.
11129 if (!InVec.hasOneUse())
11132 // If the bit convert changed the number of elements, it is unsafe
11133 // to examine the mask.
11134 if (BCNumEltsChanged)
11137 // Select the input vector, guarding against out of range extract vector.
11138 unsigned NumElems = VT.getVectorNumElements();
11139 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11140 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11142 if (InVec.getOpcode() == ISD::BITCAST) {
11143 // Don't duplicate a load with other uses.
11144 if (!InVec.hasOneUse())
11147 InVec = InVec.getOperand(0);
11149 if (ISD::isNormalLoad(InVec.getNode())) {
11150 LN0 = cast<LoadSDNode>(InVec);
11151 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11152 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
11156 // Make sure we found a non-volatile load and the extractelement is
11158 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11161 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11163 return DAG.getUNDEF(LVT);
11165 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11171 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11172 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11173 // We perform this optimization post type-legalization because
11174 // the type-legalizer often scalarizes integer-promoted vectors.
11175 // Performing this optimization before may create bit-casts which
11176 // will be type-legalized to complex code sequences.
11177 // We perform this optimization only before the operation legalizer because we
11178 // may introduce illegal operations.
11179 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11182 unsigned NumInScalars = N->getNumOperands();
11184 EVT VT = N->getValueType(0);
11186 // Check to see if this is a BUILD_VECTOR of a bunch of values
11187 // which come from any_extend or zero_extend nodes. If so, we can create
11188 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11189 // optimizations. We do not handle sign-extend because we can't fill the sign
11191 EVT SourceType = MVT::Other;
11192 bool AllAnyExt = true;
11194 for (unsigned i = 0; i != NumInScalars; ++i) {
11195 SDValue In = N->getOperand(i);
11196 // Ignore undef inputs.
11197 if (In.getOpcode() == ISD::UNDEF) continue;
11199 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11200 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11202 // Abort if the element is not an extension.
11203 if (!ZeroExt && !AnyExt) {
11204 SourceType = MVT::Other;
11208 // The input is a ZeroExt or AnyExt. Check the original type.
11209 EVT InTy = In.getOperand(0).getValueType();
11211 // Check that all of the widened source types are the same.
11212 if (SourceType == MVT::Other)
11215 else if (InTy != SourceType) {
11216 // Multiple income types. Abort.
11217 SourceType = MVT::Other;
11221 // Check if all of the extends are ANY_EXTENDs.
11222 AllAnyExt &= AnyExt;
11225 // In order to have valid types, all of the inputs must be extended from the
11226 // same source type and all of the inputs must be any or zero extend.
11227 // Scalar sizes must be a power of two.
11228 EVT OutScalarTy = VT.getScalarType();
11229 bool ValidTypes = SourceType != MVT::Other &&
11230 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11231 isPowerOf2_32(SourceType.getSizeInBits());
11233 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11234 // turn into a single shuffle instruction.
11238 bool isLE = TLI.isLittleEndian();
11239 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11240 assert(ElemRatio > 1 && "Invalid element size ratio");
11241 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11242 DAG.getConstant(0, SourceType);
11244 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11245 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11247 // Populate the new build_vector
11248 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11249 SDValue Cast = N->getOperand(i);
11250 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11251 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11252 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11254 if (Cast.getOpcode() == ISD::UNDEF)
11255 In = DAG.getUNDEF(SourceType);
11257 In = Cast->getOperand(0);
11258 unsigned Index = isLE ? (i * ElemRatio) :
11259 (i * ElemRatio + (ElemRatio - 1));
11261 assert(Index < Ops.size() && "Invalid index");
11265 // The type of the new BUILD_VECTOR node.
11266 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11267 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11268 "Invalid vector size");
11269 // Check if the new vector type is legal.
11270 if (!isTypeLegal(VecVT)) return SDValue();
11272 // Make the new BUILD_VECTOR.
11273 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11275 // The new BUILD_VECTOR node has the potential to be further optimized.
11276 AddToWorklist(BV.getNode());
11277 // Bitcast to the desired type.
11278 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11281 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11282 EVT VT = N->getValueType(0);
11284 unsigned NumInScalars = N->getNumOperands();
11287 EVT SrcVT = MVT::Other;
11288 unsigned Opcode = ISD::DELETED_NODE;
11289 unsigned NumDefs = 0;
11291 for (unsigned i = 0; i != NumInScalars; ++i) {
11292 SDValue In = N->getOperand(i);
11293 unsigned Opc = In.getOpcode();
11295 if (Opc == ISD::UNDEF)
11298 // If all scalar values are floats and converted from integers.
11299 if (Opcode == ISD::DELETED_NODE &&
11300 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11307 EVT InVT = In.getOperand(0).getValueType();
11309 // If all scalar values are typed differently, bail out. It's chosen to
11310 // simplify BUILD_VECTOR of integer types.
11311 if (SrcVT == MVT::Other)
11318 // If the vector has just one element defined, it's not worth to fold it into
11319 // a vectorized one.
11323 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11324 && "Should only handle conversion from integer to float.");
11325 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11327 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11329 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11332 // Just because the floating-point vector type is legal does not necessarily
11333 // mean that the corresponding integer vector type is.
11334 if (!isTypeLegal(NVT))
11337 SmallVector<SDValue, 8> Opnds;
11338 for (unsigned i = 0; i != NumInScalars; ++i) {
11339 SDValue In = N->getOperand(i);
11341 if (In.getOpcode() == ISD::UNDEF)
11342 Opnds.push_back(DAG.getUNDEF(SrcVT));
11344 Opnds.push_back(In.getOperand(0));
11346 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11347 AddToWorklist(BV.getNode());
11349 return DAG.getNode(Opcode, dl, VT, BV);
11352 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11353 unsigned NumInScalars = N->getNumOperands();
11355 EVT VT = N->getValueType(0);
11357 // A vector built entirely of undefs is undef.
11358 if (ISD::allOperandsUndef(N))
11359 return DAG.getUNDEF(VT);
11361 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11364 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11367 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11368 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11369 // at most two distinct vectors, turn this into a shuffle node.
11371 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11372 if (!isTypeLegal(VT))
11375 // May only combine to shuffle after legalize if shuffle is legal.
11376 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11379 SDValue VecIn1, VecIn2;
11380 bool UsesZeroVector = false;
11381 for (unsigned i = 0; i != NumInScalars; ++i) {
11382 SDValue Op = N->getOperand(i);
11383 // Ignore undef inputs.
11384 if (Op.getOpcode() == ISD::UNDEF) continue;
11386 // See if we can combine this build_vector into a blend with a zero vector.
11387 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11388 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11389 (Op.getOpcode() == ISD::ConstantFP &&
11390 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11391 UsesZeroVector = true;
11395 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11396 // constant index, bail out.
11397 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11398 !isa<ConstantSDNode>(Op.getOperand(1))) {
11399 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11403 // We allow up to two distinct input vectors.
11404 SDValue ExtractedFromVec = Op.getOperand(0);
11405 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11408 if (!VecIn1.getNode()) {
11409 VecIn1 = ExtractedFromVec;
11410 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11411 VecIn2 = ExtractedFromVec;
11413 // Too many inputs.
11414 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11419 // If everything is good, we can make a shuffle operation.
11420 if (VecIn1.getNode()) {
11421 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11422 SmallVector<int, 8> Mask;
11423 for (unsigned i = 0; i != NumInScalars; ++i) {
11424 unsigned Opcode = N->getOperand(i).getOpcode();
11425 if (Opcode == ISD::UNDEF) {
11426 Mask.push_back(-1);
11430 // Operands can also be zero.
11431 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11432 assert(UsesZeroVector &&
11433 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11434 "Unexpected node found!");
11435 Mask.push_back(NumInScalars+i);
11439 // If extracting from the first vector, just use the index directly.
11440 SDValue Extract = N->getOperand(i);
11441 SDValue ExtVal = Extract.getOperand(1);
11442 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11443 if (Extract.getOperand(0) == VecIn1) {
11444 Mask.push_back(ExtIndex);
11448 // Otherwise, use InIdx + InputVecSize
11449 Mask.push_back(InNumElements + ExtIndex);
11452 // Avoid introducing illegal shuffles with zero.
11453 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11456 // We can't generate a shuffle node with mismatched input and output types.
11457 // Attempt to transform a single input vector to the correct type.
11458 if ((VT != VecIn1.getValueType())) {
11459 // If the input vector type has a different base type to the output
11460 // vector type, bail out.
11461 EVT VTElemType = VT.getVectorElementType();
11462 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11463 (VecIn2.getNode() &&
11464 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11467 // If the input vector is too small, widen it.
11468 // We only support widening of vectors which are half the size of the
11469 // output registers. For example XMM->YMM widening on X86 with AVX.
11470 EVT VecInT = VecIn1.getValueType();
11471 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11472 // If we only have one small input, widen it by adding undef values.
11473 if (!VecIn2.getNode())
11474 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11475 DAG.getUNDEF(VecIn1.getValueType()));
11476 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11477 // If we have two small inputs of the same type, try to concat them.
11478 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11479 VecIn2 = SDValue(nullptr, 0);
11482 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11483 // If the input vector is too large, try to split it.
11484 // We don't support having two input vectors that are too large.
11485 // If the zero vector was used, we can not split the vector,
11486 // since we'd need 3 inputs.
11487 if (UsesZeroVector || VecIn2.getNode())
11490 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11493 // Try to replace VecIn1 with two extract_subvectors
11494 // No need to update the masks, they should still be correct.
11495 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11496 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11497 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11498 DAG.getConstant(0, TLI.getVectorIdxTy()));
11503 if (UsesZeroVector)
11504 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11505 DAG.getConstantFP(0.0, VT);
11507 // If VecIn2 is unused then change it to undef.
11508 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11510 // Check that we were able to transform all incoming values to the same
11512 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11513 VecIn1.getValueType() != VT)
11516 // Return the new VECTOR_SHUFFLE node.
11520 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11526 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11527 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11528 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
11529 // inputs come from at most two distinct vectors, turn this into a shuffle
11532 // If we only have one input vector, we don't need to do any concatenation.
11533 if (N->getNumOperands() == 1)
11534 return N->getOperand(0);
11536 // Check if all of the operands are undefs.
11537 EVT VT = N->getValueType(0);
11538 if (ISD::allOperandsUndef(N))
11539 return DAG.getUNDEF(VT);
11541 // Optimize concat_vectors where one of the vectors is undef.
11542 if (N->getNumOperands() == 2 &&
11543 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11544 SDValue In = N->getOperand(0);
11545 assert(In.getValueType().isVector() && "Must concat vectors");
11547 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11548 if (In->getOpcode() == ISD::BITCAST &&
11549 !In->getOperand(0)->getValueType(0).isVector()) {
11550 SDValue Scalar = In->getOperand(0);
11551 EVT SclTy = Scalar->getValueType(0);
11553 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11556 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11557 VT.getSizeInBits() / SclTy.getSizeInBits());
11558 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11561 SDLoc dl = SDLoc(N);
11562 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11563 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11567 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11568 // We have already tested above for an UNDEF only concatenation.
11569 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11570 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11571 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
11572 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
11574 bool AllBuildVectorsOrUndefs =
11575 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
11576 if (AllBuildVectorsOrUndefs) {
11577 SmallVector<SDValue, 8> Opnds;
11578 EVT SVT = VT.getScalarType();
11581 if (!SVT.isFloatingPoint()) {
11582 // If BUILD_VECTOR are from built from integer, they may have different
11583 // operand types. Get the smallest type and truncate all operands to it.
11584 bool FoundMinVT = false;
11585 for (const SDValue &Op : N->ops())
11586 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11587 EVT OpSVT = Op.getOperand(0)->getValueType(0);
11588 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
11591 assert(FoundMinVT && "Concat vector type mismatch");
11594 for (const SDValue &Op : N->ops()) {
11595 EVT OpVT = Op.getValueType();
11596 unsigned NumElts = OpVT.getVectorNumElements();
11598 if (ISD::UNDEF == Op.getOpcode())
11599 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
11601 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11602 if (SVT.isFloatingPoint()) {
11603 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
11604 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
11606 for (unsigned i = 0; i != NumElts; ++i)
11608 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
11613 assert(VT.getVectorNumElements() == Opnds.size() &&
11614 "Concat vector type mismatch");
11615 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11618 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11619 // nodes often generate nop CONCAT_VECTOR nodes.
11620 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11621 // place the incoming vectors at the exact same location.
11622 SDValue SingleSource = SDValue();
11623 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11625 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11626 SDValue Op = N->getOperand(i);
11628 if (Op.getOpcode() == ISD::UNDEF)
11631 // Check if this is the identity extract:
11632 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11635 // Find the single incoming vector for the extract_subvector.
11636 if (SingleSource.getNode()) {
11637 if (Op.getOperand(0) != SingleSource)
11640 SingleSource = Op.getOperand(0);
11642 // Check the source type is the same as the type of the result.
11643 // If not, this concat may extend the vector, so we can not
11644 // optimize it away.
11645 if (SingleSource.getValueType() != N->getValueType(0))
11649 unsigned IdentityIndex = i * PartNumElem;
11650 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11651 // The extract index must be constant.
11655 // Check that we are reading from the identity index.
11656 if (CS->getZExtValue() != IdentityIndex)
11660 if (SingleSource.getNode())
11661 return SingleSource;
11666 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11667 EVT NVT = N->getValueType(0);
11668 SDValue V = N->getOperand(0);
11670 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11672 // (extract_subvec (concat V1, V2, ...), i)
11675 // Only operand 0 is checked as 'concat' assumes all inputs of the same
11677 if (V->getOperand(0).getValueType() != NVT)
11679 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11680 unsigned NumElems = NVT.getVectorNumElements();
11681 assert((Idx % NumElems) == 0 &&
11682 "IDX in concat is not a multiple of the result vector length.");
11683 return V->getOperand(Idx / NumElems);
11687 if (V->getOpcode() == ISD::BITCAST)
11688 V = V.getOperand(0);
11690 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11692 // Handle only simple case where vector being inserted and vector
11693 // being extracted are of same type, and are half size of larger vectors.
11694 EVT BigVT = V->getOperand(0).getValueType();
11695 EVT SmallVT = V->getOperand(1).getValueType();
11696 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11699 // Only handle cases where both indexes are constants with the same type.
11700 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11701 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11703 if (InsIdx && ExtIdx &&
11704 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11705 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11707 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11709 // indices are equal or bit offsets are equal => V1
11710 // otherwise => (extract_subvec V1, ExtIdx)
11711 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11712 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11713 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11714 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11715 DAG.getNode(ISD::BITCAST, dl,
11716 N->getOperand(0).getValueType(),
11717 V->getOperand(0)), N->getOperand(1));
11724 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11725 SDValue V, SelectionDAG &DAG) {
11727 EVT VT = V.getValueType();
11729 switch (V.getOpcode()) {
11733 case ISD::CONCAT_VECTORS: {
11734 EVT OpVT = V->getOperand(0).getValueType();
11735 int OpSize = OpVT.getVectorNumElements();
11736 SmallBitVector OpUsedElements(OpSize, false);
11737 bool FoundSimplification = false;
11738 SmallVector<SDValue, 4> NewOps;
11739 NewOps.reserve(V->getNumOperands());
11740 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11741 SDValue Op = V->getOperand(i);
11742 bool OpUsed = false;
11743 for (int j = 0; j < OpSize; ++j)
11744 if (UsedElements[i * OpSize + j]) {
11745 OpUsedElements[j] = true;
11749 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11750 : DAG.getUNDEF(OpVT));
11751 FoundSimplification |= Op == NewOps.back();
11752 OpUsedElements.reset();
11754 if (FoundSimplification)
11755 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11759 case ISD::INSERT_SUBVECTOR: {
11760 SDValue BaseV = V->getOperand(0);
11761 SDValue SubV = V->getOperand(1);
11762 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11766 int SubSize = SubV.getValueType().getVectorNumElements();
11767 int Idx = IdxN->getZExtValue();
11768 bool SubVectorUsed = false;
11769 SmallBitVector SubUsedElements(SubSize, false);
11770 for (int i = 0; i < SubSize; ++i)
11771 if (UsedElements[i + Idx]) {
11772 SubVectorUsed = true;
11773 SubUsedElements[i] = true;
11774 UsedElements[i + Idx] = false;
11777 // Now recurse on both the base and sub vectors.
11778 SDValue SimplifiedSubV =
11780 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11781 : DAG.getUNDEF(SubV.getValueType());
11782 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11783 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11784 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11785 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11791 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11792 SDValue N1, SelectionDAG &DAG) {
11793 EVT VT = SVN->getValueType(0);
11794 int NumElts = VT.getVectorNumElements();
11795 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11796 for (int M : SVN->getMask())
11797 if (M >= 0 && M < NumElts)
11798 N0UsedElements[M] = true;
11799 else if (M >= NumElts)
11800 N1UsedElements[M - NumElts] = true;
11802 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11803 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11804 if (S0 == N0 && S1 == N1)
11807 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11810 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11811 // or turn a shuffle of a single concat into simpler shuffle then concat.
11812 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11813 EVT VT = N->getValueType(0);
11814 unsigned NumElts = VT.getVectorNumElements();
11816 SDValue N0 = N->getOperand(0);
11817 SDValue N1 = N->getOperand(1);
11818 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11820 SmallVector<SDValue, 4> Ops;
11821 EVT ConcatVT = N0.getOperand(0).getValueType();
11822 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11823 unsigned NumConcats = NumElts / NumElemsPerConcat;
11825 // Special case: shuffle(concat(A,B)) can be more efficiently represented
11826 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11827 // half vector elements.
11828 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11829 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11830 SVN->getMask().end(), [](int i) { return i == -1; })) {
11831 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11832 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11833 N1 = DAG.getUNDEF(ConcatVT);
11834 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11837 // Look at every vector that's inserted. We're looking for exact
11838 // subvector-sized copies from a concatenated vector
11839 for (unsigned I = 0; I != NumConcats; ++I) {
11840 // Make sure we're dealing with a copy.
11841 unsigned Begin = I * NumElemsPerConcat;
11842 bool AllUndef = true, NoUndef = true;
11843 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11844 if (SVN->getMaskElt(J) >= 0)
11851 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11854 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11855 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11858 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11859 if (FirstElt < N0.getNumOperands())
11860 Ops.push_back(N0.getOperand(FirstElt));
11862 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11864 } else if (AllUndef) {
11865 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11866 } else { // Mixed with general masks and undefs, can't do optimization.
11871 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11874 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11875 EVT VT = N->getValueType(0);
11876 unsigned NumElts = VT.getVectorNumElements();
11878 SDValue N0 = N->getOperand(0);
11879 SDValue N1 = N->getOperand(1);
11881 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11883 // Canonicalize shuffle undef, undef -> undef
11884 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11885 return DAG.getUNDEF(VT);
11887 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11889 // Canonicalize shuffle v, v -> v, undef
11891 SmallVector<int, 8> NewMask;
11892 for (unsigned i = 0; i != NumElts; ++i) {
11893 int Idx = SVN->getMaskElt(i);
11894 if (Idx >= (int)NumElts) Idx -= NumElts;
11895 NewMask.push_back(Idx);
11897 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11901 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
11902 if (N0.getOpcode() == ISD::UNDEF) {
11903 SmallVector<int, 8> NewMask;
11904 for (unsigned i = 0; i != NumElts; ++i) {
11905 int Idx = SVN->getMaskElt(i);
11907 if (Idx >= (int)NumElts)
11910 Idx = -1; // remove reference to lhs
11912 NewMask.push_back(Idx);
11914 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11918 // Remove references to rhs if it is undef
11919 if (N1.getOpcode() == ISD::UNDEF) {
11920 bool Changed = false;
11921 SmallVector<int, 8> NewMask;
11922 for (unsigned i = 0; i != NumElts; ++i) {
11923 int Idx = SVN->getMaskElt(i);
11924 if (Idx >= (int)NumElts) {
11928 NewMask.push_back(Idx);
11931 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11934 // If it is a splat, check if the argument vector is another splat or a
11936 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11937 SDNode *V = N0.getNode();
11939 // If this is a bit convert that changes the element type of the vector but
11940 // not the number of vector elements, look through it. Be careful not to
11941 // look though conversions that change things like v4f32 to v2f64.
11942 if (V->getOpcode() == ISD::BITCAST) {
11943 SDValue ConvInput = V->getOperand(0);
11944 if (ConvInput.getValueType().isVector() &&
11945 ConvInput.getValueType().getVectorNumElements() == NumElts)
11946 V = ConvInput.getNode();
11949 if (V->getOpcode() == ISD::BUILD_VECTOR) {
11950 assert(V->getNumOperands() == NumElts &&
11951 "BUILD_VECTOR has wrong number of operands");
11953 bool AllSame = true;
11954 for (unsigned i = 0; i != NumElts; ++i) {
11955 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11956 Base = V->getOperand(i);
11960 // Splat of <u, u, u, u>, return <u, u, u, u>
11961 if (!Base.getNode())
11963 for (unsigned i = 0; i != NumElts; ++i) {
11964 if (V->getOperand(i) != Base) {
11969 // Splat of <x, x, x, x>, return <x, x, x, x>
11973 // Canonicalize any other splat as a build_vector.
11974 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
11975 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
11976 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
11977 V->getValueType(0), Ops);
11979 // We may have jumped through bitcasts, so the type of the
11980 // BUILD_VECTOR may not match the type of the shuffle.
11981 if (V->getValueType(0) != VT)
11982 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
11987 // There are various patterns used to build up a vector from smaller vectors,
11988 // subvectors, or elements. Scan chains of these and replace unused insertions
11989 // or components with undef.
11990 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11993 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11994 Level < AfterLegalizeVectorOps &&
11995 (N1.getOpcode() == ISD::UNDEF ||
11996 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11997 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11998 SDValue V = partitionShuffleOfConcats(N, DAG);
12004 // If this shuffle only has a single input that is a bitcasted shuffle,
12005 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12006 // back to their original types.
12007 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12008 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12009 TLI.isTypeLegal(VT)) {
12011 // Peek through the bitcast only if there is one user.
12013 while (BC0.getOpcode() == ISD::BITCAST) {
12014 if (!BC0.hasOneUse())
12016 BC0 = BC0.getOperand(0);
12019 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12021 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12023 SmallVector<int, 8> NewMask;
12025 for (int s = 0; s != Scale; ++s)
12026 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12030 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12031 EVT SVT = VT.getScalarType();
12032 EVT InnerVT = BC0->getValueType(0);
12033 EVT InnerSVT = InnerVT.getScalarType();
12035 // Determine which shuffle works with the smaller scalar type.
12036 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12037 EVT ScaleSVT = ScaleVT.getScalarType();
12039 if (TLI.isTypeLegal(ScaleVT) &&
12040 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12041 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12043 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12044 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12046 // Scale the shuffle masks to the smaller scalar type.
12047 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12048 SmallVector<int, 8> InnerMask =
12049 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12050 SmallVector<int, 8> OuterMask =
12051 ScaleShuffleMask(SVN->getMask(), OuterScale);
12053 // Merge the shuffle masks.
12054 SmallVector<int, 8> NewMask;
12055 for (int M : OuterMask)
12056 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12058 // Test for shuffle mask legality over both commutations.
12059 SDValue SV0 = BC0->getOperand(0);
12060 SDValue SV1 = BC0->getOperand(1);
12061 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12063 std::swap(SV0, SV1);
12064 ShuffleVectorSDNode::commuteMask(NewMask);
12065 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12069 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12070 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12071 return DAG.getNode(
12072 ISD::BITCAST, SDLoc(N), VT,
12073 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12079 // Canonicalize shuffles according to rules:
12080 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12081 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12082 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12083 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12084 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12085 TLI.isTypeLegal(VT)) {
12086 // The incoming shuffle must be of the same type as the result of the
12087 // current shuffle.
12088 assert(N1->getOperand(0).getValueType() == VT &&
12089 "Shuffle types don't match");
12091 SDValue SV0 = N1->getOperand(0);
12092 SDValue SV1 = N1->getOperand(1);
12093 bool HasSameOp0 = N0 == SV0;
12094 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12095 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12096 // Commute the operands of this shuffle so that next rule
12098 return DAG.getCommutedVectorShuffle(*SVN);
12101 // Try to fold according to rules:
12102 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12103 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12104 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12105 // Don't try to fold shuffles with illegal type.
12106 // Only fold if this shuffle is the only user of the other shuffle.
12107 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12108 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12109 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12111 // The incoming shuffle must be of the same type as the result of the
12112 // current shuffle.
12113 assert(OtherSV->getOperand(0).getValueType() == VT &&
12114 "Shuffle types don't match");
12117 SmallVector<int, 4> Mask;
12118 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12119 // operand, and SV1 as the second operand.
12120 for (unsigned i = 0; i != NumElts; ++i) {
12121 int Idx = SVN->getMaskElt(i);
12123 // Propagate Undef.
12124 Mask.push_back(Idx);
12128 SDValue CurrentVec;
12129 if (Idx < (int)NumElts) {
12130 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12131 // shuffle mask to identify which vector is actually referenced.
12132 Idx = OtherSV->getMaskElt(Idx);
12134 // Propagate Undef.
12135 Mask.push_back(Idx);
12139 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12140 : OtherSV->getOperand(1);
12142 // This shuffle index references an element within N1.
12146 // Simple case where 'CurrentVec' is UNDEF.
12147 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12148 Mask.push_back(-1);
12152 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12153 // will be the first or second operand of the combined shuffle.
12154 Idx = Idx % NumElts;
12155 if (!SV0.getNode() || SV0 == CurrentVec) {
12156 // Ok. CurrentVec is the left hand side.
12157 // Update the mask accordingly.
12159 Mask.push_back(Idx);
12163 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12164 if (SV1.getNode() && SV1 != CurrentVec)
12167 // Ok. CurrentVec is the right hand side.
12168 // Update the mask accordingly.
12170 Mask.push_back(Idx + NumElts);
12173 // Check if all indices in Mask are Undef. In case, propagate Undef.
12174 bool isUndefMask = true;
12175 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12176 isUndefMask &= Mask[i] < 0;
12179 return DAG.getUNDEF(VT);
12181 if (!SV0.getNode())
12182 SV0 = DAG.getUNDEF(VT);
12183 if (!SV1.getNode())
12184 SV1 = DAG.getUNDEF(VT);
12186 // Avoid introducing shuffles with illegal mask.
12187 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12188 ShuffleVectorSDNode::commuteMask(Mask);
12190 if (!TLI.isShuffleMaskLegal(Mask, VT))
12193 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12194 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12195 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12196 std::swap(SV0, SV1);
12199 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12200 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12201 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12202 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12208 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12209 SDValue InVal = N->getOperand(0);
12210 EVT VT = N->getValueType(0);
12212 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12213 // with a VECTOR_SHUFFLE.
12214 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12215 SDValue InVec = InVal->getOperand(0);
12216 SDValue EltNo = InVal->getOperand(1);
12218 // FIXME: We could support implicit truncation if the shuffle can be
12219 // scaled to a smaller vector scalar type.
12220 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12221 if (C0 && VT == InVec.getValueType() &&
12222 VT.getScalarType() == InVal.getValueType()) {
12223 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12224 int Elt = C0->getZExtValue();
12227 if (TLI.isShuffleMaskLegal(NewMask, VT))
12228 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12236 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12237 SDValue N0 = N->getOperand(0);
12238 SDValue N2 = N->getOperand(2);
12240 // If the input vector is a concatenation, and the insert replaces
12241 // one of the halves, we can optimize into a single concat_vectors.
12242 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12243 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12244 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12245 EVT VT = N->getValueType(0);
12247 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12248 // (concat_vectors Z, Y)
12250 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12251 N->getOperand(1), N0.getOperand(1));
12253 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12254 // (concat_vectors X, Z)
12255 if (InsIdx == VT.getVectorNumElements()/2)
12256 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12257 N0.getOperand(0), N->getOperand(1));
12263 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12264 /// with the destination vector and a zero vector.
12265 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12266 /// vector_shuffle V, Zero, <0, 4, 2, 4>
12267 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12268 EVT VT = N->getValueType(0);
12269 SDValue LHS = N->getOperand(0);
12270 SDValue RHS = N->getOperand(1);
12273 // Make sure we're not running after operation legalization where it
12274 // may have custom lowered the vector shuffles.
12275 if (LegalOperations)
12278 if (N->getOpcode() != ISD::AND)
12281 if (RHS.getOpcode() == ISD::BITCAST)
12282 RHS = RHS.getOperand(0);
12284 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12285 SmallVector<int, 8> Indices;
12286 unsigned NumElts = RHS.getNumOperands();
12288 for (unsigned i = 0; i != NumElts; ++i) {
12289 SDValue Elt = RHS.getOperand(i);
12290 if (!isa<ConstantSDNode>(Elt))
12293 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12294 Indices.push_back(i);
12295 else if (cast<ConstantSDNode>(Elt)->isNullValue())
12296 Indices.push_back(NumElts+i);
12301 // Let's see if the target supports this vector_shuffle.
12302 EVT RVT = RHS.getValueType();
12303 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12306 // Return the new VECTOR_SHUFFLE node.
12307 EVT EltVT = RVT.getVectorElementType();
12308 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12309 DAG.getConstant(0, EltVT));
12310 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
12311 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12312 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12313 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12319 /// Visit a binary vector operation, like ADD.
12320 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12321 assert(N->getValueType(0).isVector() &&
12322 "SimplifyVBinOp only works on vectors!");
12324 SDValue LHS = N->getOperand(0);
12325 SDValue RHS = N->getOperand(1);
12327 if (SDValue Shuffle = XformToShuffleWithZero(N))
12330 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12332 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12333 RHS.getOpcode() == ISD::BUILD_VECTOR) {
12334 // Check if both vectors are constants. If not bail out.
12335 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12336 cast<BuildVectorSDNode>(RHS)->isConstant()))
12339 SmallVector<SDValue, 8> Ops;
12340 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12341 SDValue LHSOp = LHS.getOperand(i);
12342 SDValue RHSOp = RHS.getOperand(i);
12344 // Can't fold divide by zero.
12345 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12346 N->getOpcode() == ISD::FDIV) {
12347 if ((RHSOp.getOpcode() == ISD::Constant &&
12348 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12349 (RHSOp.getOpcode() == ISD::ConstantFP &&
12350 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12354 EVT VT = LHSOp.getValueType();
12355 EVT RVT = RHSOp.getValueType();
12357 // Integer BUILD_VECTOR operands may have types larger than the element
12358 // size (e.g., when the element type is not legal). Prior to type
12359 // legalization, the types may not match between the two BUILD_VECTORS.
12360 // Truncate one of the operands to make them match.
12361 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12362 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12364 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12368 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12370 if (FoldOp.getOpcode() != ISD::UNDEF &&
12371 FoldOp.getOpcode() != ISD::Constant &&
12372 FoldOp.getOpcode() != ISD::ConstantFP)
12374 Ops.push_back(FoldOp);
12375 AddToWorklist(FoldOp.getNode());
12378 if (Ops.size() == LHS.getNumOperands())
12379 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12382 // Type legalization might introduce new shuffles in the DAG.
12383 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12384 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
12385 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12386 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12387 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12388 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12389 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12390 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12392 if (SVN0->getMask().equals(SVN1->getMask())) {
12393 EVT VT = N->getValueType(0);
12394 SDValue UndefVector = LHS.getOperand(1);
12395 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12396 LHS.getOperand(0), RHS.getOperand(0));
12397 AddUsersToWorklist(N);
12398 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12399 &SVN0->getMask()[0]);
12406 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12407 SDValue N1, SDValue N2){
12408 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12410 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12411 cast<CondCodeSDNode>(N0.getOperand(2))->get());
12413 // If we got a simplified select_cc node back from SimplifySelectCC, then
12414 // break it down into a new SETCC node, and a new SELECT node, and then return
12415 // the SELECT node, since we were called with a SELECT node.
12416 if (SCC.getNode()) {
12417 // Check to see if we got a select_cc back (to turn into setcc/select).
12418 // Otherwise, just return whatever node we got back, like fabs.
12419 if (SCC.getOpcode() == ISD::SELECT_CC) {
12420 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12422 SCC.getOperand(0), SCC.getOperand(1),
12423 SCC.getOperand(4));
12424 AddToWorklist(SETCC.getNode());
12425 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12426 SCC.getOperand(2), SCC.getOperand(3));
12434 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12435 /// being selected between, see if we can simplify the select. Callers of this
12436 /// should assume that TheSelect is deleted if this returns true. As such, they
12437 /// should return the appropriate thing (e.g. the node) back to the top-level of
12438 /// the DAG combiner loop to avoid it being looked at.
12439 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12442 // Cannot simplify select with vector condition
12443 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12445 // If this is a select from two identical things, try to pull the operation
12446 // through the select.
12447 if (LHS.getOpcode() != RHS.getOpcode() ||
12448 !LHS.hasOneUse() || !RHS.hasOneUse())
12451 // If this is a load and the token chain is identical, replace the select
12452 // of two loads with a load through a select of the address to load from.
12453 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12454 // constants have been dropped into the constant pool.
12455 if (LHS.getOpcode() == ISD::LOAD) {
12456 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12457 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12459 // Token chains must be identical.
12460 if (LHS.getOperand(0) != RHS.getOperand(0) ||
12461 // Do not let this transformation reduce the number of volatile loads.
12462 LLD->isVolatile() || RLD->isVolatile() ||
12463 // If this is an EXTLOAD, the VT's must match.
12464 LLD->getMemoryVT() != RLD->getMemoryVT() ||
12465 // If this is an EXTLOAD, the kind of extension must match.
12466 (LLD->getExtensionType() != RLD->getExtensionType() &&
12467 // The only exception is if one of the extensions is anyext.
12468 LLD->getExtensionType() != ISD::EXTLOAD &&
12469 RLD->getExtensionType() != ISD::EXTLOAD) ||
12470 // FIXME: this discards src value information. This is
12471 // over-conservative. It would be beneficial to be able to remember
12472 // both potential memory locations. Since we are discarding
12473 // src value info, don't do the transformation if the memory
12474 // locations are not in the default address space.
12475 LLD->getPointerInfo().getAddrSpace() != 0 ||
12476 RLD->getPointerInfo().getAddrSpace() != 0 ||
12477 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12478 LLD->getBasePtr().getValueType()))
12481 // Check that the select condition doesn't reach either load. If so,
12482 // folding this will induce a cycle into the DAG. If not, this is safe to
12483 // xform, so create a select of the addresses.
12485 if (TheSelect->getOpcode() == ISD::SELECT) {
12486 SDNode *CondNode = TheSelect->getOperand(0).getNode();
12487 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12488 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12490 // The loads must not depend on one another.
12491 if (LLD->isPredecessorOf(RLD) ||
12492 RLD->isPredecessorOf(LLD))
12494 Addr = DAG.getSelect(SDLoc(TheSelect),
12495 LLD->getBasePtr().getValueType(),
12496 TheSelect->getOperand(0), LLD->getBasePtr(),
12497 RLD->getBasePtr());
12498 } else { // Otherwise SELECT_CC
12499 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12500 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12502 if ((LLD->hasAnyUseOfValue(1) &&
12503 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
12504 (RLD->hasAnyUseOfValue(1) &&
12505 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
12508 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
12509 LLD->getBasePtr().getValueType(),
12510 TheSelect->getOperand(0),
12511 TheSelect->getOperand(1),
12512 LLD->getBasePtr(), RLD->getBasePtr(),
12513 TheSelect->getOperand(4));
12517 // It is safe to replace the two loads if they have different alignments,
12518 // but the new load must be the minimum (most restrictive) alignment of the
12520 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
12521 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
12522 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12523 Load = DAG.getLoad(TheSelect->getValueType(0),
12525 // FIXME: Discards pointer and AA info.
12526 LLD->getChain(), Addr, MachinePointerInfo(),
12527 LLD->isVolatile(), LLD->isNonTemporal(),
12528 isInvariant, Alignment);
12530 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12531 RLD->getExtensionType() : LLD->getExtensionType(),
12533 TheSelect->getValueType(0),
12534 // FIXME: Discards pointer and AA info.
12535 LLD->getChain(), Addr, MachinePointerInfo(),
12536 LLD->getMemoryVT(), LLD->isVolatile(),
12537 LLD->isNonTemporal(), isInvariant, Alignment);
12540 // Users of the select now use the result of the load.
12541 CombineTo(TheSelect, Load);
12543 // Users of the old loads now use the new load's chain. We know the
12544 // old-load value is dead now.
12545 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12546 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12553 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
12554 /// where 'cond' is the comparison specified by CC.
12555 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
12556 SDValue N2, SDValue N3,
12557 ISD::CondCode CC, bool NotExtCompare) {
12558 // (x ? y : y) -> y.
12559 if (N2 == N3) return N2;
12561 EVT VT = N2.getValueType();
12562 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12563 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12564 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12566 // Determine if the condition we're dealing with is constant
12567 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12568 N0, N1, CC, DL, false);
12569 if (SCC.getNode()) AddToWorklist(SCC.getNode());
12570 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12572 // fold select_cc true, x, y -> x
12573 if (SCCC && !SCCC->isNullValue())
12575 // fold select_cc false, x, y -> y
12576 if (SCCC && SCCC->isNullValue())
12579 // Check to see if we can simplify the select into an fabs node
12580 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12581 // Allow either -0.0 or 0.0
12582 if (CFP->getValueAPF().isZero()) {
12583 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12584 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12585 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12586 N2 == N3.getOperand(0))
12587 return DAG.getNode(ISD::FABS, DL, VT, N0);
12589 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12590 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12591 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12592 N2.getOperand(0) == N3)
12593 return DAG.getNode(ISD::FABS, DL, VT, N3);
12597 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12598 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12599 // in it. This is a win when the constant is not otherwise available because
12600 // it replaces two constant pool loads with one. We only do this if the FP
12601 // type is known to be legal, because if it isn't, then we are before legalize
12602 // types an we want the other legalization to happen first (e.g. to avoid
12603 // messing with soft float) and if the ConstantFP is not legal, because if
12604 // it is legal, we may not need to store the FP constant in a constant pool.
12605 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12606 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12607 if (TLI.isTypeLegal(N2.getValueType()) &&
12608 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12609 TargetLowering::Legal &&
12610 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12611 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12612 // If both constants have multiple uses, then we won't need to do an
12613 // extra load, they are likely around in registers for other users.
12614 (TV->hasOneUse() || FV->hasOneUse())) {
12615 Constant *Elts[] = {
12616 const_cast<ConstantFP*>(FV->getConstantFPValue()),
12617 const_cast<ConstantFP*>(TV->getConstantFPValue())
12619 Type *FPTy = Elts[0]->getType();
12620 const DataLayout &TD = *TLI.getDataLayout();
12622 // Create a ConstantArray of the two constants.
12623 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12624 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12625 TD.getPrefTypeAlignment(FPTy));
12626 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12628 // Get the offsets to the 0 and 1 element of the array so that we can
12629 // select between them.
12630 SDValue Zero = DAG.getIntPtrConstant(0);
12631 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12632 SDValue One = DAG.getIntPtrConstant(EltSize);
12634 SDValue Cond = DAG.getSetCC(DL,
12635 getSetCCResultType(N0.getValueType()),
12637 AddToWorklist(Cond.getNode());
12638 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12640 AddToWorklist(CstOffset.getNode());
12641 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12643 AddToWorklist(CPIdx.getNode());
12644 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12645 MachinePointerInfo::getConstantPool(), false,
12646 false, false, Alignment);
12651 // Check to see if we can perform the "gzip trick", transforming
12652 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12653 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12654 (N1C->isNullValue() || // (a < 0) ? b : 0
12655 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
12656 EVT XType = N0.getValueType();
12657 EVT AType = N2.getValueType();
12658 if (XType.bitsGE(AType)) {
12659 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12660 // single-bit constant.
12661 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12662 unsigned ShCtV = N2C->getAPIntValue().logBase2();
12663 ShCtV = XType.getSizeInBits()-ShCtV-1;
12664 SDValue ShCt = DAG.getConstant(ShCtV,
12665 getShiftAmountTy(N0.getValueType()));
12666 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12668 AddToWorklist(Shift.getNode());
12670 if (XType.bitsGT(AType)) {
12671 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12672 AddToWorklist(Shift.getNode());
12675 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12678 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12680 DAG.getConstant(XType.getSizeInBits()-1,
12681 getShiftAmountTy(N0.getValueType())));
12682 AddToWorklist(Shift.getNode());
12684 if (XType.bitsGT(AType)) {
12685 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12686 AddToWorklist(Shift.getNode());
12689 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12693 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12694 // where y is has a single bit set.
12695 // A plaintext description would be, we can turn the SELECT_CC into an AND
12696 // when the condition can be materialized as an all-ones register. Any
12697 // single bit-test can be materialized as an all-ones register with
12698 // shift-left and shift-right-arith.
12699 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12700 N0->getValueType(0) == VT &&
12701 N1C && N1C->isNullValue() &&
12702 N2C && N2C->isNullValue()) {
12703 SDValue AndLHS = N0->getOperand(0);
12704 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12705 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12706 // Shift the tested bit over the sign bit.
12707 APInt AndMask = ConstAndRHS->getAPIntValue();
12709 DAG.getConstant(AndMask.countLeadingZeros(),
12710 getShiftAmountTy(AndLHS.getValueType()));
12711 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12713 // Now arithmetic right shift it all the way over, so the result is either
12714 // all-ones, or zero.
12716 DAG.getConstant(AndMask.getBitWidth()-1,
12717 getShiftAmountTy(Shl.getValueType()));
12718 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12720 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12724 // fold select C, 16, 0 -> shl C, 4
12725 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12726 TLI.getBooleanContents(N0.getValueType()) ==
12727 TargetLowering::ZeroOrOneBooleanContent) {
12729 // If the caller doesn't want us to simplify this into a zext of a compare,
12731 if (NotExtCompare && N2C->getAPIntValue() == 1)
12734 // Get a SetCC of the condition
12735 // NOTE: Don't create a SETCC if it's not legal on this target.
12736 if (!LegalOperations ||
12737 TLI.isOperationLegal(ISD::SETCC,
12738 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12740 // cast from setcc result type to select result type
12742 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12744 if (N2.getValueType().bitsLT(SCC.getValueType()))
12745 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12746 N2.getValueType());
12748 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12749 N2.getValueType(), SCC);
12751 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12752 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12753 N2.getValueType(), SCC);
12756 AddToWorklist(SCC.getNode());
12757 AddToWorklist(Temp.getNode());
12759 if (N2C->getAPIntValue() == 1)
12762 // shl setcc result by log2 n2c
12763 return DAG.getNode(
12764 ISD::SHL, DL, N2.getValueType(), Temp,
12765 DAG.getConstant(N2C->getAPIntValue().logBase2(),
12766 getShiftAmountTy(Temp.getValueType())));
12770 // Check to see if this is the equivalent of setcc
12771 // FIXME: Turn all of these into setcc if setcc if setcc is legal
12772 // otherwise, go ahead with the folds.
12773 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12774 EVT XType = N0.getValueType();
12775 if (!LegalOperations ||
12776 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12777 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12778 if (Res.getValueType() != VT)
12779 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12783 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12784 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12785 (!LegalOperations ||
12786 TLI.isOperationLegal(ISD::CTLZ, XType))) {
12787 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12788 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12789 DAG.getConstant(Log2_32(XType.getSizeInBits()),
12790 getShiftAmountTy(Ctlz.getValueType())));
12792 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12793 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12794 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12795 XType, DAG.getConstant(0, XType), N0);
12796 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12797 return DAG.getNode(ISD::SRL, DL, XType,
12798 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12799 DAG.getConstant(XType.getSizeInBits()-1,
12800 getShiftAmountTy(XType)));
12802 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12803 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12804 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12805 DAG.getConstant(XType.getSizeInBits()-1,
12806 getShiftAmountTy(N0.getValueType())));
12807 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12811 // Check to see if this is an integer abs.
12812 // select_cc setg[te] X, 0, X, -X ->
12813 // select_cc setgt X, -1, X, -X ->
12814 // select_cc setl[te] X, 0, -X, X ->
12815 // select_cc setlt X, 1, -X, X ->
12816 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12818 ConstantSDNode *SubC = nullptr;
12819 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12820 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12821 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12822 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12823 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12824 (N1C->isOne() && CC == ISD::SETLT)) &&
12825 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12826 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12828 EVT XType = N0.getValueType();
12829 if (SubC && SubC->isNullValue() && XType.isInteger()) {
12830 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12832 DAG.getConstant(XType.getSizeInBits()-1,
12833 getShiftAmountTy(N0.getValueType())));
12834 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12836 AddToWorklist(Shift.getNode());
12837 AddToWorklist(Add.getNode());
12838 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12845 /// This is a stub for TargetLowering::SimplifySetCC.
12846 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12847 SDValue N1, ISD::CondCode Cond,
12848 SDLoc DL, bool foldBooleans) {
12849 TargetLowering::DAGCombinerInfo
12850 DagCombineInfo(DAG, Level, false, this);
12851 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12854 /// Given an ISD::SDIV node expressing a divide by constant, return
12855 /// a DAG expression to select that will generate the same value by multiplying
12856 /// by a magic number.
12857 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12858 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12859 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12863 // Avoid division by zero.
12864 if (!C->getAPIntValue())
12867 std::vector<SDNode*> Built;
12869 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12871 for (SDNode *N : Built)
12876 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12877 /// DAG expression that will generate the same value by right shifting.
12878 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12879 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12883 // Avoid division by zero.
12884 if (!C->getAPIntValue())
12887 std::vector<SDNode *> Built;
12888 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12890 for (SDNode *N : Built)
12895 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12896 /// expression that will generate the same value by multiplying by a magic
12898 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12899 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12900 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12904 // Avoid division by zero.
12905 if (!C->getAPIntValue())
12908 std::vector<SDNode*> Built;
12910 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12912 for (SDNode *N : Built)
12917 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12918 if (Level >= AfterLegalizeDAG)
12921 // Expose the DAG combiner to the target combiner implementations.
12922 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12924 unsigned Iterations = 0;
12925 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12927 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12928 // For the reciprocal, we need to find the zero of the function:
12929 // F(X) = A X - 1 [which has a zero at X = 1/A]
12931 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12932 // does not require additional intermediate precision]
12933 EVT VT = Op.getValueType();
12935 SDValue FPOne = DAG.getConstantFP(1.0, VT);
12937 AddToWorklist(Est.getNode());
12939 // Newton iterations: Est = Est + Est (1 - Arg * Est)
12940 for (unsigned i = 0; i < Iterations; ++i) {
12941 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12942 AddToWorklist(NewEst.getNode());
12944 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12945 AddToWorklist(NewEst.getNode());
12947 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12948 AddToWorklist(NewEst.getNode());
12950 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12951 AddToWorklist(Est.getNode());
12960 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12961 /// For the reciprocal sqrt, we need to find the zero of the function:
12962 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12964 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12965 /// As a result, we precompute A/2 prior to the iteration loop.
12966 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12967 unsigned Iterations) {
12968 EVT VT = Arg.getValueType();
12970 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12972 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12973 // this entire sequence requires only one FP constant.
12974 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12975 AddToWorklist(HalfArg.getNode());
12977 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12978 AddToWorklist(HalfArg.getNode());
12980 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12981 for (unsigned i = 0; i < Iterations; ++i) {
12982 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12983 AddToWorklist(NewEst.getNode());
12985 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12986 AddToWorklist(NewEst.getNode());
12988 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12989 AddToWorklist(NewEst.getNode());
12991 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12992 AddToWorklist(Est.getNode());
12997 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12998 /// For the reciprocal sqrt, we need to find the zero of the function:
12999 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13001 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13002 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13003 unsigned Iterations) {
13004 EVT VT = Arg.getValueType();
13006 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
13007 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
13009 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13010 for (unsigned i = 0; i < Iterations; ++i) {
13011 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13012 AddToWorklist(HalfEst.getNode());
13014 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13015 AddToWorklist(Est.getNode());
13017 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13018 AddToWorklist(Est.getNode());
13020 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13021 AddToWorklist(Est.getNode());
13023 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13024 AddToWorklist(Est.getNode());
13029 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13030 if (Level >= AfterLegalizeDAG)
13033 // Expose the DAG combiner to the target combiner implementations.
13034 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13035 unsigned Iterations = 0;
13036 bool UseOneConstNR = false;
13037 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13038 AddToWorklist(Est.getNode());
13040 Est = UseOneConstNR ?
13041 BuildRsqrtNROneConst(Op, Est, Iterations) :
13042 BuildRsqrtNRTwoConst(Op, Est, Iterations);
13050 /// Return true if base is a frame index, which is known not to alias with
13051 /// anything but itself. Provides base object and offset as results.
13052 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13053 const GlobalValue *&GV, const void *&CV) {
13054 // Assume it is a primitive operation.
13055 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13057 // If it's an adding a simple constant then integrate the offset.
13058 if (Base.getOpcode() == ISD::ADD) {
13059 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13060 Base = Base.getOperand(0);
13061 Offset += C->getZExtValue();
13065 // Return the underlying GlobalValue, and update the Offset. Return false
13066 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13067 // by multiple nodes with different offsets.
13068 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13069 GV = G->getGlobal();
13070 Offset += G->getOffset();
13074 // Return the underlying Constant value, and update the Offset. Return false
13075 // for ConstantSDNodes since the same constant pool entry may be represented
13076 // by multiple nodes with different offsets.
13077 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13078 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13079 : (const void *)C->getConstVal();
13080 Offset += C->getOffset();
13083 // If it's any of the following then it can't alias with anything but itself.
13084 return isa<FrameIndexSDNode>(Base);
13087 /// Return true if there is any possibility that the two addresses overlap.
13088 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13089 // If they are the same then they must be aliases.
13090 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13092 // If they are both volatile then they cannot be reordered.
13093 if (Op0->isVolatile() && Op1->isVolatile()) return true;
13095 // Gather base node and offset information.
13096 SDValue Base1, Base2;
13097 int64_t Offset1, Offset2;
13098 const GlobalValue *GV1, *GV2;
13099 const void *CV1, *CV2;
13100 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13101 Base1, Offset1, GV1, CV1);
13102 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13103 Base2, Offset2, GV2, CV2);
13105 // If they have a same base address then check to see if they overlap.
13106 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13107 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13108 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13110 // It is possible for different frame indices to alias each other, mostly
13111 // when tail call optimization reuses return address slots for arguments.
13112 // To catch this case, look up the actual index of frame indices to compute
13113 // the real alias relationship.
13114 if (isFrameIndex1 && isFrameIndex2) {
13115 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13116 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13117 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13118 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13119 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13122 // Otherwise, if we know what the bases are, and they aren't identical, then
13123 // we know they cannot alias.
13124 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13127 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13128 // compared to the size and offset of the access, we may be able to prove they
13129 // do not alias. This check is conservative for now to catch cases created by
13130 // splitting vector types.
13131 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13132 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13133 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13134 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13135 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13136 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13137 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13139 // There is no overlap between these relatively aligned accesses of similar
13140 // size, return no alias.
13141 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13142 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13146 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13148 : DAG.getSubtarget().useAA();
13150 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13151 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13155 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13156 // Use alias analysis information.
13157 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13158 Op1->getSrcValueOffset());
13159 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13160 Op0->getSrcValueOffset() - MinOffset;
13161 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13162 Op1->getSrcValueOffset() - MinOffset;
13163 AliasAnalysis::AliasResult AAResult =
13164 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13166 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13167 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13169 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13170 if (AAResult == AliasAnalysis::NoAlias)
13174 // Otherwise we have to assume they alias.
13178 /// Walk up chain skipping non-aliasing memory nodes,
13179 /// looking for aliasing nodes and adding them to the Aliases vector.
13180 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13181 SmallVectorImpl<SDValue> &Aliases) {
13182 SmallVector<SDValue, 8> Chains; // List of chains to visit.
13183 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
13185 // Get alias information for node.
13186 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13189 Chains.push_back(OriginalChain);
13190 unsigned Depth = 0;
13192 // Look at each chain and determine if it is an alias. If so, add it to the
13193 // aliases list. If not, then continue up the chain looking for the next
13195 while (!Chains.empty()) {
13196 SDValue Chain = Chains.back();
13199 // For TokenFactor nodes, look at each operand and only continue up the
13200 // chain until we find two aliases. If we've seen two aliases, assume we'll
13201 // find more and revert to original chain since the xform is unlikely to be
13204 // FIXME: The depth check could be made to return the last non-aliasing
13205 // chain we found before we hit a tokenfactor rather than the original
13207 if (Depth > 6 || Aliases.size() == 2) {
13209 Aliases.push_back(OriginalChain);
13213 // Don't bother if we've been before.
13214 if (!Visited.insert(Chain.getNode()).second)
13217 switch (Chain.getOpcode()) {
13218 case ISD::EntryToken:
13219 // Entry token is ideal chain operand, but handled in FindBetterChain.
13224 // Get alias information for Chain.
13225 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13226 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13228 // If chain is alias then stop here.
13229 if (!(IsLoad && IsOpLoad) &&
13230 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13231 Aliases.push_back(Chain);
13233 // Look further up the chain.
13234 Chains.push_back(Chain.getOperand(0));
13240 case ISD::TokenFactor:
13241 // We have to check each of the operands of the token factor for "small"
13242 // token factors, so we queue them up. Adding the operands to the queue
13243 // (stack) in reverse order maintains the original order and increases the
13244 // likelihood that getNode will find a matching token factor (CSE.)
13245 if (Chain.getNumOperands() > 16) {
13246 Aliases.push_back(Chain);
13249 for (unsigned n = Chain.getNumOperands(); n;)
13250 Chains.push_back(Chain.getOperand(--n));
13255 // For all other instructions we will just have to take what we can get.
13256 Aliases.push_back(Chain);
13261 // We need to be careful here to also search for aliases through the
13262 // value operand of a store, etc. Consider the following situation:
13264 // L1 = load Token1, %52
13265 // S1 = store Token1, L1, %51
13266 // L2 = load Token1, %52+8
13267 // S2 = store Token1, L2, %51+8
13268 // Token2 = Token(S1, S2)
13269 // L3 = load Token2, %53
13270 // S3 = store Token2, L3, %52
13271 // L4 = load Token2, %53+8
13272 // S4 = store Token2, L4, %52+8
13273 // If we search for aliases of S3 (which loads address %52), and we look
13274 // only through the chain, then we'll miss the trivial dependence on L1
13275 // (which also loads from %52). We then might change all loads and
13276 // stores to use Token1 as their chain operand, which could result in
13277 // copying %53 into %52 before copying %52 into %51 (which should
13280 // The problem is, however, that searching for such data dependencies
13281 // can become expensive, and the cost is not directly related to the
13282 // chain depth. Instead, we'll rule out such configurations here by
13283 // insisting that we've visited all chain users (except for users
13284 // of the original chain, which is not necessary). When doing this,
13285 // we need to look through nodes we don't care about (otherwise, things
13286 // like register copies will interfere with trivial cases).
13288 SmallVector<const SDNode *, 16> Worklist;
13289 for (const SDNode *N : Visited)
13290 if (N != OriginalChain.getNode())
13291 Worklist.push_back(N);
13293 while (!Worklist.empty()) {
13294 const SDNode *M = Worklist.pop_back_val();
13296 // We have already visited M, and want to make sure we've visited any uses
13297 // of M that we care about. For uses that we've not visisted, and don't
13298 // care about, queue them to the worklist.
13300 for (SDNode::use_iterator UI = M->use_begin(),
13301 UIE = M->use_end(); UI != UIE; ++UI)
13302 if (UI.getUse().getValueType() == MVT::Other &&
13303 Visited.insert(*UI).second) {
13304 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13305 // We've not visited this use, and we care about it (it could have an
13306 // ordering dependency with the original node).
13308 Aliases.push_back(OriginalChain);
13312 // We've not visited this use, but we don't care about it. Mark it as
13313 // visited and enqueue it to the worklist.
13314 Worklist.push_back(*UI);
13319 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13320 /// (aliasing node.)
13321 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13322 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
13324 // Accumulate all the aliases to this node.
13325 GatherAllAliases(N, OldChain, Aliases);
13327 // If no operands then chain to entry token.
13328 if (Aliases.size() == 0)
13329 return DAG.getEntryNode();
13331 // If a single operand then chain to it. We don't need to revisit it.
13332 if (Aliases.size() == 1)
13335 // Construct a custom tailored token factor.
13336 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13339 /// This is the entry point for the file.
13340 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13341 CodeGenOpt::Level OptLevel) {
13342 /// This is the main entry point to this class.
13343 DAGCombiner(*this, AA, OptLevel).Run(Level);