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 visitBSWAP(SDNode *N);
259 SDValue visitCTLZ(SDNode *N);
260 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
261 SDValue visitCTTZ(SDNode *N);
262 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
263 SDValue visitCTPOP(SDNode *N);
264 SDValue visitSELECT(SDNode *N);
265 SDValue visitVSELECT(SDNode *N);
266 SDValue visitSELECT_CC(SDNode *N);
267 SDValue visitSETCC(SDNode *N);
268 SDValue visitSIGN_EXTEND(SDNode *N);
269 SDValue visitZERO_EXTEND(SDNode *N);
270 SDValue visitANY_EXTEND(SDNode *N);
271 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
272 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
273 SDValue visitTRUNCATE(SDNode *N);
274 SDValue visitBITCAST(SDNode *N);
275 SDValue visitBUILD_PAIR(SDNode *N);
276 SDValue visitFADD(SDNode *N);
277 SDValue visitFSUB(SDNode *N);
278 SDValue visitFMUL(SDNode *N);
279 SDValue visitFMA(SDNode *N);
280 SDValue visitFDIV(SDNode *N);
281 SDValue visitFREM(SDNode *N);
282 SDValue visitFSQRT(SDNode *N);
283 SDValue visitFCOPYSIGN(SDNode *N);
284 SDValue visitSINT_TO_FP(SDNode *N);
285 SDValue visitUINT_TO_FP(SDNode *N);
286 SDValue visitFP_TO_SINT(SDNode *N);
287 SDValue visitFP_TO_UINT(SDNode *N);
288 SDValue visitFP_ROUND(SDNode *N);
289 SDValue visitFP_ROUND_INREG(SDNode *N);
290 SDValue visitFP_EXTEND(SDNode *N);
291 SDValue visitFNEG(SDNode *N);
292 SDValue visitFABS(SDNode *N);
293 SDValue visitFCEIL(SDNode *N);
294 SDValue visitFTRUNC(SDNode *N);
295 SDValue visitFFLOOR(SDNode *N);
296 SDValue visitFMINNUM(SDNode *N);
297 SDValue visitFMAXNUM(SDNode *N);
298 SDValue visitBRCOND(SDNode *N);
299 SDValue visitBR_CC(SDNode *N);
300 SDValue visitLOAD(SDNode *N);
301 SDValue visitSTORE(SDNode *N);
302 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
303 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
304 SDValue visitBUILD_VECTOR(SDNode *N);
305 SDValue visitCONCAT_VECTORS(SDNode *N);
306 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
307 SDValue visitVECTOR_SHUFFLE(SDNode *N);
308 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
309 SDValue visitINSERT_SUBVECTOR(SDNode *N);
310 SDValue visitMLOAD(SDNode *N);
311 SDValue visitMSTORE(SDNode *N);
312 SDValue visitMGATHER(SDNode *N);
313 SDValue visitMSCATTER(SDNode *N);
314 SDValue visitFP_TO_FP16(SDNode *N);
316 SDValue visitFADDForFMACombine(SDNode *N);
317 SDValue visitFSUBForFMACombine(SDNode *N);
319 SDValue XformToShuffleWithZero(SDNode *N);
320 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
322 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
324 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
325 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
326 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
327 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
328 SDValue N3, ISD::CondCode CC,
329 bool NotExtCompare = false);
330 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
331 SDLoc DL, bool foldBooleans = true);
333 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
335 bool isOneUseSetCC(SDValue N) const;
337 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
339 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
340 SDValue CombineExtLoad(SDNode *N);
341 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
342 SDValue BuildSDIV(SDNode *N);
343 SDValue BuildSDIVPow2(SDNode *N);
344 SDValue BuildUDIV(SDNode *N);
345 SDValue BuildReciprocalEstimate(SDValue Op);
346 SDValue BuildRsqrtEstimate(SDValue Op);
347 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
348 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
349 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
350 bool DemandHighBits = true);
351 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
352 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
353 SDValue InnerPos, SDValue InnerNeg,
354 unsigned PosOpcode, unsigned NegOpcode,
356 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
357 SDValue ReduceLoadWidth(SDNode *N);
358 SDValue ReduceLoadOpStoreWidth(SDNode *N);
359 SDValue TransformFPLoadStorePair(SDNode *N);
360 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
361 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
363 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
365 /// Walk up chain skipping non-aliasing memory nodes,
366 /// looking for aliasing nodes and adding them to the Aliases vector.
367 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
368 SmallVectorImpl<SDValue> &Aliases);
370 /// Return true if there is any possibility that the two addresses overlap.
371 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
373 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
374 /// chain (aliasing node.)
375 SDValue FindBetterChain(SDNode *N, SDValue Chain);
377 /// Holds a pointer to an LSBaseSDNode as well as information on where it
378 /// is located in a sequence of memory operations connected by a chain.
380 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
381 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
382 // Ptr to the mem node.
383 LSBaseSDNode *MemNode;
384 // Offset from the base ptr.
385 int64_t OffsetFromBase;
386 // What is the sequence number of this mem node.
387 // Lowest mem operand in the DAG starts at zero.
388 unsigned SequenceNum;
391 /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
392 /// constant build_vector of the stored constant values in Stores.
393 SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
395 ArrayRef<MemOpLink> Stores,
398 /// This is a helper function for MergeConsecutiveStores. When the source
399 /// elements of the consecutive stores are all constants or all extracted
400 /// vector elements, try to merge them into one larger store.
401 /// \return True if a merged store was created.
402 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
403 EVT MemVT, unsigned NumElem,
404 bool IsConstantSrc, bool UseVector);
406 /// This is a helper function for MergeConsecutiveStores.
407 /// Stores that may be merged are placed in StoreNodes.
408 /// Loads that may alias with those stores are placed in AliasLoadNodes.
409 void getStoreMergeAndAliasCandidates(
410 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
411 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
413 /// Merge consecutive store operations into a wide store.
414 /// This optimization uses wide integers or vectors when possible.
415 /// \return True if some memory operations were changed.
416 bool MergeConsecutiveStores(StoreSDNode *N);
418 /// \brief Try to transform a truncation where C is a constant:
419 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
421 /// \p N needs to be a truncation and its first operand an AND. Other
422 /// requirements are checked by the function (e.g. that trunc is
423 /// single-use) and if missed an empty SDValue is returned.
424 SDValue distributeTruncateThroughAnd(SDNode *N);
427 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
428 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
429 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
430 auto *F = DAG.getMachineFunction().getFunction();
431 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
432 F->hasFnAttribute(Attribute::MinSize);
435 /// Runs the dag combiner on all nodes in the work list
436 void Run(CombineLevel AtLevel);
438 SelectionDAG &getDAG() const { return DAG; }
440 /// Returns a type large enough to hold any valid shift amount - before type
441 /// legalization these can be huge.
442 EVT getShiftAmountTy(EVT LHSTy) {
443 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
444 if (LHSTy.isVector())
446 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
447 : TLI.getPointerTy();
450 /// This method returns true if we are running before type legalization or
451 /// if the specified VT is legal.
452 bool isTypeLegal(const EVT &VT) {
453 if (!LegalTypes) return true;
454 return TLI.isTypeLegal(VT);
457 /// Convenience wrapper around TargetLowering::getSetCCResultType
458 EVT getSetCCResultType(EVT VT) const {
459 return TLI.getSetCCResultType(*DAG.getContext(), VT);
466 /// This class is a DAGUpdateListener that removes any deleted
467 /// nodes from the worklist.
468 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
471 explicit WorklistRemover(DAGCombiner &dc)
472 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
474 void NodeDeleted(SDNode *N, SDNode *E) override {
475 DC.removeFromWorklist(N);
480 //===----------------------------------------------------------------------===//
481 // TargetLowering::DAGCombinerInfo implementation
482 //===----------------------------------------------------------------------===//
484 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
485 ((DAGCombiner*)DC)->AddToWorklist(N);
488 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
489 ((DAGCombiner*)DC)->removeFromWorklist(N);
492 SDValue TargetLowering::DAGCombinerInfo::
493 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
494 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
497 SDValue TargetLowering::DAGCombinerInfo::
498 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
499 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
503 SDValue TargetLowering::DAGCombinerInfo::
504 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
505 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
508 void TargetLowering::DAGCombinerInfo::
509 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
510 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
513 //===----------------------------------------------------------------------===//
515 //===----------------------------------------------------------------------===//
517 void DAGCombiner::deleteAndRecombine(SDNode *N) {
518 removeFromWorklist(N);
520 // If the operands of this node are only used by the node, they will now be
521 // dead. Make sure to re-visit them and recursively delete dead nodes.
522 for (const SDValue &Op : N->ops())
523 // For an operand generating multiple values, one of the values may
524 // become dead allowing further simplification (e.g. split index
525 // arithmetic from an indexed load).
526 if (Op->hasOneUse() || Op->getNumValues() > 1)
527 AddToWorklist(Op.getNode());
532 /// Return 1 if we can compute the negated form of the specified expression for
533 /// the same cost as the expression itself, or 2 if we can compute the negated
534 /// form more cheaply than the expression itself.
535 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
536 const TargetLowering &TLI,
537 const TargetOptions *Options,
538 unsigned Depth = 0) {
539 // fneg is removable even if it has multiple uses.
540 if (Op.getOpcode() == ISD::FNEG) return 2;
542 // Don't allow anything with multiple uses.
543 if (!Op.hasOneUse()) return 0;
545 // Don't recurse exponentially.
546 if (Depth > 6) return 0;
548 switch (Op.getOpcode()) {
549 default: return false;
550 case ISD::ConstantFP:
551 // Don't invert constant FP values after legalize. The negated constant
552 // isn't necessarily legal.
553 return LegalOperations ? 0 : 1;
555 // FIXME: determine better conditions for this xform.
556 if (!Options->UnsafeFPMath) return 0;
558 // After operation legalization, it might not be legal to create new FSUBs.
559 if (LegalOperations &&
560 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
563 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
564 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
567 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
568 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
571 // We can't turn -(A-B) into B-A when we honor signed zeros.
572 if (!Options->UnsafeFPMath) return 0;
574 // fold (fneg (fsub A, B)) -> (fsub B, A)
579 if (Options->HonorSignDependentRoundingFPMath()) return 0;
581 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
582 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
586 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
592 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
597 /// If isNegatibleForFree returns true, return the newly negated expression.
598 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
599 bool LegalOperations, unsigned Depth = 0) {
600 const TargetOptions &Options = DAG.getTarget().Options;
601 // fneg is removable even if it has multiple uses.
602 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
604 // Don't allow anything with multiple uses.
605 assert(Op.hasOneUse() && "Unknown reuse!");
607 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
608 switch (Op.getOpcode()) {
609 default: llvm_unreachable("Unknown code");
610 case ISD::ConstantFP: {
611 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
613 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
616 // FIXME: determine better conditions for this xform.
617 assert(Options.UnsafeFPMath);
619 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
620 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
621 DAG.getTargetLoweringInfo(), &Options, Depth+1))
622 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
623 GetNegatedExpression(Op.getOperand(0), DAG,
624 LegalOperations, Depth+1),
626 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
627 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
628 GetNegatedExpression(Op.getOperand(1), DAG,
629 LegalOperations, Depth+1),
632 // We can't turn -(A-B) into B-A when we honor signed zeros.
633 assert(Options.UnsafeFPMath);
635 // fold (fneg (fsub 0, B)) -> B
636 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
638 return Op.getOperand(1);
640 // fold (fneg (fsub A, B)) -> (fsub B, A)
641 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
642 Op.getOperand(1), Op.getOperand(0));
646 assert(!Options.HonorSignDependentRoundingFPMath());
648 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
649 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
650 DAG.getTargetLoweringInfo(), &Options, Depth+1))
651 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
652 GetNegatedExpression(Op.getOperand(0), DAG,
653 LegalOperations, Depth+1),
656 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
657 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
659 GetNegatedExpression(Op.getOperand(1), DAG,
660 LegalOperations, Depth+1));
664 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
665 GetNegatedExpression(Op.getOperand(0), DAG,
666 LegalOperations, Depth+1));
668 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
669 GetNegatedExpression(Op.getOperand(0), DAG,
670 LegalOperations, Depth+1),
675 // Return true if this node is a setcc, or is a select_cc
676 // that selects between the target values used for true and false, making it
677 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
678 // the appropriate nodes based on the type of node we are checking. This
679 // simplifies life a bit for the callers.
680 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
682 if (N.getOpcode() == ISD::SETCC) {
683 LHS = N.getOperand(0);
684 RHS = N.getOperand(1);
685 CC = N.getOperand(2);
689 if (N.getOpcode() != ISD::SELECT_CC ||
690 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
691 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
694 if (TLI.getBooleanContents(N.getValueType()) ==
695 TargetLowering::UndefinedBooleanContent)
698 LHS = N.getOperand(0);
699 RHS = N.getOperand(1);
700 CC = N.getOperand(4);
704 /// Return true if this is a SetCC-equivalent operation with only one use.
705 /// If this is true, it allows the users to invert the operation for free when
706 /// it is profitable to do so.
707 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
709 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
714 /// Returns true if N is a BUILD_VECTOR node whose
715 /// elements are all the same constant or undefined.
716 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
717 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
722 unsigned SplatBitSize;
724 EVT EltVT = N->getValueType(0).getVectorElementType();
725 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
727 EltVT.getSizeInBits() >= SplatBitSize);
730 // \brief Returns the SDNode if it is a constant integer BuildVector
731 // or constant integer.
732 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
733 if (isa<ConstantSDNode>(N))
735 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
740 // \brief Returns the SDNode if it is a constant float BuildVector
741 // or constant float.
742 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
743 if (isa<ConstantFPSDNode>(N))
745 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
750 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
752 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
753 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
756 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
757 BitVector UndefElements;
758 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
760 // BuildVectors can truncate their operands. Ignore that case here.
761 // FIXME: We blindly ignore splats which include undef which is overly
763 if (CN && UndefElements.none() &&
764 CN->getValueType(0) == N.getValueType().getScalarType())
771 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
773 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
774 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
777 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
778 BitVector UndefElements;
779 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
781 if (CN && UndefElements.none())
788 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
789 SDValue N0, SDValue N1) {
790 EVT VT = N0.getValueType();
791 if (N0.getOpcode() == Opc) {
792 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
793 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
794 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
795 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
796 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
799 if (N0.hasOneUse()) {
800 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
802 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
803 if (!OpNode.getNode())
805 AddToWorklist(OpNode.getNode());
806 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
811 if (N1.getOpcode() == Opc) {
812 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
813 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
814 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
815 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
816 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
819 if (N1.hasOneUse()) {
820 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
822 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
823 if (!OpNode.getNode())
825 AddToWorklist(OpNode.getNode());
826 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
834 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
836 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
838 DEBUG(dbgs() << "\nReplacing.1 ";
840 dbgs() << "\nWith: ";
841 To[0].getNode()->dump(&DAG);
842 dbgs() << " and " << NumTo-1 << " other values\n");
843 for (unsigned i = 0, e = NumTo; i != e; ++i)
844 assert((!To[i].getNode() ||
845 N->getValueType(i) == To[i].getValueType()) &&
846 "Cannot combine value to value of different type!");
848 WorklistRemover DeadNodes(*this);
849 DAG.ReplaceAllUsesWith(N, To);
851 // Push the new nodes and any users onto the worklist
852 for (unsigned i = 0, e = NumTo; i != e; ++i) {
853 if (To[i].getNode()) {
854 AddToWorklist(To[i].getNode());
855 AddUsersToWorklist(To[i].getNode());
860 // Finally, if the node is now dead, remove it from the graph. The node
861 // may not be dead if the replacement process recursively simplified to
862 // something else needing this node.
864 deleteAndRecombine(N);
865 return SDValue(N, 0);
869 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
870 // Replace all uses. If any nodes become isomorphic to other nodes and
871 // are deleted, make sure to remove them from our worklist.
872 WorklistRemover DeadNodes(*this);
873 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
875 // Push the new node and any (possibly new) users onto the worklist.
876 AddToWorklist(TLO.New.getNode());
877 AddUsersToWorklist(TLO.New.getNode());
879 // Finally, if the node is now dead, remove it from the graph. The node
880 // may not be dead if the replacement process recursively simplified to
881 // something else needing this node.
882 if (TLO.Old.getNode()->use_empty())
883 deleteAndRecombine(TLO.Old.getNode());
886 /// Check the specified integer node value to see if it can be simplified or if
887 /// things it uses can be simplified by bit propagation. If so, return true.
888 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
889 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
890 APInt KnownZero, KnownOne;
891 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
895 AddToWorklist(Op.getNode());
897 // Replace the old value with the new one.
899 DEBUG(dbgs() << "\nReplacing.2 ";
900 TLO.Old.getNode()->dump(&DAG);
901 dbgs() << "\nWith: ";
902 TLO.New.getNode()->dump(&DAG);
905 CommitTargetLoweringOpt(TLO);
909 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
911 EVT VT = Load->getValueType(0);
912 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
914 DEBUG(dbgs() << "\nReplacing.9 ";
916 dbgs() << "\nWith: ";
917 Trunc.getNode()->dump(&DAG);
919 WorklistRemover DeadNodes(*this);
920 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
921 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
922 deleteAndRecombine(Load);
923 AddToWorklist(Trunc.getNode());
926 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
929 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
930 EVT MemVT = LD->getMemoryVT();
931 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
932 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
934 : LD->getExtensionType();
936 return DAG.getExtLoad(ExtType, dl, PVT,
937 LD->getChain(), LD->getBasePtr(),
938 MemVT, LD->getMemOperand());
941 unsigned Opc = Op.getOpcode();
944 case ISD::AssertSext:
945 return DAG.getNode(ISD::AssertSext, dl, PVT,
946 SExtPromoteOperand(Op.getOperand(0), PVT),
948 case ISD::AssertZext:
949 return DAG.getNode(ISD::AssertZext, dl, PVT,
950 ZExtPromoteOperand(Op.getOperand(0), PVT),
952 case ISD::Constant: {
954 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
955 return DAG.getNode(ExtOpc, dl, PVT, Op);
959 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
961 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
964 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
965 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
967 EVT OldVT = Op.getValueType();
969 bool Replace = false;
970 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
971 if (!NewOp.getNode())
973 AddToWorklist(NewOp.getNode());
976 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
977 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
978 DAG.getValueType(OldVT));
981 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
982 EVT OldVT = Op.getValueType();
984 bool Replace = false;
985 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
986 if (!NewOp.getNode())
988 AddToWorklist(NewOp.getNode());
991 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
992 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
995 /// Promote the specified integer binary operation if the target indicates it is
996 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
997 /// i32 since i16 instructions are longer.
998 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
999 if (!LegalOperations)
1002 EVT VT = Op.getValueType();
1003 if (VT.isVector() || !VT.isInteger())
1006 // If operation type is 'undesirable', e.g. i16 on x86, consider
1008 unsigned Opc = Op.getOpcode();
1009 if (TLI.isTypeDesirableForOp(Opc, VT))
1013 // Consult target whether it is a good idea to promote this operation and
1014 // what's the right type to promote it to.
1015 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1016 assert(PVT != VT && "Don't know what type to promote to!");
1018 bool Replace0 = false;
1019 SDValue N0 = Op.getOperand(0);
1020 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1024 bool Replace1 = false;
1025 SDValue N1 = Op.getOperand(1);
1030 NN1 = PromoteOperand(N1, PVT, Replace1);
1035 AddToWorklist(NN0.getNode());
1037 AddToWorklist(NN1.getNode());
1040 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1042 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1044 DEBUG(dbgs() << "\nPromoting ";
1045 Op.getNode()->dump(&DAG));
1047 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1048 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1053 /// Promote the specified integer shift operation if the target indicates it is
1054 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1055 /// i32 since i16 instructions are longer.
1056 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1057 if (!LegalOperations)
1060 EVT VT = Op.getValueType();
1061 if (VT.isVector() || !VT.isInteger())
1064 // If operation type is 'undesirable', e.g. i16 on x86, consider
1066 unsigned Opc = Op.getOpcode();
1067 if (TLI.isTypeDesirableForOp(Opc, VT))
1071 // Consult target whether it is a good idea to promote this operation and
1072 // what's the right type to promote it to.
1073 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1074 assert(PVT != VT && "Don't know what type to promote to!");
1076 bool Replace = false;
1077 SDValue N0 = Op.getOperand(0);
1078 if (Opc == ISD::SRA)
1079 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1080 else if (Opc == ISD::SRL)
1081 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1083 N0 = PromoteOperand(N0, PVT, Replace);
1087 AddToWorklist(N0.getNode());
1089 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1091 DEBUG(dbgs() << "\nPromoting ";
1092 Op.getNode()->dump(&DAG));
1094 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1095 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1100 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1101 if (!LegalOperations)
1104 EVT VT = Op.getValueType();
1105 if (VT.isVector() || !VT.isInteger())
1108 // If operation type is 'undesirable', e.g. i16 on x86, consider
1110 unsigned Opc = Op.getOpcode();
1111 if (TLI.isTypeDesirableForOp(Opc, VT))
1115 // Consult target whether it is a good idea to promote this operation and
1116 // what's the right type to promote it to.
1117 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1118 assert(PVT != VT && "Don't know what type to promote to!");
1119 // fold (aext (aext x)) -> (aext x)
1120 // fold (aext (zext x)) -> (zext x)
1121 // fold (aext (sext x)) -> (sext x)
1122 DEBUG(dbgs() << "\nPromoting ";
1123 Op.getNode()->dump(&DAG));
1124 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1129 bool DAGCombiner::PromoteLoad(SDValue Op) {
1130 if (!LegalOperations)
1133 EVT VT = Op.getValueType();
1134 if (VT.isVector() || !VT.isInteger())
1137 // If operation type is 'undesirable', e.g. i16 on x86, consider
1139 unsigned Opc = Op.getOpcode();
1140 if (TLI.isTypeDesirableForOp(Opc, VT))
1144 // Consult target whether it is a good idea to promote this operation and
1145 // what's the right type to promote it to.
1146 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1147 assert(PVT != VT && "Don't know what type to promote to!");
1150 SDNode *N = Op.getNode();
1151 LoadSDNode *LD = cast<LoadSDNode>(N);
1152 EVT MemVT = LD->getMemoryVT();
1153 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1154 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1156 : LD->getExtensionType();
1157 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1158 LD->getChain(), LD->getBasePtr(),
1159 MemVT, LD->getMemOperand());
1160 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1162 DEBUG(dbgs() << "\nPromoting ";
1165 Result.getNode()->dump(&DAG);
1167 WorklistRemover DeadNodes(*this);
1168 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1169 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1170 deleteAndRecombine(N);
1171 AddToWorklist(Result.getNode());
1177 /// \brief Recursively delete a node which has no uses and any operands for
1178 /// which it is the only use.
1180 /// Note that this both deletes the nodes and removes them from the worklist.
1181 /// It also adds any nodes who have had a user deleted to the worklist as they
1182 /// may now have only one use and subject to other combines.
1183 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1184 if (!N->use_empty())
1187 SmallSetVector<SDNode *, 16> Nodes;
1190 N = Nodes.pop_back_val();
1194 if (N->use_empty()) {
1195 for (const SDValue &ChildN : N->op_values())
1196 Nodes.insert(ChildN.getNode());
1198 removeFromWorklist(N);
1203 } while (!Nodes.empty());
1207 //===----------------------------------------------------------------------===//
1208 // Main DAG Combiner implementation
1209 //===----------------------------------------------------------------------===//
1211 void DAGCombiner::Run(CombineLevel AtLevel) {
1212 // set the instance variables, so that the various visit routines may use it.
1214 LegalOperations = Level >= AfterLegalizeVectorOps;
1215 LegalTypes = Level >= AfterLegalizeTypes;
1217 // Add all the dag nodes to the worklist.
1218 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1219 E = DAG.allnodes_end(); I != E; ++I)
1222 // Create a dummy node (which is not added to allnodes), that adds a reference
1223 // to the root node, preventing it from being deleted, and tracking any
1224 // changes of the root.
1225 HandleSDNode Dummy(DAG.getRoot());
1227 // while the worklist isn't empty, find a node and
1228 // try and combine it.
1229 while (!WorklistMap.empty()) {
1231 // The Worklist holds the SDNodes in order, but it may contain null entries.
1233 N = Worklist.pop_back_val();
1236 bool GoodWorklistEntry = WorklistMap.erase(N);
1237 (void)GoodWorklistEntry;
1238 assert(GoodWorklistEntry &&
1239 "Found a worklist entry without a corresponding map entry!");
1241 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1242 // N is deleted from the DAG, since they too may now be dead or may have a
1243 // reduced number of uses, allowing other xforms.
1244 if (recursivelyDeleteUnusedNodes(N))
1247 WorklistRemover DeadNodes(*this);
1249 // If this combine is running after legalizing the DAG, re-legalize any
1250 // nodes pulled off the worklist.
1251 if (Level == AfterLegalizeDAG) {
1252 SmallSetVector<SDNode *, 16> UpdatedNodes;
1253 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1255 for (SDNode *LN : UpdatedNodes) {
1257 AddUsersToWorklist(LN);
1263 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1265 // Add any operands of the new node which have not yet been combined to the
1266 // worklist as well. Because the worklist uniques things already, this
1267 // won't repeatedly process the same operand.
1268 CombinedNodes.insert(N);
1269 for (const SDValue &ChildN : N->op_values())
1270 if (!CombinedNodes.count(ChildN.getNode()))
1271 AddToWorklist(ChildN.getNode());
1273 SDValue RV = combine(N);
1280 // If we get back the same node we passed in, rather than a new node or
1281 // zero, we know that the node must have defined multiple values and
1282 // CombineTo was used. Since CombineTo takes care of the worklist
1283 // mechanics for us, we have no work to do in this case.
1284 if (RV.getNode() == N)
1287 assert(N->getOpcode() != ISD::DELETED_NODE &&
1288 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1289 "Node was deleted but visit returned new node!");
1291 DEBUG(dbgs() << " ... into: ";
1292 RV.getNode()->dump(&DAG));
1294 // Transfer debug value.
1295 DAG.TransferDbgValues(SDValue(N, 0), RV);
1296 if (N->getNumValues() == RV.getNode()->getNumValues())
1297 DAG.ReplaceAllUsesWith(N, RV.getNode());
1299 assert(N->getValueType(0) == RV.getValueType() &&
1300 N->getNumValues() == 1 && "Type mismatch");
1302 DAG.ReplaceAllUsesWith(N, &OpV);
1305 // Push the new node and any users onto the worklist
1306 AddToWorklist(RV.getNode());
1307 AddUsersToWorklist(RV.getNode());
1309 // Finally, if the node is now dead, remove it from the graph. The node
1310 // may not be dead if the replacement process recursively simplified to
1311 // something else needing this node. This will also take care of adding any
1312 // operands which have lost a user to the worklist.
1313 recursivelyDeleteUnusedNodes(N);
1316 // If the root changed (e.g. it was a dead load, update the root).
1317 DAG.setRoot(Dummy.getValue());
1318 DAG.RemoveDeadNodes();
1321 SDValue DAGCombiner::visit(SDNode *N) {
1322 switch (N->getOpcode()) {
1324 case ISD::TokenFactor: return visitTokenFactor(N);
1325 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1326 case ISD::ADD: return visitADD(N);
1327 case ISD::SUB: return visitSUB(N);
1328 case ISD::ADDC: return visitADDC(N);
1329 case ISD::SUBC: return visitSUBC(N);
1330 case ISD::ADDE: return visitADDE(N);
1331 case ISD::SUBE: return visitSUBE(N);
1332 case ISD::MUL: return visitMUL(N);
1333 case ISD::SDIV: return visitSDIV(N);
1334 case ISD::UDIV: return visitUDIV(N);
1335 case ISD::SREM: return visitSREM(N);
1336 case ISD::UREM: return visitUREM(N);
1337 case ISD::MULHU: return visitMULHU(N);
1338 case ISD::MULHS: return visitMULHS(N);
1339 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1340 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1341 case ISD::SMULO: return visitSMULO(N);
1342 case ISD::UMULO: return visitUMULO(N);
1343 case ISD::SDIVREM: return visitSDIVREM(N);
1344 case ISD::UDIVREM: return visitUDIVREM(N);
1345 case ISD::AND: return visitAND(N);
1346 case ISD::OR: return visitOR(N);
1347 case ISD::XOR: return visitXOR(N);
1348 case ISD::SHL: return visitSHL(N);
1349 case ISD::SRA: return visitSRA(N);
1350 case ISD::SRL: return visitSRL(N);
1352 case ISD::ROTL: return visitRotate(N);
1353 case ISD::BSWAP: return visitBSWAP(N);
1354 case ISD::CTLZ: return visitCTLZ(N);
1355 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1356 case ISD::CTTZ: return visitCTTZ(N);
1357 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1358 case ISD::CTPOP: return visitCTPOP(N);
1359 case ISD::SELECT: return visitSELECT(N);
1360 case ISD::VSELECT: return visitVSELECT(N);
1361 case ISD::SELECT_CC: return visitSELECT_CC(N);
1362 case ISD::SETCC: return visitSETCC(N);
1363 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1364 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1365 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1366 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1367 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1368 case ISD::TRUNCATE: return visitTRUNCATE(N);
1369 case ISD::BITCAST: return visitBITCAST(N);
1370 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1371 case ISD::FADD: return visitFADD(N);
1372 case ISD::FSUB: return visitFSUB(N);
1373 case ISD::FMUL: return visitFMUL(N);
1374 case ISD::FMA: return visitFMA(N);
1375 case ISD::FDIV: return visitFDIV(N);
1376 case ISD::FREM: return visitFREM(N);
1377 case ISD::FSQRT: return visitFSQRT(N);
1378 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1379 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1380 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1381 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1382 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1383 case ISD::FP_ROUND: return visitFP_ROUND(N);
1384 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1385 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1386 case ISD::FNEG: return visitFNEG(N);
1387 case ISD::FABS: return visitFABS(N);
1388 case ISD::FFLOOR: return visitFFLOOR(N);
1389 case ISD::FMINNUM: return visitFMINNUM(N);
1390 case ISD::FMAXNUM: return visitFMAXNUM(N);
1391 case ISD::FCEIL: return visitFCEIL(N);
1392 case ISD::FTRUNC: return visitFTRUNC(N);
1393 case ISD::BRCOND: return visitBRCOND(N);
1394 case ISD::BR_CC: return visitBR_CC(N);
1395 case ISD::LOAD: return visitLOAD(N);
1396 case ISD::STORE: return visitSTORE(N);
1397 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1398 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1399 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1400 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1401 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1402 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1403 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
1404 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1405 case ISD::MGATHER: return visitMGATHER(N);
1406 case ISD::MLOAD: return visitMLOAD(N);
1407 case ISD::MSCATTER: return visitMSCATTER(N);
1408 case ISD::MSTORE: return visitMSTORE(N);
1409 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
1414 SDValue DAGCombiner::combine(SDNode *N) {
1415 SDValue RV = visit(N);
1417 // If nothing happened, try a target-specific DAG combine.
1418 if (!RV.getNode()) {
1419 assert(N->getOpcode() != ISD::DELETED_NODE &&
1420 "Node was deleted but visit returned NULL!");
1422 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1423 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1425 // Expose the DAG combiner to the target combiner impls.
1426 TargetLowering::DAGCombinerInfo
1427 DagCombineInfo(DAG, Level, false, this);
1429 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1433 // If nothing happened still, try promoting the operation.
1434 if (!RV.getNode()) {
1435 switch (N->getOpcode()) {
1443 RV = PromoteIntBinOp(SDValue(N, 0));
1448 RV = PromoteIntShiftOp(SDValue(N, 0));
1450 case ISD::SIGN_EXTEND:
1451 case ISD::ZERO_EXTEND:
1452 case ISD::ANY_EXTEND:
1453 RV = PromoteExtend(SDValue(N, 0));
1456 if (PromoteLoad(SDValue(N, 0)))
1462 // If N is a commutative binary node, try commuting it to enable more
1464 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1465 N->getNumValues() == 1) {
1466 SDValue N0 = N->getOperand(0);
1467 SDValue N1 = N->getOperand(1);
1469 // Constant operands are canonicalized to RHS.
1470 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1471 SDValue Ops[] = {N1, N0};
1473 if (const auto *BinNode = dyn_cast<BinaryWithFlagsSDNode>(N)) {
1474 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1477 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1480 return SDValue(CSENode, 0);
1487 /// Given a node, return its input chain if it has one, otherwise return a null
1489 static SDValue getInputChainForNode(SDNode *N) {
1490 if (unsigned NumOps = N->getNumOperands()) {
1491 if (N->getOperand(0).getValueType() == MVT::Other)
1492 return N->getOperand(0);
1493 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1494 return N->getOperand(NumOps-1);
1495 for (unsigned i = 1; i < NumOps-1; ++i)
1496 if (N->getOperand(i).getValueType() == MVT::Other)
1497 return N->getOperand(i);
1502 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1503 // If N has two operands, where one has an input chain equal to the other,
1504 // the 'other' chain is redundant.
1505 if (N->getNumOperands() == 2) {
1506 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1507 return N->getOperand(0);
1508 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1509 return N->getOperand(1);
1512 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1513 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1514 SmallPtrSet<SDNode*, 16> SeenOps;
1515 bool Changed = false; // If we should replace this token factor.
1517 // Start out with this token factor.
1520 // Iterate through token factors. The TFs grows when new token factors are
1522 for (unsigned i = 0; i < TFs.size(); ++i) {
1523 SDNode *TF = TFs[i];
1525 // Check each of the operands.
1526 for (const SDValue &Op : TF->op_values()) {
1528 switch (Op.getOpcode()) {
1529 case ISD::EntryToken:
1530 // Entry tokens don't need to be added to the list. They are
1535 case ISD::TokenFactor:
1536 if (Op.hasOneUse() &&
1537 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1538 // Queue up for processing.
1539 TFs.push_back(Op.getNode());
1540 // Clean up in case the token factor is removed.
1541 AddToWorklist(Op.getNode());
1548 // Only add if it isn't already in the list.
1549 if (SeenOps.insert(Op.getNode()).second)
1560 // If we've changed things around then replace token factor.
1563 // The entry token is the only possible outcome.
1564 Result = DAG.getEntryNode();
1566 // New and improved token factor.
1567 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1570 // Add users to worklist if AA is enabled, since it may introduce
1571 // a lot of new chained token factors while removing memory deps.
1572 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1573 : DAG.getSubtarget().useAA();
1574 return CombineTo(N, Result, UseAA /*add to worklist*/);
1580 /// MERGE_VALUES can always be eliminated.
1581 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1582 WorklistRemover DeadNodes(*this);
1583 // Replacing results may cause a different MERGE_VALUES to suddenly
1584 // be CSE'd with N, and carry its uses with it. Iterate until no
1585 // uses remain, to ensure that the node can be safely deleted.
1586 // First add the users of this node to the work list so that they
1587 // can be tried again once they have new operands.
1588 AddUsersToWorklist(N);
1590 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1591 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1592 } while (!N->use_empty());
1593 deleteAndRecombine(N);
1594 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1597 static bool isNullConstant(SDValue V) {
1598 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1599 return Const != nullptr && Const->isNullValue();
1602 static bool isNullFPConstant(SDValue V) {
1603 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1604 return Const != nullptr && Const->isZero() && !Const->isNegative();
1607 static bool isAllOnesConstant(SDValue V) {
1608 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1609 return Const != nullptr && Const->isAllOnesValue();
1612 static bool isOneConstant(SDValue V) {
1613 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1614 return Const != nullptr && Const->isOne();
1617 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1618 /// ContantSDNode pointer else nullptr.
1619 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1620 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1621 return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1624 SDValue DAGCombiner::visitADD(SDNode *N) {
1625 SDValue N0 = N->getOperand(0);
1626 SDValue N1 = N->getOperand(1);
1627 EVT VT = N0.getValueType();
1630 if (VT.isVector()) {
1631 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1634 // fold (add x, 0) -> x, vector edition
1635 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1637 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1641 // fold (add x, undef) -> undef
1642 if (N0.getOpcode() == ISD::UNDEF)
1644 if (N1.getOpcode() == ISD::UNDEF)
1646 // fold (add c1, c2) -> c1+c2
1647 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1648 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1650 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1651 // canonicalize constant to RHS
1652 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1653 !isConstantIntBuildVectorOrConstantInt(N1))
1654 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1655 // fold (add x, 0) -> x
1656 if (isNullConstant(N1))
1658 // fold (add Sym, c) -> Sym+c
1659 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1660 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1661 GA->getOpcode() == ISD::GlobalAddress)
1662 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1664 (uint64_t)N1C->getSExtValue());
1665 // fold ((c1-A)+c2) -> (c1+c2)-A
1666 if (N1C && N0.getOpcode() == ISD::SUB)
1667 if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1669 return DAG.getNode(ISD::SUB, DL, VT,
1670 DAG.getConstant(N1C->getAPIntValue()+
1671 N0C->getAPIntValue(), DL, VT),
1675 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1677 // fold ((0-A) + B) -> B-A
1678 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1679 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1680 // fold (A + (0-B)) -> A-B
1681 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1682 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1683 // fold (A+(B-A)) -> B
1684 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1685 return N1.getOperand(0);
1686 // fold ((B-A)+A) -> B
1687 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1688 return N0.getOperand(0);
1689 // fold (A+(B-(A+C))) to (B-C)
1690 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1691 N0 == N1.getOperand(1).getOperand(0))
1692 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1693 N1.getOperand(1).getOperand(1));
1694 // fold (A+(B-(C+A))) to (B-C)
1695 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1696 N0 == N1.getOperand(1).getOperand(1))
1697 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1698 N1.getOperand(1).getOperand(0));
1699 // fold (A+((B-A)+or-C)) to (B+or-C)
1700 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1701 N1.getOperand(0).getOpcode() == ISD::SUB &&
1702 N0 == N1.getOperand(0).getOperand(1))
1703 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1704 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1706 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1707 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1708 SDValue N00 = N0.getOperand(0);
1709 SDValue N01 = N0.getOperand(1);
1710 SDValue N10 = N1.getOperand(0);
1711 SDValue N11 = N1.getOperand(1);
1713 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1714 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1715 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1716 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1719 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1720 return SDValue(N, 0);
1722 // fold (a+b) -> (a|b) iff a and b share no bits.
1723 if (VT.isInteger() && !VT.isVector()) {
1724 APInt LHSZero, LHSOne;
1725 APInt RHSZero, RHSOne;
1726 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1728 if (LHSZero.getBoolValue()) {
1729 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1731 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1732 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1733 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1734 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1735 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1740 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1741 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1742 isNullConstant(N1.getOperand(0).getOperand(0)))
1743 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1744 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1745 N1.getOperand(0).getOperand(1),
1747 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1748 isNullConstant(N0.getOperand(0).getOperand(0)))
1749 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1750 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1751 N0.getOperand(0).getOperand(1),
1754 if (N1.getOpcode() == ISD::AND) {
1755 SDValue AndOp0 = N1.getOperand(0);
1756 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1757 unsigned DestBits = VT.getScalarType().getSizeInBits();
1759 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1760 // and similar xforms where the inner op is either ~0 or 0.
1761 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1763 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1767 // add (sext i1), X -> sub X, (zext i1)
1768 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1769 N0.getOperand(0).getValueType() == MVT::i1 &&
1770 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1772 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1773 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1776 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1777 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1778 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1779 if (TN->getVT() == MVT::i1) {
1781 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1782 DAG.getConstant(1, DL, VT));
1783 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1790 SDValue DAGCombiner::visitADDC(SDNode *N) {
1791 SDValue N0 = N->getOperand(0);
1792 SDValue N1 = N->getOperand(1);
1793 EVT VT = N0.getValueType();
1795 // If the flag result is dead, turn this into an ADD.
1796 if (!N->hasAnyUseOfValue(1))
1797 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1798 DAG.getNode(ISD::CARRY_FALSE,
1799 SDLoc(N), MVT::Glue));
1801 // canonicalize constant to RHS.
1802 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1803 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1805 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1807 // fold (addc x, 0) -> x + no carry out
1808 if (isNullConstant(N1))
1809 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1810 SDLoc(N), MVT::Glue));
1812 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1813 APInt LHSZero, LHSOne;
1814 APInt RHSZero, RHSOne;
1815 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1817 if (LHSZero.getBoolValue()) {
1818 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1820 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1821 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1822 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1823 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1824 DAG.getNode(ISD::CARRY_FALSE,
1825 SDLoc(N), MVT::Glue));
1831 SDValue DAGCombiner::visitADDE(SDNode *N) {
1832 SDValue N0 = N->getOperand(0);
1833 SDValue N1 = N->getOperand(1);
1834 SDValue CarryIn = N->getOperand(2);
1836 // canonicalize constant to RHS
1837 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1838 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1840 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1843 // fold (adde x, y, false) -> (addc x, y)
1844 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1845 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1850 // Since it may not be valid to emit a fold to zero for vector initializers
1851 // check if we can before folding.
1852 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1854 bool LegalOperations, bool LegalTypes) {
1856 return DAG.getConstant(0, DL, VT);
1857 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1858 return DAG.getConstant(0, DL, VT);
1862 SDValue DAGCombiner::visitSUB(SDNode *N) {
1863 SDValue N0 = N->getOperand(0);
1864 SDValue N1 = N->getOperand(1);
1865 EVT VT = N0.getValueType();
1868 if (VT.isVector()) {
1869 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1872 // fold (sub x, 0) -> x, vector edition
1873 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1877 // fold (sub x, x) -> 0
1878 // FIXME: Refactor this and xor and other similar operations together.
1880 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1881 // fold (sub c1, c2) -> c1-c2
1882 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1883 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1885 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1886 // fold (sub x, c) -> (add x, -c)
1889 return DAG.getNode(ISD::ADD, DL, VT, N0,
1890 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1892 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1893 if (isAllOnesConstant(N0))
1894 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1895 // fold A-(A-B) -> B
1896 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1897 return N1.getOperand(1);
1898 // fold (A+B)-A -> B
1899 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1900 return N0.getOperand(1);
1901 // fold (A+B)-B -> A
1902 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1903 return N0.getOperand(0);
1904 // fold C2-(A+C1) -> (C2-C1)-A
1905 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1906 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1907 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1909 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1911 return DAG.getNode(ISD::SUB, DL, VT, NewC,
1914 // fold ((A+(B+or-C))-B) -> A+or-C
1915 if (N0.getOpcode() == ISD::ADD &&
1916 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1917 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1918 N0.getOperand(1).getOperand(0) == N1)
1919 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1920 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1921 // fold ((A+(C+B))-B) -> A+C
1922 if (N0.getOpcode() == ISD::ADD &&
1923 N0.getOperand(1).getOpcode() == ISD::ADD &&
1924 N0.getOperand(1).getOperand(1) == N1)
1925 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1926 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1927 // fold ((A-(B-C))-C) -> A-B
1928 if (N0.getOpcode() == ISD::SUB &&
1929 N0.getOperand(1).getOpcode() == ISD::SUB &&
1930 N0.getOperand(1).getOperand(1) == N1)
1931 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1932 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1934 // If either operand of a sub is undef, the result is undef
1935 if (N0.getOpcode() == ISD::UNDEF)
1937 if (N1.getOpcode() == ISD::UNDEF)
1940 // If the relocation model supports it, consider symbol offsets.
1941 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1942 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1943 // fold (sub Sym, c) -> Sym-c
1944 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1945 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1947 (uint64_t)N1C->getSExtValue());
1948 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1949 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1950 if (GA->getGlobal() == GB->getGlobal())
1951 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1955 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1956 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1957 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1958 if (TN->getVT() == MVT::i1) {
1960 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1961 DAG.getConstant(1, DL, VT));
1962 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1969 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1970 SDValue N0 = N->getOperand(0);
1971 SDValue N1 = N->getOperand(1);
1972 EVT VT = N0.getValueType();
1974 // If the flag result is dead, turn this into an SUB.
1975 if (!N->hasAnyUseOfValue(1))
1976 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1977 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1980 // fold (subc x, x) -> 0 + no borrow
1983 return CombineTo(N, DAG.getConstant(0, DL, VT),
1984 DAG.getNode(ISD::CARRY_FALSE, DL,
1988 // fold (subc x, 0) -> x + no borrow
1989 if (isNullConstant(N1))
1990 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1993 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1994 if (isAllOnesConstant(N0))
1995 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1996 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
2002 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2003 SDValue N0 = N->getOperand(0);
2004 SDValue N1 = N->getOperand(1);
2005 SDValue CarryIn = N->getOperand(2);
2007 // fold (sube x, y, false) -> (subc x, y)
2008 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2009 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2014 SDValue DAGCombiner::visitMUL(SDNode *N) {
2015 SDValue N0 = N->getOperand(0);
2016 SDValue N1 = N->getOperand(1);
2017 EVT VT = N0.getValueType();
2019 // fold (mul x, undef) -> 0
2020 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2021 return DAG.getConstant(0, SDLoc(N), VT);
2023 bool N0IsConst = false;
2024 bool N1IsConst = false;
2025 bool N1IsOpaqueConst = false;
2026 bool N0IsOpaqueConst = false;
2027 APInt ConstValue0, ConstValue1;
2029 if (VT.isVector()) {
2030 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2033 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2034 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2036 N0IsConst = isa<ConstantSDNode>(N0);
2038 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2039 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2041 N1IsConst = isa<ConstantSDNode>(N1);
2043 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2044 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2048 // fold (mul c1, c2) -> c1*c2
2049 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2050 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2051 N0.getNode(), N1.getNode());
2053 // canonicalize constant to RHS (vector doesn't have to splat)
2054 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2055 !isConstantIntBuildVectorOrConstantInt(N1))
2056 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2057 // fold (mul x, 0) -> 0
2058 if (N1IsConst && ConstValue1 == 0)
2060 // We require a splat of the entire scalar bit width for non-contiguous
2063 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2064 // fold (mul x, 1) -> x
2065 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2067 // fold (mul x, -1) -> 0-x
2068 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2070 return DAG.getNode(ISD::SUB, DL, VT,
2071 DAG.getConstant(0, DL, VT), N0);
2073 // fold (mul x, (1 << c)) -> x << c
2074 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2077 return DAG.getNode(ISD::SHL, DL, VT, N0,
2078 DAG.getConstant(ConstValue1.logBase2(), DL,
2079 getShiftAmountTy(N0.getValueType())));
2081 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2082 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2084 unsigned Log2Val = (-ConstValue1).logBase2();
2086 // FIXME: If the input is something that is easily negated (e.g. a
2087 // single-use add), we should put the negate there.
2088 return DAG.getNode(ISD::SUB, DL, VT,
2089 DAG.getConstant(0, DL, VT),
2090 DAG.getNode(ISD::SHL, DL, VT, N0,
2091 DAG.getConstant(Log2Val, DL,
2092 getShiftAmountTy(N0.getValueType()))));
2096 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2097 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2098 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2099 isa<ConstantSDNode>(N0.getOperand(1)))) {
2100 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2101 N1, N0.getOperand(1));
2102 AddToWorklist(C3.getNode());
2103 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2104 N0.getOperand(0), C3);
2107 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2110 SDValue Sh(nullptr,0), Y(nullptr,0);
2111 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2112 if (N0.getOpcode() == ISD::SHL &&
2113 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2114 isa<ConstantSDNode>(N0.getOperand(1))) &&
2115 N0.getNode()->hasOneUse()) {
2117 } else if (N1.getOpcode() == ISD::SHL &&
2118 isa<ConstantSDNode>(N1.getOperand(1)) &&
2119 N1.getNode()->hasOneUse()) {
2124 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2125 Sh.getOperand(0), Y);
2126 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2127 Mul, Sh.getOperand(1));
2131 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2132 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2133 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2134 isa<ConstantSDNode>(N0.getOperand(1))))
2135 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2136 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2137 N0.getOperand(0), N1),
2138 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2139 N0.getOperand(1), N1));
2142 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2148 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2149 SDValue N0 = N->getOperand(0);
2150 SDValue N1 = N->getOperand(1);
2151 EVT VT = N->getValueType(0);
2155 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2158 // fold (sdiv c1, c2) -> c1/c2
2159 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2160 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2161 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2162 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2163 // fold (sdiv X, 1) -> X
2164 if (N1C && N1C->isOne())
2166 // fold (sdiv X, -1) -> 0-X
2167 if (N1C && N1C->isAllOnesValue()) {
2169 return DAG.getNode(ISD::SUB, DL, VT,
2170 DAG.getConstant(0, DL, VT), N0);
2172 // If we know the sign bits of both operands are zero, strength reduce to a
2173 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2174 if (!VT.isVector()) {
2175 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2176 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2180 // fold (sdiv X, pow2) -> simple ops after legalize
2181 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2182 (N1C->getAPIntValue().isPowerOf2() ||
2183 (-N1C->getAPIntValue()).isPowerOf2())) {
2184 // If dividing by powers of two is cheap, then don't perform the following
2186 if (TLI.isPow2SDivCheap())
2189 // Target-specific implementation of sdiv x, pow2.
2190 SDValue Res = BuildSDIVPow2(N);
2194 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2197 // Splat the sign bit into the register
2199 DAG.getNode(ISD::SRA, DL, VT, N0,
2200 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2201 getShiftAmountTy(N0.getValueType())));
2202 AddToWorklist(SGN.getNode());
2204 // Add (N0 < 0) ? abs2 - 1 : 0;
2206 DAG.getNode(ISD::SRL, DL, VT, SGN,
2207 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2208 getShiftAmountTy(SGN.getValueType())));
2209 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2210 AddToWorklist(SRL.getNode());
2211 AddToWorklist(ADD.getNode()); // Divide by pow2
2212 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2213 DAG.getConstant(lg2, DL,
2214 getShiftAmountTy(ADD.getValueType())));
2216 // If we're dividing by a positive value, we're done. Otherwise, we must
2217 // negate the result.
2218 if (N1C->getAPIntValue().isNonNegative())
2221 AddToWorklist(SRA.getNode());
2222 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2225 // If integer divide is expensive and we satisfy the requirements, emit an
2226 // alternate sequence.
2227 if (N1C && !TLI.isIntDivCheap()) {
2228 SDValue Op = BuildSDIV(N);
2229 if (Op.getNode()) return Op;
2233 if (N0.getOpcode() == ISD::UNDEF)
2234 return DAG.getConstant(0, SDLoc(N), VT);
2235 // X / undef -> undef
2236 if (N1.getOpcode() == ISD::UNDEF)
2242 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2243 SDValue N0 = N->getOperand(0);
2244 SDValue N1 = N->getOperand(1);
2245 EVT VT = N->getValueType(0);
2249 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2252 // fold (udiv c1, c2) -> c1/c2
2253 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2254 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2256 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT,
2259 // fold (udiv x, (1 << c)) -> x >>u c
2260 if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2()) {
2262 return DAG.getNode(ISD::SRL, DL, VT, N0,
2263 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2264 getShiftAmountTy(N0.getValueType())));
2266 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2267 if (N1.getOpcode() == ISD::SHL) {
2268 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2269 if (SHC->getAPIntValue().isPowerOf2()) {
2270 EVT ADDVT = N1.getOperand(1).getValueType();
2272 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2274 DAG.getConstant(SHC->getAPIntValue()
2277 AddToWorklist(Add.getNode());
2278 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2282 // fold (udiv x, c) -> alternate
2283 if (N1C && !TLI.isIntDivCheap()) {
2284 SDValue Op = BuildUDIV(N);
2285 if (Op.getNode()) return Op;
2289 if (N0.getOpcode() == ISD::UNDEF)
2290 return DAG.getConstant(0, SDLoc(N), VT);
2291 // X / undef -> undef
2292 if (N1.getOpcode() == ISD::UNDEF)
2298 SDValue DAGCombiner::visitSREM(SDNode *N) {
2299 SDValue N0 = N->getOperand(0);
2300 SDValue N1 = N->getOperand(1);
2301 EVT VT = N->getValueType(0);
2303 // fold (srem c1, c2) -> c1%c2
2304 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2305 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2307 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT,
2310 // If we know the sign bits of both operands are zero, strength reduce to a
2311 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2312 if (!VT.isVector()) {
2313 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2314 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2317 // If X/C can be simplified by the division-by-constant logic, lower
2318 // X%C to the equivalent of X-X/C*C.
2319 if (N1C && !N1C->isNullValue()) {
2320 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2321 AddToWorklist(Div.getNode());
2322 SDValue OptimizedDiv = combine(Div.getNode());
2323 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2324 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2326 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2327 AddToWorklist(Mul.getNode());
2333 if (N0.getOpcode() == ISD::UNDEF)
2334 return DAG.getConstant(0, SDLoc(N), VT);
2335 // X % undef -> undef
2336 if (N1.getOpcode() == ISD::UNDEF)
2342 SDValue DAGCombiner::visitUREM(SDNode *N) {
2343 SDValue N0 = N->getOperand(0);
2344 SDValue N1 = N->getOperand(1);
2345 EVT VT = N->getValueType(0);
2347 // fold (urem c1, c2) -> c1%c2
2348 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2349 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2351 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT,
2354 // fold (urem x, pow2) -> (and x, pow2-1)
2355 if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2356 N1C->getAPIntValue().isPowerOf2()) {
2358 return DAG.getNode(ISD::AND, DL, VT, N0,
2359 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2361 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2362 if (N1.getOpcode() == ISD::SHL) {
2363 if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2364 if (SHC->getAPIntValue().isPowerOf2()) {
2367 DAG.getNode(ISD::ADD, DL, VT, N1,
2368 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2370 AddToWorklist(Add.getNode());
2371 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2376 // If X/C can be simplified by the division-by-constant logic, lower
2377 // X%C to the equivalent of X-X/C*C.
2378 if (N1C && !N1C->isNullValue()) {
2379 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2380 AddToWorklist(Div.getNode());
2381 SDValue OptimizedDiv = combine(Div.getNode());
2382 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2383 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2385 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2386 AddToWorklist(Mul.getNode());
2392 if (N0.getOpcode() == ISD::UNDEF)
2393 return DAG.getConstant(0, SDLoc(N), VT);
2394 // X % undef -> undef
2395 if (N1.getOpcode() == ISD::UNDEF)
2401 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2402 SDValue N0 = N->getOperand(0);
2403 SDValue N1 = N->getOperand(1);
2404 EVT VT = N->getValueType(0);
2407 // fold (mulhs x, 0) -> 0
2408 if (isNullConstant(N1))
2410 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2411 if (isOneConstant(N1)) {
2413 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2414 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2416 getShiftAmountTy(N0.getValueType())));
2418 // fold (mulhs x, undef) -> 0
2419 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2420 return DAG.getConstant(0, SDLoc(N), VT);
2422 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2424 if (VT.isSimple() && !VT.isVector()) {
2425 MVT Simple = VT.getSimpleVT();
2426 unsigned SimpleSize = Simple.getSizeInBits();
2427 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2428 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2429 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2430 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2431 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2432 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2433 DAG.getConstant(SimpleSize, DL,
2434 getShiftAmountTy(N1.getValueType())));
2435 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2442 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2443 SDValue N0 = N->getOperand(0);
2444 SDValue N1 = N->getOperand(1);
2445 EVT VT = N->getValueType(0);
2448 // fold (mulhu x, 0) -> 0
2449 if (isNullConstant(N1))
2451 // fold (mulhu x, 1) -> 0
2452 if (isOneConstant(N1))
2453 return DAG.getConstant(0, DL, N0.getValueType());
2454 // fold (mulhu x, undef) -> 0
2455 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2456 return DAG.getConstant(0, DL, VT);
2458 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2460 if (VT.isSimple() && !VT.isVector()) {
2461 MVT Simple = VT.getSimpleVT();
2462 unsigned SimpleSize = Simple.getSizeInBits();
2463 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2464 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2465 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2466 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2467 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2468 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2469 DAG.getConstant(SimpleSize, DL,
2470 getShiftAmountTy(N1.getValueType())));
2471 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2478 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2479 /// give the opcodes for the two computations that are being performed. Return
2480 /// true if a simplification was made.
2481 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2483 // If the high half is not needed, just compute the low half.
2484 bool HiExists = N->hasAnyUseOfValue(1);
2486 (!LegalOperations ||
2487 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2488 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2489 return CombineTo(N, Res, Res);
2492 // If the low half is not needed, just compute the high half.
2493 bool LoExists = N->hasAnyUseOfValue(0);
2495 (!LegalOperations ||
2496 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2497 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2498 return CombineTo(N, Res, Res);
2501 // If both halves are used, return as it is.
2502 if (LoExists && HiExists)
2505 // If the two computed results can be simplified separately, separate them.
2507 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2508 AddToWorklist(Lo.getNode());
2509 SDValue LoOpt = combine(Lo.getNode());
2510 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2511 (!LegalOperations ||
2512 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2513 return CombineTo(N, LoOpt, LoOpt);
2517 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2518 AddToWorklist(Hi.getNode());
2519 SDValue HiOpt = combine(Hi.getNode());
2520 if (HiOpt.getNode() && HiOpt != Hi &&
2521 (!LegalOperations ||
2522 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2523 return CombineTo(N, HiOpt, HiOpt);
2529 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2530 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2531 if (Res.getNode()) return Res;
2533 EVT VT = N->getValueType(0);
2536 // If the type is twice as wide is legal, transform the mulhu to a wider
2537 // multiply plus a shift.
2538 if (VT.isSimple() && !VT.isVector()) {
2539 MVT Simple = VT.getSimpleVT();
2540 unsigned SimpleSize = Simple.getSizeInBits();
2541 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2542 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2543 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2544 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2545 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2546 // Compute the high part as N1.
2547 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2548 DAG.getConstant(SimpleSize, DL,
2549 getShiftAmountTy(Lo.getValueType())));
2550 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2551 // Compute the low part as N0.
2552 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2553 return CombineTo(N, Lo, Hi);
2560 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2561 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2562 if (Res.getNode()) return Res;
2564 EVT VT = N->getValueType(0);
2567 // If the type is twice as wide is legal, transform the mulhu to a wider
2568 // multiply plus a shift.
2569 if (VT.isSimple() && !VT.isVector()) {
2570 MVT Simple = VT.getSimpleVT();
2571 unsigned SimpleSize = Simple.getSizeInBits();
2572 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2573 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2574 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2575 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2576 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2577 // Compute the high part as N1.
2578 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2579 DAG.getConstant(SimpleSize, DL,
2580 getShiftAmountTy(Lo.getValueType())));
2581 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2582 // Compute the low part as N0.
2583 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2584 return CombineTo(N, Lo, Hi);
2591 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2592 // (smulo x, 2) -> (saddo x, x)
2593 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2594 if (C2->getAPIntValue() == 2)
2595 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2596 N->getOperand(0), N->getOperand(0));
2601 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2602 // (umulo x, 2) -> (uaddo x, x)
2603 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2604 if (C2->getAPIntValue() == 2)
2605 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2606 N->getOperand(0), N->getOperand(0));
2611 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2612 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2613 if (Res.getNode()) return Res;
2618 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2619 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2620 if (Res.getNode()) return Res;
2625 /// If this is a binary operator with two operands of the same opcode, try to
2627 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2628 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2629 EVT VT = N0.getValueType();
2630 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2632 // Bail early if none of these transforms apply.
2633 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2635 // For each of OP in AND/OR/XOR:
2636 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2637 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2638 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2639 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2640 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2642 // do not sink logical op inside of a vector extend, since it may combine
2644 EVT Op0VT = N0.getOperand(0).getValueType();
2645 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2646 N0.getOpcode() == ISD::SIGN_EXTEND ||
2647 N0.getOpcode() == ISD::BSWAP ||
2648 // Avoid infinite looping with PromoteIntBinOp.
2649 (N0.getOpcode() == ISD::ANY_EXTEND &&
2650 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2651 (N0.getOpcode() == ISD::TRUNCATE &&
2652 (!TLI.isZExtFree(VT, Op0VT) ||
2653 !TLI.isTruncateFree(Op0VT, VT)) &&
2654 TLI.isTypeLegal(Op0VT))) &&
2656 Op0VT == N1.getOperand(0).getValueType() &&
2657 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2658 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2659 N0.getOperand(0).getValueType(),
2660 N0.getOperand(0), N1.getOperand(0));
2661 AddToWorklist(ORNode.getNode());
2662 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2665 // For each of OP in SHL/SRL/SRA/AND...
2666 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2667 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2668 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2669 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2670 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2671 N0.getOperand(1) == N1.getOperand(1)) {
2672 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2673 N0.getOperand(0).getValueType(),
2674 N0.getOperand(0), N1.getOperand(0));
2675 AddToWorklist(ORNode.getNode());
2676 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2677 ORNode, N0.getOperand(1));
2680 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2681 // Only perform this optimization after type legalization and before
2682 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2683 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2684 // we don't want to undo this promotion.
2685 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2687 if ((N0.getOpcode() == ISD::BITCAST ||
2688 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2689 Level == AfterLegalizeTypes) {
2690 SDValue In0 = N0.getOperand(0);
2691 SDValue In1 = N1.getOperand(0);
2692 EVT In0Ty = In0.getValueType();
2693 EVT In1Ty = In1.getValueType();
2695 // If both incoming values are integers, and the original types are the
2697 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2698 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2699 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2700 AddToWorklist(Op.getNode());
2705 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2706 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2707 // If both shuffles use the same mask, and both shuffle within a single
2708 // vector, then it is worthwhile to move the swizzle after the operation.
2709 // The type-legalizer generates this pattern when loading illegal
2710 // vector types from memory. In many cases this allows additional shuffle
2712 // There are other cases where moving the shuffle after the xor/and/or
2713 // is profitable even if shuffles don't perform a swizzle.
2714 // If both shuffles use the same mask, and both shuffles have the same first
2715 // or second operand, then it might still be profitable to move the shuffle
2716 // after the xor/and/or operation.
2717 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2718 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2719 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2721 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2722 "Inputs to shuffles are not the same type");
2724 // Check that both shuffles use the same mask. The masks are known to be of
2725 // the same length because the result vector type is the same.
2726 // Check also that shuffles have only one use to avoid introducing extra
2728 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2729 SVN0->getMask().equals(SVN1->getMask())) {
2730 SDValue ShOp = N0->getOperand(1);
2732 // Don't try to fold this node if it requires introducing a
2733 // build vector of all zeros that might be illegal at this stage.
2734 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2736 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2741 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2742 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2743 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2744 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2745 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2746 N0->getOperand(0), N1->getOperand(0));
2747 AddToWorklist(NewNode.getNode());
2748 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2749 &SVN0->getMask()[0]);
2752 // Don't try to fold this node if it requires introducing a
2753 // build vector of all zeros that might be illegal at this stage.
2754 ShOp = N0->getOperand(0);
2755 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2757 ShOp = DAG.getConstant(0, SDLoc(N), VT);
2762 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2763 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2764 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2765 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2766 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2767 N0->getOperand(1), N1->getOperand(1));
2768 AddToWorklist(NewNode.getNode());
2769 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2770 &SVN0->getMask()[0]);
2778 /// This contains all DAGCombine rules which reduce two values combined by
2779 /// an And operation to a single value. This makes them reusable in the context
2780 /// of visitSELECT(). Rules involving constants are not included as
2781 /// visitSELECT() already handles those cases.
2782 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2783 SDNode *LocReference) {
2784 EVT VT = N1.getValueType();
2786 // fold (and x, undef) -> 0
2787 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2788 return DAG.getConstant(0, SDLoc(LocReference), VT);
2789 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2790 SDValue LL, LR, RL, RR, CC0, CC1;
2791 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2792 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2793 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2795 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2796 LL.getValueType().isInteger()) {
2797 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2798 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2799 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2800 LR.getValueType(), LL, RL);
2801 AddToWorklist(ORNode.getNode());
2802 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2804 if (isAllOnesConstant(LR)) {
2805 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2806 if (Op1 == ISD::SETEQ) {
2807 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2808 LR.getValueType(), LL, RL);
2809 AddToWorklist(ANDNode.getNode());
2810 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2812 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2813 if (Op1 == ISD::SETGT) {
2814 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2815 LR.getValueType(), LL, RL);
2816 AddToWorklist(ORNode.getNode());
2817 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2821 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2822 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2823 Op0 == Op1 && LL.getValueType().isInteger() &&
2824 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2825 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2827 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2828 LL, DAG.getConstant(1, DL,
2829 LL.getValueType()));
2830 AddToWorklist(ADDNode.getNode());
2831 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2832 DAG.getConstant(2, DL, LL.getValueType()),
2835 // canonicalize equivalent to ll == rl
2836 if (LL == RR && LR == RL) {
2837 Op1 = ISD::getSetCCSwappedOperands(Op1);
2840 if (LL == RL && LR == RR) {
2841 bool isInteger = LL.getValueType().isInteger();
2842 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2843 if (Result != ISD::SETCC_INVALID &&
2844 (!LegalOperations ||
2845 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2846 TLI.isOperationLegal(ISD::SETCC,
2847 getSetCCResultType(N0.getSimpleValueType())))))
2848 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2853 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2854 VT.getSizeInBits() <= 64) {
2855 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2856 APInt ADDC = ADDI->getAPIntValue();
2857 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2858 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2859 // immediate for an add, but it is legal if its top c2 bits are set,
2860 // transform the ADD so the immediate doesn't need to be materialized
2862 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2863 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2864 SRLI->getZExtValue());
2865 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2867 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2870 DAG.getNode(ISD::ADD, DL, VT,
2871 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2872 CombineTo(N0.getNode(), NewAdd);
2873 // Return N so it doesn't get rechecked!
2874 return SDValue(LocReference, 0);
2885 SDValue DAGCombiner::visitAND(SDNode *N) {
2886 SDValue N0 = N->getOperand(0);
2887 SDValue N1 = N->getOperand(1);
2888 EVT VT = N1.getValueType();
2891 if (VT.isVector()) {
2892 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2895 // fold (and x, 0) -> 0, vector edition
2896 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2897 // do not return N0, because undef node may exist in N0
2898 return DAG.getConstant(
2899 APInt::getNullValue(
2900 N0.getValueType().getScalarType().getSizeInBits()),
2901 SDLoc(N), N0.getValueType());
2902 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2903 // do not return N1, because undef node may exist in N1
2904 return DAG.getConstant(
2905 APInt::getNullValue(
2906 N1.getValueType().getScalarType().getSizeInBits()),
2907 SDLoc(N), N1.getValueType());
2909 // fold (and x, -1) -> x, vector edition
2910 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2912 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2916 // fold (and c1, c2) -> c1&c2
2917 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2918 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2919 if (N0C && N1C && !N1C->isOpaque())
2920 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2921 // canonicalize constant to RHS
2922 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2923 !isConstantIntBuildVectorOrConstantInt(N1))
2924 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2925 // fold (and x, -1) -> x
2926 if (isAllOnesConstant(N1))
2928 // if (and x, c) is known to be zero, return 0
2929 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2930 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2931 APInt::getAllOnesValue(BitWidth)))
2932 return DAG.getConstant(0, SDLoc(N), VT);
2934 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2936 // fold (and (or x, C), D) -> D if (C & D) == D
2937 if (N1C && N0.getOpcode() == ISD::OR)
2938 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2939 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2941 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2942 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2943 SDValue N0Op0 = N0.getOperand(0);
2944 APInt Mask = ~N1C->getAPIntValue();
2945 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2946 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2947 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2948 N0.getValueType(), N0Op0);
2950 // Replace uses of the AND with uses of the Zero extend node.
2953 // We actually want to replace all uses of the any_extend with the
2954 // zero_extend, to avoid duplicating things. This will later cause this
2955 // AND to be folded.
2956 CombineTo(N0.getNode(), Zext);
2957 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2960 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2961 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2962 // already be zero by virtue of the width of the base type of the load.
2964 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2966 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2967 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2968 N0.getOpcode() == ISD::LOAD) {
2969 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2970 N0 : N0.getOperand(0) );
2972 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2973 // This can be a pure constant or a vector splat, in which case we treat the
2974 // vector as a scalar and use the splat value.
2975 APInt Constant = APInt::getNullValue(1);
2976 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2977 Constant = C->getAPIntValue();
2978 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2979 APInt SplatValue, SplatUndef;
2980 unsigned SplatBitSize;
2982 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2983 SplatBitSize, HasAnyUndefs);
2985 // Undef bits can contribute to a possible optimisation if set, so
2987 SplatValue |= SplatUndef;
2989 // The splat value may be something like "0x00FFFFFF", which means 0 for
2990 // the first vector value and FF for the rest, repeating. We need a mask
2991 // that will apply equally to all members of the vector, so AND all the
2992 // lanes of the constant together.
2993 EVT VT = Vector->getValueType(0);
2994 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2996 // If the splat value has been compressed to a bitlength lower
2997 // than the size of the vector lane, we need to re-expand it to
2999 if (BitWidth > SplatBitSize)
3000 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3001 SplatBitSize < BitWidth;
3002 SplatBitSize = SplatBitSize * 2)
3003 SplatValue |= SplatValue.shl(SplatBitSize);
3005 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3006 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3007 if (SplatBitSize % BitWidth == 0) {
3008 Constant = APInt::getAllOnesValue(BitWidth);
3009 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3010 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3015 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3016 // actually legal and isn't going to get expanded, else this is a false
3018 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3019 Load->getValueType(0),
3020 Load->getMemoryVT());
3022 // Resize the constant to the same size as the original memory access before
3023 // extension. If it is still the AllOnesValue then this AND is completely
3026 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3029 switch (Load->getExtensionType()) {
3030 default: B = false; break;
3031 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3033 case ISD::NON_EXTLOAD: B = true; break;
3036 if (B && Constant.isAllOnesValue()) {
3037 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3038 // preserve semantics once we get rid of the AND.
3039 SDValue NewLoad(Load, 0);
3040 if (Load->getExtensionType() == ISD::EXTLOAD) {
3041 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3042 Load->getValueType(0), SDLoc(Load),
3043 Load->getChain(), Load->getBasePtr(),
3044 Load->getOffset(), Load->getMemoryVT(),
3045 Load->getMemOperand());
3046 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3047 if (Load->getNumValues() == 3) {
3048 // PRE/POST_INC loads have 3 values.
3049 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3050 NewLoad.getValue(2) };
3051 CombineTo(Load, To, 3, true);
3053 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3057 // Fold the AND away, taking care not to fold to the old load node if we
3059 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3061 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3065 // fold (and (load x), 255) -> (zextload x, i8)
3066 // fold (and (extload x, i16), 255) -> (zextload x, i8)
3067 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3068 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3069 (N0.getOpcode() == ISD::ANY_EXTEND &&
3070 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3071 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3072 LoadSDNode *LN0 = HasAnyExt
3073 ? cast<LoadSDNode>(N0.getOperand(0))
3074 : cast<LoadSDNode>(N0);
3075 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3076 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3077 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3078 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3079 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3080 EVT LoadedVT = LN0->getMemoryVT();
3081 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3083 if (ExtVT == LoadedVT &&
3084 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3088 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3089 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3090 LN0->getMemOperand());
3092 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3093 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3096 // Do not change the width of a volatile load.
3097 // Do not generate loads of non-round integer types since these can
3098 // be expensive (and would be wrong if the type is not byte sized).
3099 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3100 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3102 EVT PtrType = LN0->getOperand(1).getValueType();
3104 unsigned Alignment = LN0->getAlignment();
3105 SDValue NewPtr = LN0->getBasePtr();
3107 // For big endian targets, we need to add an offset to the pointer
3108 // to load the correct bytes. For little endian systems, we merely
3109 // need to read fewer bytes from the same pointer.
3110 if (TLI.isBigEndian()) {
3111 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3112 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3113 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3115 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3116 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3117 Alignment = MinAlign(Alignment, PtrOff);
3120 AddToWorklist(NewPtr.getNode());
3123 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3124 LN0->getChain(), NewPtr,
3125 LN0->getPointerInfo(),
3126 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3127 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3129 CombineTo(LN0, Load, Load.getValue(1));
3130 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3136 if (SDValue Combined = visitANDLike(N0, N1, N))
3139 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3140 if (N0.getOpcode() == N1.getOpcode()) {
3141 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3142 if (Tmp.getNode()) return Tmp;
3145 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3146 // fold (and (sra)) -> (and (srl)) when possible.
3147 if (!VT.isVector() &&
3148 SimplifyDemandedBits(SDValue(N, 0)))
3149 return SDValue(N, 0);
3151 // fold (zext_inreg (extload x)) -> (zextload x)
3152 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3153 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3154 EVT MemVT = LN0->getMemoryVT();
3155 // If we zero all the possible extended bits, then we can turn this into
3156 // a zextload if we are running before legalize or the operation is legal.
3157 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3158 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3159 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3160 ((!LegalOperations && !LN0->isVolatile()) ||
3161 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3162 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3163 LN0->getChain(), LN0->getBasePtr(),
3164 MemVT, LN0->getMemOperand());
3166 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3167 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3170 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3171 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3173 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3174 EVT MemVT = LN0->getMemoryVT();
3175 // If we zero all the possible extended bits, then we can turn this into
3176 // a zextload if we are running before legalize or the operation is legal.
3177 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3178 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3179 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3180 ((!LegalOperations && !LN0->isVolatile()) ||
3181 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3182 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3183 LN0->getChain(), LN0->getBasePtr(),
3184 MemVT, LN0->getMemOperand());
3186 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3187 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3190 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3191 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3192 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3193 N0.getOperand(1), false);
3194 if (BSwap.getNode())
3201 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3202 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3203 bool DemandHighBits) {
3204 if (!LegalOperations)
3207 EVT VT = N->getValueType(0);
3208 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3210 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3213 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3214 bool LookPassAnd0 = false;
3215 bool LookPassAnd1 = false;
3216 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3218 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3220 if (N0.getOpcode() == ISD::AND) {
3221 if (!N0.getNode()->hasOneUse())
3223 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3224 if (!N01C || N01C->getZExtValue() != 0xFF00)
3226 N0 = N0.getOperand(0);
3227 LookPassAnd0 = true;
3230 if (N1.getOpcode() == ISD::AND) {
3231 if (!N1.getNode()->hasOneUse())
3233 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3234 if (!N11C || N11C->getZExtValue() != 0xFF)
3236 N1 = N1.getOperand(0);
3237 LookPassAnd1 = true;
3240 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3242 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3244 if (!N0.getNode()->hasOneUse() ||
3245 !N1.getNode()->hasOneUse())
3248 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3249 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3252 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3255 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3256 SDValue N00 = N0->getOperand(0);
3257 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3258 if (!N00.getNode()->hasOneUse())
3260 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3261 if (!N001C || N001C->getZExtValue() != 0xFF)
3263 N00 = N00.getOperand(0);
3264 LookPassAnd0 = true;
3267 SDValue N10 = N1->getOperand(0);
3268 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3269 if (!N10.getNode()->hasOneUse())
3271 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3272 if (!N101C || N101C->getZExtValue() != 0xFF00)
3274 N10 = N10.getOperand(0);
3275 LookPassAnd1 = true;
3281 // Make sure everything beyond the low halfword gets set to zero since the SRL
3282 // 16 will clear the top bits.
3283 unsigned OpSizeInBits = VT.getSizeInBits();
3284 if (DemandHighBits && OpSizeInBits > 16) {
3285 // If the left-shift isn't masked out then the only way this is a bswap is
3286 // if all bits beyond the low 8 are 0. In that case the entire pattern
3287 // reduces to a left shift anyway: leave it for other parts of the combiner.
3291 // However, if the right shift isn't masked out then it might be because
3292 // it's not needed. See if we can spot that too.
3293 if (!LookPassAnd1 &&
3294 !DAG.MaskedValueIsZero(
3295 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3299 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3300 if (OpSizeInBits > 16) {
3302 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3303 DAG.getConstant(OpSizeInBits - 16, DL,
3304 getShiftAmountTy(VT)));
3309 /// Return true if the specified node is an element that makes up a 32-bit
3310 /// packed halfword byteswap.
3311 /// ((x & 0x000000ff) << 8) |
3312 /// ((x & 0x0000ff00) >> 8) |
3313 /// ((x & 0x00ff0000) << 8) |
3314 /// ((x & 0xff000000) >> 8)
3315 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3316 if (!N.getNode()->hasOneUse())
3319 unsigned Opc = N.getOpcode();
3320 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3323 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3328 switch (N1C->getZExtValue()) {
3331 case 0xFF: Num = 0; break;
3332 case 0xFF00: Num = 1; break;
3333 case 0xFF0000: Num = 2; break;
3334 case 0xFF000000: Num = 3; break;
3337 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3338 SDValue N0 = N.getOperand(0);
3339 if (Opc == ISD::AND) {
3340 if (Num == 0 || Num == 2) {
3342 // (x >> 8) & 0xff0000
3343 if (N0.getOpcode() != ISD::SRL)
3345 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3346 if (!C || C->getZExtValue() != 8)
3349 // (x << 8) & 0xff00
3350 // (x << 8) & 0xff000000
3351 if (N0.getOpcode() != ISD::SHL)
3353 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3354 if (!C || C->getZExtValue() != 8)
3357 } else if (Opc == ISD::SHL) {
3359 // (x & 0xff0000) << 8
3360 if (Num != 0 && Num != 2)
3362 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3363 if (!C || C->getZExtValue() != 8)
3365 } else { // Opc == ISD::SRL
3366 // (x & 0xff00) >> 8
3367 // (x & 0xff000000) >> 8
3368 if (Num != 1 && Num != 3)
3370 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3371 if (!C || C->getZExtValue() != 8)
3378 Parts[Num] = N0.getOperand(0).getNode();
3382 /// Match a 32-bit packed halfword bswap. That is
3383 /// ((x & 0x000000ff) << 8) |
3384 /// ((x & 0x0000ff00) >> 8) |
3385 /// ((x & 0x00ff0000) << 8) |
3386 /// ((x & 0xff000000) >> 8)
3387 /// => (rotl (bswap x), 16)
3388 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3389 if (!LegalOperations)
3392 EVT VT = N->getValueType(0);
3395 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3399 // (or (or (and), (and)), (or (and), (and)))
3400 // (or (or (or (and), (and)), (and)), (and))
3401 if (N0.getOpcode() != ISD::OR)
3403 SDValue N00 = N0.getOperand(0);
3404 SDValue N01 = N0.getOperand(1);
3405 SDNode *Parts[4] = {};
3407 if (N1.getOpcode() == ISD::OR &&
3408 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3409 // (or (or (and), (and)), (or (and), (and)))
3410 SDValue N000 = N00.getOperand(0);
3411 if (!isBSwapHWordElement(N000, Parts))
3414 SDValue N001 = N00.getOperand(1);
3415 if (!isBSwapHWordElement(N001, Parts))
3417 SDValue N010 = N01.getOperand(0);
3418 if (!isBSwapHWordElement(N010, Parts))
3420 SDValue N011 = N01.getOperand(1);
3421 if (!isBSwapHWordElement(N011, Parts))
3424 // (or (or (or (and), (and)), (and)), (and))
3425 if (!isBSwapHWordElement(N1, Parts))
3427 if (!isBSwapHWordElement(N01, Parts))
3429 if (N00.getOpcode() != ISD::OR)
3431 SDValue N000 = N00.getOperand(0);
3432 if (!isBSwapHWordElement(N000, Parts))
3434 SDValue N001 = N00.getOperand(1);
3435 if (!isBSwapHWordElement(N001, Parts))
3439 // Make sure the parts are all coming from the same node.
3440 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3444 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3445 SDValue(Parts[0], 0));
3447 // Result of the bswap should be rotated by 16. If it's not legal, then
3448 // do (x << 16) | (x >> 16).
3449 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3450 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3451 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3452 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3453 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3454 return DAG.getNode(ISD::OR, DL, VT,
3455 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3456 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3459 /// This contains all DAGCombine rules which reduce two values combined by
3460 /// an Or operation to a single value \see visitANDLike().
3461 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3462 EVT VT = N1.getValueType();
3463 // fold (or x, undef) -> -1
3464 if (!LegalOperations &&
3465 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3466 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3467 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3468 SDLoc(LocReference), VT);
3470 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3471 SDValue LL, LR, RL, RR, CC0, CC1;
3472 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3473 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3474 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3476 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3477 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3478 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3479 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3480 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3481 LR.getValueType(), LL, RL);
3482 AddToWorklist(ORNode.getNode());
3483 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3485 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3486 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3487 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3488 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3489 LR.getValueType(), LL, RL);
3490 AddToWorklist(ANDNode.getNode());
3491 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3494 // canonicalize equivalent to ll == rl
3495 if (LL == RR && LR == RL) {
3496 Op1 = ISD::getSetCCSwappedOperands(Op1);
3499 if (LL == RL && LR == RR) {
3500 bool isInteger = LL.getValueType().isInteger();
3501 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3502 if (Result != ISD::SETCC_INVALID &&
3503 (!LegalOperations ||
3504 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3505 TLI.isOperationLegal(ISD::SETCC,
3506 getSetCCResultType(N0.getValueType())))))
3507 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3512 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3513 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3514 // Don't increase # computations.
3515 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3516 // We can only do this xform if we know that bits from X that are set in C2
3517 // but not in C1 are already zero. Likewise for Y.
3518 if (const ConstantSDNode *N0O1C =
3519 getAsNonOpaqueConstant(N0.getOperand(1))) {
3520 if (const ConstantSDNode *N1O1C =
3521 getAsNonOpaqueConstant(N1.getOperand(1))) {
3522 // We can only do this xform if we know that bits from X that are set in
3523 // C2 but not in C1 are already zero. Likewise for Y.
3524 const APInt &LHSMask = N0O1C->getAPIntValue();
3525 const APInt &RHSMask = N1O1C->getAPIntValue();
3527 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3528 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3529 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3530 N0.getOperand(0), N1.getOperand(0));
3531 SDLoc DL(LocReference);
3532 return DAG.getNode(ISD::AND, DL, VT, X,
3533 DAG.getConstant(LHSMask | RHSMask, DL, VT));
3539 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3540 if (N0.getOpcode() == ISD::AND &&
3541 N1.getOpcode() == ISD::AND &&
3542 N0.getOperand(0) == N1.getOperand(0) &&
3543 // Don't increase # computations.
3544 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3545 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3546 N0.getOperand(1), N1.getOperand(1));
3547 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3553 SDValue DAGCombiner::visitOR(SDNode *N) {
3554 SDValue N0 = N->getOperand(0);
3555 SDValue N1 = N->getOperand(1);
3556 EVT VT = N1.getValueType();
3559 if (VT.isVector()) {
3560 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3563 // fold (or x, 0) -> x, vector edition
3564 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3566 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3569 // fold (or x, -1) -> -1, vector edition
3570 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3571 // do not return N0, because undef node may exist in N0
3572 return DAG.getConstant(
3573 APInt::getAllOnesValue(
3574 N0.getValueType().getScalarType().getSizeInBits()),
3575 SDLoc(N), N0.getValueType());
3576 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3577 // do not return N1, because undef node may exist in N1
3578 return DAG.getConstant(
3579 APInt::getAllOnesValue(
3580 N1.getValueType().getScalarType().getSizeInBits()),
3581 SDLoc(N), N1.getValueType());
3583 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3584 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3585 // Do this only if the resulting shuffle is legal.
3586 if (isa<ShuffleVectorSDNode>(N0) &&
3587 isa<ShuffleVectorSDNode>(N1) &&
3588 // Avoid folding a node with illegal type.
3589 TLI.isTypeLegal(VT) &&
3590 N0->getOperand(1) == N1->getOperand(1) &&
3591 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3592 bool CanFold = true;
3593 unsigned NumElts = VT.getVectorNumElements();
3594 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3595 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3596 // We construct two shuffle masks:
3597 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3598 // and N1 as the second operand.
3599 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3600 // and N0 as the second operand.
3601 // We do this because OR is commutable and therefore there might be
3602 // two ways to fold this node into a shuffle.
3603 SmallVector<int,4> Mask1;
3604 SmallVector<int,4> Mask2;
3606 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3607 int M0 = SV0->getMaskElt(i);
3608 int M1 = SV1->getMaskElt(i);
3610 // Both shuffle indexes are undef. Propagate Undef.
3611 if (M0 < 0 && M1 < 0) {
3612 Mask1.push_back(M0);
3613 Mask2.push_back(M0);
3617 if (M0 < 0 || M1 < 0 ||
3618 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3619 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3624 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3625 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3629 // Fold this sequence only if the resulting shuffle is 'legal'.
3630 if (TLI.isShuffleMaskLegal(Mask1, VT))
3631 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3632 N1->getOperand(0), &Mask1[0]);
3633 if (TLI.isShuffleMaskLegal(Mask2, VT))
3634 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3635 N0->getOperand(0), &Mask2[0]);
3640 // fold (or c1, c2) -> c1|c2
3641 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3642 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3643 if (N0C && N1C && !N1C->isOpaque())
3644 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3645 // canonicalize constant to RHS
3646 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3647 !isConstantIntBuildVectorOrConstantInt(N1))
3648 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3649 // fold (or x, 0) -> x
3650 if (isNullConstant(N1))
3652 // fold (or x, -1) -> -1
3653 if (isAllOnesConstant(N1))
3655 // fold (or x, c) -> c iff (x & ~c) == 0
3656 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3659 if (SDValue Combined = visitORLike(N0, N1, N))
3662 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3663 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3664 if (BSwap.getNode())
3666 BSwap = MatchBSwapHWordLow(N, N0, N1);
3667 if (BSwap.getNode())
3671 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3673 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3674 // iff (c1 & c2) == 0.
3675 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3676 isa<ConstantSDNode>(N0.getOperand(1))) {
3677 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3678 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3679 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3682 ISD::AND, SDLoc(N), VT,
3683 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3687 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3688 if (N0.getOpcode() == N1.getOpcode()) {
3689 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3690 if (Tmp.getNode()) return Tmp;
3693 // See if this is some rotate idiom.
3694 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3695 return SDValue(Rot, 0);
3697 // Simplify the operands using demanded-bits information.
3698 if (!VT.isVector() &&
3699 SimplifyDemandedBits(SDValue(N, 0)))
3700 return SDValue(N, 0);
3705 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3706 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3707 if (Op.getOpcode() == ISD::AND) {
3708 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3709 Mask = Op.getOperand(1);
3710 Op = Op.getOperand(0);
3716 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3724 // Return true if we can prove that, whenever Neg and Pos are both in the
3725 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3726 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3728 // (or (shift1 X, Neg), (shift2 X, Pos))
3730 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3731 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3732 // to consider shift amounts with defined behavior.
3733 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3734 // If OpSize is a power of 2 then:
3736 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3737 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3739 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3740 // for the stronger condition:
3742 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3744 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3745 // we can just replace Neg with Neg' for the rest of the function.
3747 // In other cases we check for the even stronger condition:
3749 // Neg == OpSize - Pos [B]
3751 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3752 // behavior if Pos == 0 (and consequently Neg == OpSize).
3754 // We could actually use [A] whenever OpSize is a power of 2, but the
3755 // only extra cases that it would match are those uninteresting ones
3756 // where Neg and Pos are never in range at the same time. E.g. for
3757 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3758 // as well as (sub 32, Pos), but:
3760 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3762 // always invokes undefined behavior for 32-bit X.
3764 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3765 unsigned MaskLoBits = 0;
3766 if (Neg.getOpcode() == ISD::AND &&
3767 isPowerOf2_64(OpSize) &&
3768 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3769 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3770 Neg = Neg.getOperand(0);
3771 MaskLoBits = Log2_64(OpSize);
3774 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3775 if (Neg.getOpcode() != ISD::SUB)
3777 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3780 SDValue NegOp1 = Neg.getOperand(1);
3782 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3783 // Pos'. The truncation is redundant for the purpose of the equality.
3785 Pos.getOpcode() == ISD::AND &&
3786 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3787 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3788 Pos = Pos.getOperand(0);
3790 // The condition we need is now:
3792 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3794 // If NegOp1 == Pos then we need:
3796 // OpSize & Mask == NegC & Mask
3798 // (because "x & Mask" is a truncation and distributes through subtraction).
3801 Width = NegC->getAPIntValue();
3802 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3803 // Then the condition we want to prove becomes:
3805 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3807 // which, again because "x & Mask" is a truncation, becomes:
3809 // NegC & Mask == (OpSize - PosC) & Mask
3810 // OpSize & Mask == (NegC + PosC) & Mask
3811 else if (Pos.getOpcode() == ISD::ADD &&
3812 Pos.getOperand(0) == NegOp1 &&
3813 Pos.getOperand(1).getOpcode() == ISD::Constant)
3814 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3815 NegC->getAPIntValue());
3819 // Now we just need to check that OpSize & Mask == Width & Mask.
3821 // Opsize & Mask is 0 since Mask is Opsize - 1.
3822 return Width.getLoBits(MaskLoBits) == 0;
3823 return Width == OpSize;
3826 // A subroutine of MatchRotate used once we have found an OR of two opposite
3827 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3828 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3829 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3830 // Neg with outer conversions stripped away.
3831 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3832 SDValue Neg, SDValue InnerPos,
3833 SDValue InnerNeg, unsigned PosOpcode,
3834 unsigned NegOpcode, SDLoc DL) {
3835 // fold (or (shl x, (*ext y)),
3836 // (srl x, (*ext (sub 32, y)))) ->
3837 // (rotl x, y) or (rotr x, (sub 32, y))
3839 // fold (or (shl x, (*ext (sub 32, y))),
3840 // (srl x, (*ext y))) ->
3841 // (rotr x, y) or (rotl x, (sub 32, y))
3842 EVT VT = Shifted.getValueType();
3843 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3844 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3845 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3846 HasPos ? Pos : Neg).getNode();
3852 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3853 // idioms for rotate, and if the target supports rotation instructions, generate
3855 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3856 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3857 EVT VT = LHS.getValueType();
3858 if (!TLI.isTypeLegal(VT)) return nullptr;
3860 // The target must have at least one rotate flavor.
3861 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3862 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3863 if (!HasROTL && !HasROTR) return nullptr;
3865 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3866 SDValue LHSShift; // The shift.
3867 SDValue LHSMask; // AND value if any.
3868 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3869 return nullptr; // Not part of a rotate.
3871 SDValue RHSShift; // The shift.
3872 SDValue RHSMask; // AND value if any.
3873 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3874 return nullptr; // Not part of a rotate.
3876 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3877 return nullptr; // Not shifting the same value.
3879 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3880 return nullptr; // Shifts must disagree.
3882 // Canonicalize shl to left side in a shl/srl pair.
3883 if (RHSShift.getOpcode() == ISD::SHL) {
3884 std::swap(LHS, RHS);
3885 std::swap(LHSShift, RHSShift);
3886 std::swap(LHSMask , RHSMask );
3889 unsigned OpSizeInBits = VT.getSizeInBits();
3890 SDValue LHSShiftArg = LHSShift.getOperand(0);
3891 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3892 SDValue RHSShiftArg = RHSShift.getOperand(0);
3893 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3895 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3896 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3897 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3898 RHSShiftAmt.getOpcode() == ISD::Constant) {
3899 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3900 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3901 if ((LShVal + RShVal) != OpSizeInBits)
3904 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3905 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3907 // If there is an AND of either shifted operand, apply it to the result.
3908 if (LHSMask.getNode() || RHSMask.getNode()) {
3909 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3911 if (LHSMask.getNode()) {
3912 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3913 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3915 if (RHSMask.getNode()) {
3916 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3917 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3920 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3923 return Rot.getNode();
3926 // If there is a mask here, and we have a variable shift, we can't be sure
3927 // that we're masking out the right stuff.
3928 if (LHSMask.getNode() || RHSMask.getNode())
3931 // If the shift amount is sign/zext/any-extended just peel it off.
3932 SDValue LExtOp0 = LHSShiftAmt;
3933 SDValue RExtOp0 = RHSShiftAmt;
3934 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3935 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3936 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3937 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3938 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3939 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3940 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3941 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3942 LExtOp0 = LHSShiftAmt.getOperand(0);
3943 RExtOp0 = RHSShiftAmt.getOperand(0);
3946 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3947 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3951 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3952 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3959 SDValue DAGCombiner::visitXOR(SDNode *N) {
3960 SDValue N0 = N->getOperand(0);
3961 SDValue N1 = N->getOperand(1);
3962 EVT VT = N0.getValueType();
3965 if (VT.isVector()) {
3966 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3969 // fold (xor x, 0) -> x, vector edition
3970 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3972 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3976 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3977 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3978 return DAG.getConstant(0, SDLoc(N), VT);
3979 // fold (xor x, undef) -> undef
3980 if (N0.getOpcode() == ISD::UNDEF)
3982 if (N1.getOpcode() == ISD::UNDEF)
3984 // fold (xor c1, c2) -> c1^c2
3985 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3986 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
3988 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3989 // canonicalize constant to RHS
3990 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3991 !isConstantIntBuildVectorOrConstantInt(N1))
3992 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3993 // fold (xor x, 0) -> x
3994 if (isNullConstant(N1))
3997 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4000 // fold !(x cc y) -> (x !cc y)
4001 SDValue LHS, RHS, CC;
4002 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4003 bool isInt = LHS.getValueType().isInteger();
4004 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4007 if (!LegalOperations ||
4008 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4009 switch (N0.getOpcode()) {
4011 llvm_unreachable("Unhandled SetCC Equivalent!");
4013 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4014 case ISD::SELECT_CC:
4015 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4016 N0.getOperand(3), NotCC);
4021 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4022 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4023 N0.getNode()->hasOneUse() &&
4024 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4025 SDValue V = N0.getOperand(0);
4027 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4028 DAG.getConstant(1, DL, V.getValueType()));
4029 AddToWorklist(V.getNode());
4030 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4033 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4034 if (isOneConstant(N1) && VT == MVT::i1 &&
4035 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4036 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4037 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4038 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4039 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4040 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4041 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4042 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4045 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4046 if (isAllOnesConstant(N1) &&
4047 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4048 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4049 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4050 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4051 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4052 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4053 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4054 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4057 // fold (xor (and x, y), y) -> (and (not x), y)
4058 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4059 N0->getOperand(1) == N1) {
4060 SDValue X = N0->getOperand(0);
4061 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4062 AddToWorklist(NotX.getNode());
4063 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4065 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4066 if (N1C && N0.getOpcode() == ISD::XOR) {
4067 if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4069 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4070 DAG.getConstant(N1C->getAPIntValue() ^
4071 N00C->getAPIntValue(), DL, VT));
4073 if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4075 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4076 DAG.getConstant(N1C->getAPIntValue() ^
4077 N01C->getAPIntValue(), DL, VT));
4080 // fold (xor x, x) -> 0
4082 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4084 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4085 // Here is a concrete example of this equivalence:
4087 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4088 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4092 // i16 ~1 == 0b1111111111111110
4093 // i16 rol(~1, 14) == 0b1011111111111111
4095 // Some additional tips to help conceptualize this transform:
4096 // - Try to see the operation as placing a single zero in a value of all ones.
4097 // - There exists no value for x which would allow the result to contain zero.
4098 // - Values of x larger than the bitwidth are undefined and do not require a
4099 // consistent result.
4100 // - Pushing the zero left requires shifting one bits in from the right.
4101 // A rotate left of ~1 is a nice way of achieving the desired result.
4102 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4103 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4105 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4109 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4110 if (N0.getOpcode() == N1.getOpcode()) {
4111 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4112 if (Tmp.getNode()) return Tmp;
4115 // Simplify the expression using non-local knowledge.
4116 if (!VT.isVector() &&
4117 SimplifyDemandedBits(SDValue(N, 0)))
4118 return SDValue(N, 0);
4123 /// Handle transforms common to the three shifts, when the shift amount is a
4125 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4126 SDNode *LHS = N->getOperand(0).getNode();
4127 if (!LHS->hasOneUse()) return SDValue();
4129 // We want to pull some binops through shifts, so that we have (and (shift))
4130 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4131 // thing happens with address calculations, so it's important to canonicalize
4133 bool HighBitSet = false; // Can we transform this if the high bit is set?
4135 switch (LHS->getOpcode()) {
4136 default: return SDValue();
4139 HighBitSet = false; // We can only transform sra if the high bit is clear.
4142 HighBitSet = true; // We can only transform sra if the high bit is set.
4145 if (N->getOpcode() != ISD::SHL)
4146 return SDValue(); // only shl(add) not sr[al](add).
4147 HighBitSet = false; // We can only transform sra if the high bit is clear.
4151 // We require the RHS of the binop to be a constant and not opaque as well.
4152 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4153 if (!BinOpCst) return SDValue();
4155 // FIXME: disable this unless the input to the binop is a shift by a constant.
4156 // If it is not a shift, it pessimizes some common cases like:
4158 // void foo(int *X, int i) { X[i & 1235] = 1; }
4159 // int bar(int *X, int i) { return X[i & 255]; }
4160 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4161 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4162 BinOpLHSVal->getOpcode() != ISD::SRA &&
4163 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4164 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4167 EVT VT = N->getValueType(0);
4169 // If this is a signed shift right, and the high bit is modified by the
4170 // logical operation, do not perform the transformation. The highBitSet
4171 // boolean indicates the value of the high bit of the constant which would
4172 // cause it to be modified for this operation.
4173 if (N->getOpcode() == ISD::SRA) {
4174 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4175 if (BinOpRHSSignSet != HighBitSet)
4179 if (!TLI.isDesirableToCommuteWithShift(LHS))
4182 // Fold the constants, shifting the binop RHS by the shift amount.
4183 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4185 LHS->getOperand(1), N->getOperand(1));
4186 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4188 // Create the new shift.
4189 SDValue NewShift = DAG.getNode(N->getOpcode(),
4190 SDLoc(LHS->getOperand(0)),
4191 VT, LHS->getOperand(0), N->getOperand(1));
4193 // Create the new binop.
4194 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4197 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4198 assert(N->getOpcode() == ISD::TRUNCATE);
4199 assert(N->getOperand(0).getOpcode() == ISD::AND);
4201 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4202 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4203 SDValue N01 = N->getOperand(0).getOperand(1);
4205 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4206 if (!N01C->isOpaque()) {
4207 EVT TruncVT = N->getValueType(0);
4208 SDValue N00 = N->getOperand(0).getOperand(0);
4209 APInt TruncC = N01C->getAPIntValue();
4210 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4213 return DAG.getNode(ISD::AND, DL, TruncVT,
4214 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4215 DAG.getConstant(TruncC, DL, TruncVT));
4223 SDValue DAGCombiner::visitRotate(SDNode *N) {
4224 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4225 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4226 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4227 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4228 if (NewOp1.getNode())
4229 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4230 N->getOperand(0), NewOp1);
4235 SDValue DAGCombiner::visitSHL(SDNode *N) {
4236 SDValue N0 = N->getOperand(0);
4237 SDValue N1 = N->getOperand(1);
4238 EVT VT = N0.getValueType();
4239 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4242 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4243 if (VT.isVector()) {
4244 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4247 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4248 // If setcc produces all-one true value then:
4249 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4250 if (N1CV && N1CV->isConstant()) {
4251 if (N0.getOpcode() == ISD::AND) {
4252 SDValue N00 = N0->getOperand(0);
4253 SDValue N01 = N0->getOperand(1);
4254 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4256 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4257 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4258 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4259 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4261 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4264 N1C = isConstOrConstSplat(N1);
4269 // fold (shl c1, c2) -> c1<<c2
4270 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4271 if (N0C && N1C && !N1C->isOpaque())
4272 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4273 // fold (shl 0, x) -> 0
4274 if (isNullConstant(N0))
4276 // fold (shl x, c >= size(x)) -> undef
4277 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4278 return DAG.getUNDEF(VT);
4279 // fold (shl x, 0) -> x
4280 if (N1C && N1C->isNullValue())
4282 // fold (shl undef, x) -> 0
4283 if (N0.getOpcode() == ISD::UNDEF)
4284 return DAG.getConstant(0, SDLoc(N), VT);
4285 // if (shl x, c) is known to be zero, return 0
4286 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4287 APInt::getAllOnesValue(OpSizeInBits)))
4288 return DAG.getConstant(0, SDLoc(N), VT);
4289 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4290 if (N1.getOpcode() == ISD::TRUNCATE &&
4291 N1.getOperand(0).getOpcode() == ISD::AND) {
4292 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4293 if (NewOp1.getNode())
4294 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4297 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4298 return SDValue(N, 0);
4300 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4301 if (N1C && N0.getOpcode() == ISD::SHL) {
4302 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4303 uint64_t c1 = N0C1->getZExtValue();
4304 uint64_t c2 = N1C->getZExtValue();
4306 if (c1 + c2 >= OpSizeInBits)
4307 return DAG.getConstant(0, DL, VT);
4308 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4309 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4313 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4314 // For this to be valid, the second form must not preserve any of the bits
4315 // that are shifted out by the inner shift in the first form. This means
4316 // the outer shift size must be >= the number of bits added by the ext.
4317 // As a corollary, we don't care what kind of ext it is.
4318 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4319 N0.getOpcode() == ISD::ANY_EXTEND ||
4320 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4321 N0.getOperand(0).getOpcode() == ISD::SHL) {
4322 SDValue N0Op0 = N0.getOperand(0);
4323 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4324 uint64_t c1 = N0Op0C1->getZExtValue();
4325 uint64_t c2 = N1C->getZExtValue();
4326 EVT InnerShiftVT = N0Op0.getValueType();
4327 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4328 if (c2 >= OpSizeInBits - InnerShiftSize) {
4330 if (c1 + c2 >= OpSizeInBits)
4331 return DAG.getConstant(0, DL, VT);
4332 return DAG.getNode(ISD::SHL, DL, VT,
4333 DAG.getNode(N0.getOpcode(), DL, VT,
4334 N0Op0->getOperand(0)),
4335 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4340 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4341 // Only fold this if the inner zext has no other uses to avoid increasing
4342 // the total number of instructions.
4343 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4344 N0.getOperand(0).getOpcode() == ISD::SRL) {
4345 SDValue N0Op0 = N0.getOperand(0);
4346 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4347 uint64_t c1 = N0Op0C1->getZExtValue();
4348 if (c1 < VT.getScalarSizeInBits()) {
4349 uint64_t c2 = N1C->getZExtValue();
4351 SDValue NewOp0 = N0.getOperand(0);
4352 EVT CountVT = NewOp0.getOperand(1).getValueType();
4354 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4356 DAG.getConstant(c2, DL, CountVT));
4357 AddToWorklist(NewSHL.getNode());
4358 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4364 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
4365 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
4366 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4367 cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4368 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4369 uint64_t C1 = N0C1->getZExtValue();
4370 uint64_t C2 = N1C->getZExtValue();
4373 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4374 DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4375 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4376 DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4380 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4381 // (and (srl x, (sub c1, c2), MASK)
4382 // Only fold this if the inner shift has no other uses -- if it does, folding
4383 // this will increase the total number of instructions.
4384 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4385 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4386 uint64_t c1 = N0C1->getZExtValue();
4387 if (c1 < OpSizeInBits) {
4388 uint64_t c2 = N1C->getZExtValue();
4389 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4392 Mask = Mask.shl(c2 - c1);
4394 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4395 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4397 Mask = Mask.lshr(c1 - c2);
4399 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4400 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4403 return DAG.getNode(ISD::AND, DL, VT, Shift,
4404 DAG.getConstant(Mask, DL, VT));
4408 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4409 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4410 unsigned BitSize = VT.getScalarSizeInBits();
4412 SDValue HiBitsMask =
4413 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4414 BitSize - N1C->getZExtValue()),
4416 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4420 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4421 // Variant of version done on multiply, except mul by a power of 2 is turned
4424 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4425 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4426 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4427 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4428 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4429 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4432 if (N1C && !N1C->isOpaque()) {
4433 SDValue NewSHL = visitShiftByConstant(N, N1C);
4434 if (NewSHL.getNode())
4441 SDValue DAGCombiner::visitSRA(SDNode *N) {
4442 SDValue N0 = N->getOperand(0);
4443 SDValue N1 = N->getOperand(1);
4444 EVT VT = N0.getValueType();
4445 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4448 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4449 if (VT.isVector()) {
4450 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4453 N1C = isConstOrConstSplat(N1);
4456 // fold (sra c1, c2) -> (sra c1, c2)
4457 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4458 if (N0C && N1C && !N1C->isOpaque())
4459 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4460 // fold (sra 0, x) -> 0
4461 if (isNullConstant(N0))
4463 // fold (sra -1, x) -> -1
4464 if (isAllOnesConstant(N0))
4466 // fold (sra x, (setge c, size(x))) -> undef
4467 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4468 return DAG.getUNDEF(VT);
4469 // fold (sra x, 0) -> x
4470 if (N1C && N1C->isNullValue())
4472 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4474 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4475 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4476 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4478 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4479 ExtVT, VT.getVectorNumElements());
4480 if ((!LegalOperations ||
4481 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4482 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4483 N0.getOperand(0), DAG.getValueType(ExtVT));
4486 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4487 if (N1C && N0.getOpcode() == ISD::SRA) {
4488 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4489 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4490 if (Sum >= OpSizeInBits)
4491 Sum = OpSizeInBits - 1;
4493 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4494 DAG.getConstant(Sum, DL, N1.getValueType()));
4498 // fold (sra (shl X, m), (sub result_size, n))
4499 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4500 // result_size - n != m.
4501 // If truncate is free for the target sext(shl) is likely to result in better
4503 if (N0.getOpcode() == ISD::SHL && N1C) {
4504 // Get the two constanst of the shifts, CN0 = m, CN = n.
4505 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4507 LLVMContext &Ctx = *DAG.getContext();
4508 // Determine what the truncate's result bitsize and type would be.
4509 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4512 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4514 // Determine the residual right-shift amount.
4515 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4517 // If the shift is not a no-op (in which case this should be just a sign
4518 // extend already), the truncated to type is legal, sign_extend is legal
4519 // on that type, and the truncate to that type is both legal and free,
4520 // perform the transform.
4521 if ((ShiftAmt > 0) &&
4522 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4523 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4524 TLI.isTruncateFree(VT, TruncVT)) {
4527 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4528 getShiftAmountTy(N0.getOperand(0).getValueType()));
4529 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4530 N0.getOperand(0), Amt);
4531 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4533 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4534 N->getValueType(0), Trunc);
4539 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4540 if (N1.getOpcode() == ISD::TRUNCATE &&
4541 N1.getOperand(0).getOpcode() == ISD::AND) {
4542 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4543 if (NewOp1.getNode())
4544 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4547 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4548 // if c1 is equal to the number of bits the trunc removes
4549 if (N0.getOpcode() == ISD::TRUNCATE &&
4550 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4551 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4552 N0.getOperand(0).hasOneUse() &&
4553 N0.getOperand(0).getOperand(1).hasOneUse() &&
4555 SDValue N0Op0 = N0.getOperand(0);
4556 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4557 unsigned LargeShiftVal = LargeShift->getZExtValue();
4558 EVT LargeVT = N0Op0.getValueType();
4560 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4563 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4564 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4565 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4566 N0Op0.getOperand(0), Amt);
4567 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4572 // Simplify, based on bits shifted out of the LHS.
4573 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4574 return SDValue(N, 0);
4577 // If the sign bit is known to be zero, switch this to a SRL.
4578 if (DAG.SignBitIsZero(N0))
4579 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4581 if (N1C && !N1C->isOpaque()) {
4582 SDValue NewSRA = visitShiftByConstant(N, N1C);
4583 if (NewSRA.getNode())
4590 SDValue DAGCombiner::visitSRL(SDNode *N) {
4591 SDValue N0 = N->getOperand(0);
4592 SDValue N1 = N->getOperand(1);
4593 EVT VT = N0.getValueType();
4594 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4597 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4598 if (VT.isVector()) {
4599 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4602 N1C = isConstOrConstSplat(N1);
4605 // fold (srl c1, c2) -> c1 >>u c2
4606 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4607 if (N0C && N1C && !N1C->isOpaque())
4608 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4609 // fold (srl 0, x) -> 0
4610 if (isNullConstant(N0))
4612 // fold (srl x, c >= size(x)) -> undef
4613 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4614 return DAG.getUNDEF(VT);
4615 // fold (srl x, 0) -> x
4616 if (N1C && N1C->isNullValue())
4618 // if (srl x, c) is known to be zero, return 0
4619 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4620 APInt::getAllOnesValue(OpSizeInBits)))
4621 return DAG.getConstant(0, SDLoc(N), VT);
4623 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4624 if (N1C && N0.getOpcode() == ISD::SRL) {
4625 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4626 uint64_t c1 = N01C->getZExtValue();
4627 uint64_t c2 = N1C->getZExtValue();
4629 if (c1 + c2 >= OpSizeInBits)
4630 return DAG.getConstant(0, DL, VT);
4631 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4632 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4636 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4637 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4638 N0.getOperand(0).getOpcode() == ISD::SRL &&
4639 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4641 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4642 uint64_t c2 = N1C->getZExtValue();
4643 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4644 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4645 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4646 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4647 if (c1 + OpSizeInBits == InnerShiftSize) {
4649 if (c1 + c2 >= InnerShiftSize)
4650 return DAG.getConstant(0, DL, VT);
4651 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4652 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4653 N0.getOperand(0)->getOperand(0),
4654 DAG.getConstant(c1 + c2, DL,
4659 // fold (srl (shl x, c), c) -> (and x, cst2)
4660 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4661 unsigned BitSize = N0.getScalarValueSizeInBits();
4662 if (BitSize <= 64) {
4663 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4665 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4666 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4670 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4671 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4672 // Shifting in all undef bits?
4673 EVT SmallVT = N0.getOperand(0).getValueType();
4674 unsigned BitSize = SmallVT.getScalarSizeInBits();
4675 if (N1C->getZExtValue() >= BitSize)
4676 return DAG.getUNDEF(VT);
4678 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4679 uint64_t ShiftAmt = N1C->getZExtValue();
4681 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4683 DAG.getConstant(ShiftAmt, DL0,
4684 getShiftAmountTy(SmallVT)));
4685 AddToWorklist(SmallShift.getNode());
4686 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4688 return DAG.getNode(ISD::AND, DL, VT,
4689 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4690 DAG.getConstant(Mask, DL, VT));
4694 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4695 // bit, which is unmodified by sra.
4696 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4697 if (N0.getOpcode() == ISD::SRA)
4698 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4701 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4702 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4703 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4704 APInt KnownZero, KnownOne;
4705 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4707 // If any of the input bits are KnownOne, then the input couldn't be all
4708 // zeros, thus the result of the srl will always be zero.
4709 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4711 // If all of the bits input the to ctlz node are known to be zero, then
4712 // the result of the ctlz is "32" and the result of the shift is one.
4713 APInt UnknownBits = ~KnownZero;
4714 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4716 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4717 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4718 // Okay, we know that only that the single bit specified by UnknownBits
4719 // could be set on input to the CTLZ node. If this bit is set, the SRL
4720 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4721 // to an SRL/XOR pair, which is likely to simplify more.
4722 unsigned ShAmt = UnknownBits.countTrailingZeros();
4723 SDValue Op = N0.getOperand(0);
4727 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4728 DAG.getConstant(ShAmt, DL,
4729 getShiftAmountTy(Op.getValueType())));
4730 AddToWorklist(Op.getNode());
4734 return DAG.getNode(ISD::XOR, DL, VT,
4735 Op, DAG.getConstant(1, DL, VT));
4739 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4740 if (N1.getOpcode() == ISD::TRUNCATE &&
4741 N1.getOperand(0).getOpcode() == ISD::AND) {
4742 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4743 if (NewOp1.getNode())
4744 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4747 // fold operands of srl based on knowledge that the low bits are not
4749 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4750 return SDValue(N, 0);
4752 if (N1C && !N1C->isOpaque()) {
4753 SDValue NewSRL = visitShiftByConstant(N, N1C);
4754 if (NewSRL.getNode())
4758 // Attempt to convert a srl of a load into a narrower zero-extending load.
4759 SDValue NarrowLoad = ReduceLoadWidth(N);
4760 if (NarrowLoad.getNode())
4763 // Here is a common situation. We want to optimize:
4766 // %b = and i32 %a, 2
4767 // %c = srl i32 %b, 1
4768 // brcond i32 %c ...
4774 // %c = setcc eq %b, 0
4777 // However when after the source operand of SRL is optimized into AND, the SRL
4778 // itself may not be optimized further. Look for it and add the BRCOND into
4780 if (N->hasOneUse()) {
4781 SDNode *Use = *N->use_begin();
4782 if (Use->getOpcode() == ISD::BRCOND)
4784 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4785 // Also look pass the truncate.
4786 Use = *Use->use_begin();
4787 if (Use->getOpcode() == ISD::BRCOND)
4795 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4796 SDValue N0 = N->getOperand(0);
4797 EVT VT = N->getValueType(0);
4799 // fold (bswap c1) -> c2
4800 if (isConstantIntBuildVectorOrConstantInt(N0))
4801 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4802 // fold (bswap (bswap x)) -> x
4803 if (N0.getOpcode() == ISD::BSWAP)
4804 return N0->getOperand(0);
4808 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4809 SDValue N0 = N->getOperand(0);
4810 EVT VT = N->getValueType(0);
4812 // fold (ctlz c1) -> c2
4813 if (isConstantIntBuildVectorOrConstantInt(N0))
4814 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4818 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4819 SDValue N0 = N->getOperand(0);
4820 EVT VT = N->getValueType(0);
4822 // fold (ctlz_zero_undef c1) -> c2
4823 if (isConstantIntBuildVectorOrConstantInt(N0))
4824 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4828 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4829 SDValue N0 = N->getOperand(0);
4830 EVT VT = N->getValueType(0);
4832 // fold (cttz c1) -> c2
4833 if (isConstantIntBuildVectorOrConstantInt(N0))
4834 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4838 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4839 SDValue N0 = N->getOperand(0);
4840 EVT VT = N->getValueType(0);
4842 // fold (cttz_zero_undef c1) -> c2
4843 if (isConstantIntBuildVectorOrConstantInt(N0))
4844 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4848 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4849 SDValue N0 = N->getOperand(0);
4850 EVT VT = N->getValueType(0);
4852 // fold (ctpop c1) -> c2
4853 if (isConstantIntBuildVectorOrConstantInt(N0))
4854 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4859 /// \brief Generate Min/Max node
4860 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4861 SDValue True, SDValue False,
4862 ISD::CondCode CC, const TargetLowering &TLI,
4863 SelectionDAG &DAG) {
4864 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4874 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4875 if (TLI.isOperationLegal(Opcode, VT))
4876 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4885 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4886 if (TLI.isOperationLegal(Opcode, VT))
4887 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4895 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4896 SDValue N0 = N->getOperand(0);
4897 SDValue N1 = N->getOperand(1);
4898 SDValue N2 = N->getOperand(2);
4899 EVT VT = N->getValueType(0);
4900 EVT VT0 = N0.getValueType();
4902 // fold (select C, X, X) -> X
4905 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4906 // fold (select true, X, Y) -> X
4907 // fold (select false, X, Y) -> Y
4908 return !N0C->isNullValue() ? N1 : N2;
4910 // fold (select C, 1, X) -> (or C, X)
4911 if (VT == MVT::i1 && isOneConstant(N1))
4912 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4913 // fold (select C, 0, 1) -> (xor C, 1)
4914 // We can't do this reliably if integer based booleans have different contents
4915 // to floating point based booleans. This is because we can't tell whether we
4916 // have an integer-based boolean or a floating-point-based boolean unless we
4917 // can find the SETCC that produced it and inspect its operands. This is
4918 // fairly easy if C is the SETCC node, but it can potentially be
4919 // undiscoverable (or not reasonably discoverable). For example, it could be
4920 // in another basic block or it could require searching a complicated
4922 if (VT.isInteger() &&
4923 (VT0 == MVT::i1 || (VT0.isInteger() &&
4924 TLI.getBooleanContents(false, false) ==
4925 TLI.getBooleanContents(false, true) &&
4926 TLI.getBooleanContents(false, false) ==
4927 TargetLowering::ZeroOrOneBooleanContent)) &&
4928 isNullConstant(N1) && isOneConstant(N2)) {
4932 return DAG.getNode(ISD::XOR, DL, VT0,
4933 N0, DAG.getConstant(1, DL, VT0));
4936 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4937 N0, DAG.getConstant(1, DL0, VT0));
4938 AddToWorklist(XORNode.getNode());
4940 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4941 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4943 // fold (select C, 0, X) -> (and (not C), X)
4944 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
4945 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4946 AddToWorklist(NOTNode.getNode());
4947 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4949 // fold (select C, X, 1) -> (or (not C), X)
4950 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
4951 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4952 AddToWorklist(NOTNode.getNode());
4953 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4955 // fold (select C, X, 0) -> (and C, X)
4956 if (VT == MVT::i1 && isNullConstant(N2))
4957 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4958 // fold (select X, X, Y) -> (or X, Y)
4959 // fold (select X, 1, Y) -> (or X, Y)
4960 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
4961 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4962 // fold (select X, Y, X) -> (and X, Y)
4963 // fold (select X, Y, 0) -> (and X, Y)
4964 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
4965 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4967 // If we can fold this based on the true/false value, do so.
4968 if (SimplifySelectOps(N, N1, N2))
4969 return SDValue(N, 0); // Don't revisit N.
4971 // fold selects based on a setcc into other things, such as min/max/abs
4972 if (N0.getOpcode() == ISD::SETCC) {
4973 // select x, y (fcmp lt x, y) -> fminnum x, y
4974 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4976 // This is OK if we don't care about what happens if either operand is a
4980 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4981 // no signed zeros as well as no nans.
4982 const TargetOptions &Options = DAG.getTarget().Options;
4983 if (Options.UnsafeFPMath &&
4984 VT.isFloatingPoint() && N0.hasOneUse() &&
4985 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4986 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4989 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4990 N1, N2, CC, TLI, DAG);
4995 if ((!LegalOperations &&
4996 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4997 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4998 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4999 N0.getOperand(0), N0.getOperand(1),
5000 N1, N2, N0.getOperand(2));
5001 return SimplifySelect(SDLoc(N), N0, N1, N2);
5004 if (VT0 == MVT::i1) {
5005 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5006 // select (and Cond0, Cond1), X, Y
5007 // -> select Cond0, (select Cond1, X, Y), Y
5008 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5009 SDValue Cond0 = N0->getOperand(0);
5010 SDValue Cond1 = N0->getOperand(1);
5011 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5012 N1.getValueType(), Cond1, N1, N2);
5013 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5016 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5017 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5018 SDValue Cond0 = N0->getOperand(0);
5019 SDValue Cond1 = N0->getOperand(1);
5020 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5021 N1.getValueType(), Cond1, N1, N2);
5022 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5027 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5028 if (N1->getOpcode() == ISD::SELECT) {
5029 SDValue N1_0 = N1->getOperand(0);
5030 SDValue N1_1 = N1->getOperand(1);
5031 SDValue N1_2 = N1->getOperand(2);
5032 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5033 // Create the actual and node if we can generate good code for it.
5034 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5035 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5037 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5040 // Otherwise see if we can optimize the "and" to a better pattern.
5041 if (SDValue Combined = visitANDLike(N0, N1_0, N))
5042 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5046 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5047 if (N2->getOpcode() == ISD::SELECT) {
5048 SDValue N2_0 = N2->getOperand(0);
5049 SDValue N2_1 = N2->getOperand(1);
5050 SDValue N2_2 = N2->getOperand(2);
5051 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5052 // Create the actual or node if we can generate good code for it.
5053 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
5054 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5056 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5059 // Otherwise see if we can optimize to a better pattern.
5060 if (SDValue Combined = visitORLike(N0, N2_0, N))
5061 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5071 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5074 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5076 // Split the inputs.
5077 SDValue Lo, Hi, LL, LH, RL, RH;
5078 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5079 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5081 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5082 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5084 return std::make_pair(Lo, Hi);
5087 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5088 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5089 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5091 SDValue Cond = N->getOperand(0);
5092 SDValue LHS = N->getOperand(1);
5093 SDValue RHS = N->getOperand(2);
5094 EVT VT = N->getValueType(0);
5095 int NumElems = VT.getVectorNumElements();
5096 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5097 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5098 Cond.getOpcode() == ISD::BUILD_VECTOR);
5100 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5101 // binary ones here.
5102 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5105 // We're sure we have an even number of elements due to the
5106 // concat_vectors we have as arguments to vselect.
5107 // Skip BV elements until we find one that's not an UNDEF
5108 // After we find an UNDEF element, keep looping until we get to half the
5109 // length of the BV and see if all the non-undef nodes are the same.
5110 ConstantSDNode *BottomHalf = nullptr;
5111 for (int i = 0; i < NumElems / 2; ++i) {
5112 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5115 if (BottomHalf == nullptr)
5116 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5117 else if (Cond->getOperand(i).getNode() != BottomHalf)
5121 // Do the same for the second half of the BuildVector
5122 ConstantSDNode *TopHalf = nullptr;
5123 for (int i = NumElems / 2; i < NumElems; ++i) {
5124 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5127 if (TopHalf == nullptr)
5128 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5129 else if (Cond->getOperand(i).getNode() != TopHalf)
5133 assert(TopHalf && BottomHalf &&
5134 "One half of the selector was all UNDEFs and the other was all the "
5135 "same value. This should have been addressed before this function.");
5137 ISD::CONCAT_VECTORS, dl, VT,
5138 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5139 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5142 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5144 if (Level >= AfterLegalizeTypes)
5147 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5148 SDValue Mask = MSC->getMask();
5149 SDValue Data = MSC->getValue();
5152 // If the MSCATTER data type requires splitting and the mask is provided by a
5153 // SETCC, then split both nodes and its operands before legalization. This
5154 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5155 // and enables future optimizations (e.g. min/max pattern matching on X86).
5156 if (Mask.getOpcode() != ISD::SETCC)
5159 // Check if any splitting is required.
5160 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5161 TargetLowering::TypeSplitVector)
5163 SDValue MaskLo, MaskHi, Lo, Hi;
5164 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5167 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5169 SDValue Chain = MSC->getChain();
5171 EVT MemoryVT = MSC->getMemoryVT();
5172 unsigned Alignment = MSC->getOriginalAlignment();
5174 EVT LoMemVT, HiMemVT;
5175 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5177 SDValue DataLo, DataHi;
5178 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5180 SDValue BasePtr = MSC->getBasePtr();
5181 SDValue IndexLo, IndexHi;
5182 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5184 MachineMemOperand *MMO = DAG.getMachineFunction().
5185 getMachineMemOperand(MSC->getPointerInfo(),
5186 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5187 Alignment, MSC->getAAInfo(), MSC->getRanges());
5189 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5190 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5193 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5194 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5197 AddToWorklist(Lo.getNode());
5198 AddToWorklist(Hi.getNode());
5200 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5203 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5205 if (Level >= AfterLegalizeTypes)
5208 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5209 SDValue Mask = MST->getMask();
5210 SDValue Data = MST->getValue();
5213 // If the MSTORE data type requires splitting and the mask is provided by a
5214 // SETCC, then split both nodes and its operands before legalization. This
5215 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5216 // and enables future optimizations (e.g. min/max pattern matching on X86).
5217 if (Mask.getOpcode() == ISD::SETCC) {
5219 // Check if any splitting is required.
5220 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5221 TargetLowering::TypeSplitVector)
5224 SDValue MaskLo, MaskHi, Lo, Hi;
5225 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5228 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5230 SDValue Chain = MST->getChain();
5231 SDValue Ptr = MST->getBasePtr();
5233 EVT MemoryVT = MST->getMemoryVT();
5234 unsigned Alignment = MST->getOriginalAlignment();
5236 // if Alignment is equal to the vector size,
5237 // take the half of it for the second part
5238 unsigned SecondHalfAlignment =
5239 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5240 Alignment/2 : Alignment;
5242 EVT LoMemVT, HiMemVT;
5243 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5245 SDValue DataLo, DataHi;
5246 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5248 MachineMemOperand *MMO = DAG.getMachineFunction().
5249 getMachineMemOperand(MST->getPointerInfo(),
5250 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5251 Alignment, MST->getAAInfo(), MST->getRanges());
5253 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5254 MST->isTruncatingStore());
5256 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5257 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5258 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5260 MMO = DAG.getMachineFunction().
5261 getMachineMemOperand(MST->getPointerInfo(),
5262 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5263 SecondHalfAlignment, MST->getAAInfo(),
5266 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5267 MST->isTruncatingStore());
5269 AddToWorklist(Lo.getNode());
5270 AddToWorklist(Hi.getNode());
5272 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5277 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5279 if (Level >= AfterLegalizeTypes)
5282 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5283 SDValue Mask = MGT->getMask();
5286 // If the MGATHER result requires splitting and the mask is provided by a
5287 // SETCC, then split both nodes and its operands before legalization. This
5288 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5289 // and enables future optimizations (e.g. min/max pattern matching on X86).
5291 if (Mask.getOpcode() != ISD::SETCC)
5294 EVT VT = N->getValueType(0);
5296 // Check if any splitting is required.
5297 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5298 TargetLowering::TypeSplitVector)
5301 SDValue MaskLo, MaskHi, Lo, Hi;
5302 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5304 SDValue Src0 = MGT->getValue();
5305 SDValue Src0Lo, Src0Hi;
5306 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5309 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5311 SDValue Chain = MGT->getChain();
5312 EVT MemoryVT = MGT->getMemoryVT();
5313 unsigned Alignment = MGT->getOriginalAlignment();
5315 EVT LoMemVT, HiMemVT;
5316 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5318 SDValue BasePtr = MGT->getBasePtr();
5319 SDValue Index = MGT->getIndex();
5320 SDValue IndexLo, IndexHi;
5321 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5323 MachineMemOperand *MMO = DAG.getMachineFunction().
5324 getMachineMemOperand(MGT->getPointerInfo(),
5325 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5326 Alignment, MGT->getAAInfo(), MGT->getRanges());
5328 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5329 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5332 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5333 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5336 AddToWorklist(Lo.getNode());
5337 AddToWorklist(Hi.getNode());
5339 // Build a factor node to remember that this load is independent of the
5341 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5344 // Legalized the chain result - switch anything that used the old chain to
5346 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5348 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5350 SDValue RetOps[] = { GatherRes, Chain };
5351 return DAG.getMergeValues(RetOps, DL);
5354 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5356 if (Level >= AfterLegalizeTypes)
5359 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5360 SDValue Mask = MLD->getMask();
5363 // If the MLOAD result requires splitting and the mask is provided by a
5364 // SETCC, then split both nodes and its operands before legalization. This
5365 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5366 // and enables future optimizations (e.g. min/max pattern matching on X86).
5368 if (Mask.getOpcode() == ISD::SETCC) {
5369 EVT VT = N->getValueType(0);
5371 // Check if any splitting is required.
5372 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5373 TargetLowering::TypeSplitVector)
5376 SDValue MaskLo, MaskHi, Lo, Hi;
5377 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5379 SDValue Src0 = MLD->getSrc0();
5380 SDValue Src0Lo, Src0Hi;
5381 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5384 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5386 SDValue Chain = MLD->getChain();
5387 SDValue Ptr = MLD->getBasePtr();
5388 EVT MemoryVT = MLD->getMemoryVT();
5389 unsigned Alignment = MLD->getOriginalAlignment();
5391 // if Alignment is equal to the vector size,
5392 // take the half of it for the second part
5393 unsigned SecondHalfAlignment =
5394 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5395 Alignment/2 : Alignment;
5397 EVT LoMemVT, HiMemVT;
5398 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5400 MachineMemOperand *MMO = DAG.getMachineFunction().
5401 getMachineMemOperand(MLD->getPointerInfo(),
5402 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5403 Alignment, MLD->getAAInfo(), MLD->getRanges());
5405 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5408 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5409 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5410 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5412 MMO = DAG.getMachineFunction().
5413 getMachineMemOperand(MLD->getPointerInfo(),
5414 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5415 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5417 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5420 AddToWorklist(Lo.getNode());
5421 AddToWorklist(Hi.getNode());
5423 // Build a factor node to remember that this load is independent of the
5425 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5428 // Legalized the chain result - switch anything that used the old chain to
5430 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5432 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5434 SDValue RetOps[] = { LoadRes, Chain };
5435 return DAG.getMergeValues(RetOps, DL);
5440 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5441 SDValue N0 = N->getOperand(0);
5442 SDValue N1 = N->getOperand(1);
5443 SDValue N2 = N->getOperand(2);
5446 // Canonicalize integer abs.
5447 // vselect (setg[te] X, 0), X, -X ->
5448 // vselect (setgt X, -1), X, -X ->
5449 // vselect (setl[te] X, 0), -X, X ->
5450 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5451 if (N0.getOpcode() == ISD::SETCC) {
5452 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5453 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5455 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5457 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5458 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5459 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5460 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5461 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5462 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5463 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5466 EVT VT = LHS.getValueType();
5467 SDValue Shift = DAG.getNode(
5468 ISD::SRA, DL, VT, LHS,
5469 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5470 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5471 AddToWorklist(Shift.getNode());
5472 AddToWorklist(Add.getNode());
5473 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5477 if (SimplifySelectOps(N, N1, N2))
5478 return SDValue(N, 0); // Don't revisit N.
5480 // If the VSELECT result requires splitting and the mask is provided by a
5481 // SETCC, then split both nodes and its operands before legalization. This
5482 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5483 // and enables future optimizations (e.g. min/max pattern matching on X86).
5484 if (N0.getOpcode() == ISD::SETCC) {
5485 EVT VT = N->getValueType(0);
5487 // Check if any splitting is required.
5488 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5489 TargetLowering::TypeSplitVector)
5492 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5493 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5494 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5495 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5497 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5498 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5500 // Add the new VSELECT nodes to the work list in case they need to be split
5502 AddToWorklist(Lo.getNode());
5503 AddToWorklist(Hi.getNode());
5505 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5508 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5509 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5511 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5512 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5515 // The ConvertSelectToConcatVector function is assuming both the above
5516 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5518 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5519 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5520 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5521 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5529 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5530 SDValue N0 = N->getOperand(0);
5531 SDValue N1 = N->getOperand(1);
5532 SDValue N2 = N->getOperand(2);
5533 SDValue N3 = N->getOperand(3);
5534 SDValue N4 = N->getOperand(4);
5535 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5537 // fold select_cc lhs, rhs, x, x, cc -> x
5541 // Determine if the condition we're dealing with is constant
5542 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5543 N0, N1, CC, SDLoc(N), false);
5544 if (SCC.getNode()) {
5545 AddToWorklist(SCC.getNode());
5547 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5548 if (!SCCC->isNullValue())
5549 return N2; // cond always true -> true val
5551 return N3; // cond always false -> false val
5552 } else if (SCC->getOpcode() == ISD::UNDEF) {
5553 // When the condition is UNDEF, just return the first operand. This is
5554 // coherent the DAG creation, no setcc node is created in this case
5556 } else if (SCC.getOpcode() == ISD::SETCC) {
5557 // Fold to a simpler select_cc
5558 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5559 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5564 // If we can fold this based on the true/false value, do so.
5565 if (SimplifySelectOps(N, N2, N3))
5566 return SDValue(N, 0); // Don't revisit N.
5568 // fold select_cc into other things, such as min/max/abs
5569 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5572 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5573 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5574 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5578 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5579 // dag node into a ConstantSDNode or a build_vector of constants.
5580 // This function is called by the DAGCombiner when visiting sext/zext/aext
5581 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5582 // Vector extends are not folded if operations are legal; this is to
5583 // avoid introducing illegal build_vector dag nodes.
5584 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5585 SelectionDAG &DAG, bool LegalTypes,
5586 bool LegalOperations) {
5587 unsigned Opcode = N->getOpcode();
5588 SDValue N0 = N->getOperand(0);
5589 EVT VT = N->getValueType(0);
5591 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5592 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5593 && "Expected EXTEND dag node in input!");
5595 // fold (sext c1) -> c1
5596 // fold (zext c1) -> c1
5597 // fold (aext c1) -> c1
5598 if (isa<ConstantSDNode>(N0))
5599 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5601 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5602 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5603 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5604 EVT SVT = VT.getScalarType();
5605 if (!(VT.isVector() &&
5606 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5607 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5610 // We can fold this node into a build_vector.
5611 unsigned VTBits = SVT.getSizeInBits();
5612 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5613 unsigned ShAmt = VTBits - EVTBits;
5614 SmallVector<SDValue, 8> Elts;
5615 unsigned NumElts = VT.getVectorNumElements();
5618 for (unsigned i=0; i != NumElts; ++i) {
5619 SDValue Op = N0->getOperand(i);
5620 if (Op->getOpcode() == ISD::UNDEF) {
5621 Elts.push_back(DAG.getUNDEF(SVT));
5626 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5627 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5628 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5629 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5632 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5636 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5639 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5640 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5641 // transformation. Returns true if extension are possible and the above
5642 // mentioned transformation is profitable.
5643 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5645 SmallVectorImpl<SDNode *> &ExtendNodes,
5646 const TargetLowering &TLI) {
5647 bool HasCopyToRegUses = false;
5648 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5649 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5650 UE = N0.getNode()->use_end();
5655 if (UI.getUse().getResNo() != N0.getResNo())
5657 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5658 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5659 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5660 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5661 // Sign bits will be lost after a zext.
5664 for (unsigned i = 0; i != 2; ++i) {
5665 SDValue UseOp = User->getOperand(i);
5668 if (!isa<ConstantSDNode>(UseOp))
5673 ExtendNodes.push_back(User);
5676 // If truncates aren't free and there are users we can't
5677 // extend, it isn't worthwhile.
5680 // Remember if this value is live-out.
5681 if (User->getOpcode() == ISD::CopyToReg)
5682 HasCopyToRegUses = true;
5685 if (HasCopyToRegUses) {
5686 bool BothLiveOut = false;
5687 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5689 SDUse &Use = UI.getUse();
5690 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5696 // Both unextended and extended values are live out. There had better be
5697 // a good reason for the transformation.
5698 return ExtendNodes.size();
5703 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5704 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5705 ISD::NodeType ExtType) {
5706 // Extend SetCC uses if necessary.
5707 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5708 SDNode *SetCC = SetCCs[i];
5709 SmallVector<SDValue, 4> Ops;
5711 for (unsigned j = 0; j != 2; ++j) {
5712 SDValue SOp = SetCC->getOperand(j);
5714 Ops.push_back(ExtLoad);
5716 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5719 Ops.push_back(SetCC->getOperand(2));
5720 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5724 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5725 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5726 SDValue N0 = N->getOperand(0);
5727 EVT DstVT = N->getValueType(0);
5728 EVT SrcVT = N0.getValueType();
5730 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5731 N->getOpcode() == ISD::ZERO_EXTEND) &&
5732 "Unexpected node type (not an extend)!");
5734 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5735 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5736 // (v8i32 (sext (v8i16 (load x))))
5738 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5739 // (v4i32 (sextload (x + 16)))))
5740 // Where uses of the original load, i.e.:
5742 // are replaced with:
5744 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5745 // (v4i32 (sextload (x + 16)))))))
5747 // This combine is only applicable to illegal, but splittable, vectors.
5748 // All legal types, and illegal non-vector types, are handled elsewhere.
5749 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5751 if (N0->getOpcode() != ISD::LOAD)
5754 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5756 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5757 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5758 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5761 SmallVector<SDNode *, 4> SetCCs;
5762 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5765 ISD::LoadExtType ExtType =
5766 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5768 // Try to split the vector types to get down to legal types.
5769 EVT SplitSrcVT = SrcVT;
5770 EVT SplitDstVT = DstVT;
5771 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5772 SplitSrcVT.getVectorNumElements() > 1) {
5773 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5774 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5777 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5781 const unsigned NumSplits =
5782 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5783 const unsigned Stride = SplitSrcVT.getStoreSize();
5784 SmallVector<SDValue, 4> Loads;
5785 SmallVector<SDValue, 4> Chains;
5787 SDValue BasePtr = LN0->getBasePtr();
5788 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5789 const unsigned Offset = Idx * Stride;
5790 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5792 SDValue SplitLoad = DAG.getExtLoad(
5793 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5794 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5795 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5796 Align, LN0->getAAInfo());
5798 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5799 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5801 Loads.push_back(SplitLoad.getValue(0));
5802 Chains.push_back(SplitLoad.getValue(1));
5805 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5806 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5808 CombineTo(N, NewValue);
5810 // Replace uses of the original load (before extension)
5811 // with a truncate of the concatenated sextloaded vectors.
5813 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5814 CombineTo(N0.getNode(), Trunc, NewChain);
5815 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5816 (ISD::NodeType)N->getOpcode());
5817 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5820 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5821 SDValue N0 = N->getOperand(0);
5822 EVT VT = N->getValueType(0);
5824 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5826 return SDValue(Res, 0);
5828 // fold (sext (sext x)) -> (sext x)
5829 // fold (sext (aext x)) -> (sext x)
5830 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5831 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5834 if (N0.getOpcode() == ISD::TRUNCATE) {
5835 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5836 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
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!
5848 // See if the value being truncated is already sign extended. If so, just
5849 // eliminate the trunc/sext pair.
5850 SDValue Op = N0.getOperand(0);
5851 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5852 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5853 unsigned DestBits = VT.getScalarType().getSizeInBits();
5854 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5856 if (OpBits == DestBits) {
5857 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5858 // bits, it is already ready.
5859 if (NumSignBits > DestBits-MidBits)
5861 } else if (OpBits < DestBits) {
5862 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5863 // bits, just sext from i32.
5864 if (NumSignBits > OpBits-MidBits)
5865 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5867 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5868 // bits, just truncate to i32.
5869 if (NumSignBits > OpBits-MidBits)
5870 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5873 // fold (sext (truncate x)) -> (sextinreg x).
5874 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5875 N0.getValueType())) {
5876 if (OpBits < DestBits)
5877 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5878 else if (OpBits > DestBits)
5879 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5880 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5881 DAG.getValueType(N0.getValueType()));
5885 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5886 // Only generate vector extloads when 1) they're legal, and 2) they are
5887 // deemed desirable by the target.
5888 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5889 ((!LegalOperations && !VT.isVector() &&
5890 !cast<LoadSDNode>(N0)->isVolatile()) ||
5891 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5892 bool DoXform = true;
5893 SmallVector<SDNode*, 4> SetCCs;
5894 if (!N0.hasOneUse())
5895 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5897 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5899 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5900 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5902 LN0->getBasePtr(), N0.getValueType(),
5903 LN0->getMemOperand());
5904 CombineTo(N, ExtLoad);
5905 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5906 N0.getValueType(), ExtLoad);
5907 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5908 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5910 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5914 // fold (sext (load x)) to multiple smaller sextloads.
5915 // Only on illegal but splittable vectors.
5916 if (SDValue ExtLoad = CombineExtLoad(N))
5919 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5920 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5921 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5922 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5923 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5924 EVT MemVT = LN0->getMemoryVT();
5925 if ((!LegalOperations && !LN0->isVolatile()) ||
5926 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5927 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5929 LN0->getBasePtr(), MemVT,
5930 LN0->getMemOperand());
5931 CombineTo(N, ExtLoad);
5932 CombineTo(N0.getNode(),
5933 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5934 N0.getValueType(), ExtLoad),
5935 ExtLoad.getValue(1));
5936 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5940 // fold (sext (and/or/xor (load x), cst)) ->
5941 // (and/or/xor (sextload x), (sext cst))
5942 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5943 N0.getOpcode() == ISD::XOR) &&
5944 isa<LoadSDNode>(N0.getOperand(0)) &&
5945 N0.getOperand(1).getOpcode() == ISD::Constant &&
5946 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5947 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5948 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5949 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5950 bool DoXform = true;
5951 SmallVector<SDNode*, 4> SetCCs;
5952 if (!N0.hasOneUse())
5953 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5956 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5957 LN0->getChain(), LN0->getBasePtr(),
5959 LN0->getMemOperand());
5960 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5961 Mask = Mask.sext(VT.getSizeInBits());
5963 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5964 ExtLoad, DAG.getConstant(Mask, DL, VT));
5965 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5966 SDLoc(N0.getOperand(0)),
5967 N0.getOperand(0).getValueType(), ExtLoad);
5969 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5970 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5972 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5977 if (N0.getOpcode() == ISD::SETCC) {
5978 EVT N0VT = N0.getOperand(0).getValueType();
5979 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5980 // Only do this before legalize for now.
5981 if (VT.isVector() && !LegalOperations &&
5982 TLI.getBooleanContents(N0VT) ==
5983 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5984 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5985 // of the same size as the compared operands. Only optimize sext(setcc())
5986 // if this is the case.
5987 EVT SVT = getSetCCResultType(N0VT);
5989 // We know that the # elements of the results is the same as the
5990 // # elements of the compare (and the # elements of the compare result
5991 // for that matter). Check to see that they are the same size. If so,
5992 // we know that the element size of the sext'd result matches the
5993 // element size of the compare operands.
5994 if (VT.getSizeInBits() == SVT.getSizeInBits())
5995 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5997 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5999 // If the desired elements are smaller or larger than the source
6000 // elements we can use a matching integer vector type and then
6001 // truncate/sign extend
6002 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6003 if (SVT == MatchingVectorType) {
6004 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6005 N0.getOperand(0), N0.getOperand(1),
6006 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6007 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6011 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6012 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6015 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6017 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6018 NegOne, DAG.getConstant(0, DL, VT),
6019 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6020 if (SCC.getNode()) return SCC;
6022 if (!VT.isVector()) {
6023 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6024 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
6026 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6027 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6028 N0.getOperand(0), N0.getOperand(1), CC);
6029 return DAG.getSelect(DL, VT, SetCC,
6030 NegOne, DAG.getConstant(0, DL, VT));
6035 // fold (sext x) -> (zext x) if the sign bit is known zero.
6036 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6037 DAG.SignBitIsZero(N0))
6038 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6043 // isTruncateOf - If N is a truncate of some other value, return true, record
6044 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6045 // This function computes KnownZero to avoid a duplicated call to
6046 // computeKnownBits in the caller.
6047 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6050 if (N->getOpcode() == ISD::TRUNCATE) {
6051 Op = N->getOperand(0);
6052 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6056 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6057 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6060 SDValue Op0 = N->getOperand(0);
6061 SDValue Op1 = N->getOperand(1);
6062 assert(Op0.getValueType() == Op1.getValueType());
6064 if (isNullConstant(Op0))
6066 else if (isNullConstant(Op1))
6071 DAG.computeKnownBits(Op, KnownZero, KnownOne);
6073 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6079 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6080 SDValue N0 = N->getOperand(0);
6081 EVT VT = N->getValueType(0);
6083 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6085 return SDValue(Res, 0);
6087 // fold (zext (zext x)) -> (zext x)
6088 // fold (zext (aext x)) -> (zext x)
6089 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6090 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6093 // fold (zext (truncate x)) -> (zext x) or
6094 // (zext (truncate x)) -> (truncate x)
6095 // This is valid when the truncated bits of x are already zero.
6096 // FIXME: We should extend this to work for vectors too.
6099 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6100 APInt TruncatedBits =
6101 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6102 APInt(Op.getValueSizeInBits(), 0) :
6103 APInt::getBitsSet(Op.getValueSizeInBits(),
6104 N0.getValueSizeInBits(),
6105 std::min(Op.getValueSizeInBits(),
6106 VT.getSizeInBits()));
6107 if (TruncatedBits == (KnownZero & TruncatedBits)) {
6108 if (VT.bitsGT(Op.getValueType()))
6109 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6110 if (VT.bitsLT(Op.getValueType()))
6111 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6117 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6118 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6119 if (N0.getOpcode() == ISD::TRUNCATE) {
6120 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6121 if (NarrowLoad.getNode()) {
6122 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6123 if (NarrowLoad.getNode() != N0.getNode()) {
6124 CombineTo(N0.getNode(), NarrowLoad);
6125 // CombineTo deleted the truncate, if needed, but not what's under it.
6128 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6132 // fold (zext (truncate x)) -> (and x, mask)
6133 if (N0.getOpcode() == ISD::TRUNCATE &&
6134 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6136 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6137 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6138 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6139 if (NarrowLoad.getNode()) {
6140 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6141 if (NarrowLoad.getNode() != N0.getNode()) {
6142 CombineTo(N0.getNode(), NarrowLoad);
6143 // CombineTo deleted the truncate, if needed, but not what's under it.
6146 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6149 SDValue Op = N0.getOperand(0);
6150 if (Op.getValueType().bitsLT(VT)) {
6151 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6152 AddToWorklist(Op.getNode());
6153 } else if (Op.getValueType().bitsGT(VT)) {
6154 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6155 AddToWorklist(Op.getNode());
6157 return DAG.getZeroExtendInReg(Op, SDLoc(N),
6158 N0.getValueType().getScalarType());
6161 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6162 // if either of the casts is not free.
6163 if (N0.getOpcode() == ISD::AND &&
6164 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6165 N0.getOperand(1).getOpcode() == ISD::Constant &&
6166 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6167 N0.getValueType()) ||
6168 !TLI.isZExtFree(N0.getValueType(), VT))) {
6169 SDValue X = N0.getOperand(0).getOperand(0);
6170 if (X.getValueType().bitsLT(VT)) {
6171 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6172 } else if (X.getValueType().bitsGT(VT)) {
6173 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6175 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6176 Mask = Mask.zext(VT.getSizeInBits());
6178 return DAG.getNode(ISD::AND, DL, VT,
6179 X, DAG.getConstant(Mask, DL, VT));
6182 // fold (zext (load x)) -> (zext (truncate (zextload x)))
6183 // Only generate vector extloads when 1) they're legal, and 2) they are
6184 // deemed desirable by the target.
6185 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6186 ((!LegalOperations && !VT.isVector() &&
6187 !cast<LoadSDNode>(N0)->isVolatile()) ||
6188 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6189 bool DoXform = true;
6190 SmallVector<SDNode*, 4> SetCCs;
6191 if (!N0.hasOneUse())
6192 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6194 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6196 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6197 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6199 LN0->getBasePtr(), N0.getValueType(),
6200 LN0->getMemOperand());
6201 CombineTo(N, ExtLoad);
6202 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6203 N0.getValueType(), ExtLoad);
6204 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6206 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6208 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6212 // fold (zext (load x)) to multiple smaller zextloads.
6213 // Only on illegal but splittable vectors.
6214 if (SDValue ExtLoad = CombineExtLoad(N))
6217 // fold (zext (and/or/xor (load x), cst)) ->
6218 // (and/or/xor (zextload x), (zext cst))
6219 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6220 N0.getOpcode() == ISD::XOR) &&
6221 isa<LoadSDNode>(N0.getOperand(0)) &&
6222 N0.getOperand(1).getOpcode() == ISD::Constant &&
6223 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6224 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6225 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6226 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6227 bool DoXform = true;
6228 SmallVector<SDNode*, 4> SetCCs;
6229 if (!N0.hasOneUse())
6230 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6233 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6234 LN0->getChain(), LN0->getBasePtr(),
6236 LN0->getMemOperand());
6237 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6238 Mask = Mask.zext(VT.getSizeInBits());
6240 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6241 ExtLoad, DAG.getConstant(Mask, DL, VT));
6242 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6243 SDLoc(N0.getOperand(0)),
6244 N0.getOperand(0).getValueType(), ExtLoad);
6246 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6247 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6249 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6254 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6255 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6256 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6257 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6258 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6259 EVT MemVT = LN0->getMemoryVT();
6260 if ((!LegalOperations && !LN0->isVolatile()) ||
6261 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6262 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6264 LN0->getBasePtr(), MemVT,
6265 LN0->getMemOperand());
6266 CombineTo(N, ExtLoad);
6267 CombineTo(N0.getNode(),
6268 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6270 ExtLoad.getValue(1));
6271 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6275 if (N0.getOpcode() == ISD::SETCC) {
6276 if (!LegalOperations && VT.isVector() &&
6277 N0.getValueType().getVectorElementType() == MVT::i1) {
6278 EVT N0VT = N0.getOperand(0).getValueType();
6279 if (getSetCCResultType(N0VT) == N0.getValueType())
6282 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6283 // Only do this before legalize for now.
6284 EVT EltVT = VT.getVectorElementType();
6286 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6287 DAG.getConstant(1, DL, EltVT));
6288 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6289 // We know that the # elements of the results is the same as the
6290 // # elements of the compare (and the # elements of the compare result
6291 // for that matter). Check to see that they are the same size. If so,
6292 // we know that the element size of the sext'd result matches the
6293 // element size of the compare operands.
6294 return DAG.getNode(ISD::AND, DL, VT,
6295 DAG.getSetCC(DL, VT, N0.getOperand(0),
6297 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6298 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6301 // If the desired elements are smaller or larger than the source
6302 // elements we can use a matching integer vector type and then
6303 // truncate/sign extend
6304 EVT MatchingElementType =
6305 EVT::getIntegerVT(*DAG.getContext(),
6306 N0VT.getScalarType().getSizeInBits());
6307 EVT MatchingVectorType =
6308 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6309 N0VT.getVectorNumElements());
6311 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6313 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6314 return DAG.getNode(ISD::AND, DL, VT,
6315 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6316 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6319 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6322 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6323 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6324 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6325 if (SCC.getNode()) return SCC;
6328 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6329 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6330 isa<ConstantSDNode>(N0.getOperand(1)) &&
6331 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6333 SDValue ShAmt = N0.getOperand(1);
6334 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6335 if (N0.getOpcode() == ISD::SHL) {
6336 SDValue InnerZExt = N0.getOperand(0);
6337 // If the original shl may be shifting out bits, do not perform this
6339 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6340 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6341 if (ShAmtVal > KnownZeroBits)
6347 // Ensure that the shift amount is wide enough for the shifted value.
6348 if (VT.getSizeInBits() >= 256)
6349 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6351 return DAG.getNode(N0.getOpcode(), DL, VT,
6352 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6359 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6360 SDValue N0 = N->getOperand(0);
6361 EVT VT = N->getValueType(0);
6363 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6365 return SDValue(Res, 0);
6367 // fold (aext (aext x)) -> (aext x)
6368 // fold (aext (zext x)) -> (zext x)
6369 // fold (aext (sext x)) -> (sext x)
6370 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6371 N0.getOpcode() == ISD::ZERO_EXTEND ||
6372 N0.getOpcode() == ISD::SIGN_EXTEND)
6373 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6375 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6376 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6377 if (N0.getOpcode() == ISD::TRUNCATE) {
6378 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6379 if (NarrowLoad.getNode()) {
6380 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6381 if (NarrowLoad.getNode() != N0.getNode()) {
6382 CombineTo(N0.getNode(), NarrowLoad);
6383 // CombineTo deleted the truncate, if needed, but not what's under it.
6386 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6390 // fold (aext (truncate x))
6391 if (N0.getOpcode() == ISD::TRUNCATE) {
6392 SDValue TruncOp = N0.getOperand(0);
6393 if (TruncOp.getValueType() == VT)
6394 return TruncOp; // x iff x size == zext size.
6395 if (TruncOp.getValueType().bitsGT(VT))
6396 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6397 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6400 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6401 // if the trunc is not free.
6402 if (N0.getOpcode() == ISD::AND &&
6403 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6404 N0.getOperand(1).getOpcode() == ISD::Constant &&
6405 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6406 N0.getValueType())) {
6407 SDValue X = N0.getOperand(0).getOperand(0);
6408 if (X.getValueType().bitsLT(VT)) {
6409 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6410 } else if (X.getValueType().bitsGT(VT)) {
6411 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6413 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6414 Mask = Mask.zext(VT.getSizeInBits());
6416 return DAG.getNode(ISD::AND, DL, VT,
6417 X, DAG.getConstant(Mask, DL, VT));
6420 // fold (aext (load x)) -> (aext (truncate (extload x)))
6421 // None of the supported targets knows how to perform load and any_ext
6422 // on vectors in one instruction. We only perform this transformation on
6424 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6425 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6426 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6427 bool DoXform = true;
6428 SmallVector<SDNode*, 4> SetCCs;
6429 if (!N0.hasOneUse())
6430 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6432 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6433 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6435 LN0->getBasePtr(), N0.getValueType(),
6436 LN0->getMemOperand());
6437 CombineTo(N, ExtLoad);
6438 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6439 N0.getValueType(), ExtLoad);
6440 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6441 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6443 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6447 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6448 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6449 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
6450 if (N0.getOpcode() == ISD::LOAD &&
6451 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6453 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6454 ISD::LoadExtType ExtType = LN0->getExtensionType();
6455 EVT MemVT = LN0->getMemoryVT();
6456 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6457 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6458 VT, LN0->getChain(), LN0->getBasePtr(),
6459 MemVT, LN0->getMemOperand());
6460 CombineTo(N, ExtLoad);
6461 CombineTo(N0.getNode(),
6462 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6463 N0.getValueType(), ExtLoad),
6464 ExtLoad.getValue(1));
6465 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6469 if (N0.getOpcode() == ISD::SETCC) {
6471 // aext(setcc) -> vsetcc
6472 // aext(setcc) -> truncate(vsetcc)
6473 // aext(setcc) -> aext(vsetcc)
6474 // Only do this before legalize for now.
6475 if (VT.isVector() && !LegalOperations) {
6476 EVT N0VT = N0.getOperand(0).getValueType();
6477 // We know that the # elements of the results is the same as the
6478 // # elements of the compare (and the # elements of the compare result
6479 // for that matter). Check to see that they are the same size. If so,
6480 // we know that the element size of the sext'd result matches the
6481 // element size of the compare operands.
6482 if (VT.getSizeInBits() == N0VT.getSizeInBits())
6483 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6485 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6486 // If the desired elements are smaller or larger than the source
6487 // elements we can use a matching integer vector type and then
6488 // truncate/any extend
6490 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6492 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6494 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6495 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6499 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6502 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6503 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6504 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6512 /// See if the specified operand can be simplified with the knowledge that only
6513 /// the bits specified by Mask are used. If so, return the simpler operand,
6514 /// otherwise return a null SDValue.
6515 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6516 switch (V.getOpcode()) {
6518 case ISD::Constant: {
6519 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6520 assert(CV && "Const value should be ConstSDNode.");
6521 const APInt &CVal = CV->getAPIntValue();
6522 APInt NewVal = CVal & Mask;
6524 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6529 // If the LHS or RHS don't contribute bits to the or, drop them.
6530 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6531 return V.getOperand(1);
6532 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6533 return V.getOperand(0);
6536 // Only look at single-use SRLs.
6537 if (!V.getNode()->hasOneUse())
6539 if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6540 // See if we can recursively simplify the LHS.
6541 unsigned Amt = RHSC->getZExtValue();
6543 // Watch out for shift count overflow though.
6544 if (Amt >= Mask.getBitWidth()) break;
6545 APInt NewMask = Mask << Amt;
6546 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6547 if (SimplifyLHS.getNode())
6548 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6549 SimplifyLHS, V.getOperand(1));
6555 /// If the result of a wider load is shifted to right of N bits and then
6556 /// truncated to a narrower type and where N is a multiple of number of bits of
6557 /// the narrower type, transform it to a narrower load from address + N / num of
6558 /// bits of new type. If the result is to be extended, also fold the extension
6559 /// to form a extending load.
6560 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6561 unsigned Opc = N->getOpcode();
6563 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6564 SDValue N0 = N->getOperand(0);
6565 EVT VT = N->getValueType(0);
6568 // This transformation isn't valid for vector loads.
6572 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6574 if (Opc == ISD::SIGN_EXTEND_INREG) {
6575 ExtType = ISD::SEXTLOAD;
6576 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6577 } else if (Opc == ISD::SRL) {
6578 // Another special-case: SRL is basically zero-extending a narrower value.
6579 ExtType = ISD::ZEXTLOAD;
6581 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6582 if (!N01) return SDValue();
6583 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6584 VT.getSizeInBits() - N01->getZExtValue());
6586 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6589 unsigned EVTBits = ExtVT.getSizeInBits();
6591 // Do not generate loads of non-round integer types since these can
6592 // be expensive (and would be wrong if the type is not byte sized).
6593 if (!ExtVT.isRound())
6597 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6598 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6599 ShAmt = N01->getZExtValue();
6600 // Is the shift amount a multiple of size of VT?
6601 if ((ShAmt & (EVTBits-1)) == 0) {
6602 N0 = N0.getOperand(0);
6603 // Is the load width a multiple of size of VT?
6604 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6608 // At this point, we must have a load or else we can't do the transform.
6609 if (!isa<LoadSDNode>(N0)) return SDValue();
6611 // Because a SRL must be assumed to *need* to zero-extend the high bits
6612 // (as opposed to anyext the high bits), we can't combine the zextload
6613 // lowering of SRL and an sextload.
6614 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6617 // If the shift amount is larger than the input type then we're not
6618 // accessing any of the loaded bytes. If the load was a zextload/extload
6619 // then the result of the shift+trunc is zero/undef (handled elsewhere).
6620 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6625 // If the load is shifted left (and the result isn't shifted back right),
6626 // we can fold the truncate through the shift.
6627 unsigned ShLeftAmt = 0;
6628 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6629 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6630 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6631 ShLeftAmt = N01->getZExtValue();
6632 N0 = N0.getOperand(0);
6636 // If we haven't found a load, we can't narrow it. Don't transform one with
6637 // multiple uses, this would require adding a new load.
6638 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6641 // Don't change the width of a volatile load.
6642 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6643 if (LN0->isVolatile())
6646 // Verify that we are actually reducing a load width here.
6647 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6650 // For the transform to be legal, the load must produce only two values
6651 // (the value loaded and the chain). Don't transform a pre-increment
6652 // load, for example, which produces an extra value. Otherwise the
6653 // transformation is not equivalent, and the downstream logic to replace
6654 // uses gets things wrong.
6655 if (LN0->getNumValues() > 2)
6658 // If the load that we're shrinking is an extload and we're not just
6659 // discarding the extension we can't simply shrink the load. Bail.
6660 // TODO: It would be possible to merge the extensions in some cases.
6661 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6662 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6665 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6668 EVT PtrType = N0.getOperand(1).getValueType();
6670 if (PtrType == MVT::Untyped || PtrType.isExtended())
6671 // It's not possible to generate a constant of extended or untyped type.
6674 // For big endian targets, we need to adjust the offset to the pointer to
6675 // load the correct bytes.
6676 if (TLI.isBigEndian()) {
6677 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6678 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6679 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6682 uint64_t PtrOff = ShAmt / 8;
6683 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6685 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6686 PtrType, LN0->getBasePtr(),
6687 DAG.getConstant(PtrOff, DL, PtrType));
6688 AddToWorklist(NewPtr.getNode());
6691 if (ExtType == ISD::NON_EXTLOAD)
6692 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6693 LN0->getPointerInfo().getWithOffset(PtrOff),
6694 LN0->isVolatile(), LN0->isNonTemporal(),
6695 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6697 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6698 LN0->getPointerInfo().getWithOffset(PtrOff),
6699 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6700 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6702 // Replace the old load's chain with the new load's chain.
6703 WorklistRemover DeadNodes(*this);
6704 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6706 // Shift the result left, if we've swallowed a left shift.
6707 SDValue Result = Load;
6708 if (ShLeftAmt != 0) {
6709 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6710 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6712 // If the shift amount is as large as the result size (but, presumably,
6713 // no larger than the source) then the useful bits of the result are
6714 // zero; we can't simply return the shortened shift, because the result
6715 // of that operation is undefined.
6717 if (ShLeftAmt >= VT.getSizeInBits())
6718 Result = DAG.getConstant(0, DL, VT);
6720 Result = DAG.getNode(ISD::SHL, DL, VT,
6721 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6724 // Return the new loaded value.
6728 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6729 SDValue N0 = N->getOperand(0);
6730 SDValue N1 = N->getOperand(1);
6731 EVT VT = N->getValueType(0);
6732 EVT EVT = cast<VTSDNode>(N1)->getVT();
6733 unsigned VTBits = VT.getScalarType().getSizeInBits();
6734 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6736 // fold (sext_in_reg c1) -> c1
6737 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6738 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6740 // If the input is already sign extended, just drop the extension.
6741 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6744 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6745 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6746 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6747 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6748 N0.getOperand(0), N1);
6750 // fold (sext_in_reg (sext x)) -> (sext x)
6751 // fold (sext_in_reg (aext x)) -> (sext x)
6752 // if x is small enough.
6753 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6754 SDValue N00 = N0.getOperand(0);
6755 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6756 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6757 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6760 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6761 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6762 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6764 // fold operands of sext_in_reg based on knowledge that the top bits are not
6766 if (SimplifyDemandedBits(SDValue(N, 0)))
6767 return SDValue(N, 0);
6769 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6770 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6771 SDValue NarrowLoad = ReduceLoadWidth(N);
6772 if (NarrowLoad.getNode())
6775 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6776 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6777 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6778 if (N0.getOpcode() == ISD::SRL) {
6779 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6780 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6781 // We can turn this into an SRA iff the input to the SRL is already sign
6783 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6784 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6785 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6786 N0.getOperand(0), N0.getOperand(1));
6790 // fold (sext_inreg (extload x)) -> (sextload x)
6791 if (ISD::isEXTLoad(N0.getNode()) &&
6792 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6793 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6794 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6795 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6796 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6797 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6799 LN0->getBasePtr(), EVT,
6800 LN0->getMemOperand());
6801 CombineTo(N, ExtLoad);
6802 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6803 AddToWorklist(ExtLoad.getNode());
6804 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6806 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6807 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6809 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6810 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6811 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6812 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6813 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6815 LN0->getBasePtr(), EVT,
6816 LN0->getMemOperand());
6817 CombineTo(N, ExtLoad);
6818 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6819 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6822 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6823 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6824 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6825 N0.getOperand(1), false);
6826 if (BSwap.getNode())
6827 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6831 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6832 // into a build_vector.
6833 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6834 SmallVector<SDValue, 8> Elts;
6835 unsigned NumElts = N0->getNumOperands();
6836 unsigned ShAmt = VTBits - EVTBits;
6838 for (unsigned i = 0; i != NumElts; ++i) {
6839 SDValue Op = N0->getOperand(i);
6840 if (Op->getOpcode() == ISD::UNDEF) {
6845 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6846 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6847 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6848 SDLoc(Op), Op.getValueType()));
6851 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6857 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6858 SDValue N0 = N->getOperand(0);
6859 EVT VT = N->getValueType(0);
6861 if (N0.getOpcode() == ISD::UNDEF)
6862 return DAG.getUNDEF(VT);
6864 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6866 return SDValue(Res, 0);
6871 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6872 SDValue N0 = N->getOperand(0);
6873 EVT VT = N->getValueType(0);
6874 bool isLE = TLI.isLittleEndian();
6877 if (N0.getValueType() == N->getValueType(0))
6879 // fold (truncate c1) -> c1
6880 if (isConstantIntBuildVectorOrConstantInt(N0))
6881 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6882 // fold (truncate (truncate x)) -> (truncate x)
6883 if (N0.getOpcode() == ISD::TRUNCATE)
6884 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6885 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6886 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6887 N0.getOpcode() == ISD::SIGN_EXTEND ||
6888 N0.getOpcode() == ISD::ANY_EXTEND) {
6889 if (N0.getOperand(0).getValueType().bitsLT(VT))
6890 // if the source is smaller than the dest, we still need an extend
6891 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6893 if (N0.getOperand(0).getValueType().bitsGT(VT))
6894 // if the source is larger than the dest, than we just need the truncate
6895 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6896 // if the source and dest are the same type, we can drop both the extend
6897 // and the truncate.
6898 return N0.getOperand(0);
6901 // Fold extract-and-trunc into a narrow extract. For example:
6902 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6903 // i32 y = TRUNCATE(i64 x)
6905 // v16i8 b = BITCAST (v2i64 val)
6906 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6908 // Note: We only run this optimization after type legalization (which often
6909 // creates this pattern) and before operation legalization after which
6910 // we need to be more careful about the vector instructions that we generate.
6911 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6912 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6914 EVT VecTy = N0.getOperand(0).getValueType();
6915 EVT ExTy = N0.getValueType();
6916 EVT TrTy = N->getValueType(0);
6918 unsigned NumElem = VecTy.getVectorNumElements();
6919 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6921 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6922 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6924 SDValue EltNo = N0->getOperand(1);
6925 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6926 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6927 EVT IndexTy = TLI.getVectorIdxTy();
6928 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6930 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6931 NVT, N0.getOperand(0));
6934 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6936 DAG.getConstant(Index, DL, IndexTy));
6940 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6941 if (N0.getOpcode() == ISD::SELECT) {
6942 EVT SrcVT = N0.getValueType();
6943 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6944 TLI.isTruncateFree(SrcVT, VT)) {
6946 SDValue Cond = N0.getOperand(0);
6947 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6948 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6949 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6953 // Fold a series of buildvector, bitcast, and truncate if possible.
6955 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6956 // (2xi32 (buildvector x, y)).
6957 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6958 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6959 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6960 N0.getOperand(0).hasOneUse()) {
6962 SDValue BuildVect = N0.getOperand(0);
6963 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6964 EVT TruncVecEltTy = VT.getVectorElementType();
6966 // Check that the element types match.
6967 if (BuildVectEltTy == TruncVecEltTy) {
6968 // Now we only need to compute the offset of the truncated elements.
6969 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6970 unsigned TruncVecNumElts = VT.getVectorNumElements();
6971 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6973 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6974 "Invalid number of elements");
6976 SmallVector<SDValue, 8> Opnds;
6977 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6978 Opnds.push_back(BuildVect.getOperand(i));
6980 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6984 // See if we can simplify the input to this truncate through knowledge that
6985 // only the low bits are being used.
6986 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6987 // Currently we only perform this optimization on scalars because vectors
6988 // may have different active low bits.
6989 if (!VT.isVector()) {
6991 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6992 VT.getSizeInBits()));
6993 if (Shorter.getNode())
6994 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6996 // fold (truncate (load x)) -> (smaller load x)
6997 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6998 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6999 SDValue Reduced = ReduceLoadWidth(N);
7000 if (Reduced.getNode())
7002 // Handle the case where the load remains an extending load even
7003 // after truncation.
7004 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7005 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7006 if (!LN0->isVolatile() &&
7007 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7008 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7009 VT, LN0->getChain(), LN0->getBasePtr(),
7011 LN0->getMemOperand());
7012 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7017 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7018 // where ... are all 'undef'.
7019 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7020 SmallVector<EVT, 8> VTs;
7023 unsigned NumDefs = 0;
7025 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7026 SDValue X = N0.getOperand(i);
7027 if (X.getOpcode() != ISD::UNDEF) {
7032 // Stop if more than one members are non-undef.
7035 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7036 VT.getVectorElementType(),
7037 X.getValueType().getVectorNumElements()));
7041 return DAG.getUNDEF(VT);
7044 assert(V.getNode() && "The single defined operand is empty!");
7045 SmallVector<SDValue, 8> Opnds;
7046 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7048 Opnds.push_back(DAG.getUNDEF(VTs[i]));
7051 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7052 AddToWorklist(NV.getNode());
7053 Opnds.push_back(NV);
7055 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7059 // Simplify the operands using demanded-bits information.
7060 if (!VT.isVector() &&
7061 SimplifyDemandedBits(SDValue(N, 0)))
7062 return SDValue(N, 0);
7067 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7068 SDValue Elt = N->getOperand(i);
7069 if (Elt.getOpcode() != ISD::MERGE_VALUES)
7070 return Elt.getNode();
7071 return Elt.getOperand(Elt.getResNo()).getNode();
7074 /// build_pair (load, load) -> load
7075 /// if load locations are consecutive.
7076 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7077 assert(N->getOpcode() == ISD::BUILD_PAIR);
7079 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7080 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7081 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7082 LD1->getAddressSpace() != LD2->getAddressSpace())
7084 EVT LD1VT = LD1->getValueType(0);
7086 if (ISD::isNON_EXTLoad(LD2) &&
7088 // If both are volatile this would reduce the number of volatile loads.
7089 // If one is volatile it might be ok, but play conservative and bail out.
7090 !LD1->isVolatile() &&
7091 !LD2->isVolatile() &&
7092 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7093 unsigned Align = LD1->getAlignment();
7094 unsigned NewAlign = TLI.getDataLayout()->
7095 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7097 if (NewAlign <= Align &&
7098 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7099 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7100 LD1->getBasePtr(), LD1->getPointerInfo(),
7101 false, false, false, Align);
7107 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7108 SDValue N0 = N->getOperand(0);
7109 EVT VT = N->getValueType(0);
7111 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7112 // Only do this before legalize, since afterward the target may be depending
7113 // on the bitconvert.
7114 // First check to see if this is all constant.
7116 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7118 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7120 EVT DestEltVT = N->getValueType(0).getVectorElementType();
7121 assert(!DestEltVT.isVector() &&
7122 "Element type of vector ValueType must not be vector!");
7124 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7127 // If the input is a constant, let getNode fold it.
7128 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7129 // If we can't allow illegal operations, we need to check that this is just
7130 // a fp -> int or int -> conversion and that the resulting operation will
7132 if (!LegalOperations ||
7133 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7134 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7135 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7136 TLI.isOperationLegal(ISD::Constant, VT)))
7137 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7140 // (conv (conv x, t1), t2) -> (conv x, t2)
7141 if (N0.getOpcode() == ISD::BITCAST)
7142 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7145 // fold (conv (load x)) -> (load (conv*)x)
7146 // If the resultant load doesn't need a higher alignment than the original!
7147 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7148 // Do not change the width of a volatile load.
7149 !cast<LoadSDNode>(N0)->isVolatile() &&
7150 // Do not remove the cast if the types differ in endian layout.
7151 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7152 TLI.hasBigEndianPartOrdering(VT) &&
7153 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7154 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7155 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7156 unsigned Align = TLI.getDataLayout()->
7157 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7158 unsigned OrigAlign = LN0->getAlignment();
7160 if (Align <= OrigAlign) {
7161 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7162 LN0->getBasePtr(), LN0->getPointerInfo(),
7163 LN0->isVolatile(), LN0->isNonTemporal(),
7164 LN0->isInvariant(), OrigAlign,
7166 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7171 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7172 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7173 // This often reduces constant pool loads.
7174 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7175 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7176 N0.getNode()->hasOneUse() && VT.isInteger() &&
7177 !VT.isVector() && !N0.getValueType().isVector()) {
7178 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7180 AddToWorklist(NewConv.getNode());
7183 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7184 if (N0.getOpcode() == ISD::FNEG)
7185 return DAG.getNode(ISD::XOR, DL, VT,
7186 NewConv, DAG.getConstant(SignBit, DL, VT));
7187 assert(N0.getOpcode() == ISD::FABS);
7188 return DAG.getNode(ISD::AND, DL, VT,
7189 NewConv, DAG.getConstant(~SignBit, DL, VT));
7192 // fold (bitconvert (fcopysign cst, x)) ->
7193 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7194 // Note that we don't handle (copysign x, cst) because this can always be
7195 // folded to an fneg or fabs.
7196 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7197 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7198 VT.isInteger() && !VT.isVector()) {
7199 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7200 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7201 if (isTypeLegal(IntXVT)) {
7202 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7203 IntXVT, N0.getOperand(1));
7204 AddToWorklist(X.getNode());
7206 // If X has a different width than the result/lhs, sext it or truncate it.
7207 unsigned VTWidth = VT.getSizeInBits();
7208 if (OrigXWidth < VTWidth) {
7209 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7210 AddToWorklist(X.getNode());
7211 } else if (OrigXWidth > VTWidth) {
7212 // To get the sign bit in the right place, we have to shift it right
7213 // before truncating.
7215 X = DAG.getNode(ISD::SRL, DL,
7216 X.getValueType(), X,
7217 DAG.getConstant(OrigXWidth-VTWidth, DL,
7219 AddToWorklist(X.getNode());
7220 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7221 AddToWorklist(X.getNode());
7224 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7225 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7226 X, DAG.getConstant(SignBit, SDLoc(X), VT));
7227 AddToWorklist(X.getNode());
7229 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7230 VT, N0.getOperand(0));
7231 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7232 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7233 AddToWorklist(Cst.getNode());
7235 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7239 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7240 if (N0.getOpcode() == ISD::BUILD_PAIR) {
7241 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7242 if (CombineLD.getNode())
7246 // Remove double bitcasts from shuffles - this is often a legacy of
7247 // XformToShuffleWithZero being used to combine bitmaskings (of
7248 // float vectors bitcast to integer vectors) into shuffles.
7249 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7250 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7251 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7252 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7253 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7254 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7256 // If operands are a bitcast, peek through if it casts the original VT.
7257 // If operands are a UNDEF or constant, just bitcast back to original VT.
7258 auto PeekThroughBitcast = [&](SDValue Op) {
7259 if (Op.getOpcode() == ISD::BITCAST &&
7260 Op.getOperand(0)->getValueType(0) == VT)
7261 return SDValue(Op.getOperand(0));
7262 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7263 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7264 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7268 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7269 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7274 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7275 SmallVector<int, 8> NewMask;
7276 for (int M : SVN->getMask())
7277 for (int i = 0; i != MaskScale; ++i)
7278 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7280 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7282 std::swap(SV0, SV1);
7283 ShuffleVectorSDNode::commuteMask(NewMask);
7284 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7288 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7294 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7295 EVT VT = N->getValueType(0);
7296 return CombineConsecutiveLoads(N, VT);
7299 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7300 /// operands. DstEltVT indicates the destination element value type.
7301 SDValue DAGCombiner::
7302 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7303 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7305 // If this is already the right type, we're done.
7306 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7308 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7309 unsigned DstBitSize = DstEltVT.getSizeInBits();
7311 // If this is a conversion of N elements of one type to N elements of another
7312 // type, convert each element. This handles FP<->INT cases.
7313 if (SrcBitSize == DstBitSize) {
7314 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7315 BV->getValueType(0).getVectorNumElements());
7317 // Due to the FP element handling below calling this routine recursively,
7318 // we can end up with a scalar-to-vector node here.
7319 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7320 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7321 DAG.getNode(ISD::BITCAST, SDLoc(BV),
7322 DstEltVT, BV->getOperand(0)));
7324 SmallVector<SDValue, 8> Ops;
7325 for (SDValue Op : BV->op_values()) {
7326 // If the vector element type is not legal, the BUILD_VECTOR operands
7327 // are promoted and implicitly truncated. Make that explicit here.
7328 if (Op.getValueType() != SrcEltVT)
7329 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7330 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7332 AddToWorklist(Ops.back().getNode());
7334 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7337 // Otherwise, we're growing or shrinking the elements. To avoid having to
7338 // handle annoying details of growing/shrinking FP values, we convert them to
7340 if (SrcEltVT.isFloatingPoint()) {
7341 // Convert the input float vector to a int vector where the elements are the
7343 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7344 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7348 // Now we know the input is an integer vector. If the output is a FP type,
7349 // convert to integer first, then to FP of the right size.
7350 if (DstEltVT.isFloatingPoint()) {
7351 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7352 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7354 // Next, convert to FP elements of the same size.
7355 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7360 // Okay, we know the src/dst types are both integers of differing types.
7361 // Handling growing first.
7362 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7363 if (SrcBitSize < DstBitSize) {
7364 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7366 SmallVector<SDValue, 8> Ops;
7367 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7368 i += NumInputsPerOutput) {
7369 bool isLE = TLI.isLittleEndian();
7370 APInt NewBits = APInt(DstBitSize, 0);
7371 bool EltIsUndef = true;
7372 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7373 // Shift the previously computed bits over.
7374 NewBits <<= SrcBitSize;
7375 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7376 if (Op.getOpcode() == ISD::UNDEF) continue;
7379 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7380 zextOrTrunc(SrcBitSize).zext(DstBitSize);
7384 Ops.push_back(DAG.getUNDEF(DstEltVT));
7386 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7389 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7390 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7393 // Finally, this must be the case where we are shrinking elements: each input
7394 // turns into multiple outputs.
7395 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7396 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7397 NumOutputsPerInput*BV->getNumOperands());
7398 SmallVector<SDValue, 8> Ops;
7400 for (const SDValue &Op : BV->op_values()) {
7401 if (Op.getOpcode() == ISD::UNDEF) {
7402 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7406 APInt OpVal = cast<ConstantSDNode>(Op)->
7407 getAPIntValue().zextOrTrunc(SrcBitSize);
7409 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7410 APInt ThisVal = OpVal.trunc(DstBitSize);
7411 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7412 OpVal = OpVal.lshr(DstBitSize);
7415 // For big endian targets, swap the order of the pieces of each element.
7416 if (TLI.isBigEndian())
7417 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7420 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7423 /// Try to perform FMA combining on a given FADD node.
7424 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7425 SDValue N0 = N->getOperand(0);
7426 SDValue N1 = N->getOperand(1);
7427 EVT VT = N->getValueType(0);
7430 const TargetOptions &Options = DAG.getTarget().Options;
7431 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7432 Options.UnsafeFPMath);
7434 // Floating-point multiply-add with intermediate rounding.
7435 bool HasFMAD = (LegalOperations &&
7436 TLI.isOperationLegal(ISD::FMAD, VT));
7438 // Floating-point multiply-add without intermediate rounding.
7439 bool HasFMA = ((!LegalOperations ||
7440 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7441 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7444 // No valid opcode, do not combine.
7445 if (!HasFMAD && !HasFMA)
7448 // Always prefer FMAD to FMA for precision.
7449 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7450 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7451 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7453 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7454 if (N0.getOpcode() == ISD::FMUL &&
7455 (Aggressive || N0->hasOneUse())) {
7456 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7457 N0.getOperand(0), N0.getOperand(1), N1);
7460 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7461 // Note: Commutes FADD operands.
7462 if (N1.getOpcode() == ISD::FMUL &&
7463 (Aggressive || N1->hasOneUse())) {
7464 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7465 N1.getOperand(0), N1.getOperand(1), N0);
7468 // Look through FP_EXTEND nodes to do more combining.
7469 if (UnsafeFPMath && LookThroughFPExt) {
7470 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7471 if (N0.getOpcode() == ISD::FP_EXTEND) {
7472 SDValue N00 = N0.getOperand(0);
7473 if (N00.getOpcode() == ISD::FMUL)
7474 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7475 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7477 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7478 N00.getOperand(1)), N1);
7481 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7482 // Note: Commutes FADD operands.
7483 if (N1.getOpcode() == ISD::FP_EXTEND) {
7484 SDValue N10 = N1.getOperand(0);
7485 if (N10.getOpcode() == ISD::FMUL)
7486 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7487 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7489 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7490 N10.getOperand(1)), N0);
7494 // More folding opportunities when target permits.
7495 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7496 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7497 if (N0.getOpcode() == PreferredFusedOpcode &&
7498 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7499 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7500 N0.getOperand(0), N0.getOperand(1),
7501 DAG.getNode(PreferredFusedOpcode, SL, VT,
7502 N0.getOperand(2).getOperand(0),
7503 N0.getOperand(2).getOperand(1),
7507 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7508 if (N1->getOpcode() == PreferredFusedOpcode &&
7509 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7510 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7511 N1.getOperand(0), N1.getOperand(1),
7512 DAG.getNode(PreferredFusedOpcode, SL, VT,
7513 N1.getOperand(2).getOperand(0),
7514 N1.getOperand(2).getOperand(1),
7518 if (UnsafeFPMath && LookThroughFPExt) {
7519 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7520 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7521 auto FoldFAddFMAFPExtFMul = [&] (
7522 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7523 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7524 DAG.getNode(PreferredFusedOpcode, SL, VT,
7525 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7526 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7529 if (N0.getOpcode() == PreferredFusedOpcode) {
7530 SDValue N02 = N0.getOperand(2);
7531 if (N02.getOpcode() == ISD::FP_EXTEND) {
7532 SDValue N020 = N02.getOperand(0);
7533 if (N020.getOpcode() == ISD::FMUL)
7534 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7535 N020.getOperand(0), N020.getOperand(1),
7540 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7541 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7542 // FIXME: This turns two single-precision and one double-precision
7543 // operation into two double-precision operations, which might not be
7544 // interesting for all targets, especially GPUs.
7545 auto FoldFAddFPExtFMAFMul = [&] (
7546 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7547 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7548 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7549 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7550 DAG.getNode(PreferredFusedOpcode, SL, VT,
7551 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7552 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7555 if (N0.getOpcode() == ISD::FP_EXTEND) {
7556 SDValue N00 = N0.getOperand(0);
7557 if (N00.getOpcode() == PreferredFusedOpcode) {
7558 SDValue N002 = N00.getOperand(2);
7559 if (N002.getOpcode() == ISD::FMUL)
7560 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7561 N002.getOperand(0), N002.getOperand(1),
7566 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7567 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7568 if (N1.getOpcode() == PreferredFusedOpcode) {
7569 SDValue N12 = N1.getOperand(2);
7570 if (N12.getOpcode() == ISD::FP_EXTEND) {
7571 SDValue N120 = N12.getOperand(0);
7572 if (N120.getOpcode() == ISD::FMUL)
7573 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7574 N120.getOperand(0), N120.getOperand(1),
7579 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7580 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7581 // FIXME: This turns two single-precision and one double-precision
7582 // operation into two double-precision operations, which might not be
7583 // interesting for all targets, especially GPUs.
7584 if (N1.getOpcode() == ISD::FP_EXTEND) {
7585 SDValue N10 = N1.getOperand(0);
7586 if (N10.getOpcode() == PreferredFusedOpcode) {
7587 SDValue N102 = N10.getOperand(2);
7588 if (N102.getOpcode() == ISD::FMUL)
7589 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7590 N102.getOperand(0), N102.getOperand(1),
7600 /// Try to perform FMA combining on a given FSUB node.
7601 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7602 SDValue N0 = N->getOperand(0);
7603 SDValue N1 = N->getOperand(1);
7604 EVT VT = N->getValueType(0);
7607 const TargetOptions &Options = DAG.getTarget().Options;
7608 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7609 Options.UnsafeFPMath);
7611 // Floating-point multiply-add with intermediate rounding.
7612 bool HasFMAD = (LegalOperations &&
7613 TLI.isOperationLegal(ISD::FMAD, VT));
7615 // Floating-point multiply-add without intermediate rounding.
7616 bool HasFMA = ((!LegalOperations ||
7617 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7618 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7621 // No valid opcode, do not combine.
7622 if (!HasFMAD && !HasFMA)
7625 // Always prefer FMAD to FMA for precision.
7626 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7627 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7628 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7630 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7631 if (N0.getOpcode() == ISD::FMUL &&
7632 (Aggressive || N0->hasOneUse())) {
7633 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7634 N0.getOperand(0), N0.getOperand(1),
7635 DAG.getNode(ISD::FNEG, SL, VT, N1));
7638 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7639 // Note: Commutes FSUB operands.
7640 if (N1.getOpcode() == ISD::FMUL &&
7641 (Aggressive || N1->hasOneUse()))
7642 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7643 DAG.getNode(ISD::FNEG, SL, VT,
7645 N1.getOperand(1), N0);
7647 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7648 if (N0.getOpcode() == ISD::FNEG &&
7649 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7650 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7651 SDValue N00 = N0.getOperand(0).getOperand(0);
7652 SDValue N01 = N0.getOperand(0).getOperand(1);
7653 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7654 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7655 DAG.getNode(ISD::FNEG, SL, VT, N1));
7658 // Look through FP_EXTEND nodes to do more combining.
7659 if (UnsafeFPMath && LookThroughFPExt) {
7660 // fold (fsub (fpext (fmul x, y)), z)
7661 // -> (fma (fpext x), (fpext y), (fneg z))
7662 if (N0.getOpcode() == ISD::FP_EXTEND) {
7663 SDValue N00 = N0.getOperand(0);
7664 if (N00.getOpcode() == ISD::FMUL)
7665 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7666 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7668 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7670 DAG.getNode(ISD::FNEG, SL, VT, N1));
7673 // fold (fsub x, (fpext (fmul y, z)))
7674 // -> (fma (fneg (fpext y)), (fpext z), x)
7675 // Note: Commutes FSUB operands.
7676 if (N1.getOpcode() == ISD::FP_EXTEND) {
7677 SDValue N10 = N1.getOperand(0);
7678 if (N10.getOpcode() == ISD::FMUL)
7679 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7680 DAG.getNode(ISD::FNEG, SL, VT,
7681 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7682 N10.getOperand(0))),
7683 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7688 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7689 // -> (fneg (fma (fpext x), (fpext y), z))
7690 // Note: This could be removed with appropriate canonicalization of the
7691 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7692 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7693 // from implementing the canonicalization in visitFSUB.
7694 if (N0.getOpcode() == ISD::FP_EXTEND) {
7695 SDValue N00 = N0.getOperand(0);
7696 if (N00.getOpcode() == ISD::FNEG) {
7697 SDValue N000 = N00.getOperand(0);
7698 if (N000.getOpcode() == ISD::FMUL) {
7699 return DAG.getNode(ISD::FNEG, SL, VT,
7700 DAG.getNode(PreferredFusedOpcode, SL, VT,
7701 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7702 N000.getOperand(0)),
7703 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7704 N000.getOperand(1)),
7710 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7711 // -> (fneg (fma (fpext x)), (fpext y), z)
7712 // Note: This could be removed with appropriate canonicalization of the
7713 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7714 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7715 // from implementing the canonicalization in visitFSUB.
7716 if (N0.getOpcode() == ISD::FNEG) {
7717 SDValue N00 = N0.getOperand(0);
7718 if (N00.getOpcode() == ISD::FP_EXTEND) {
7719 SDValue N000 = N00.getOperand(0);
7720 if (N000.getOpcode() == ISD::FMUL) {
7721 return DAG.getNode(ISD::FNEG, SL, VT,
7722 DAG.getNode(PreferredFusedOpcode, SL, VT,
7723 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7724 N000.getOperand(0)),
7725 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7726 N000.getOperand(1)),
7734 // More folding opportunities when target permits.
7735 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7736 // fold (fsub (fma x, y, (fmul u, v)), z)
7737 // -> (fma x, y (fma u, v, (fneg z)))
7738 if (N0.getOpcode() == PreferredFusedOpcode &&
7739 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7740 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7741 N0.getOperand(0), N0.getOperand(1),
7742 DAG.getNode(PreferredFusedOpcode, SL, VT,
7743 N0.getOperand(2).getOperand(0),
7744 N0.getOperand(2).getOperand(1),
7745 DAG.getNode(ISD::FNEG, SL, VT,
7749 // fold (fsub x, (fma y, z, (fmul u, v)))
7750 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7751 if (N1.getOpcode() == PreferredFusedOpcode &&
7752 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7753 SDValue N20 = N1.getOperand(2).getOperand(0);
7754 SDValue N21 = N1.getOperand(2).getOperand(1);
7755 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7756 DAG.getNode(ISD::FNEG, SL, VT,
7759 DAG.getNode(PreferredFusedOpcode, SL, VT,
7760 DAG.getNode(ISD::FNEG, SL, VT, N20),
7765 if (UnsafeFPMath && LookThroughFPExt) {
7766 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7767 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7768 if (N0.getOpcode() == PreferredFusedOpcode) {
7769 SDValue N02 = N0.getOperand(2);
7770 if (N02.getOpcode() == ISD::FP_EXTEND) {
7771 SDValue N020 = N02.getOperand(0);
7772 if (N020.getOpcode() == ISD::FMUL)
7773 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7774 N0.getOperand(0), N0.getOperand(1),
7775 DAG.getNode(PreferredFusedOpcode, SL, VT,
7776 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7777 N020.getOperand(0)),
7778 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7779 N020.getOperand(1)),
7780 DAG.getNode(ISD::FNEG, SL, VT,
7785 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7786 // -> (fma (fpext x), (fpext y),
7787 // (fma (fpext u), (fpext v), (fneg z)))
7788 // FIXME: This turns two single-precision and one double-precision
7789 // operation into two double-precision operations, which might not be
7790 // interesting for all targets, especially GPUs.
7791 if (N0.getOpcode() == ISD::FP_EXTEND) {
7792 SDValue N00 = N0.getOperand(0);
7793 if (N00.getOpcode() == PreferredFusedOpcode) {
7794 SDValue N002 = N00.getOperand(2);
7795 if (N002.getOpcode() == ISD::FMUL)
7796 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7797 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7799 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7801 DAG.getNode(PreferredFusedOpcode, SL, VT,
7802 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7803 N002.getOperand(0)),
7804 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7805 N002.getOperand(1)),
7806 DAG.getNode(ISD::FNEG, SL, VT,
7811 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7812 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7813 if (N1.getOpcode() == PreferredFusedOpcode &&
7814 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7815 SDValue N120 = N1.getOperand(2).getOperand(0);
7816 if (N120.getOpcode() == ISD::FMUL) {
7817 SDValue N1200 = N120.getOperand(0);
7818 SDValue N1201 = N120.getOperand(1);
7819 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7820 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7822 DAG.getNode(PreferredFusedOpcode, SL, VT,
7823 DAG.getNode(ISD::FNEG, SL, VT,
7824 DAG.getNode(ISD::FP_EXTEND, SL,
7826 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7832 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7833 // -> (fma (fneg (fpext y)), (fpext z),
7834 // (fma (fneg (fpext u)), (fpext v), x))
7835 // FIXME: This turns two single-precision and one double-precision
7836 // operation into two double-precision operations, which might not be
7837 // interesting for all targets, especially GPUs.
7838 if (N1.getOpcode() == ISD::FP_EXTEND &&
7839 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7840 SDValue N100 = N1.getOperand(0).getOperand(0);
7841 SDValue N101 = N1.getOperand(0).getOperand(1);
7842 SDValue N102 = N1.getOperand(0).getOperand(2);
7843 if (N102.getOpcode() == ISD::FMUL) {
7844 SDValue N1020 = N102.getOperand(0);
7845 SDValue N1021 = N102.getOperand(1);
7846 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7847 DAG.getNode(ISD::FNEG, SL, VT,
7848 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7850 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7851 DAG.getNode(PreferredFusedOpcode, SL, VT,
7852 DAG.getNode(ISD::FNEG, SL, VT,
7853 DAG.getNode(ISD::FP_EXTEND, SL,
7855 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7866 SDValue DAGCombiner::visitFADD(SDNode *N) {
7867 SDValue N0 = N->getOperand(0);
7868 SDValue N1 = N->getOperand(1);
7869 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7870 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7871 EVT VT = N->getValueType(0);
7873 const TargetOptions &Options = DAG.getTarget().Options;
7877 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7880 // fold (fadd c1, c2) -> c1 + c2
7882 return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7884 // canonicalize constant to RHS
7885 if (N0CFP && !N1CFP)
7886 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7888 // fold (fadd A, (fneg B)) -> (fsub A, B)
7889 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7890 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7891 return DAG.getNode(ISD::FSUB, DL, VT, N0,
7892 GetNegatedExpression(N1, DAG, LegalOperations));
7894 // fold (fadd (fneg A), B) -> (fsub B, A)
7895 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7896 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7897 return DAG.getNode(ISD::FSUB, DL, VT, N1,
7898 GetNegatedExpression(N0, DAG, LegalOperations));
7900 // If 'unsafe math' is enabled, fold lots of things.
7901 if (Options.UnsafeFPMath) {
7902 // No FP constant should be created after legalization as Instruction
7903 // Selection pass has a hard time dealing with FP constants.
7904 bool AllowNewConst = (Level < AfterLegalizeDAG);
7906 // fold (fadd A, 0) -> A
7907 if (N1CFP && N1CFP->isZero())
7910 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7911 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7912 isa<ConstantFPSDNode>(N0.getOperand(1)))
7913 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7914 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7916 // If allowed, fold (fadd (fneg x), x) -> 0.0
7917 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7918 return DAG.getConstantFP(0.0, DL, VT);
7920 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7921 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7922 return DAG.getConstantFP(0.0, DL, VT);
7924 // We can fold chains of FADD's of the same value into multiplications.
7925 // This transform is not safe in general because we are reducing the number
7926 // of rounding steps.
7927 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7928 if (N0.getOpcode() == ISD::FMUL) {
7929 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7930 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7932 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7933 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7934 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7935 DAG.getConstantFP(1.0, DL, VT));
7936 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7939 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7940 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7941 N1.getOperand(0) == N1.getOperand(1) &&
7942 N0.getOperand(0) == N1.getOperand(0)) {
7943 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7944 DAG.getConstantFP(2.0, DL, VT));
7945 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7949 if (N1.getOpcode() == ISD::FMUL) {
7950 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7951 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7953 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7954 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7955 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7956 DAG.getConstantFP(1.0, DL, VT));
7957 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7960 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7961 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7962 N0.getOperand(0) == N0.getOperand(1) &&
7963 N1.getOperand(0) == N0.getOperand(0)) {
7964 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7965 DAG.getConstantFP(2.0, DL, VT));
7966 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7970 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7971 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7972 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7973 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7974 (N0.getOperand(0) == N1)) {
7975 return DAG.getNode(ISD::FMUL, DL, VT,
7976 N1, DAG.getConstantFP(3.0, DL, VT));
7980 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7981 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7982 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7983 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7984 N1.getOperand(0) == N0) {
7985 return DAG.getNode(ISD::FMUL, DL, VT,
7986 N0, DAG.getConstantFP(3.0, DL, VT));
7990 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7991 if (AllowNewConst &&
7992 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7993 N0.getOperand(0) == N0.getOperand(1) &&
7994 N1.getOperand(0) == N1.getOperand(1) &&
7995 N0.getOperand(0) == N1.getOperand(0)) {
7996 return DAG.getNode(ISD::FMUL, DL, VT,
7997 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
8000 } // enable-unsafe-fp-math
8002 // FADD -> FMA combines:
8003 SDValue Fused = visitFADDForFMACombine(N);
8005 AddToWorklist(Fused.getNode());
8012 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8013 SDValue N0 = N->getOperand(0);
8014 SDValue N1 = N->getOperand(1);
8015 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8016 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8017 EVT VT = N->getValueType(0);
8019 const TargetOptions &Options = DAG.getTarget().Options;
8023 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8026 // fold (fsub c1, c2) -> c1-c2
8028 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
8030 // fold (fsub A, (fneg B)) -> (fadd A, B)
8031 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8032 return DAG.getNode(ISD::FADD, dl, VT, N0,
8033 GetNegatedExpression(N1, DAG, LegalOperations));
8035 // If 'unsafe math' is enabled, fold lots of things.
8036 if (Options.UnsafeFPMath) {
8038 if (N1CFP && N1CFP->isZero())
8041 // (fsub 0, B) -> -B
8042 if (N0CFP && N0CFP->isZero()) {
8043 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8044 return GetNegatedExpression(N1, DAG, LegalOperations);
8045 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8046 return DAG.getNode(ISD::FNEG, dl, VT, N1);
8049 // (fsub x, x) -> 0.0
8051 return DAG.getConstantFP(0.0f, dl, VT);
8053 // (fsub x, (fadd x, y)) -> (fneg y)
8054 // (fsub x, (fadd y, x)) -> (fneg y)
8055 if (N1.getOpcode() == ISD::FADD) {
8056 SDValue N10 = N1->getOperand(0);
8057 SDValue N11 = N1->getOperand(1);
8059 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8060 return GetNegatedExpression(N11, DAG, LegalOperations);
8062 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8063 return GetNegatedExpression(N10, DAG, LegalOperations);
8067 // FSUB -> FMA combines:
8068 SDValue Fused = visitFSUBForFMACombine(N);
8070 AddToWorklist(Fused.getNode());
8077 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8078 SDValue N0 = N->getOperand(0);
8079 SDValue N1 = N->getOperand(1);
8080 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8081 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8082 EVT VT = N->getValueType(0);
8084 const TargetOptions &Options = DAG.getTarget().Options;
8087 if (VT.isVector()) {
8088 // This just handles C1 * C2 for vectors. Other vector folds are below.
8089 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8093 // fold (fmul c1, c2) -> c1*c2
8095 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8097 // canonicalize constant to RHS
8098 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8099 !isConstantFPBuildVectorOrConstantFP(N1))
8100 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8102 // fold (fmul A, 1.0) -> A
8103 if (N1CFP && N1CFP->isExactlyValue(1.0))
8106 if (Options.UnsafeFPMath) {
8107 // fold (fmul A, 0) -> 0
8108 if (N1CFP && N1CFP->isZero())
8111 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8112 if (N0.getOpcode() == ISD::FMUL) {
8113 // Fold scalars or any vector constants (not just splats).
8114 // This fold is done in general by InstCombine, but extra fmul insts
8115 // may have been generated during lowering.
8116 SDValue N00 = N0.getOperand(0);
8117 SDValue N01 = N0.getOperand(1);
8118 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8119 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8120 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8122 // Check 1: Make sure that the first operand of the inner multiply is NOT
8123 // a constant. Otherwise, we may induce infinite looping.
8124 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8125 // Check 2: Make sure that the second operand of the inner multiply and
8126 // the second operand of the outer multiply are constants.
8127 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8128 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8129 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8130 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8135 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8136 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8137 // during an early run of DAGCombiner can prevent folding with fmuls
8138 // inserted during lowering.
8139 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8140 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8141 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8142 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8146 // fold (fmul X, 2.0) -> (fadd X, X)
8147 if (N1CFP && N1CFP->isExactlyValue(+2.0))
8148 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8150 // fold (fmul X, -1.0) -> (fneg X)
8151 if (N1CFP && N1CFP->isExactlyValue(-1.0))
8152 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8153 return DAG.getNode(ISD::FNEG, DL, VT, N0);
8155 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8156 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8157 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8158 // Both can be negated for free, check to see if at least one is cheaper
8160 if (LHSNeg == 2 || RHSNeg == 2)
8161 return DAG.getNode(ISD::FMUL, DL, VT,
8162 GetNegatedExpression(N0, DAG, LegalOperations),
8163 GetNegatedExpression(N1, DAG, LegalOperations));
8170 SDValue DAGCombiner::visitFMA(SDNode *N) {
8171 SDValue N0 = N->getOperand(0);
8172 SDValue N1 = N->getOperand(1);
8173 SDValue N2 = N->getOperand(2);
8174 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8175 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8176 EVT VT = N->getValueType(0);
8178 const TargetOptions &Options = DAG.getTarget().Options;
8180 // Constant fold FMA.
8181 if (isa<ConstantFPSDNode>(N0) &&
8182 isa<ConstantFPSDNode>(N1) &&
8183 isa<ConstantFPSDNode>(N2)) {
8184 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8187 if (Options.UnsafeFPMath) {
8188 if (N0CFP && N0CFP->isZero())
8190 if (N1CFP && N1CFP->isZero())
8193 if (N0CFP && N0CFP->isExactlyValue(1.0))
8194 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8195 if (N1CFP && N1CFP->isExactlyValue(1.0))
8196 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8198 // Canonicalize (fma c, x, y) -> (fma x, c, y)
8199 if (N0CFP && !N1CFP)
8200 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8202 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8203 if (Options.UnsafeFPMath && N1CFP &&
8204 N2.getOpcode() == ISD::FMUL &&
8205 N0 == N2.getOperand(0) &&
8206 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8207 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8208 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8212 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8213 if (Options.UnsafeFPMath &&
8214 N0.getOpcode() == ISD::FMUL && N1CFP &&
8215 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8216 return DAG.getNode(ISD::FMA, dl, VT,
8218 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8222 // (fma x, 1, y) -> (fadd x, y)
8223 // (fma x, -1, y) -> (fadd (fneg x), y)
8225 if (N1CFP->isExactlyValue(1.0))
8226 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8228 if (N1CFP->isExactlyValue(-1.0) &&
8229 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8230 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8231 AddToWorklist(RHSNeg.getNode());
8232 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8236 // (fma x, c, x) -> (fmul x, (c+1))
8237 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8238 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8239 DAG.getNode(ISD::FADD, dl, VT,
8240 N1, DAG.getConstantFP(1.0, dl, VT)));
8242 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8243 if (Options.UnsafeFPMath && N1CFP &&
8244 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8245 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8246 DAG.getNode(ISD::FADD, dl, VT,
8247 N1, DAG.getConstantFP(-1.0, dl, VT)));
8253 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8254 SDValue N0 = N->getOperand(0);
8255 SDValue N1 = N->getOperand(1);
8256 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8257 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8258 EVT VT = N->getValueType(0);
8260 const TargetOptions &Options = DAG.getTarget().Options;
8264 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8267 // fold (fdiv c1, c2) -> c1/c2
8269 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8271 if (Options.UnsafeFPMath) {
8272 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8274 // Compute the reciprocal 1.0 / c2.
8275 APFloat N1APF = N1CFP->getValueAPF();
8276 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8277 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8278 // Only do the transform if the reciprocal is a legal fp immediate that
8279 // isn't too nasty (eg NaN, denormal, ...).
8280 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8281 (!LegalOperations ||
8282 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8283 // backend)... we should handle this gracefully after Legalize.
8284 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8285 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8286 TLI.isFPImmLegal(Recip, VT)))
8287 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8288 DAG.getConstantFP(Recip, DL, VT));
8291 // If this FDIV is part of a reciprocal square root, it may be folded
8292 // into a target-specific square root estimate instruction.
8293 if (N1.getOpcode() == ISD::FSQRT) {
8294 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8295 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8297 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8298 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8299 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8300 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8301 AddToWorklist(RV.getNode());
8302 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8304 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8305 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8306 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8307 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8308 AddToWorklist(RV.getNode());
8309 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8311 } else if (N1.getOpcode() == ISD::FMUL) {
8312 // Look through an FMUL. Even though this won't remove the FDIV directly,
8313 // it's still worthwhile to get rid of the FSQRT if possible.
8316 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8317 SqrtOp = N1.getOperand(0);
8318 OtherOp = N1.getOperand(1);
8319 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8320 SqrtOp = N1.getOperand(1);
8321 OtherOp = N1.getOperand(0);
8323 if (SqrtOp.getNode()) {
8324 // We found a FSQRT, so try to make this fold:
8325 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8326 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8327 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8328 AddToWorklist(RV.getNode());
8329 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8334 // Fold into a reciprocal estimate and multiply instead of a real divide.
8335 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8336 AddToWorklist(RV.getNode());
8337 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8341 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8342 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8343 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8344 // Both can be negated for free, check to see if at least one is cheaper
8346 if (LHSNeg == 2 || RHSNeg == 2)
8347 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8348 GetNegatedExpression(N0, DAG, LegalOperations),
8349 GetNegatedExpression(N1, DAG, LegalOperations));
8353 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8355 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8356 // Notice that this is not always beneficial. One reason is different target
8357 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8358 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8359 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8360 if (Options.UnsafeFPMath) {
8361 // Skip if current node is a reciprocal.
8362 if (N0CFP && N0CFP->isExactlyValue(1.0))
8365 SmallVector<SDNode *, 4> Users;
8366 // Find all FDIV users of the same divisor.
8367 for (auto *U : N1->uses()) {
8368 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8372 if (TLI.combineRepeatedFPDivisors(Users.size())) {
8373 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8374 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8376 // Dividend / Divisor -> Dividend * Reciprocal
8377 for (auto *U : Users) {
8378 SDValue Dividend = U->getOperand(0);
8379 if (Dividend != FPOne) {
8380 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8382 DAG.ReplaceAllUsesWith(U, NewNode.getNode());
8392 SDValue DAGCombiner::visitFREM(SDNode *N) {
8393 SDValue N0 = N->getOperand(0);
8394 SDValue N1 = N->getOperand(1);
8395 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8396 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8397 EVT VT = N->getValueType(0);
8399 // fold (frem c1, c2) -> fmod(c1,c2)
8401 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8406 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8407 if (DAG.getTarget().Options.UnsafeFPMath &&
8408 !TLI.isFsqrtCheap()) {
8409 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8410 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8411 EVT VT = RV.getValueType();
8413 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8414 AddToWorklist(RV.getNode());
8416 // Unfortunately, RV is now NaN if the input was exactly 0.
8417 // Select out this case and force the answer to 0.
8418 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8420 DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8421 N->getOperand(0), Zero, ISD::SETEQ);
8422 AddToWorklist(ZeroCmp.getNode());
8423 AddToWorklist(RV.getNode());
8425 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8426 DL, VT, ZeroCmp, Zero, RV);
8433 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8434 SDValue N0 = N->getOperand(0);
8435 SDValue N1 = N->getOperand(1);
8436 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8437 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8438 EVT VT = N->getValueType(0);
8440 if (N0CFP && N1CFP) // Constant fold
8441 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8444 const APFloat& V = N1CFP->getValueAPF();
8445 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8446 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8447 if (!V.isNegative()) {
8448 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8449 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8451 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8452 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8453 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8457 // copysign(fabs(x), y) -> copysign(x, y)
8458 // copysign(fneg(x), y) -> copysign(x, y)
8459 // copysign(copysign(x,z), y) -> copysign(x, y)
8460 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8461 N0.getOpcode() == ISD::FCOPYSIGN)
8462 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8463 N0.getOperand(0), N1);
8465 // copysign(x, abs(y)) -> abs(x)
8466 if (N1.getOpcode() == ISD::FABS)
8467 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8469 // copysign(x, copysign(y,z)) -> copysign(x, z)
8470 if (N1.getOpcode() == ISD::FCOPYSIGN)
8471 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8472 N0, N1.getOperand(1));
8474 // copysign(x, fp_extend(y)) -> copysign(x, y)
8475 // copysign(x, fp_round(y)) -> copysign(x, y)
8476 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8477 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8478 N0, N1.getOperand(0));
8483 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8484 SDValue N0 = N->getOperand(0);
8485 EVT VT = N->getValueType(0);
8486 EVT OpVT = N0.getValueType();
8488 // fold (sint_to_fp c1) -> c1fp
8489 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8490 // ...but only if the target supports immediate floating-point values
8491 (!LegalOperations ||
8492 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8493 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8495 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8496 // but UINT_TO_FP is legal on this target, try to convert.
8497 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8498 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8499 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8500 if (DAG.SignBitIsZero(N0))
8501 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8504 // The next optimizations are desirable only if SELECT_CC can be lowered.
8505 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8506 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8507 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8509 (!LegalOperations ||
8510 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8513 { N0.getOperand(0), N0.getOperand(1),
8514 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8516 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8519 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8520 // (select_cc x, y, 1.0, 0.0,, cc)
8521 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8522 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8523 (!LegalOperations ||
8524 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8527 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8528 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8529 N0.getOperand(0).getOperand(2) };
8530 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8537 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8538 SDValue N0 = N->getOperand(0);
8539 EVT VT = N->getValueType(0);
8540 EVT OpVT = N0.getValueType();
8542 // fold (uint_to_fp c1) -> c1fp
8543 if (isConstantIntBuildVectorOrConstantInt(N0) &&
8544 // ...but only if the target supports immediate floating-point values
8545 (!LegalOperations ||
8546 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8547 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8549 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8550 // but SINT_TO_FP is legal on this target, try to convert.
8551 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8552 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8553 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8554 if (DAG.SignBitIsZero(N0))
8555 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8558 // The next optimizations are desirable only if SELECT_CC can be lowered.
8559 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8560 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8562 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8563 (!LegalOperations ||
8564 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8567 { N0.getOperand(0), N0.getOperand(1),
8568 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8570 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8577 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8578 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8579 SDValue N0 = N->getOperand(0);
8580 EVT VT = N->getValueType(0);
8582 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8585 SDValue Src = N0.getOperand(0);
8586 EVT SrcVT = Src.getValueType();
8587 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8588 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8590 // We can safely assume the conversion won't overflow the output range,
8591 // because (for example) (uint8_t)18293.f is undefined behavior.
8593 // Since we can assume the conversion won't overflow, our decision as to
8594 // whether the input will fit in the float should depend on the minimum
8595 // of the input range and output range.
8597 // This means this is also safe for a signed input and unsigned output, since
8598 // a negative input would lead to undefined behavior.
8599 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8600 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8601 unsigned ActualSize = std::min(InputSize, OutputSize);
8602 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8604 // We can only fold away the float conversion if the input range can be
8605 // represented exactly in the float range.
8606 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8607 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8608 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8610 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8612 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8613 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8616 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8621 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8622 SDValue N0 = N->getOperand(0);
8623 EVT VT = N->getValueType(0);
8625 // fold (fp_to_sint c1fp) -> c1
8626 if (isConstantFPBuildVectorOrConstantFP(N0))
8627 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8629 return FoldIntToFPToInt(N, DAG);
8632 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8633 SDValue N0 = N->getOperand(0);
8634 EVT VT = N->getValueType(0);
8636 // fold (fp_to_uint c1fp) -> c1
8637 if (isConstantFPBuildVectorOrConstantFP(N0))
8638 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8640 return FoldIntToFPToInt(N, DAG);
8643 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8644 SDValue N0 = N->getOperand(0);
8645 SDValue N1 = N->getOperand(1);
8646 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8647 EVT VT = N->getValueType(0);
8649 // fold (fp_round c1fp) -> c1fp
8651 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8653 // fold (fp_round (fp_extend x)) -> x
8654 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8655 return N0.getOperand(0);
8657 // fold (fp_round (fp_round x)) -> (fp_round x)
8658 if (N0.getOpcode() == ISD::FP_ROUND) {
8659 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8660 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8661 // If the first fp_round isn't a value preserving truncation, it might
8662 // introduce a tie in the second fp_round, that wouldn't occur in the
8663 // single-step fp_round we want to fold to.
8664 // In other words, double rounding isn't the same as rounding.
8665 // Also, this is a value preserving truncation iff both fp_round's are.
8666 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8668 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8669 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8673 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8674 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8675 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8676 N0.getOperand(0), N1);
8677 AddToWorklist(Tmp.getNode());
8678 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8679 Tmp, N0.getOperand(1));
8685 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8686 SDValue N0 = N->getOperand(0);
8687 EVT VT = N->getValueType(0);
8688 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8689 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8691 // fold (fp_round_inreg c1fp) -> c1fp
8692 if (N0CFP && isTypeLegal(EVT)) {
8694 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8695 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8701 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8702 SDValue N0 = N->getOperand(0);
8703 EVT VT = N->getValueType(0);
8705 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8706 if (N->hasOneUse() &&
8707 N->use_begin()->getOpcode() == ISD::FP_ROUND)
8710 // fold (fp_extend c1fp) -> c1fp
8711 if (isConstantFPBuildVectorOrConstantFP(N0))
8712 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8714 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8715 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8716 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8717 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8719 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8721 if (N0.getOpcode() == ISD::FP_ROUND
8722 && N0.getNode()->getConstantOperandVal(1) == 1) {
8723 SDValue In = N0.getOperand(0);
8724 if (In.getValueType() == VT) return In;
8725 if (VT.bitsLT(In.getValueType()))
8726 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8727 In, N0.getOperand(1));
8728 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8731 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8732 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8733 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8734 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8735 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8737 LN0->getBasePtr(), N0.getValueType(),
8738 LN0->getMemOperand());
8739 CombineTo(N, ExtLoad);
8740 CombineTo(N0.getNode(),
8741 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8742 N0.getValueType(), ExtLoad,
8743 DAG.getIntPtrConstant(1, SDLoc(N0))),
8744 ExtLoad.getValue(1));
8745 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8751 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8752 SDValue N0 = N->getOperand(0);
8753 EVT VT = N->getValueType(0);
8755 // fold (fceil c1) -> fceil(c1)
8756 if (isConstantFPBuildVectorOrConstantFP(N0))
8757 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8762 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8763 SDValue N0 = N->getOperand(0);
8764 EVT VT = N->getValueType(0);
8766 // fold (ftrunc c1) -> ftrunc(c1)
8767 if (isConstantFPBuildVectorOrConstantFP(N0))
8768 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8773 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8774 SDValue N0 = N->getOperand(0);
8775 EVT VT = N->getValueType(0);
8777 // fold (ffloor c1) -> ffloor(c1)
8778 if (isConstantFPBuildVectorOrConstantFP(N0))
8779 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8784 // FIXME: FNEG and FABS have a lot in common; refactor.
8785 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8786 SDValue N0 = N->getOperand(0);
8787 EVT VT = N->getValueType(0);
8789 // Constant fold FNEG.
8790 if (isConstantFPBuildVectorOrConstantFP(N0))
8791 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8793 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8794 &DAG.getTarget().Options))
8795 return GetNegatedExpression(N0, DAG, LegalOperations);
8797 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8798 // constant pool values.
8799 if (!TLI.isFNegFree(VT) &&
8800 N0.getOpcode() == ISD::BITCAST &&
8801 N0.getNode()->hasOneUse()) {
8802 SDValue Int = N0.getOperand(0);
8803 EVT IntVT = Int.getValueType();
8804 if (IntVT.isInteger() && !IntVT.isVector()) {
8806 if (N0.getValueType().isVector()) {
8807 // For a vector, get a mask such as 0x80... per scalar element
8809 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8810 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8812 // For a scalar, just generate 0x80...
8813 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8816 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8817 DAG.getConstant(SignMask, DL0, IntVT));
8818 AddToWorklist(Int.getNode());
8819 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8823 // (fneg (fmul c, x)) -> (fmul -c, x)
8824 if (N0.getOpcode() == ISD::FMUL &&
8825 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
8826 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8828 APFloat CVal = CFP1->getValueAPF();
8830 if (Level >= AfterLegalizeDAG &&
8831 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8832 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8834 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8835 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8842 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8843 SDValue N0 = N->getOperand(0);
8844 SDValue N1 = N->getOperand(1);
8845 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8846 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8848 if (N0CFP && N1CFP) {
8849 const APFloat &C0 = N0CFP->getValueAPF();
8850 const APFloat &C1 = N1CFP->getValueAPF();
8851 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8855 EVT VT = N->getValueType(0);
8856 // Canonicalize to constant on RHS.
8857 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8863 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8864 SDValue N0 = N->getOperand(0);
8865 SDValue N1 = N->getOperand(1);
8866 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8867 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8869 if (N0CFP && N1CFP) {
8870 const APFloat &C0 = N0CFP->getValueAPF();
8871 const APFloat &C1 = N1CFP->getValueAPF();
8872 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8876 EVT VT = N->getValueType(0);
8877 // Canonicalize to constant on RHS.
8878 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8884 SDValue DAGCombiner::visitFABS(SDNode *N) {
8885 SDValue N0 = N->getOperand(0);
8886 EVT VT = N->getValueType(0);
8888 // fold (fabs c1) -> fabs(c1)
8889 if (isConstantFPBuildVectorOrConstantFP(N0))
8890 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8892 // fold (fabs (fabs x)) -> (fabs x)
8893 if (N0.getOpcode() == ISD::FABS)
8894 return N->getOperand(0);
8896 // fold (fabs (fneg x)) -> (fabs x)
8897 // fold (fabs (fcopysign x, y)) -> (fabs x)
8898 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8899 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8901 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8902 // constant pool values.
8903 if (!TLI.isFAbsFree(VT) &&
8904 N0.getOpcode() == ISD::BITCAST &&
8905 N0.getNode()->hasOneUse()) {
8906 SDValue Int = N0.getOperand(0);
8907 EVT IntVT = Int.getValueType();
8908 if (IntVT.isInteger() && !IntVT.isVector()) {
8910 if (N0.getValueType().isVector()) {
8911 // For a vector, get a mask such as 0x7f... per scalar element
8913 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8914 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8916 // For a scalar, just generate 0x7f...
8917 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8920 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8921 DAG.getConstant(SignMask, DL, IntVT));
8922 AddToWorklist(Int.getNode());
8923 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8930 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8931 SDValue Chain = N->getOperand(0);
8932 SDValue N1 = N->getOperand(1);
8933 SDValue N2 = N->getOperand(2);
8935 // If N is a constant we could fold this into a fallthrough or unconditional
8936 // branch. However that doesn't happen very often in normal code, because
8937 // Instcombine/SimplifyCFG should have handled the available opportunities.
8938 // If we did this folding here, it would be necessary to update the
8939 // MachineBasicBlock CFG, which is awkward.
8941 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8943 if (N1.getOpcode() == ISD::SETCC &&
8944 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8945 N1.getOperand(0).getValueType())) {
8946 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8947 Chain, N1.getOperand(2),
8948 N1.getOperand(0), N1.getOperand(1), N2);
8951 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8952 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8953 (N1.getOperand(0).hasOneUse() &&
8954 N1.getOperand(0).getOpcode() == ISD::SRL))) {
8955 SDNode *Trunc = nullptr;
8956 if (N1.getOpcode() == ISD::TRUNCATE) {
8957 // Look pass the truncate.
8958 Trunc = N1.getNode();
8959 N1 = N1.getOperand(0);
8962 // Match this pattern so that we can generate simpler code:
8965 // %b = and i32 %a, 2
8966 // %c = srl i32 %b, 1
8967 // brcond i32 %c ...
8972 // %b = and i32 %a, 2
8973 // %c = setcc eq %b, 0
8976 // This applies only when the AND constant value has one bit set and the
8977 // SRL constant is equal to the log2 of the AND constant. The back-end is
8978 // smart enough to convert the result into a TEST/JMP sequence.
8979 SDValue Op0 = N1.getOperand(0);
8980 SDValue Op1 = N1.getOperand(1);
8982 if (Op0.getOpcode() == ISD::AND &&
8983 Op1.getOpcode() == ISD::Constant) {
8984 SDValue AndOp1 = Op0.getOperand(1);
8986 if (AndOp1.getOpcode() == ISD::Constant) {
8987 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8989 if (AndConst.isPowerOf2() &&
8990 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8994 getSetCCResultType(Op0.getValueType()),
8995 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8998 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8999 MVT::Other, Chain, SetCC, N2);
9000 // Don't add the new BRCond into the worklist or else SimplifySelectCC
9001 // will convert it back to (X & C1) >> C2.
9002 CombineTo(N, NewBRCond, false);
9003 // Truncate is dead.
9005 deleteAndRecombine(Trunc);
9006 // Replace the uses of SRL with SETCC
9007 WorklistRemover DeadNodes(*this);
9008 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9009 deleteAndRecombine(N1.getNode());
9010 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9016 // Restore N1 if the above transformation doesn't match.
9017 N1 = N->getOperand(1);
9020 // Transform br(xor(x, y)) -> br(x != y)
9021 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9022 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9023 SDNode *TheXor = N1.getNode();
9024 SDValue Op0 = TheXor->getOperand(0);
9025 SDValue Op1 = TheXor->getOperand(1);
9026 if (Op0.getOpcode() == Op1.getOpcode()) {
9027 // Avoid missing important xor optimizations.
9028 SDValue Tmp = visitXOR(TheXor);
9029 if (Tmp.getNode()) {
9030 if (Tmp.getNode() != TheXor) {
9031 DEBUG(dbgs() << "\nReplacing.8 ";
9033 dbgs() << "\nWith: ";
9034 Tmp.getNode()->dump(&DAG);
9036 WorklistRemover DeadNodes(*this);
9037 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9038 deleteAndRecombine(TheXor);
9039 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9040 MVT::Other, Chain, Tmp, N2);
9043 // visitXOR has changed XOR's operands or replaced the XOR completely,
9045 return SDValue(N, 0);
9049 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9051 if (isOneConstant(Op0) && Op0.hasOneUse() &&
9052 Op0.getOpcode() == ISD::XOR) {
9053 TheXor = Op0.getNode();
9057 EVT SetCCVT = N1.getValueType();
9059 SetCCVT = getSetCCResultType(SetCCVT);
9060 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9063 Equal ? ISD::SETEQ : ISD::SETNE);
9064 // Replace the uses of XOR with SETCC
9065 WorklistRemover DeadNodes(*this);
9066 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9067 deleteAndRecombine(N1.getNode());
9068 return DAG.getNode(ISD::BRCOND, SDLoc(N),
9069 MVT::Other, Chain, SetCC, N2);
9076 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9078 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9079 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9080 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9082 // If N is a constant we could fold this into a fallthrough or unconditional
9083 // branch. However that doesn't happen very often in normal code, because
9084 // Instcombine/SimplifyCFG should have handled the available opportunities.
9085 // If we did this folding here, it would be necessary to update the
9086 // MachineBasicBlock CFG, which is awkward.
9088 // Use SimplifySetCC to simplify SETCC's.
9089 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9090 CondLHS, CondRHS, CC->get(), SDLoc(N),
9092 if (Simp.getNode()) AddToWorklist(Simp.getNode());
9094 // fold to a simpler setcc
9095 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9096 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9097 N->getOperand(0), Simp.getOperand(2),
9098 Simp.getOperand(0), Simp.getOperand(1),
9104 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9105 /// and that N may be folded in the load / store addressing mode.
9106 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9108 const TargetLowering &TLI) {
9112 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9113 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9115 VT = LD->getMemoryVT();
9116 AS = LD->getAddressSpace();
9117 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9118 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9120 VT = ST->getMemoryVT();
9121 AS = ST->getAddressSpace();
9125 TargetLowering::AddrMode AM;
9126 if (N->getOpcode() == ISD::ADD) {
9127 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9130 AM.BaseOffs = Offset->getSExtValue();
9134 } else if (N->getOpcode() == ISD::SUB) {
9135 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9138 AM.BaseOffs = -Offset->getSExtValue();
9145 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()), AS);
9148 /// Try turning a load/store into a pre-indexed load/store when the base
9149 /// pointer is an add or subtract and it has other uses besides the load/store.
9150 /// After the transformation, the new indexed load/store has effectively folded
9151 /// the add/subtract in and all of its other uses are redirected to the
9153 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9154 if (Level < AfterLegalizeDAG)
9160 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9161 if (LD->isIndexed())
9163 VT = LD->getMemoryVT();
9164 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9165 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9167 Ptr = LD->getBasePtr();
9168 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9169 if (ST->isIndexed())
9171 VT = ST->getMemoryVT();
9172 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9173 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9175 Ptr = ST->getBasePtr();
9181 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9182 // out. There is no reason to make this a preinc/predec.
9183 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9184 Ptr.getNode()->hasOneUse())
9187 // Ask the target to do addressing mode selection.
9190 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9191 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9194 // Backends without true r+i pre-indexed forms may need to pass a
9195 // constant base with a variable offset so that constant coercion
9196 // will work with the patterns in canonical form.
9197 bool Swapped = false;
9198 if (isa<ConstantSDNode>(BasePtr)) {
9199 std::swap(BasePtr, Offset);
9203 // Don't create a indexed load / store with zero offset.
9204 if (isNullConstant(Offset))
9207 // Try turning it into a pre-indexed load / store except when:
9208 // 1) The new base ptr is a frame index.
9209 // 2) If N is a store and the new base ptr is either the same as or is a
9210 // predecessor of the value being stored.
9211 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9212 // that would create a cycle.
9213 // 4) All uses are load / store ops that use it as old base ptr.
9215 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9216 // (plus the implicit offset) to a register to preinc anyway.
9217 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9222 SDValue Val = cast<StoreSDNode>(N)->getValue();
9223 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9227 // If the offset is a constant, there may be other adds of constants that
9228 // can be folded with this one. We should do this to avoid having to keep
9229 // a copy of the original base pointer.
9230 SmallVector<SDNode *, 16> OtherUses;
9231 if (isa<ConstantSDNode>(Offset))
9232 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9233 UE = BasePtr.getNode()->use_end();
9235 SDUse &Use = UI.getUse();
9236 // Skip the use that is Ptr and uses of other results from BasePtr's
9237 // node (important for nodes that return multiple results).
9238 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9241 if (Use.getUser()->isPredecessorOf(N))
9244 if (Use.getUser()->getOpcode() != ISD::ADD &&
9245 Use.getUser()->getOpcode() != ISD::SUB) {
9250 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9251 if (!isa<ConstantSDNode>(Op1)) {
9256 // FIXME: In some cases, we can be smarter about this.
9257 if (Op1.getValueType() != Offset.getValueType()) {
9262 OtherUses.push_back(Use.getUser());
9266 std::swap(BasePtr, Offset);
9268 // Now check for #3 and #4.
9269 bool RealUse = false;
9271 // Caches for hasPredecessorHelper
9272 SmallPtrSet<const SDNode *, 32> Visited;
9273 SmallVector<const SDNode *, 16> Worklist;
9275 for (SDNode *Use : Ptr.getNode()->uses()) {
9278 if (N->hasPredecessorHelper(Use, Visited, Worklist))
9281 // If Ptr may be folded in addressing mode of other use, then it's
9282 // not profitable to do this transformation.
9283 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9292 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9293 BasePtr, Offset, AM);
9295 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9296 BasePtr, Offset, AM);
9299 DEBUG(dbgs() << "\nReplacing.4 ";
9301 dbgs() << "\nWith: ";
9302 Result.getNode()->dump(&DAG);
9304 WorklistRemover DeadNodes(*this);
9306 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9307 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9309 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9312 // Finally, since the node is now dead, remove it from the graph.
9313 deleteAndRecombine(N);
9316 std::swap(BasePtr, Offset);
9318 // Replace other uses of BasePtr that can be updated to use Ptr
9319 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9320 unsigned OffsetIdx = 1;
9321 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9323 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9324 BasePtr.getNode() && "Expected BasePtr operand");
9326 // We need to replace ptr0 in the following expression:
9327 // x0 * offset0 + y0 * ptr0 = t0
9329 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9331 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9332 // indexed load/store and the expresion that needs to be re-written.
9334 // Therefore, we have:
9335 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9337 ConstantSDNode *CN =
9338 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9340 APInt Offset0 = CN->getAPIntValue();
9341 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9343 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9344 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9345 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9346 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9348 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9350 APInt CNV = Offset0;
9351 if (X0 < 0) CNV = -CNV;
9352 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9353 else CNV = CNV - Offset1;
9355 SDLoc DL(OtherUses[i]);
9357 // We can now generate the new expression.
9358 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9359 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9361 SDValue NewUse = DAG.getNode(Opcode,
9363 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9364 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9365 deleteAndRecombine(OtherUses[i]);
9368 // Replace the uses of Ptr with uses of the updated base value.
9369 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9370 deleteAndRecombine(Ptr.getNode());
9375 /// Try to combine a load/store with a add/sub of the base pointer node into a
9376 /// post-indexed load/store. The transformation folded the add/subtract into the
9377 /// new indexed load/store effectively and all of its uses are redirected to the
9379 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9380 if (Level < AfterLegalizeDAG)
9386 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9387 if (LD->isIndexed())
9389 VT = LD->getMemoryVT();
9390 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9391 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9393 Ptr = LD->getBasePtr();
9394 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9395 if (ST->isIndexed())
9397 VT = ST->getMemoryVT();
9398 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9399 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9401 Ptr = ST->getBasePtr();
9407 if (Ptr.getNode()->hasOneUse())
9410 for (SDNode *Op : Ptr.getNode()->uses()) {
9412 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9417 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9418 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9419 // Don't create a indexed load / store with zero offset.
9420 if (isNullConstant(Offset))
9423 // Try turning it into a post-indexed load / store except when
9424 // 1) All uses are load / store ops that use it as base ptr (and
9425 // it may be folded as addressing mmode).
9426 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9427 // nor a successor of N. Otherwise, if Op is folded that would
9430 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9434 bool TryNext = false;
9435 for (SDNode *Use : BasePtr.getNode()->uses()) {
9436 if (Use == Ptr.getNode())
9439 // If all the uses are load / store addresses, then don't do the
9441 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9442 bool RealUse = false;
9443 for (SDNode *UseUse : Use->uses()) {
9444 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9459 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9460 SDValue Result = isLoad
9461 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9462 BasePtr, Offset, AM)
9463 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9464 BasePtr, Offset, AM);
9467 DEBUG(dbgs() << "\nReplacing.5 ";
9469 dbgs() << "\nWith: ";
9470 Result.getNode()->dump(&DAG);
9472 WorklistRemover DeadNodes(*this);
9474 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9475 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9477 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9480 // Finally, since the node is now dead, remove it from the graph.
9481 deleteAndRecombine(N);
9483 // Replace the uses of Use with uses of the updated base value.
9484 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9485 Result.getValue(isLoad ? 1 : 0));
9486 deleteAndRecombine(Op);
9495 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9496 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9497 ISD::MemIndexedMode AM = LD->getAddressingMode();
9498 assert(AM != ISD::UNINDEXED);
9499 SDValue BP = LD->getOperand(1);
9500 SDValue Inc = LD->getOperand(2);
9502 // Some backends use TargetConstants for load offsets, but don't expect
9503 // TargetConstants in general ADD nodes. We can convert these constants into
9504 // regular Constants (if the constant is not opaque).
9505 assert((Inc.getOpcode() != ISD::TargetConstant ||
9506 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9507 "Cannot split out indexing using opaque target constants");
9508 if (Inc.getOpcode() == ISD::TargetConstant) {
9509 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9510 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9511 ConstInc->getValueType(0));
9515 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9516 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9519 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9520 LoadSDNode *LD = cast<LoadSDNode>(N);
9521 SDValue Chain = LD->getChain();
9522 SDValue Ptr = LD->getBasePtr();
9524 // If load is not volatile and there are no uses of the loaded value (and
9525 // the updated indexed value in case of indexed loads), change uses of the
9526 // chain value into uses of the chain input (i.e. delete the dead load).
9527 if (!LD->isVolatile()) {
9528 if (N->getValueType(1) == MVT::Other) {
9530 if (!N->hasAnyUseOfValue(0)) {
9531 // It's not safe to use the two value CombineTo variant here. e.g.
9532 // v1, chain2 = load chain1, loc
9533 // v2, chain3 = load chain2, loc
9535 // Now we replace use of chain2 with chain1. This makes the second load
9536 // isomorphic to the one we are deleting, and thus makes this load live.
9537 DEBUG(dbgs() << "\nReplacing.6 ";
9539 dbgs() << "\nWith chain: ";
9540 Chain.getNode()->dump(&DAG);
9542 WorklistRemover DeadNodes(*this);
9543 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9546 deleteAndRecombine(N);
9548 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9552 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9554 // If this load has an opaque TargetConstant offset, then we cannot split
9555 // the indexing into an add/sub directly (that TargetConstant may not be
9556 // valid for a different type of node, and we cannot convert an opaque
9557 // target constant into a regular constant).
9558 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9559 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9561 if (!N->hasAnyUseOfValue(0) &&
9562 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9563 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9565 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9566 Index = SplitIndexingFromLoad(LD);
9567 // Try to fold the base pointer arithmetic into subsequent loads and
9569 AddUsersToWorklist(N);
9571 Index = DAG.getUNDEF(N->getValueType(1));
9572 DEBUG(dbgs() << "\nReplacing.7 ";
9574 dbgs() << "\nWith: ";
9575 Undef.getNode()->dump(&DAG);
9576 dbgs() << " and 2 other values\n");
9577 WorklistRemover DeadNodes(*this);
9578 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9579 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9580 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9581 deleteAndRecombine(N);
9582 return SDValue(N, 0); // Return N so it doesn't get rechecked!
9587 // If this load is directly stored, replace the load value with the stored
9589 // TODO: Handle store large -> read small portion.
9590 // TODO: Handle TRUNCSTORE/LOADEXT
9591 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9592 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9593 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9594 if (PrevST->getBasePtr() == Ptr &&
9595 PrevST->getValue().getValueType() == N->getValueType(0))
9596 return CombineTo(N, Chain.getOperand(1), Chain);
9600 // Try to infer better alignment information than the load already has.
9601 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9602 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9603 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9605 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9606 LD->getValueType(0),
9607 Chain, Ptr, LD->getPointerInfo(),
9609 LD->isVolatile(), LD->isNonTemporal(),
9610 LD->isInvariant(), Align, LD->getAAInfo());
9611 if (NewLoad.getNode() != N)
9612 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9617 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9618 : DAG.getSubtarget().useAA();
9620 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9621 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9624 if (UseAA && LD->isUnindexed()) {
9625 // Walk up chain skipping non-aliasing memory nodes.
9626 SDValue BetterChain = FindBetterChain(N, Chain);
9628 // If there is a better chain.
9629 if (Chain != BetterChain) {
9632 // Replace the chain to void dependency.
9633 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9634 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9635 BetterChain, Ptr, LD->getMemOperand());
9637 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9638 LD->getValueType(0),
9639 BetterChain, Ptr, LD->getMemoryVT(),
9640 LD->getMemOperand());
9643 // Create token factor to keep old chain connected.
9644 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9645 MVT::Other, Chain, ReplLoad.getValue(1));
9647 // Make sure the new and old chains are cleaned up.
9648 AddToWorklist(Token.getNode());
9650 // Replace uses with load result and token factor. Don't add users
9652 return CombineTo(N, ReplLoad.getValue(0), Token, false);
9656 // Try transforming N to an indexed load.
9657 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9658 return SDValue(N, 0);
9660 // Try to slice up N to more direct loads if the slices are mapped to
9661 // different register banks or pairing can take place.
9663 return SDValue(N, 0);
9669 /// \brief Helper structure used to slice a load in smaller loads.
9670 /// Basically a slice is obtained from the following sequence:
9671 /// Origin = load Ty1, Base
9672 /// Shift = srl Ty1 Origin, CstTy Amount
9673 /// Inst = trunc Shift to Ty2
9675 /// Then, it will be rewriten into:
9676 /// Slice = load SliceTy, Base + SliceOffset
9677 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9679 /// SliceTy is deduced from the number of bits that are actually used to
9681 struct LoadedSlice {
9682 /// \brief Helper structure used to compute the cost of a slice.
9684 /// Are we optimizing for code size.
9689 unsigned CrossRegisterBanksCopies;
9693 Cost(bool ForCodeSize = false)
9694 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9695 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9697 /// \brief Get the cost of one isolated slice.
9698 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9699 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9700 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9701 EVT TruncType = LS.Inst->getValueType(0);
9702 EVT LoadedType = LS.getLoadedType();
9703 if (TruncType != LoadedType &&
9704 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9708 /// \brief Account for slicing gain in the current cost.
9709 /// Slicing provide a few gains like removing a shift or a
9710 /// truncate. This method allows to grow the cost of the original
9711 /// load with the gain from this slice.
9712 void addSliceGain(const LoadedSlice &LS) {
9713 // Each slice saves a truncate.
9714 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9715 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9716 LS.Inst->getOperand(0).getValueType()))
9718 // If there is a shift amount, this slice gets rid of it.
9721 // If this slice can merge a cross register bank copy, account for it.
9722 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9723 ++CrossRegisterBanksCopies;
9726 Cost &operator+=(const Cost &RHS) {
9728 Truncates += RHS.Truncates;
9729 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9735 bool operator==(const Cost &RHS) const {
9736 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9737 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9738 ZExts == RHS.ZExts && Shift == RHS.Shift;
9741 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9743 bool operator<(const Cost &RHS) const {
9744 // Assume cross register banks copies are as expensive as loads.
9745 // FIXME: Do we want some more target hooks?
9746 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9747 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9748 // Unless we are optimizing for code size, consider the
9749 // expensive operation first.
9750 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9751 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9752 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9753 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9756 bool operator>(const Cost &RHS) const { return RHS < *this; }
9758 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9760 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9762 // The last instruction that represent the slice. This should be a
9763 // truncate instruction.
9765 // The original load instruction.
9767 // The right shift amount in bits from the original load.
9769 // The DAG from which Origin came from.
9770 // This is used to get some contextual information about legal types, etc.
9773 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9774 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9775 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9777 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9778 /// \return Result is \p BitWidth and has used bits set to 1 and
9779 /// not used bits set to 0.
9780 APInt getUsedBits() const {
9781 // Reproduce the trunc(lshr) sequence:
9782 // - Start from the truncated value.
9783 // - Zero extend to the desired bit width.
9785 assert(Origin && "No original load to compare against.");
9786 unsigned BitWidth = Origin->getValueSizeInBits(0);
9787 assert(Inst && "This slice is not bound to an instruction");
9788 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9789 "Extracted slice is bigger than the whole type!");
9790 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9791 UsedBits.setAllBits();
9792 UsedBits = UsedBits.zext(BitWidth);
9797 /// \brief Get the size of the slice to be loaded in bytes.
9798 unsigned getLoadedSize() const {
9799 unsigned SliceSize = getUsedBits().countPopulation();
9800 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9801 return SliceSize / 8;
9804 /// \brief Get the type that will be loaded for this slice.
9805 /// Note: This may not be the final type for the slice.
9806 EVT getLoadedType() const {
9807 assert(DAG && "Missing context");
9808 LLVMContext &Ctxt = *DAG->getContext();
9809 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9812 /// \brief Get the alignment of the load used for this slice.
9813 unsigned getAlignment() const {
9814 unsigned Alignment = Origin->getAlignment();
9815 unsigned Offset = getOffsetFromBase();
9817 Alignment = MinAlign(Alignment, Alignment + Offset);
9821 /// \brief Check if this slice can be rewritten with legal operations.
9822 bool isLegal() const {
9823 // An invalid slice is not legal.
9824 if (!Origin || !Inst || !DAG)
9827 // Offsets are for indexed load only, we do not handle that.
9828 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9831 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9833 // Check that the type is legal.
9834 EVT SliceType = getLoadedType();
9835 if (!TLI.isTypeLegal(SliceType))
9838 // Check that the load is legal for this type.
9839 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9842 // Check that the offset can be computed.
9843 // 1. Check its type.
9844 EVT PtrType = Origin->getBasePtr().getValueType();
9845 if (PtrType == MVT::Untyped || PtrType.isExtended())
9848 // 2. Check that it fits in the immediate.
9849 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9852 // 3. Check that the computation is legal.
9853 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9856 // Check that the zext is legal if it needs one.
9857 EVT TruncateType = Inst->getValueType(0);
9858 if (TruncateType != SliceType &&
9859 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9865 /// \brief Get the offset in bytes of this slice in the original chunk of
9867 /// \pre DAG != nullptr.
9868 uint64_t getOffsetFromBase() const {
9869 assert(DAG && "Missing context.");
9871 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9872 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9873 uint64_t Offset = Shift / 8;
9874 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9875 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9876 "The size of the original loaded type is not a multiple of a"
9878 // If Offset is bigger than TySizeInBytes, it means we are loading all
9879 // zeros. This should have been optimized before in the process.
9880 assert(TySizeInBytes > Offset &&
9881 "Invalid shift amount for given loaded size");
9883 Offset = TySizeInBytes - Offset - getLoadedSize();
9887 /// \brief Generate the sequence of instructions to load the slice
9888 /// represented by this object and redirect the uses of this slice to
9889 /// this new sequence of instructions.
9890 /// \pre this->Inst && this->Origin are valid Instructions and this
9891 /// object passed the legal check: LoadedSlice::isLegal returned true.
9892 /// \return The last instruction of the sequence used to load the slice.
9893 SDValue loadSlice() const {
9894 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9895 const SDValue &OldBaseAddr = Origin->getBasePtr();
9896 SDValue BaseAddr = OldBaseAddr;
9897 // Get the offset in that chunk of bytes w.r.t. the endianess.
9898 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9899 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9901 // BaseAddr = BaseAddr + Offset.
9902 EVT ArithType = BaseAddr.getValueType();
9904 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9905 DAG->getConstant(Offset, DL, ArithType));
9908 // Create the type of the loaded slice according to its size.
9909 EVT SliceType = getLoadedType();
9911 // Create the load for the slice.
9912 SDValue LastInst = DAG->getLoad(
9913 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9914 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9915 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9916 // If the final type is not the same as the loaded type, this means that
9917 // we have to pad with zero. Create a zero extend for that.
9918 EVT FinalType = Inst->getValueType(0);
9919 if (SliceType != FinalType)
9921 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9925 /// \brief Check if this slice can be merged with an expensive cross register
9926 /// bank copy. E.g.,
9928 /// f = bitcast i32 i to float
9929 bool canMergeExpensiveCrossRegisterBankCopy() const {
9930 if (!Inst || !Inst->hasOneUse())
9932 SDNode *Use = *Inst->use_begin();
9933 if (Use->getOpcode() != ISD::BITCAST)
9935 assert(DAG && "Missing context");
9936 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9937 EVT ResVT = Use->getValueType(0);
9938 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9939 const TargetRegisterClass *ArgRC =
9940 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9941 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9944 // At this point, we know that we perform a cross-register-bank copy.
9945 // Check if it is expensive.
9946 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9947 // Assume bitcasts are cheap, unless both register classes do not
9948 // explicitly share a common sub class.
9949 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9952 // Check if it will be merged with the load.
9953 // 1. Check the alignment constraint.
9954 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9955 ResVT.getTypeForEVT(*DAG->getContext()));
9957 if (RequiredAlignment > getAlignment())
9960 // 2. Check that the load is a legal operation for that type.
9961 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9964 // 3. Check that we do not have a zext in the way.
9965 if (Inst->getValueType(0) != getLoadedType())
9973 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9974 /// \p UsedBits looks like 0..0 1..1 0..0.
9975 static bool areUsedBitsDense(const APInt &UsedBits) {
9976 // If all the bits are one, this is dense!
9977 if (UsedBits.isAllOnesValue())
9980 // Get rid of the unused bits on the right.
9981 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9982 // Get rid of the unused bits on the left.
9983 if (NarrowedUsedBits.countLeadingZeros())
9984 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9985 // Check that the chunk of bits is completely used.
9986 return NarrowedUsedBits.isAllOnesValue();
9989 /// \brief Check whether or not \p First and \p Second are next to each other
9990 /// in memory. This means that there is no hole between the bits loaded
9991 /// by \p First and the bits loaded by \p Second.
9992 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9993 const LoadedSlice &Second) {
9994 assert(First.Origin == Second.Origin && First.Origin &&
9995 "Unable to match different memory origins.");
9996 APInt UsedBits = First.getUsedBits();
9997 assert((UsedBits & Second.getUsedBits()) == 0 &&
9998 "Slices are not supposed to overlap.");
9999 UsedBits |= Second.getUsedBits();
10000 return areUsedBitsDense(UsedBits);
10003 /// \brief Adjust the \p GlobalLSCost according to the target
10004 /// paring capabilities and the layout of the slices.
10005 /// \pre \p GlobalLSCost should account for at least as many loads as
10006 /// there is in the slices in \p LoadedSlices.
10007 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10008 LoadedSlice::Cost &GlobalLSCost) {
10009 unsigned NumberOfSlices = LoadedSlices.size();
10010 // If there is less than 2 elements, no pairing is possible.
10011 if (NumberOfSlices < 2)
10014 // Sort the slices so that elements that are likely to be next to each
10015 // other in memory are next to each other in the list.
10016 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10017 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10018 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10019 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10021 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10022 // First (resp. Second) is the first (resp. Second) potentially candidate
10023 // to be placed in a paired load.
10024 const LoadedSlice *First = nullptr;
10025 const LoadedSlice *Second = nullptr;
10026 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10027 // Set the beginning of the pair.
10030 Second = &LoadedSlices[CurrSlice];
10032 // If First is NULL, it means we start a new pair.
10033 // Get to the next slice.
10037 EVT LoadedType = First->getLoadedType();
10039 // If the types of the slices are different, we cannot pair them.
10040 if (LoadedType != Second->getLoadedType())
10043 // Check if the target supplies paired loads for this type.
10044 unsigned RequiredAlignment = 0;
10045 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10046 // move to the next pair, this type is hopeless.
10050 // Check if we meet the alignment requirement.
10051 if (RequiredAlignment > First->getAlignment())
10054 // Check that both loads are next to each other in memory.
10055 if (!areSlicesNextToEachOther(*First, *Second))
10058 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10059 --GlobalLSCost.Loads;
10060 // Move to the next pair.
10065 /// \brief Check the profitability of all involved LoadedSlice.
10066 /// Currently, it is considered profitable if there is exactly two
10067 /// involved slices (1) which are (2) next to each other in memory, and
10068 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10070 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10071 /// the elements themselves.
10073 /// FIXME: When the cost model will be mature enough, we can relax
10074 /// constraints (1) and (2).
10075 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10076 const APInt &UsedBits, bool ForCodeSize) {
10077 unsigned NumberOfSlices = LoadedSlices.size();
10078 if (StressLoadSlicing)
10079 return NumberOfSlices > 1;
10082 if (NumberOfSlices != 2)
10086 if (!areUsedBitsDense(UsedBits))
10090 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10091 // The original code has one big load.
10092 OrigCost.Loads = 1;
10093 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10094 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10095 // Accumulate the cost of all the slices.
10096 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10097 GlobalSlicingCost += SliceCost;
10099 // Account as cost in the original configuration the gain obtained
10100 // with the current slices.
10101 OrigCost.addSliceGain(LS);
10104 // If the target supports paired load, adjust the cost accordingly.
10105 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10106 return OrigCost > GlobalSlicingCost;
10109 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10110 /// operations, split it in the various pieces being extracted.
10112 /// This sort of thing is introduced by SROA.
10113 /// This slicing takes care not to insert overlapping loads.
10114 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10115 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10116 if (Level < AfterLegalizeDAG)
10119 LoadSDNode *LD = cast<LoadSDNode>(N);
10120 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10121 !LD->getValueType(0).isInteger())
10124 // Keep track of already used bits to detect overlapping values.
10125 // In that case, we will just abort the transformation.
10126 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10128 SmallVector<LoadedSlice, 4> LoadedSlices;
10130 // Check if this load is used as several smaller chunks of bits.
10131 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10132 // of computation for each trunc.
10133 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10134 UI != UIEnd; ++UI) {
10135 // Skip the uses of the chain.
10136 if (UI.getUse().getResNo() != 0)
10139 SDNode *User = *UI;
10140 unsigned Shift = 0;
10142 // Check if this is a trunc(lshr).
10143 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10144 isa<ConstantSDNode>(User->getOperand(1))) {
10145 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10146 User = *User->use_begin();
10149 // At this point, User is a Truncate, iff we encountered, trunc or
10151 if (User->getOpcode() != ISD::TRUNCATE)
10154 // The width of the type must be a power of 2 and greater than 8-bits.
10155 // Otherwise the load cannot be represented in LLVM IR.
10156 // Moreover, if we shifted with a non-8-bits multiple, the slice
10157 // will be across several bytes. We do not support that.
10158 unsigned Width = User->getValueSizeInBits(0);
10159 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10162 // Build the slice for this chain of computations.
10163 LoadedSlice LS(User, LD, Shift, &DAG);
10164 APInt CurrentUsedBits = LS.getUsedBits();
10166 // Check if this slice overlaps with another.
10167 if ((CurrentUsedBits & UsedBits) != 0)
10169 // Update the bits used globally.
10170 UsedBits |= CurrentUsedBits;
10172 // Check if the new slice would be legal.
10176 // Record the slice.
10177 LoadedSlices.push_back(LS);
10180 // Abort slicing if it does not seem to be profitable.
10181 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10186 // Rewrite each chain to use an independent load.
10187 // By construction, each chain can be represented by a unique load.
10189 // Prepare the argument for the new token factor for all the slices.
10190 SmallVector<SDValue, 8> ArgChains;
10191 for (SmallVectorImpl<LoadedSlice>::const_iterator
10192 LSIt = LoadedSlices.begin(),
10193 LSItEnd = LoadedSlices.end();
10194 LSIt != LSItEnd; ++LSIt) {
10195 SDValue SliceInst = LSIt->loadSlice();
10196 CombineTo(LSIt->Inst, SliceInst, true);
10197 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10198 SliceInst = SliceInst.getOperand(0);
10199 assert(SliceInst->getOpcode() == ISD::LOAD &&
10200 "It takes more than a zext to get to the loaded slice!!");
10201 ArgChains.push_back(SliceInst.getValue(1));
10204 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10206 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10210 /// Check to see if V is (and load (ptr), imm), where the load is having
10211 /// specific bytes cleared out. If so, return the byte size being masked out
10212 /// and the shift amount.
10213 static std::pair<unsigned, unsigned>
10214 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10215 std::pair<unsigned, unsigned> Result(0, 0);
10217 // Check for the structure we're looking for.
10218 if (V->getOpcode() != ISD::AND ||
10219 !isa<ConstantSDNode>(V->getOperand(1)) ||
10220 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10223 // Check the chain and pointer.
10224 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10225 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
10227 // The store should be chained directly to the load or be an operand of a
10229 if (LD == Chain.getNode())
10231 else if (Chain->getOpcode() != ISD::TokenFactor)
10232 return Result; // Fail.
10235 for (const SDValue &ChainOp : Chain->op_values())
10236 if (ChainOp.getNode() == LD) {
10240 if (!isOk) return Result;
10243 // This only handles simple types.
10244 if (V.getValueType() != MVT::i16 &&
10245 V.getValueType() != MVT::i32 &&
10246 V.getValueType() != MVT::i64)
10249 // Check the constant mask. Invert it so that the bits being masked out are
10250 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10251 // follow the sign bit for uniformity.
10252 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10253 unsigned NotMaskLZ = countLeadingZeros(NotMask);
10254 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
10255 unsigned NotMaskTZ = countTrailingZeros(NotMask);
10256 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10257 if (NotMaskLZ == 64) return Result; // All zero mask.
10259 // See if we have a continuous run of bits. If so, we have 0*1+0*
10260 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10263 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10264 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10265 NotMaskLZ -= 64-V.getValueSizeInBits();
10267 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10268 switch (MaskedBytes) {
10272 default: return Result; // All one mask, or 5-byte mask.
10275 // Verify that the first bit starts at a multiple of mask so that the access
10276 // is aligned the same as the access width.
10277 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10279 Result.first = MaskedBytes;
10280 Result.second = NotMaskTZ/8;
10285 /// Check to see if IVal is something that provides a value as specified by
10286 /// MaskInfo. If so, replace the specified store with a narrower store of
10287 /// truncated IVal.
10289 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10290 SDValue IVal, StoreSDNode *St,
10292 unsigned NumBytes = MaskInfo.first;
10293 unsigned ByteShift = MaskInfo.second;
10294 SelectionDAG &DAG = DC->getDAG();
10296 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10297 // that uses this. If not, this is not a replacement.
10298 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10299 ByteShift*8, (ByteShift+NumBytes)*8);
10300 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10302 // Check that it is legal on the target to do this. It is legal if the new
10303 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10305 MVT VT = MVT::getIntegerVT(NumBytes*8);
10306 if (!DC->isTypeLegal(VT))
10309 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10310 // shifted by ByteShift and truncated down to NumBytes.
10313 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10314 DAG.getConstant(ByteShift*8, DL,
10315 DC->getShiftAmountTy(IVal.getValueType())));
10318 // Figure out the offset for the store and the alignment of the access.
10320 unsigned NewAlign = St->getAlignment();
10322 if (DAG.getTargetLoweringInfo().isLittleEndian())
10323 StOffset = ByteShift;
10325 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10327 SDValue Ptr = St->getBasePtr();
10330 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10331 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10332 NewAlign = MinAlign(NewAlign, StOffset);
10335 // Truncate down to the new size.
10336 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10339 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10340 St->getPointerInfo().getWithOffset(StOffset),
10341 false, false, NewAlign).getNode();
10345 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10346 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10347 /// narrowing the load and store if it would end up being a win for performance
10349 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10350 StoreSDNode *ST = cast<StoreSDNode>(N);
10351 if (ST->isVolatile())
10354 SDValue Chain = ST->getChain();
10355 SDValue Value = ST->getValue();
10356 SDValue Ptr = ST->getBasePtr();
10357 EVT VT = Value.getValueType();
10359 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10362 unsigned Opc = Value.getOpcode();
10364 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10365 // is a byte mask indicating a consecutive number of bytes, check to see if
10366 // Y is known to provide just those bytes. If so, we try to replace the
10367 // load + replace + store sequence with a single (narrower) store, which makes
10369 if (Opc == ISD::OR) {
10370 std::pair<unsigned, unsigned> MaskedLoad;
10371 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10372 if (MaskedLoad.first)
10373 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10374 Value.getOperand(1), ST,this))
10375 return SDValue(NewST, 0);
10377 // Or is commutative, so try swapping X and Y.
10378 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10379 if (MaskedLoad.first)
10380 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10381 Value.getOperand(0), ST,this))
10382 return SDValue(NewST, 0);
10385 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10386 Value.getOperand(1).getOpcode() != ISD::Constant)
10389 SDValue N0 = Value.getOperand(0);
10390 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10391 Chain == SDValue(N0.getNode(), 1)) {
10392 LoadSDNode *LD = cast<LoadSDNode>(N0);
10393 if (LD->getBasePtr() != Ptr ||
10394 LD->getPointerInfo().getAddrSpace() !=
10395 ST->getPointerInfo().getAddrSpace())
10398 // Find the type to narrow it the load / op / store to.
10399 SDValue N1 = Value.getOperand(1);
10400 unsigned BitWidth = N1.getValueSizeInBits();
10401 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10402 if (Opc == ISD::AND)
10403 Imm ^= APInt::getAllOnesValue(BitWidth);
10404 if (Imm == 0 || Imm.isAllOnesValue())
10406 unsigned ShAmt = Imm.countTrailingZeros();
10407 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10408 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10409 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10410 // The narrowing should be profitable, the load/store operation should be
10411 // legal (or custom) and the store size should be equal to the NewVT width.
10412 while (NewBW < BitWidth &&
10413 (NewVT.getStoreSizeInBits() != NewBW ||
10414 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10415 !TLI.isNarrowingProfitable(VT, NewVT))) {
10416 NewBW = NextPowerOf2(NewBW);
10417 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10419 if (NewBW >= BitWidth)
10422 // If the lsb changed does not start at the type bitwidth boundary,
10423 // start at the previous one.
10425 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10426 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10427 std::min(BitWidth, ShAmt + NewBW));
10428 if ((Imm & Mask) == Imm) {
10429 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10430 if (Opc == ISD::AND)
10431 NewImm ^= APInt::getAllOnesValue(NewBW);
10432 uint64_t PtrOff = ShAmt / 8;
10433 // For big endian targets, we need to adjust the offset to the pointer to
10434 // load the correct bytes.
10435 if (TLI.isBigEndian())
10436 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10438 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10439 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10440 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10443 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10444 Ptr.getValueType(), Ptr,
10445 DAG.getConstant(PtrOff, SDLoc(LD),
10446 Ptr.getValueType()));
10447 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10448 LD->getChain(), NewPtr,
10449 LD->getPointerInfo().getWithOffset(PtrOff),
10450 LD->isVolatile(), LD->isNonTemporal(),
10451 LD->isInvariant(), NewAlign,
10453 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10454 DAG.getConstant(NewImm, SDLoc(Value),
10456 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10458 ST->getPointerInfo().getWithOffset(PtrOff),
10459 false, false, NewAlign);
10461 AddToWorklist(NewPtr.getNode());
10462 AddToWorklist(NewLD.getNode());
10463 AddToWorklist(NewVal.getNode());
10464 WorklistRemover DeadNodes(*this);
10465 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10474 /// For a given floating point load / store pair, if the load value isn't used
10475 /// by any other operations, then consider transforming the pair to integer
10476 /// load / store operations if the target deems the transformation profitable.
10477 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10478 StoreSDNode *ST = cast<StoreSDNode>(N);
10479 SDValue Chain = ST->getChain();
10480 SDValue Value = ST->getValue();
10481 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10482 Value.hasOneUse() &&
10483 Chain == SDValue(Value.getNode(), 1)) {
10484 LoadSDNode *LD = cast<LoadSDNode>(Value);
10485 EVT VT = LD->getMemoryVT();
10486 if (!VT.isFloatingPoint() ||
10487 VT != ST->getMemoryVT() ||
10488 LD->isNonTemporal() ||
10489 ST->isNonTemporal() ||
10490 LD->getPointerInfo().getAddrSpace() != 0 ||
10491 ST->getPointerInfo().getAddrSpace() != 0)
10494 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10495 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10496 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10497 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10498 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10501 unsigned LDAlign = LD->getAlignment();
10502 unsigned STAlign = ST->getAlignment();
10503 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10504 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10505 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10508 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10509 LD->getChain(), LD->getBasePtr(),
10510 LD->getPointerInfo(),
10511 false, false, false, LDAlign);
10513 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10514 NewLD, ST->getBasePtr(),
10515 ST->getPointerInfo(),
10516 false, false, STAlign);
10518 AddToWorklist(NewLD.getNode());
10519 AddToWorklist(NewST.getNode());
10520 WorklistRemover DeadNodes(*this);
10521 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10530 /// Helper struct to parse and store a memory address as base + index + offset.
10531 /// We ignore sign extensions when it is safe to do so.
10532 /// The following two expressions are not equivalent. To differentiate we need
10533 /// to store whether there was a sign extension involved in the index
10535 /// (load (i64 add (i64 copyfromreg %c)
10536 /// (i64 signextend (add (i8 load %index)
10540 /// (load (i64 add (i64 copyfromreg %c)
10541 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10543 struct BaseIndexOffset {
10547 bool IsIndexSignExt;
10549 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10551 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10552 bool IsIndexSignExt) :
10553 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10555 bool equalBaseIndex(const BaseIndexOffset &Other) {
10556 return Other.Base == Base && Other.Index == Index &&
10557 Other.IsIndexSignExt == IsIndexSignExt;
10560 /// Parses tree in Ptr for base, index, offset addresses.
10561 static BaseIndexOffset match(SDValue Ptr) {
10562 bool IsIndexSignExt = false;
10564 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10565 // instruction, then it could be just the BASE or everything else we don't
10566 // know how to handle. Just use Ptr as BASE and give up.
10567 if (Ptr->getOpcode() != ISD::ADD)
10568 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10570 // We know that we have at least an ADD instruction. Try to pattern match
10571 // the simple case of BASE + OFFSET.
10572 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10573 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10574 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10578 // Inside a loop the current BASE pointer is calculated using an ADD and a
10579 // MUL instruction. In this case Ptr is the actual BASE pointer.
10580 // (i64 add (i64 %array_ptr)
10581 // (i64 mul (i64 %induction_var)
10582 // (i64 %element_size)))
10583 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10584 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10586 // Look at Base + Index + Offset cases.
10587 SDValue Base = Ptr->getOperand(0);
10588 SDValue IndexOffset = Ptr->getOperand(1);
10590 // Skip signextends.
10591 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10592 IndexOffset = IndexOffset->getOperand(0);
10593 IsIndexSignExt = true;
10596 // Either the case of Base + Index (no offset) or something else.
10597 if (IndexOffset->getOpcode() != ISD::ADD)
10598 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10600 // Now we have the case of Base + Index + offset.
10601 SDValue Index = IndexOffset->getOperand(0);
10602 SDValue Offset = IndexOffset->getOperand(1);
10604 if (!isa<ConstantSDNode>(Offset))
10605 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10607 // Ignore signextends.
10608 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10609 Index = Index->getOperand(0);
10610 IsIndexSignExt = true;
10611 } else IsIndexSignExt = false;
10613 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10614 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10619 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10621 ArrayRef<MemOpLink> Stores,
10623 SmallVector<SDValue, 8> BuildVector;
10625 for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I)
10626 BuildVector.push_back(cast<StoreSDNode>(Stores[I].MemNode)->getValue());
10628 return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10631 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10632 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10633 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10634 // Make sure we have something to merge.
10638 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10639 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10640 unsigned LatestNodeUsed = 0;
10642 for (unsigned i=0; i < NumElem; ++i) {
10643 // Find a chain for the new wide-store operand. Notice that some
10644 // of the store nodes that we found may not be selected for inclusion
10645 // in the wide store. The chain we use needs to be the chain of the
10646 // latest store node which is *used* and replaced by the wide store.
10647 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10648 LatestNodeUsed = i;
10651 // The latest Node in the DAG.
10652 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10653 SDLoc DL(StoreNodes[0].MemNode);
10657 // Find a legal type for the vector store.
10658 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10659 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10660 if (IsConstantSrc) {
10661 StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Ty);
10663 SmallVector<SDValue, 8> Ops;
10664 for (unsigned i = 0; i < NumElem ; ++i) {
10665 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10666 SDValue Val = St->getValue();
10667 // All of the operands of a BUILD_VECTOR must have the same type.
10668 if (Val.getValueType() != MemVT)
10670 Ops.push_back(Val);
10673 // Build the extracted vector elements back into a vector.
10674 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10677 // We should always use a vector store when merging extracted vector
10678 // elements, so this path implies a store of constants.
10679 assert(IsConstantSrc && "Merged vector elements should use vector store");
10681 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
10682 APInt StoreInt(SizeInBits, 0);
10684 // Construct a single integer constant which is made of the smaller
10685 // constant inputs.
10686 bool IsLE = TLI.isLittleEndian();
10687 for (unsigned i = 0; i < NumElem ; ++i) {
10688 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10689 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10690 SDValue Val = St->getValue();
10691 StoreInt <<= ElementSizeBytes * 8;
10692 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10693 StoreInt |= C->getAPIntValue().zext(SizeInBits);
10694 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10695 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10697 llvm_unreachable("Invalid constant element type");
10701 // Create the new Load and Store operations.
10702 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10703 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10706 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10707 FirstInChain->getBasePtr(),
10708 FirstInChain->getPointerInfo(),
10710 FirstInChain->getAlignment());
10712 // Replace the last store with the new store
10713 CombineTo(LatestOp, NewStore);
10714 // Erase all other stores.
10715 for (unsigned i = 0; i < NumElem ; ++i) {
10716 if (StoreNodes[i].MemNode == LatestOp)
10718 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10719 // ReplaceAllUsesWith will replace all uses that existed when it was
10720 // called, but graph optimizations may cause new ones to appear. For
10721 // example, the case in pr14333 looks like
10723 // St's chain -> St -> another store -> X
10725 // And the only difference from St to the other store is the chain.
10726 // When we change it's chain to be St's chain they become identical,
10727 // get CSEed and the net result is that X is now a use of St.
10728 // Since we know that St is redundant, just iterate.
10729 while (!St->use_empty())
10730 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10731 deleteAndRecombine(St);
10737 static bool allowableAlignment(const SelectionDAG &DAG,
10738 const TargetLowering &TLI, EVT EVTTy,
10739 unsigned AS, unsigned Align) {
10740 if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10743 Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10744 unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10745 return (Align >= ABIAlignment);
10748 void DAGCombiner::getStoreMergeAndAliasCandidates(
10749 StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10750 SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10751 // This holds the base pointer, index, and the offset in bytes from the base
10753 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10755 // We must have a base and an offset.
10756 if (!BasePtr.Base.getNode())
10759 // Do not handle stores to undef base pointers.
10760 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10763 // Walk up the chain and look for nodes with offsets from the same
10764 // base pointer. Stop when reaching an instruction with a different kind
10765 // or instruction which has a different base pointer.
10766 EVT MemVT = St->getMemoryVT();
10768 StoreSDNode *Index = St;
10770 // If the chain has more than one use, then we can't reorder the mem ops.
10771 if (Index != St && !SDValue(Index, 0)->hasOneUse())
10774 // Find the base pointer and offset for this memory node.
10775 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10777 // Check that the base pointer is the same as the original one.
10778 if (!Ptr.equalBaseIndex(BasePtr))
10781 // The memory operands must not be volatile.
10782 if (Index->isVolatile() || Index->isIndexed())
10786 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10787 if (St->isTruncatingStore())
10790 // The stored memory type must be the same.
10791 if (Index->getMemoryVT() != MemVT)
10794 // We found a potential memory operand to merge.
10795 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10797 // Find the next memory operand in the chain. If the next operand in the
10798 // chain is a store then move up and continue the scan with the next
10799 // memory operand. If the next operand is a load save it and use alias
10800 // information to check if it interferes with anything.
10801 SDNode *NextInChain = Index->getChain().getNode();
10803 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10804 // We found a store node. Use it for the next iteration.
10807 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10808 if (Ldn->isVolatile()) {
10813 // Save the load node for later. Continue the scan.
10814 AliasLoadNodes.push_back(Ldn);
10815 NextInChain = Ldn->getChain().getNode();
10825 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10826 if (OptLevel == CodeGenOpt::None)
10829 EVT MemVT = St->getMemoryVT();
10830 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10831 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10832 Attribute::NoImplicitFloat);
10834 // This function cannot currently deal with non-byte-sized memory sizes.
10835 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10838 // Don't merge vectors into wider inputs.
10839 if (MemVT.isVector() || !MemVT.isSimple())
10842 // Perform an early exit check. Do not bother looking at stored values that
10843 // are not constants, loads, or extracted vector elements.
10844 SDValue StoredVal = St->getValue();
10845 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10846 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10847 isa<ConstantFPSDNode>(StoredVal);
10848 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10850 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10853 // Only look at ends of store sequences.
10854 SDValue Chain = SDValue(St, 0);
10855 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10858 // Save the LoadSDNodes that we find in the chain.
10859 // We need to make sure that these nodes do not interfere with
10860 // any of the store nodes.
10861 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10863 // Save the StoreSDNodes that we find in the chain.
10864 SmallVector<MemOpLink, 8> StoreNodes;
10866 getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
10868 // Check if there is anything to merge.
10869 if (StoreNodes.size() < 2)
10872 // Sort the memory operands according to their distance from the base pointer.
10873 std::sort(StoreNodes.begin(), StoreNodes.end(),
10874 [](MemOpLink LHS, MemOpLink RHS) {
10875 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10876 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10877 LHS.SequenceNum > RHS.SequenceNum);
10880 // Scan the memory operations on the chain and find the first non-consecutive
10881 // store memory address.
10882 unsigned LastConsecutiveStore = 0;
10883 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10884 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10886 // Check that the addresses are consecutive starting from the second
10887 // element in the list of stores.
10889 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10890 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10894 bool Alias = false;
10895 // Check if this store interferes with any of the loads that we found.
10896 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10897 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10901 // We found a load that alias with this store. Stop the sequence.
10905 // Mark this node as useful.
10906 LastConsecutiveStore = i;
10909 // The node with the lowest store address.
10910 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10911 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10912 unsigned FirstStoreAlign = FirstInChain->getAlignment();
10914 // Store the constants into memory as one consecutive store.
10915 if (IsConstantSrc) {
10916 unsigned LastLegalType = 0;
10917 unsigned LastLegalVectorType = 0;
10918 bool NonZero = false;
10919 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10920 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10921 SDValue StoredVal = St->getValue();
10923 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10924 NonZero |= !C->isNullValue();
10925 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10926 NonZero |= !C->getConstantFPValue()->isNullValue();
10932 // Find a legal type for the constant store.
10933 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
10934 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10935 if (TLI.isTypeLegal(StoreTy) &&
10936 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10937 FirstStoreAlign)) {
10938 LastLegalType = i+1;
10939 // Or check whether a truncstore is legal.
10940 } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10941 TargetLowering::TypePromoteInteger) {
10942 EVT LegalizedStoredValueTy =
10943 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10944 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10945 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10946 FirstStoreAlign)) {
10947 LastLegalType = i + 1;
10951 // Find a legal type for the vector store.
10952 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10953 if (TLI.isTypeLegal(Ty) &&
10954 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
10955 LastLegalVectorType = i + 1;
10960 // We only use vectors if the constant is known to be zero or the target
10961 // allows it and the function is not marked with the noimplicitfloat
10964 LastLegalVectorType = 0;
10965 } else if (NonZero && !TLI.storeOfVectorConstantIsCheap(MemVT,
10966 LastLegalVectorType,
10968 LastLegalVectorType = 0;
10971 // Check if we found a legal integer type to store.
10972 if (LastLegalType == 0 && LastLegalVectorType == 0)
10975 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10976 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10978 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10982 // When extracting multiple vector elements, try to store them
10983 // in one vector store rather than a sequence of scalar stores.
10984 if (IsExtractVecEltSrc) {
10985 unsigned NumElem = 0;
10986 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10987 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10988 SDValue StoredVal = St->getValue();
10989 // This restriction could be loosened.
10990 // Bail out if any stored values are not elements extracted from a vector.
10991 // It should be possible to handle mixed sources, but load sources need
10992 // more careful handling (see the block of code below that handles
10993 // consecutive loads).
10994 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10997 // Find a legal type for the vector store.
10998 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10999 if (TLI.isTypeLegal(Ty) &&
11000 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
11004 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11008 // Below we handle the case of multiple consecutive stores that
11009 // come from multiple consecutive loads. We merge them into a single
11010 // wide load and a single wide store.
11012 // Look for load nodes which are used by the stored values.
11013 SmallVector<MemOpLink, 8> LoadNodes;
11015 // Find acceptable loads. Loads need to have the same chain (token factor),
11016 // must not be zext, volatile, indexed, and they must be consecutive.
11017 BaseIndexOffset LdBasePtr;
11018 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11019 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11020 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11023 // Loads must only have one use.
11024 if (!Ld->hasNUsesOfValue(1, 0))
11027 // The memory operands must not be volatile.
11028 if (Ld->isVolatile() || Ld->isIndexed())
11031 // We do not accept ext loads.
11032 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11035 // The stored memory type must be the same.
11036 if (Ld->getMemoryVT() != MemVT)
11039 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11040 // If this is not the first ptr that we check.
11041 if (LdBasePtr.Base.getNode()) {
11042 // The base ptr must be the same.
11043 if (!LdPtr.equalBaseIndex(LdBasePtr))
11046 // Check that all other base pointers are the same as this one.
11050 // We found a potential memory operand to merge.
11051 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11054 if (LoadNodes.size() < 2)
11057 // If we have load/store pair instructions and we only have two values,
11059 unsigned RequiredAlignment;
11060 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11061 St->getAlignment() >= RequiredAlignment)
11064 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11065 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11066 unsigned FirstLoadAlign = FirstLoad->getAlignment();
11068 // Scan the memory operations on the chain and find the first non-consecutive
11069 // load memory address. These variables hold the index in the store node
11071 unsigned LastConsecutiveLoad = 0;
11072 // This variable refers to the size and not index in the array.
11073 unsigned LastLegalVectorType = 0;
11074 unsigned LastLegalIntegerType = 0;
11075 StartAddress = LoadNodes[0].OffsetFromBase;
11076 SDValue FirstChain = FirstLoad->getChain();
11077 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11078 // All loads much share the same chain.
11079 if (LoadNodes[i].MemNode->getChain() != FirstChain)
11082 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11083 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11085 LastConsecutiveLoad = i;
11087 // Find a legal type for the vector store.
11088 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
11089 if (TLI.isTypeLegal(StoreTy) &&
11090 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11091 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
11092 LastLegalVectorType = i + 1;
11095 // Find a legal type for the integer store.
11096 unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11097 StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11098 if (TLI.isTypeLegal(StoreTy) &&
11099 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
11100 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
11101 LastLegalIntegerType = i + 1;
11102 // Or check whether a truncstore and extload is legal.
11103 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
11104 TargetLowering::TypePromoteInteger) {
11105 EVT LegalizedStoredValueTy =
11106 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
11107 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11108 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11109 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11110 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11111 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11112 FirstStoreAlign) &&
11113 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11115 LastLegalIntegerType = i+1;
11119 // Only use vector types if the vector type is larger than the integer type.
11120 // If they are the same, use integers.
11121 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11122 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11124 // We add +1 here because the LastXXX variables refer to location while
11125 // the NumElem refers to array/index size.
11126 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11127 NumElem = std::min(LastLegalType, NumElem);
11132 // The latest Node in the DAG.
11133 unsigned LatestNodeUsed = 0;
11134 for (unsigned i=1; i<NumElem; ++i) {
11135 // Find a chain for the new wide-store operand. Notice that some
11136 // of the store nodes that we found may not be selected for inclusion
11137 // in the wide store. The chain we use needs to be the chain of the
11138 // latest store node which is *used* and replaced by the wide store.
11139 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11140 LatestNodeUsed = i;
11143 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11145 // Find if it is better to use vectors or integers to load and store
11149 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11151 unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11152 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
11155 SDLoc LoadDL(LoadNodes[0].MemNode);
11156 SDLoc StoreDL(StoreNodes[0].MemNode);
11158 SDValue NewLoad = DAG.getLoad(
11159 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11160 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11162 SDValue NewStore = DAG.getStore(
11163 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11164 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11166 // Replace one of the loads with the new load.
11167 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11168 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11169 SDValue(NewLoad.getNode(), 1));
11171 // Remove the rest of the load chains.
11172 for (unsigned i = 1; i < NumElem ; ++i) {
11173 // Replace all chain users of the old load nodes with the chain of the new
11175 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11176 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11179 // Replace the last store with the new store.
11180 CombineTo(LatestOp, NewStore);
11181 // Erase all other stores.
11182 for (unsigned i = 0; i < NumElem ; ++i) {
11183 // Remove all Store nodes.
11184 if (StoreNodes[i].MemNode == LatestOp)
11186 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11187 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11188 deleteAndRecombine(St);
11194 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11195 StoreSDNode *ST = cast<StoreSDNode>(N);
11196 SDValue Chain = ST->getChain();
11197 SDValue Value = ST->getValue();
11198 SDValue Ptr = ST->getBasePtr();
11200 // If this is a store of a bit convert, store the input value if the
11201 // resultant store does not need a higher alignment than the original.
11202 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11203 ST->isUnindexed()) {
11204 unsigned OrigAlign = ST->getAlignment();
11205 EVT SVT = Value.getOperand(0).getValueType();
11206 unsigned Align = TLI.getDataLayout()->
11207 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11208 if (Align <= OrigAlign &&
11209 ((!LegalOperations && !ST->isVolatile()) ||
11210 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11211 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11212 Ptr, ST->getPointerInfo(), ST->isVolatile(),
11213 ST->isNonTemporal(), OrigAlign,
11217 // Turn 'store undef, Ptr' -> nothing.
11218 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11221 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11222 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11223 // NOTE: If the original store is volatile, this transform must not increase
11224 // the number of stores. For example, on x86-32 an f64 can be stored in one
11225 // processor operation but an i64 (which is not legal) requires two. So the
11226 // transform should not be done in this case.
11227 if (Value.getOpcode() != ISD::TargetConstantFP) {
11229 switch (CFP->getSimpleValueType(0).SimpleTy) {
11230 default: llvm_unreachable("Unknown FP type");
11231 case MVT::f16: // We don't do this for these yet.
11237 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11238 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11240 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11241 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11243 return DAG.getStore(Chain, SDLoc(N), Tmp,
11244 Ptr, ST->getMemOperand());
11248 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11249 !ST->isVolatile()) ||
11250 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11252 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11253 getZExtValue(), SDLoc(CFP), MVT::i64);
11254 return DAG.getStore(Chain, SDLoc(N), Tmp,
11255 Ptr, ST->getMemOperand());
11258 if (!ST->isVolatile() &&
11259 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11260 // Many FP stores are not made apparent until after legalize, e.g. for
11261 // argument passing. Since this is so common, custom legalize the
11262 // 64-bit integer store into two 32-bit stores.
11263 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11264 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11265 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11266 if (TLI.isBigEndian()) std::swap(Lo, Hi);
11268 unsigned Alignment = ST->getAlignment();
11269 bool isVolatile = ST->isVolatile();
11270 bool isNonTemporal = ST->isNonTemporal();
11271 AAMDNodes AAInfo = ST->getAAInfo();
11275 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11276 Ptr, ST->getPointerInfo(),
11277 isVolatile, isNonTemporal,
11278 ST->getAlignment(), AAInfo);
11279 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11280 DAG.getConstant(4, DL, Ptr.getValueType()));
11281 Alignment = MinAlign(Alignment, 4U);
11282 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11283 Ptr, ST->getPointerInfo().getWithOffset(4),
11284 isVolatile, isNonTemporal,
11285 Alignment, AAInfo);
11286 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11295 // Try to infer better alignment information than the store already has.
11296 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11297 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11298 if (Align > ST->getAlignment()) {
11300 DAG.getTruncStore(Chain, SDLoc(N), Value,
11301 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11302 ST->isVolatile(), ST->isNonTemporal(), Align,
11304 if (NewStore.getNode() != N)
11305 return CombineTo(ST, NewStore, true);
11310 // Try transforming a pair floating point load / store ops to integer
11311 // load / store ops.
11312 SDValue NewST = TransformFPLoadStorePair(N);
11313 if (NewST.getNode())
11316 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11317 : DAG.getSubtarget().useAA();
11319 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11320 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11323 if (UseAA && ST->isUnindexed()) {
11324 // Walk up chain skipping non-aliasing memory nodes.
11325 SDValue BetterChain = FindBetterChain(N, Chain);
11327 // If there is a better chain.
11328 if (Chain != BetterChain) {
11331 // Replace the chain to avoid dependency.
11332 if (ST->isTruncatingStore()) {
11333 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11334 ST->getMemoryVT(), ST->getMemOperand());
11336 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11337 ST->getMemOperand());
11340 // Create token to keep both nodes around.
11341 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11342 MVT::Other, Chain, ReplStore);
11344 // Make sure the new and old chains are cleaned up.
11345 AddToWorklist(Token.getNode());
11347 // Don't add users to work list.
11348 return CombineTo(N, Token, false);
11352 // Try transforming N to an indexed store.
11353 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11354 return SDValue(N, 0);
11356 // FIXME: is there such a thing as a truncating indexed store?
11357 if (ST->isTruncatingStore() && ST->isUnindexed() &&
11358 Value.getValueType().isInteger()) {
11359 // See if we can simplify the input to this truncstore with knowledge that
11360 // only the low bits are being used. For example:
11361 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
11363 GetDemandedBits(Value,
11364 APInt::getLowBitsSet(
11365 Value.getValueType().getScalarType().getSizeInBits(),
11366 ST->getMemoryVT().getScalarType().getSizeInBits()));
11367 AddToWorklist(Value.getNode());
11368 if (Shorter.getNode())
11369 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11370 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11372 // Otherwise, see if we can simplify the operation with
11373 // SimplifyDemandedBits, which only works if the value has a single use.
11374 if (SimplifyDemandedBits(Value,
11375 APInt::getLowBitsSet(
11376 Value.getValueType().getScalarType().getSizeInBits(),
11377 ST->getMemoryVT().getScalarType().getSizeInBits())))
11378 return SDValue(N, 0);
11381 // If this is a load followed by a store to the same location, then the store
11383 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11384 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11385 ST->isUnindexed() && !ST->isVolatile() &&
11386 // There can't be any side effects between the load and store, such as
11387 // a call or store.
11388 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11389 // The store is dead, remove it.
11394 // If this is a store followed by a store with the same value to the same
11395 // location, then the store is dead/noop.
11396 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11397 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11398 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11399 ST1->isUnindexed() && !ST1->isVolatile()) {
11400 // The store is dead, remove it.
11405 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11406 // truncating store. We can do this even if this is already a truncstore.
11407 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11408 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11409 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11410 ST->getMemoryVT())) {
11411 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11412 Ptr, ST->getMemoryVT(), ST->getMemOperand());
11415 // Only perform this optimization before the types are legal, because we
11416 // don't want to perform this optimization on every DAGCombine invocation.
11418 bool EverChanged = false;
11421 // There can be multiple store sequences on the same chain.
11422 // Keep trying to merge store sequences until we are unable to do so
11423 // or until we merge the last store on the chain.
11424 bool Changed = MergeConsecutiveStores(ST);
11425 EverChanged |= Changed;
11426 if (!Changed) break;
11427 } while (ST->getOpcode() != ISD::DELETED_NODE);
11430 return SDValue(N, 0);
11433 return ReduceLoadOpStoreWidth(N);
11436 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11437 SDValue InVec = N->getOperand(0);
11438 SDValue InVal = N->getOperand(1);
11439 SDValue EltNo = N->getOperand(2);
11442 // If the inserted element is an UNDEF, just use the input vector.
11443 if (InVal.getOpcode() == ISD::UNDEF)
11446 EVT VT = InVec.getValueType();
11448 // If we can't generate a legal BUILD_VECTOR, exit
11449 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11452 // Check that we know which element is being inserted
11453 if (!isa<ConstantSDNode>(EltNo))
11455 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11457 // Canonicalize insert_vector_elt dag nodes.
11459 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11460 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11462 // Do this only if the child insert_vector node has one use; also
11463 // do this only if indices are both constants and Idx1 < Idx0.
11464 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11465 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11466 unsigned OtherElt =
11467 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11468 if (Elt < OtherElt) {
11470 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11471 InVec.getOperand(0), InVal, EltNo);
11472 AddToWorklist(NewOp.getNode());
11473 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11474 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11478 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11479 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11480 // vector elements.
11481 SmallVector<SDValue, 8> Ops;
11482 // Do not combine these two vectors if the output vector will not replace
11483 // the input vector.
11484 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11485 Ops.append(InVec.getNode()->op_begin(),
11486 InVec.getNode()->op_end());
11487 } else if (InVec.getOpcode() == ISD::UNDEF) {
11488 unsigned NElts = VT.getVectorNumElements();
11489 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11494 // Insert the element
11495 if (Elt < Ops.size()) {
11496 // All the operands of BUILD_VECTOR must have the same type;
11497 // we enforce that here.
11498 EVT OpVT = Ops[0].getValueType();
11499 if (InVal.getValueType() != OpVT)
11500 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11501 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11502 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11506 // Return the new vector
11507 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11510 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11511 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11512 EVT ResultVT = EVE->getValueType(0);
11513 EVT VecEltVT = InVecVT.getVectorElementType();
11514 unsigned Align = OriginalLoad->getAlignment();
11515 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11516 VecEltVT.getTypeForEVT(*DAG.getContext()));
11518 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11523 SDValue NewPtr = OriginalLoad->getBasePtr();
11525 EVT PtrType = NewPtr.getValueType();
11526 MachinePointerInfo MPI;
11528 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11529 int Elt = ConstEltNo->getZExtValue();
11530 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11531 Offset = DAG.getConstant(PtrOff, DL, PtrType);
11532 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11534 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11535 Offset = DAG.getNode(
11536 ISD::MUL, DL, PtrType, Offset,
11537 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11538 MPI = OriginalLoad->getPointerInfo();
11540 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11542 // The replacement we need to do here is a little tricky: we need to
11543 // replace an extractelement of a load with a load.
11544 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11545 // Note that this replacement assumes that the extractvalue is the only
11546 // use of the load; that's okay because we don't want to perform this
11547 // transformation in other cases anyway.
11550 if (ResultVT.bitsGT(VecEltVT)) {
11551 // If the result type of vextract is wider than the load, then issue an
11552 // extending load instead.
11553 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11557 Load = DAG.getExtLoad(
11558 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11559 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11560 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11561 Chain = Load.getValue(1);
11563 Load = DAG.getLoad(
11564 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11565 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11566 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11567 Chain = Load.getValue(1);
11568 if (ResultVT.bitsLT(VecEltVT))
11569 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11571 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11573 WorklistRemover DeadNodes(*this);
11574 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11575 SDValue To[] = { Load, Chain };
11576 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11577 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11578 // worklist explicitly as well.
11579 AddToWorklist(Load.getNode());
11580 AddUsersToWorklist(Load.getNode()); // Add users too
11581 // Make sure to revisit this node to clean it up; it will usually be dead.
11582 AddToWorklist(EVE);
11584 return SDValue(EVE, 0);
11587 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11588 // (vextract (scalar_to_vector val, 0) -> val
11589 SDValue InVec = N->getOperand(0);
11590 EVT VT = InVec.getValueType();
11591 EVT NVT = N->getValueType(0);
11593 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11594 // Check if the result type doesn't match the inserted element type. A
11595 // SCALAR_TO_VECTOR may truncate the inserted element and the
11596 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11597 SDValue InOp = InVec.getOperand(0);
11598 if (InOp.getValueType() != NVT) {
11599 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11600 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11605 SDValue EltNo = N->getOperand(1);
11606 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11608 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11609 // We only perform this optimization before the op legalization phase because
11610 // we may introduce new vector instructions which are not backed by TD
11611 // patterns. For example on AVX, extracting elements from a wide vector
11612 // without using extract_subvector. However, if we can find an underlying
11613 // scalar value, then we can always use that.
11614 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11616 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11617 int NumElem = VT.getVectorNumElements();
11618 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11619 // Find the new index to extract from.
11620 int OrigElt = SVOp->getMaskElt(Elt);
11622 // Extracting an undef index is undef.
11624 return DAG.getUNDEF(NVT);
11626 // Select the right vector half to extract from.
11628 if (OrigElt < NumElem) {
11629 SVInVec = InVec->getOperand(0);
11631 SVInVec = InVec->getOperand(1);
11632 OrigElt -= NumElem;
11635 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11636 SDValue InOp = SVInVec.getOperand(OrigElt);
11637 if (InOp.getValueType() != NVT) {
11638 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11639 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11645 // FIXME: We should handle recursing on other vector shuffles and
11646 // scalar_to_vector here as well.
11648 if (!LegalOperations) {
11649 EVT IndexTy = TLI.getVectorIdxTy();
11650 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11651 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11655 bool BCNumEltsChanged = false;
11656 EVT ExtVT = VT.getVectorElementType();
11659 // If the result of load has to be truncated, then it's not necessarily
11661 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11664 if (InVec.getOpcode() == ISD::BITCAST) {
11665 // Don't duplicate a load with other uses.
11666 if (!InVec.hasOneUse())
11669 EVT BCVT = InVec.getOperand(0).getValueType();
11670 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11672 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11673 BCNumEltsChanged = true;
11674 InVec = InVec.getOperand(0);
11675 ExtVT = BCVT.getVectorElementType();
11678 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11679 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11680 ISD::isNormalLoad(InVec.getNode()) &&
11681 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11682 SDValue Index = N->getOperand(1);
11683 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11684 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11688 // Perform only after legalization to ensure build_vector / vector_shuffle
11689 // optimizations have already been done.
11690 if (!LegalOperations) return SDValue();
11692 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11693 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11694 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11697 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11699 LoadSDNode *LN0 = nullptr;
11700 const ShuffleVectorSDNode *SVN = nullptr;
11701 if (ISD::isNormalLoad(InVec.getNode())) {
11702 LN0 = cast<LoadSDNode>(InVec);
11703 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11704 InVec.getOperand(0).getValueType() == ExtVT &&
11705 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11706 // Don't duplicate a load with other uses.
11707 if (!InVec.hasOneUse())
11710 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11711 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11712 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11714 // (load $addr+1*size)
11716 // Don't duplicate a load with other uses.
11717 if (!InVec.hasOneUse())
11720 // If the bit convert changed the number of elements, it is unsafe
11721 // to examine the mask.
11722 if (BCNumEltsChanged)
11725 // Select the input vector, guarding against out of range extract vector.
11726 unsigned NumElems = VT.getVectorNumElements();
11727 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11728 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11730 if (InVec.getOpcode() == ISD::BITCAST) {
11731 // Don't duplicate a load with other uses.
11732 if (!InVec.hasOneUse())
11735 InVec = InVec.getOperand(0);
11737 if (ISD::isNormalLoad(InVec.getNode())) {
11738 LN0 = cast<LoadSDNode>(InVec);
11739 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11740 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11744 // Make sure we found a non-volatile load and the extractelement is
11746 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11749 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11751 return DAG.getUNDEF(LVT);
11753 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11759 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11760 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11761 // We perform this optimization post type-legalization because
11762 // the type-legalizer often scalarizes integer-promoted vectors.
11763 // Performing this optimization before may create bit-casts which
11764 // will be type-legalized to complex code sequences.
11765 // We perform this optimization only before the operation legalizer because we
11766 // may introduce illegal operations.
11767 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11770 unsigned NumInScalars = N->getNumOperands();
11772 EVT VT = N->getValueType(0);
11774 // Check to see if this is a BUILD_VECTOR of a bunch of values
11775 // which come from any_extend or zero_extend nodes. If so, we can create
11776 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11777 // optimizations. We do not handle sign-extend because we can't fill the sign
11779 EVT SourceType = MVT::Other;
11780 bool AllAnyExt = true;
11782 for (unsigned i = 0; i != NumInScalars; ++i) {
11783 SDValue In = N->getOperand(i);
11784 // Ignore undef inputs.
11785 if (In.getOpcode() == ISD::UNDEF) continue;
11787 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11788 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11790 // Abort if the element is not an extension.
11791 if (!ZeroExt && !AnyExt) {
11792 SourceType = MVT::Other;
11796 // The input is a ZeroExt or AnyExt. Check the original type.
11797 EVT InTy = In.getOperand(0).getValueType();
11799 // Check that all of the widened source types are the same.
11800 if (SourceType == MVT::Other)
11803 else if (InTy != SourceType) {
11804 // Multiple income types. Abort.
11805 SourceType = MVT::Other;
11809 // Check if all of the extends are ANY_EXTENDs.
11810 AllAnyExt &= AnyExt;
11813 // In order to have valid types, all of the inputs must be extended from the
11814 // same source type and all of the inputs must be any or zero extend.
11815 // Scalar sizes must be a power of two.
11816 EVT OutScalarTy = VT.getScalarType();
11817 bool ValidTypes = SourceType != MVT::Other &&
11818 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11819 isPowerOf2_32(SourceType.getSizeInBits());
11821 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11822 // turn into a single shuffle instruction.
11826 bool isLE = TLI.isLittleEndian();
11827 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11828 assert(ElemRatio > 1 && "Invalid element size ratio");
11829 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11830 DAG.getConstant(0, SDLoc(N), SourceType);
11832 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11833 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11835 // Populate the new build_vector
11836 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11837 SDValue Cast = N->getOperand(i);
11838 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11839 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11840 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11842 if (Cast.getOpcode() == ISD::UNDEF)
11843 In = DAG.getUNDEF(SourceType);
11845 In = Cast->getOperand(0);
11846 unsigned Index = isLE ? (i * ElemRatio) :
11847 (i * ElemRatio + (ElemRatio - 1));
11849 assert(Index < Ops.size() && "Invalid index");
11853 // The type of the new BUILD_VECTOR node.
11854 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11855 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11856 "Invalid vector size");
11857 // Check if the new vector type is legal.
11858 if (!isTypeLegal(VecVT)) return SDValue();
11860 // Make the new BUILD_VECTOR.
11861 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11863 // The new BUILD_VECTOR node has the potential to be further optimized.
11864 AddToWorklist(BV.getNode());
11865 // Bitcast to the desired type.
11866 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11869 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11870 EVT VT = N->getValueType(0);
11872 unsigned NumInScalars = N->getNumOperands();
11875 EVT SrcVT = MVT::Other;
11876 unsigned Opcode = ISD::DELETED_NODE;
11877 unsigned NumDefs = 0;
11879 for (unsigned i = 0; i != NumInScalars; ++i) {
11880 SDValue In = N->getOperand(i);
11881 unsigned Opc = In.getOpcode();
11883 if (Opc == ISD::UNDEF)
11886 // If all scalar values are floats and converted from integers.
11887 if (Opcode == ISD::DELETED_NODE &&
11888 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11895 EVT InVT = In.getOperand(0).getValueType();
11897 // If all scalar values are typed differently, bail out. It's chosen to
11898 // simplify BUILD_VECTOR of integer types.
11899 if (SrcVT == MVT::Other)
11906 // If the vector has just one element defined, it's not worth to fold it into
11907 // a vectorized one.
11911 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11912 && "Should only handle conversion from integer to float.");
11913 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11915 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11917 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11920 // Just because the floating-point vector type is legal does not necessarily
11921 // mean that the corresponding integer vector type is.
11922 if (!isTypeLegal(NVT))
11925 SmallVector<SDValue, 8> Opnds;
11926 for (unsigned i = 0; i != NumInScalars; ++i) {
11927 SDValue In = N->getOperand(i);
11929 if (In.getOpcode() == ISD::UNDEF)
11930 Opnds.push_back(DAG.getUNDEF(SrcVT));
11932 Opnds.push_back(In.getOperand(0));
11934 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11935 AddToWorklist(BV.getNode());
11937 return DAG.getNode(Opcode, dl, VT, BV);
11940 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11941 unsigned NumInScalars = N->getNumOperands();
11943 EVT VT = N->getValueType(0);
11945 // A vector built entirely of undefs is undef.
11946 if (ISD::allOperandsUndef(N))
11947 return DAG.getUNDEF(VT);
11949 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11952 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11955 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11956 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11957 // at most two distinct vectors, turn this into a shuffle node.
11959 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11960 if (!isTypeLegal(VT))
11963 // May only combine to shuffle after legalize if shuffle is legal.
11964 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11967 SDValue VecIn1, VecIn2;
11968 bool UsesZeroVector = false;
11969 for (unsigned i = 0; i != NumInScalars; ++i) {
11970 SDValue Op = N->getOperand(i);
11971 // Ignore undef inputs.
11972 if (Op.getOpcode() == ISD::UNDEF) continue;
11974 // See if we can combine this build_vector into a blend with a zero vector.
11975 if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
11976 UsesZeroVector = true;
11980 // If this input is something other than a EXTRACT_VECTOR_ELT with a
11981 // constant index, bail out.
11982 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11983 !isa<ConstantSDNode>(Op.getOperand(1))) {
11984 VecIn1 = VecIn2 = SDValue(nullptr, 0);
11988 // We allow up to two distinct input vectors.
11989 SDValue ExtractedFromVec = Op.getOperand(0);
11990 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11993 if (!VecIn1.getNode()) {
11994 VecIn1 = ExtractedFromVec;
11995 } else if (!VecIn2.getNode() && !UsesZeroVector) {
11996 VecIn2 = ExtractedFromVec;
11998 // Too many inputs.
11999 VecIn1 = VecIn2 = SDValue(nullptr, 0);
12004 // If everything is good, we can make a shuffle operation.
12005 if (VecIn1.getNode()) {
12006 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12007 SmallVector<int, 8> Mask;
12008 for (unsigned i = 0; i != NumInScalars; ++i) {
12009 unsigned Opcode = N->getOperand(i).getOpcode();
12010 if (Opcode == ISD::UNDEF) {
12011 Mask.push_back(-1);
12015 // Operands can also be zero.
12016 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12017 assert(UsesZeroVector &&
12018 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12019 "Unexpected node found!");
12020 Mask.push_back(NumInScalars+i);
12024 // If extracting from the first vector, just use the index directly.
12025 SDValue Extract = N->getOperand(i);
12026 SDValue ExtVal = Extract.getOperand(1);
12027 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12028 if (Extract.getOperand(0) == VecIn1) {
12029 Mask.push_back(ExtIndex);
12033 // Otherwise, use InIdx + InputVecSize
12034 Mask.push_back(InNumElements + ExtIndex);
12037 // Avoid introducing illegal shuffles with zero.
12038 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12041 // We can't generate a shuffle node with mismatched input and output types.
12042 // Attempt to transform a single input vector to the correct type.
12043 if ((VT != VecIn1.getValueType())) {
12044 // If the input vector type has a different base type to the output
12045 // vector type, bail out.
12046 EVT VTElemType = VT.getVectorElementType();
12047 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12048 (VecIn2.getNode() &&
12049 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12052 // If the input vector is too small, widen it.
12053 // We only support widening of vectors which are half the size of the
12054 // output registers. For example XMM->YMM widening on X86 with AVX.
12055 EVT VecInT = VecIn1.getValueType();
12056 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12057 // If we only have one small input, widen it by adding undef values.
12058 if (!VecIn2.getNode())
12059 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12060 DAG.getUNDEF(VecIn1.getValueType()));
12061 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12062 // If we have two small inputs of the same type, try to concat them.
12063 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12064 VecIn2 = SDValue(nullptr, 0);
12067 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12068 // If the input vector is too large, try to split it.
12069 // We don't support having two input vectors that are too large.
12070 // If the zero vector was used, we can not split the vector,
12071 // since we'd need 3 inputs.
12072 if (UsesZeroVector || VecIn2.getNode())
12075 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12078 // Try to replace VecIn1 with two extract_subvectors
12079 // No need to update the masks, they should still be correct.
12080 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12081 DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
12082 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12083 DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
12088 if (UsesZeroVector)
12089 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12090 DAG.getConstantFP(0.0, dl, VT);
12092 // If VecIn2 is unused then change it to undef.
12093 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12095 // Check that we were able to transform all incoming values to the same
12097 if (VecIn2.getValueType() != VecIn1.getValueType() ||
12098 VecIn1.getValueType() != VT)
12101 // Return the new VECTOR_SHUFFLE node.
12105 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12111 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12112 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12113 EVT OpVT = N->getOperand(0).getValueType();
12115 // If the operands are legal vectors, leave them alone.
12116 if (TLI.isTypeLegal(OpVT))
12120 EVT VT = N->getValueType(0);
12121 SmallVector<SDValue, 8> Ops;
12123 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12124 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12126 // Keep track of what we encounter.
12127 bool AnyInteger = false;
12128 bool AnyFP = false;
12129 for (const SDValue &Op : N->ops()) {
12130 if (ISD::BITCAST == Op.getOpcode() &&
12131 !Op.getOperand(0).getValueType().isVector())
12132 Ops.push_back(Op.getOperand(0));
12133 else if (ISD::UNDEF == Op.getOpcode())
12134 Ops.push_back(ScalarUndef);
12138 // Note whether we encounter an integer or floating point scalar.
12139 // If it's neither, bail out, it could be something weird like x86mmx.
12140 EVT LastOpVT = Ops.back().getValueType();
12141 if (LastOpVT.isFloatingPoint())
12143 else if (LastOpVT.isInteger())
12149 // If any of the operands is a floating point scalar bitcast to a vector,
12150 // use floating point types throughout, and bitcast everything.
12151 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12153 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12154 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12156 for (SDValue &Op : Ops) {
12157 if (Op.getValueType() == SVT)
12159 if (Op.getOpcode() == ISD::UNDEF)
12162 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12167 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12168 VT.getSizeInBits() / SVT.getSizeInBits());
12169 return DAG.getNode(ISD::BITCAST, DL, VT,
12170 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12173 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12174 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12175 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
12176 // inputs come from at most two distinct vectors, turn this into a shuffle
12179 // If we only have one input vector, we don't need to do any concatenation.
12180 if (N->getNumOperands() == 1)
12181 return N->getOperand(0);
12183 // Check if all of the operands are undefs.
12184 EVT VT = N->getValueType(0);
12185 if (ISD::allOperandsUndef(N))
12186 return DAG.getUNDEF(VT);
12188 // Optimize concat_vectors where all but the first of the vectors are undef.
12189 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12190 return Op.getOpcode() == ISD::UNDEF;
12192 SDValue In = N->getOperand(0);
12193 assert(In.getValueType().isVector() && "Must concat vectors");
12195 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12196 if (In->getOpcode() == ISD::BITCAST &&
12197 !In->getOperand(0)->getValueType(0).isVector()) {
12198 SDValue Scalar = In->getOperand(0);
12200 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12201 // look through the trunc so we can still do the transform:
12202 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12203 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12204 !TLI.isTypeLegal(Scalar.getValueType()) &&
12205 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12206 Scalar = Scalar->getOperand(0);
12208 EVT SclTy = Scalar->getValueType(0);
12210 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12213 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12214 VT.getSizeInBits() / SclTy.getSizeInBits());
12215 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12218 SDLoc dl = SDLoc(N);
12219 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12220 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12224 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12225 // We have already tested above for an UNDEF only concatenation.
12226 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12227 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12228 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12229 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12231 bool AllBuildVectorsOrUndefs =
12232 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12233 if (AllBuildVectorsOrUndefs) {
12234 SmallVector<SDValue, 8> Opnds;
12235 EVT SVT = VT.getScalarType();
12238 if (!SVT.isFloatingPoint()) {
12239 // If BUILD_VECTOR are from built from integer, they may have different
12240 // operand types. Get the smallest type and truncate all operands to it.
12241 bool FoundMinVT = false;
12242 for (const SDValue &Op : N->ops())
12243 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12244 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12245 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12248 assert(FoundMinVT && "Concat vector type mismatch");
12251 for (const SDValue &Op : N->ops()) {
12252 EVT OpVT = Op.getValueType();
12253 unsigned NumElts = OpVT.getVectorNumElements();
12255 if (ISD::UNDEF == Op.getOpcode())
12256 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12258 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12259 if (SVT.isFloatingPoint()) {
12260 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12261 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12263 for (unsigned i = 0; i != NumElts; ++i)
12265 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12270 assert(VT.getVectorNumElements() == Opnds.size() &&
12271 "Concat vector type mismatch");
12272 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12275 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12276 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12279 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12280 // nodes often generate nop CONCAT_VECTOR nodes.
12281 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12282 // place the incoming vectors at the exact same location.
12283 SDValue SingleSource = SDValue();
12284 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12286 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12287 SDValue Op = N->getOperand(i);
12289 if (Op.getOpcode() == ISD::UNDEF)
12292 // Check if this is the identity extract:
12293 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12296 // Find the single incoming vector for the extract_subvector.
12297 if (SingleSource.getNode()) {
12298 if (Op.getOperand(0) != SingleSource)
12301 SingleSource = Op.getOperand(0);
12303 // Check the source type is the same as the type of the result.
12304 // If not, this concat may extend the vector, so we can not
12305 // optimize it away.
12306 if (SingleSource.getValueType() != N->getValueType(0))
12310 unsigned IdentityIndex = i * PartNumElem;
12311 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12312 // The extract index must be constant.
12316 // Check that we are reading from the identity index.
12317 if (CS->getZExtValue() != IdentityIndex)
12321 if (SingleSource.getNode())
12322 return SingleSource;
12327 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12328 EVT NVT = N->getValueType(0);
12329 SDValue V = N->getOperand(0);
12331 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12333 // (extract_subvec (concat V1, V2, ...), i)
12336 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12338 if (V->getOperand(0).getValueType() != NVT)
12340 unsigned Idx = N->getConstantOperandVal(1);
12341 unsigned NumElems = NVT.getVectorNumElements();
12342 assert((Idx % NumElems) == 0 &&
12343 "IDX in concat is not a multiple of the result vector length.");
12344 return V->getOperand(Idx / NumElems);
12348 if (V->getOpcode() == ISD::BITCAST)
12349 V = V.getOperand(0);
12351 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12353 // Handle only simple case where vector being inserted and vector
12354 // being extracted are of same type, and are half size of larger vectors.
12355 EVT BigVT = V->getOperand(0).getValueType();
12356 EVT SmallVT = V->getOperand(1).getValueType();
12357 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12360 // Only handle cases where both indexes are constants with the same type.
12361 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12362 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12364 if (InsIdx && ExtIdx &&
12365 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12366 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12368 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12370 // indices are equal or bit offsets are equal => V1
12371 // otherwise => (extract_subvec V1, ExtIdx)
12372 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12373 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12374 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12375 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12376 DAG.getNode(ISD::BITCAST, dl,
12377 N->getOperand(0).getValueType(),
12378 V->getOperand(0)), N->getOperand(1));
12385 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12386 SDValue V, SelectionDAG &DAG) {
12388 EVT VT = V.getValueType();
12390 switch (V.getOpcode()) {
12394 case ISD::CONCAT_VECTORS: {
12395 EVT OpVT = V->getOperand(0).getValueType();
12396 int OpSize = OpVT.getVectorNumElements();
12397 SmallBitVector OpUsedElements(OpSize, false);
12398 bool FoundSimplification = false;
12399 SmallVector<SDValue, 4> NewOps;
12400 NewOps.reserve(V->getNumOperands());
12401 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12402 SDValue Op = V->getOperand(i);
12403 bool OpUsed = false;
12404 for (int j = 0; j < OpSize; ++j)
12405 if (UsedElements[i * OpSize + j]) {
12406 OpUsedElements[j] = true;
12410 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12411 : DAG.getUNDEF(OpVT));
12412 FoundSimplification |= Op == NewOps.back();
12413 OpUsedElements.reset();
12415 if (FoundSimplification)
12416 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12420 case ISD::INSERT_SUBVECTOR: {
12421 SDValue BaseV = V->getOperand(0);
12422 SDValue SubV = V->getOperand(1);
12423 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12427 int SubSize = SubV.getValueType().getVectorNumElements();
12428 int Idx = IdxN->getZExtValue();
12429 bool SubVectorUsed = false;
12430 SmallBitVector SubUsedElements(SubSize, false);
12431 for (int i = 0; i < SubSize; ++i)
12432 if (UsedElements[i + Idx]) {
12433 SubVectorUsed = true;
12434 SubUsedElements[i] = true;
12435 UsedElements[i + Idx] = false;
12438 // Now recurse on both the base and sub vectors.
12439 SDValue SimplifiedSubV =
12441 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12442 : DAG.getUNDEF(SubV.getValueType());
12443 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12444 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12445 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12446 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12452 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12453 SDValue N1, SelectionDAG &DAG) {
12454 EVT VT = SVN->getValueType(0);
12455 int NumElts = VT.getVectorNumElements();
12456 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12457 for (int M : SVN->getMask())
12458 if (M >= 0 && M < NumElts)
12459 N0UsedElements[M] = true;
12460 else if (M >= NumElts)
12461 N1UsedElements[M - NumElts] = true;
12463 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12464 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12465 if (S0 == N0 && S1 == N1)
12468 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12471 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12472 // or turn a shuffle of a single concat into simpler shuffle then concat.
12473 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12474 EVT VT = N->getValueType(0);
12475 unsigned NumElts = VT.getVectorNumElements();
12477 SDValue N0 = N->getOperand(0);
12478 SDValue N1 = N->getOperand(1);
12479 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12481 SmallVector<SDValue, 4> Ops;
12482 EVT ConcatVT = N0.getOperand(0).getValueType();
12483 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12484 unsigned NumConcats = NumElts / NumElemsPerConcat;
12486 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12487 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12488 // half vector elements.
12489 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12490 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12491 SVN->getMask().end(), [](int i) { return i == -1; })) {
12492 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12493 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12494 N1 = DAG.getUNDEF(ConcatVT);
12495 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12498 // Look at every vector that's inserted. We're looking for exact
12499 // subvector-sized copies from a concatenated vector
12500 for (unsigned I = 0; I != NumConcats; ++I) {
12501 // Make sure we're dealing with a copy.
12502 unsigned Begin = I * NumElemsPerConcat;
12503 bool AllUndef = true, NoUndef = true;
12504 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12505 if (SVN->getMaskElt(J) >= 0)
12512 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12515 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12516 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12519 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12520 if (FirstElt < N0.getNumOperands())
12521 Ops.push_back(N0.getOperand(FirstElt));
12523 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12525 } else if (AllUndef) {
12526 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12527 } else { // Mixed with general masks and undefs, can't do optimization.
12532 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12535 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12536 EVT VT = N->getValueType(0);
12537 unsigned NumElts = VT.getVectorNumElements();
12539 SDValue N0 = N->getOperand(0);
12540 SDValue N1 = N->getOperand(1);
12542 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12544 // Canonicalize shuffle undef, undef -> undef
12545 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12546 return DAG.getUNDEF(VT);
12548 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12550 // Canonicalize shuffle v, v -> v, undef
12552 SmallVector<int, 8> NewMask;
12553 for (unsigned i = 0; i != NumElts; ++i) {
12554 int Idx = SVN->getMaskElt(i);
12555 if (Idx >= (int)NumElts) Idx -= NumElts;
12556 NewMask.push_back(Idx);
12558 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12562 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12563 if (N0.getOpcode() == ISD::UNDEF) {
12564 SmallVector<int, 8> NewMask;
12565 for (unsigned i = 0; i != NumElts; ++i) {
12566 int Idx = SVN->getMaskElt(i);
12568 if (Idx >= (int)NumElts)
12571 Idx = -1; // remove reference to lhs
12573 NewMask.push_back(Idx);
12575 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12579 // Remove references to rhs if it is undef
12580 if (N1.getOpcode() == ISD::UNDEF) {
12581 bool Changed = false;
12582 SmallVector<int, 8> NewMask;
12583 for (unsigned i = 0; i != NumElts; ++i) {
12584 int Idx = SVN->getMaskElt(i);
12585 if (Idx >= (int)NumElts) {
12589 NewMask.push_back(Idx);
12592 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12595 // If it is a splat, check if the argument vector is another splat or a
12597 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12598 SDNode *V = N0.getNode();
12600 // If this is a bit convert that changes the element type of the vector but
12601 // not the number of vector elements, look through it. Be careful not to
12602 // look though conversions that change things like v4f32 to v2f64.
12603 if (V->getOpcode() == ISD::BITCAST) {
12604 SDValue ConvInput = V->getOperand(0);
12605 if (ConvInput.getValueType().isVector() &&
12606 ConvInput.getValueType().getVectorNumElements() == NumElts)
12607 V = ConvInput.getNode();
12610 if (V->getOpcode() == ISD::BUILD_VECTOR) {
12611 assert(V->getNumOperands() == NumElts &&
12612 "BUILD_VECTOR has wrong number of operands");
12614 bool AllSame = true;
12615 for (unsigned i = 0; i != NumElts; ++i) {
12616 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12617 Base = V->getOperand(i);
12621 // Splat of <u, u, u, u>, return <u, u, u, u>
12622 if (!Base.getNode())
12624 for (unsigned i = 0; i != NumElts; ++i) {
12625 if (V->getOperand(i) != Base) {
12630 // Splat of <x, x, x, x>, return <x, x, x, x>
12634 // Canonicalize any other splat as a build_vector.
12635 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12636 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12637 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12638 V->getValueType(0), Ops);
12640 // We may have jumped through bitcasts, so the type of the
12641 // BUILD_VECTOR may not match the type of the shuffle.
12642 if (V->getValueType(0) != VT)
12643 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12648 // There are various patterns used to build up a vector from smaller vectors,
12649 // subvectors, or elements. Scan chains of these and replace unused insertions
12650 // or components with undef.
12651 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12654 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12655 Level < AfterLegalizeVectorOps &&
12656 (N1.getOpcode() == ISD::UNDEF ||
12657 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12658 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12659 SDValue V = partitionShuffleOfConcats(N, DAG);
12665 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12666 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12667 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12668 SmallVector<SDValue, 8> Ops;
12669 for (int M : SVN->getMask()) {
12670 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12672 int Idx = M % NumElts;
12673 SDValue &S = (M < (int)NumElts ? N0 : N1);
12674 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12675 Op = S.getOperand(Idx);
12676 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12678 Op = S.getOperand(0);
12680 // Operand can't be combined - bail out.
12686 if (Ops.size() == VT.getVectorNumElements()) {
12687 // BUILD_VECTOR requires all inputs to be of the same type, find the
12688 // maximum type and extend them all.
12689 EVT SVT = VT.getScalarType();
12690 if (SVT.isInteger())
12691 for (SDValue &Op : Ops)
12692 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12693 if (SVT != VT.getScalarType())
12694 for (SDValue &Op : Ops)
12695 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12696 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12697 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12698 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12702 // If this shuffle only has a single input that is a bitcasted shuffle,
12703 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12704 // back to their original types.
12705 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12706 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12707 TLI.isTypeLegal(VT)) {
12709 // Peek through the bitcast only if there is one user.
12711 while (BC0.getOpcode() == ISD::BITCAST) {
12712 if (!BC0.hasOneUse())
12714 BC0 = BC0.getOperand(0);
12717 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12719 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12721 SmallVector<int, 8> NewMask;
12723 for (int s = 0; s != Scale; ++s)
12724 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12728 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12729 EVT SVT = VT.getScalarType();
12730 EVT InnerVT = BC0->getValueType(0);
12731 EVT InnerSVT = InnerVT.getScalarType();
12733 // Determine which shuffle works with the smaller scalar type.
12734 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12735 EVT ScaleSVT = ScaleVT.getScalarType();
12737 if (TLI.isTypeLegal(ScaleVT) &&
12738 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12739 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12741 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12742 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12744 // Scale the shuffle masks to the smaller scalar type.
12745 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12746 SmallVector<int, 8> InnerMask =
12747 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12748 SmallVector<int, 8> OuterMask =
12749 ScaleShuffleMask(SVN->getMask(), OuterScale);
12751 // Merge the shuffle masks.
12752 SmallVector<int, 8> NewMask;
12753 for (int M : OuterMask)
12754 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12756 // Test for shuffle mask legality over both commutations.
12757 SDValue SV0 = BC0->getOperand(0);
12758 SDValue SV1 = BC0->getOperand(1);
12759 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12761 std::swap(SV0, SV1);
12762 ShuffleVectorSDNode::commuteMask(NewMask);
12763 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12767 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12768 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12769 return DAG.getNode(
12770 ISD::BITCAST, SDLoc(N), VT,
12771 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12777 // Canonicalize shuffles according to rules:
12778 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12779 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12780 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12781 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12782 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12783 TLI.isTypeLegal(VT)) {
12784 // The incoming shuffle must be of the same type as the result of the
12785 // current shuffle.
12786 assert(N1->getOperand(0).getValueType() == VT &&
12787 "Shuffle types don't match");
12789 SDValue SV0 = N1->getOperand(0);
12790 SDValue SV1 = N1->getOperand(1);
12791 bool HasSameOp0 = N0 == SV0;
12792 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12793 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12794 // Commute the operands of this shuffle so that next rule
12796 return DAG.getCommutedVectorShuffle(*SVN);
12799 // Try to fold according to rules:
12800 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12801 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12802 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12803 // Don't try to fold shuffles with illegal type.
12804 // Only fold if this shuffle is the only user of the other shuffle.
12805 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12806 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12807 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12809 // The incoming shuffle must be of the same type as the result of the
12810 // current shuffle.
12811 assert(OtherSV->getOperand(0).getValueType() == VT &&
12812 "Shuffle types don't match");
12815 SmallVector<int, 4> Mask;
12816 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12817 // operand, and SV1 as the second operand.
12818 for (unsigned i = 0; i != NumElts; ++i) {
12819 int Idx = SVN->getMaskElt(i);
12821 // Propagate Undef.
12822 Mask.push_back(Idx);
12826 SDValue CurrentVec;
12827 if (Idx < (int)NumElts) {
12828 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12829 // shuffle mask to identify which vector is actually referenced.
12830 Idx = OtherSV->getMaskElt(Idx);
12832 // Propagate Undef.
12833 Mask.push_back(Idx);
12837 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12838 : OtherSV->getOperand(1);
12840 // This shuffle index references an element within N1.
12844 // Simple case where 'CurrentVec' is UNDEF.
12845 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12846 Mask.push_back(-1);
12850 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12851 // will be the first or second operand of the combined shuffle.
12852 Idx = Idx % NumElts;
12853 if (!SV0.getNode() || SV0 == CurrentVec) {
12854 // Ok. CurrentVec is the left hand side.
12855 // Update the mask accordingly.
12857 Mask.push_back(Idx);
12861 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12862 if (SV1.getNode() && SV1 != CurrentVec)
12865 // Ok. CurrentVec is the right hand side.
12866 // Update the mask accordingly.
12868 Mask.push_back(Idx + NumElts);
12871 // Check if all indices in Mask are Undef. In case, propagate Undef.
12872 bool isUndefMask = true;
12873 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12874 isUndefMask &= Mask[i] < 0;
12877 return DAG.getUNDEF(VT);
12879 if (!SV0.getNode())
12880 SV0 = DAG.getUNDEF(VT);
12881 if (!SV1.getNode())
12882 SV1 = DAG.getUNDEF(VT);
12884 // Avoid introducing shuffles with illegal mask.
12885 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12886 ShuffleVectorSDNode::commuteMask(Mask);
12888 if (!TLI.isShuffleMaskLegal(Mask, VT))
12891 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12892 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12893 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12894 std::swap(SV0, SV1);
12897 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12898 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12899 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12900 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12906 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12907 SDValue InVal = N->getOperand(0);
12908 EVT VT = N->getValueType(0);
12910 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12911 // with a VECTOR_SHUFFLE.
12912 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12913 SDValue InVec = InVal->getOperand(0);
12914 SDValue EltNo = InVal->getOperand(1);
12916 // FIXME: We could support implicit truncation if the shuffle can be
12917 // scaled to a smaller vector scalar type.
12918 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12919 if (C0 && VT == InVec.getValueType() &&
12920 VT.getScalarType() == InVal.getValueType()) {
12921 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12922 int Elt = C0->getZExtValue();
12925 if (TLI.isShuffleMaskLegal(NewMask, VT))
12926 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12934 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12935 SDValue N0 = N->getOperand(0);
12936 SDValue N2 = N->getOperand(2);
12938 // If the input vector is a concatenation, and the insert replaces
12939 // one of the halves, we can optimize into a single concat_vectors.
12940 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12941 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12942 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12943 EVT VT = N->getValueType(0);
12945 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12946 // (concat_vectors Z, Y)
12948 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12949 N->getOperand(1), N0.getOperand(1));
12951 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12952 // (concat_vectors X, Z)
12953 if (InsIdx == VT.getVectorNumElements()/2)
12954 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12955 N0.getOperand(0), N->getOperand(1));
12961 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12962 SDValue N0 = N->getOperand(0);
12964 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12965 if (N0->getOpcode() == ISD::FP16_TO_FP)
12966 return N0->getOperand(0);
12971 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12972 /// with the destination vector and a zero vector.
12973 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12974 /// vector_shuffle V, Zero, <0, 4, 2, 4>
12975 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12976 EVT VT = N->getValueType(0);
12977 SDValue LHS = N->getOperand(0);
12978 SDValue RHS = N->getOperand(1);
12981 // Make sure we're not running after operation legalization where it
12982 // may have custom lowered the vector shuffles.
12983 if (LegalOperations)
12986 if (N->getOpcode() != ISD::AND)
12989 if (RHS.getOpcode() == ISD::BITCAST)
12990 RHS = RHS.getOperand(0);
12992 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12993 SmallVector<int, 8> Indices;
12994 unsigned NumElts = RHS.getNumOperands();
12996 for (unsigned i = 0; i != NumElts; ++i) {
12997 SDValue Elt = RHS.getOperand(i);
12998 if (isAllOnesConstant(Elt))
12999 Indices.push_back(i);
13000 else if (isNullConstant(Elt))
13001 Indices.push_back(NumElts+i);
13006 // Let's see if the target supports this vector_shuffle.
13007 EVT RVT = RHS.getValueType();
13008 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
13011 // Return the new VECTOR_SHUFFLE node.
13012 EVT EltVT = RVT.getVectorElementType();
13013 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
13014 DAG.getConstant(0, dl, EltVT));
13015 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
13016 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
13017 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
13018 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
13024 /// Visit a binary vector operation, like ADD.
13025 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13026 assert(N->getValueType(0).isVector() &&
13027 "SimplifyVBinOp only works on vectors!");
13029 SDValue LHS = N->getOperand(0);
13030 SDValue RHS = N->getOperand(1);
13032 if (SDValue Shuffle = XformToShuffleWithZero(N))
13035 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
13037 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
13038 RHS.getOpcode() == ISD::BUILD_VECTOR) {
13039 // Check if both vectors are constants. If not bail out.
13040 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
13041 cast<BuildVectorSDNode>(RHS)->isConstant()))
13044 SmallVector<SDValue, 8> Ops;
13045 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
13046 SDValue LHSOp = LHS.getOperand(i);
13047 SDValue RHSOp = RHS.getOperand(i);
13049 // Can't fold divide by zero.
13050 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
13051 N->getOpcode() == ISD::FDIV) {
13052 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
13053 cast<ConstantFPSDNode>(RHSOp.getNode())->isZero()))
13057 EVT VT = LHSOp.getValueType();
13058 EVT RVT = RHSOp.getValueType();
13060 // Integer BUILD_VECTOR operands may have types larger than the element
13061 // size (e.g., when the element type is not legal). Prior to type
13062 // legalization, the types may not match between the two BUILD_VECTORS.
13063 // Truncate one of the operands to make them match.
13064 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
13065 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
13067 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
13071 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
13073 if (FoldOp.getOpcode() != ISD::UNDEF &&
13074 FoldOp.getOpcode() != ISD::Constant &&
13075 FoldOp.getOpcode() != ISD::ConstantFP)
13077 Ops.push_back(FoldOp);
13078 AddToWorklist(FoldOp.getNode());
13081 if (Ops.size() == LHS.getNumOperands())
13082 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
13085 // Type legalization might introduce new shuffles in the DAG.
13086 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13087 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
13088 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13089 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13090 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13091 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13092 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13093 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13095 if (SVN0->getMask().equals(SVN1->getMask())) {
13096 EVT VT = N->getValueType(0);
13097 SDValue UndefVector = LHS.getOperand(1);
13098 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13099 LHS.getOperand(0), RHS.getOperand(0));
13100 AddUsersToWorklist(N);
13101 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13102 &SVN0->getMask()[0]);
13109 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13110 SDValue N1, SDValue N2){
13111 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13113 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13114 cast<CondCodeSDNode>(N0.getOperand(2))->get());
13116 // If we got a simplified select_cc node back from SimplifySelectCC, then
13117 // break it down into a new SETCC node, and a new SELECT node, and then return
13118 // the SELECT node, since we were called with a SELECT node.
13119 if (SCC.getNode()) {
13120 // Check to see if we got a select_cc back (to turn into setcc/select).
13121 // Otherwise, just return whatever node we got back, like fabs.
13122 if (SCC.getOpcode() == ISD::SELECT_CC) {
13123 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13125 SCC.getOperand(0), SCC.getOperand(1),
13126 SCC.getOperand(4));
13127 AddToWorklist(SETCC.getNode());
13128 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13129 SCC.getOperand(2), SCC.getOperand(3));
13137 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13138 /// being selected between, see if we can simplify the select. Callers of this
13139 /// should assume that TheSelect is deleted if this returns true. As such, they
13140 /// should return the appropriate thing (e.g. the node) back to the top-level of
13141 /// the DAG combiner loop to avoid it being looked at.
13142 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13145 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13146 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13147 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13148 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13149 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13150 SDValue Sqrt = RHS;
13153 const ConstantFPSDNode *NegZero = nullptr;
13155 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13156 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13157 CmpLHS = TheSelect->getOperand(0);
13158 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13160 // SELECT or VSELECT
13161 SDValue Cmp = TheSelect->getOperand(0);
13162 if (Cmp.getOpcode() == ISD::SETCC) {
13163 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13164 CmpLHS = Cmp.getOperand(0);
13165 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13168 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13169 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13170 CC == ISD::SETULT || CC == ISD::SETLT)) {
13171 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13172 CombineTo(TheSelect, Sqrt);
13177 // Cannot simplify select with vector condition
13178 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13180 // If this is a select from two identical things, try to pull the operation
13181 // through the select.
13182 if (LHS.getOpcode() != RHS.getOpcode() ||
13183 !LHS.hasOneUse() || !RHS.hasOneUse())
13186 // If this is a load and the token chain is identical, replace the select
13187 // of two loads with a load through a select of the address to load from.
13188 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13189 // constants have been dropped into the constant pool.
13190 if (LHS.getOpcode() == ISD::LOAD) {
13191 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13192 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13194 // Token chains must be identical.
13195 if (LHS.getOperand(0) != RHS.getOperand(0) ||
13196 // Do not let this transformation reduce the number of volatile loads.
13197 LLD->isVolatile() || RLD->isVolatile() ||
13198 // FIXME: If either is a pre/post inc/dec load,
13199 // we'd need to split out the address adjustment.
13200 LLD->isIndexed() || RLD->isIndexed() ||
13201 // If this is an EXTLOAD, the VT's must match.
13202 LLD->getMemoryVT() != RLD->getMemoryVT() ||
13203 // If this is an EXTLOAD, the kind of extension must match.
13204 (LLD->getExtensionType() != RLD->getExtensionType() &&
13205 // The only exception is if one of the extensions is anyext.
13206 LLD->getExtensionType() != ISD::EXTLOAD &&
13207 RLD->getExtensionType() != ISD::EXTLOAD) ||
13208 // FIXME: this discards src value information. This is
13209 // over-conservative. It would be beneficial to be able to remember
13210 // both potential memory locations. Since we are discarding
13211 // src value info, don't do the transformation if the memory
13212 // locations are not in the default address space.
13213 LLD->getPointerInfo().getAddrSpace() != 0 ||
13214 RLD->getPointerInfo().getAddrSpace() != 0 ||
13215 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13216 LLD->getBasePtr().getValueType()))
13219 // Check that the select condition doesn't reach either load. If so,
13220 // folding this will induce a cycle into the DAG. If not, this is safe to
13221 // xform, so create a select of the addresses.
13223 if (TheSelect->getOpcode() == ISD::SELECT) {
13224 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13225 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13226 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13228 // The loads must not depend on one another.
13229 if (LLD->isPredecessorOf(RLD) ||
13230 RLD->isPredecessorOf(LLD))
13232 Addr = DAG.getSelect(SDLoc(TheSelect),
13233 LLD->getBasePtr().getValueType(),
13234 TheSelect->getOperand(0), LLD->getBasePtr(),
13235 RLD->getBasePtr());
13236 } else { // Otherwise SELECT_CC
13237 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13238 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13240 if ((LLD->hasAnyUseOfValue(1) &&
13241 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13242 (RLD->hasAnyUseOfValue(1) &&
13243 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13246 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13247 LLD->getBasePtr().getValueType(),
13248 TheSelect->getOperand(0),
13249 TheSelect->getOperand(1),
13250 LLD->getBasePtr(), RLD->getBasePtr(),
13251 TheSelect->getOperand(4));
13255 // It is safe to replace the two loads if they have different alignments,
13256 // but the new load must be the minimum (most restrictive) alignment of the
13258 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13259 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13260 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13261 Load = DAG.getLoad(TheSelect->getValueType(0),
13263 // FIXME: Discards pointer and AA info.
13264 LLD->getChain(), Addr, MachinePointerInfo(),
13265 LLD->isVolatile(), LLD->isNonTemporal(),
13266 isInvariant, Alignment);
13268 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13269 RLD->getExtensionType() : LLD->getExtensionType(),
13271 TheSelect->getValueType(0),
13272 // FIXME: Discards pointer and AA info.
13273 LLD->getChain(), Addr, MachinePointerInfo(),
13274 LLD->getMemoryVT(), LLD->isVolatile(),
13275 LLD->isNonTemporal(), isInvariant, Alignment);
13278 // Users of the select now use the result of the load.
13279 CombineTo(TheSelect, Load);
13281 // Users of the old loads now use the new load's chain. We know the
13282 // old-load value is dead now.
13283 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13284 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13291 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13292 /// where 'cond' is the comparison specified by CC.
13293 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13294 SDValue N2, SDValue N3,
13295 ISD::CondCode CC, bool NotExtCompare) {
13296 // (x ? y : y) -> y.
13297 if (N2 == N3) return N2;
13299 EVT VT = N2.getValueType();
13300 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13301 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13303 // Determine if the condition we're dealing with is constant
13304 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13305 N0, N1, CC, DL, false);
13306 if (SCC.getNode()) AddToWorklist(SCC.getNode());
13308 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13309 // fold select_cc true, x, y -> x
13310 // fold select_cc false, x, y -> y
13311 return !SCCC->isNullValue() ? N2 : N3;
13314 // Check to see if we can simplify the select into an fabs node
13315 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13316 // Allow either -0.0 or 0.0
13317 if (CFP->isZero()) {
13318 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13319 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13320 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13321 N2 == N3.getOperand(0))
13322 return DAG.getNode(ISD::FABS, DL, VT, N0);
13324 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13325 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13326 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13327 N2.getOperand(0) == N3)
13328 return DAG.getNode(ISD::FABS, DL, VT, N3);
13332 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13333 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13334 // in it. This is a win when the constant is not otherwise available because
13335 // it replaces two constant pool loads with one. We only do this if the FP
13336 // type is known to be legal, because if it isn't, then we are before legalize
13337 // types an we want the other legalization to happen first (e.g. to avoid
13338 // messing with soft float) and if the ConstantFP is not legal, because if
13339 // it is legal, we may not need to store the FP constant in a constant pool.
13340 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13341 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13342 if (TLI.isTypeLegal(N2.getValueType()) &&
13343 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13344 TargetLowering::Legal &&
13345 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13346 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13347 // If both constants have multiple uses, then we won't need to do an
13348 // extra load, they are likely around in registers for other users.
13349 (TV->hasOneUse() || FV->hasOneUse())) {
13350 Constant *Elts[] = {
13351 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13352 const_cast<ConstantFP*>(TV->getConstantFPValue())
13354 Type *FPTy = Elts[0]->getType();
13355 const DataLayout &TD = *TLI.getDataLayout();
13357 // Create a ConstantArray of the two constants.
13358 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13359 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13360 TD.getPrefTypeAlignment(FPTy));
13361 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13363 // Get the offsets to the 0 and 1 element of the array so that we can
13364 // select between them.
13365 SDValue Zero = DAG.getIntPtrConstant(0, DL);
13366 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13367 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13369 SDValue Cond = DAG.getSetCC(DL,
13370 getSetCCResultType(N0.getValueType()),
13372 AddToWorklist(Cond.getNode());
13373 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13375 AddToWorklist(CstOffset.getNode());
13376 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13378 AddToWorklist(CPIdx.getNode());
13379 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13380 MachinePointerInfo::getConstantPool(), false,
13381 false, false, Alignment);
13385 // Check to see if we can perform the "gzip trick", transforming
13386 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13387 if (isNullConstant(N3) && CC == ISD::SETLT &&
13388 (isNullConstant(N1) || // (a < 0) ? b : 0
13389 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
13390 EVT XType = N0.getValueType();
13391 EVT AType = N2.getValueType();
13392 if (XType.bitsGE(AType)) {
13393 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13394 // single-bit constant.
13395 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13396 unsigned ShCtV = N2C->getAPIntValue().logBase2();
13397 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13398 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13399 getShiftAmountTy(N0.getValueType()));
13400 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13402 AddToWorklist(Shift.getNode());
13404 if (XType.bitsGT(AType)) {
13405 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13406 AddToWorklist(Shift.getNode());
13409 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13412 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13414 DAG.getConstant(XType.getSizeInBits() - 1,
13416 getShiftAmountTy(N0.getValueType())));
13417 AddToWorklist(Shift.getNode());
13419 if (XType.bitsGT(AType)) {
13420 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13421 AddToWorklist(Shift.getNode());
13424 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13428 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13429 // where y is has a single bit set.
13430 // A plaintext description would be, we can turn the SELECT_CC into an AND
13431 // when the condition can be materialized as an all-ones register. Any
13432 // single bit-test can be materialized as an all-ones register with
13433 // shift-left and shift-right-arith.
13434 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13435 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13436 SDValue AndLHS = N0->getOperand(0);
13437 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13438 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13439 // Shift the tested bit over the sign bit.
13440 APInt AndMask = ConstAndRHS->getAPIntValue();
13442 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13443 getShiftAmountTy(AndLHS.getValueType()));
13444 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13446 // Now arithmetic right shift it all the way over, so the result is either
13447 // all-ones, or zero.
13449 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13450 getShiftAmountTy(Shl.getValueType()));
13451 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13453 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13457 // fold select C, 16, 0 -> shl C, 4
13458 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13459 TLI.getBooleanContents(N0.getValueType()) ==
13460 TargetLowering::ZeroOrOneBooleanContent) {
13462 // If the caller doesn't want us to simplify this into a zext of a compare,
13464 if (NotExtCompare && N2C->isOne())
13467 // Get a SetCC of the condition
13468 // NOTE: Don't create a SETCC if it's not legal on this target.
13469 if (!LegalOperations ||
13470 TLI.isOperationLegal(ISD::SETCC,
13471 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13473 // cast from setcc result type to select result type
13475 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13477 if (N2.getValueType().bitsLT(SCC.getValueType()))
13478 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13479 N2.getValueType());
13481 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13482 N2.getValueType(), SCC);
13484 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13485 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13486 N2.getValueType(), SCC);
13489 AddToWorklist(SCC.getNode());
13490 AddToWorklist(Temp.getNode());
13495 // shl setcc result by log2 n2c
13496 return DAG.getNode(
13497 ISD::SHL, DL, N2.getValueType(), Temp,
13498 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13499 getShiftAmountTy(Temp.getValueType())));
13503 // Check to see if this is the equivalent of setcc
13504 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13505 // otherwise, go ahead with the folds.
13506 if (0 && isNullConstant(N3) && isOneConstant(N2)) {
13507 EVT XType = N0.getValueType();
13508 if (!LegalOperations ||
13509 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13510 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13511 if (Res.getValueType() != VT)
13512 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13516 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13517 if (isNullConstant(N1) && CC == ISD::SETEQ &&
13518 (!LegalOperations ||
13519 TLI.isOperationLegal(ISD::CTLZ, XType))) {
13520 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13521 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13522 DAG.getConstant(Log2_32(XType.getSizeInBits()),
13524 getShiftAmountTy(Ctlz.getValueType())));
13526 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13527 if (isNullConstant(N1) && CC == ISD::SETGT) {
13529 SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13530 XType, DAG.getConstant(0, DL, XType), N0);
13531 SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13532 return DAG.getNode(ISD::SRL, DL, XType,
13533 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13534 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13535 getShiftAmountTy(XType)));
13537 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13538 if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
13540 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13541 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13542 getShiftAmountTy(N0.getValueType())));
13543 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13548 // Check to see if this is an integer abs.
13549 // select_cc setg[te] X, 0, X, -X ->
13550 // select_cc setgt X, -1, X, -X ->
13551 // select_cc setl[te] X, 0, -X, X ->
13552 // select_cc setlt X, 1, -X, X ->
13553 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13555 ConstantSDNode *SubC = nullptr;
13556 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13557 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13558 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13559 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13560 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13561 (N1C->isOne() && CC == ISD::SETLT)) &&
13562 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13563 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13565 EVT XType = N0.getValueType();
13566 if (SubC && SubC->isNullValue() && XType.isInteger()) {
13568 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13570 DAG.getConstant(XType.getSizeInBits() - 1, DL,
13571 getShiftAmountTy(N0.getValueType())));
13572 SDValue Add = DAG.getNode(ISD::ADD, DL,
13574 AddToWorklist(Shift.getNode());
13575 AddToWorklist(Add.getNode());
13576 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13583 /// This is a stub for TargetLowering::SimplifySetCC.
13584 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13585 SDValue N1, ISD::CondCode Cond,
13586 SDLoc DL, bool foldBooleans) {
13587 TargetLowering::DAGCombinerInfo
13588 DagCombineInfo(DAG, Level, false, this);
13589 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13592 /// Given an ISD::SDIV node expressing a divide by constant, return
13593 /// a DAG expression to select that will generate the same value by multiplying
13594 /// by a magic number.
13595 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13596 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13597 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13601 // Avoid division by zero.
13602 if (C->isNullValue())
13605 std::vector<SDNode*> Built;
13607 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13609 for (SDNode *N : Built)
13614 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13615 /// DAG expression that will generate the same value by right shifting.
13616 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13617 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13621 // Avoid division by zero.
13622 if (C->isNullValue())
13625 std::vector<SDNode *> Built;
13626 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13628 for (SDNode *N : Built)
13633 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13634 /// expression that will generate the same value by multiplying by a magic
13636 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13637 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13638 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13642 // Avoid division by zero.
13643 if (C->isNullValue())
13646 std::vector<SDNode*> Built;
13648 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13650 for (SDNode *N : Built)
13655 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13656 if (Level >= AfterLegalizeDAG)
13659 // Expose the DAG combiner to the target combiner implementations.
13660 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13662 unsigned Iterations = 0;
13663 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13665 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13666 // For the reciprocal, we need to find the zero of the function:
13667 // F(X) = A X - 1 [which has a zero at X = 1/A]
13669 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13670 // does not require additional intermediate precision]
13671 EVT VT = Op.getValueType();
13673 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13675 AddToWorklist(Est.getNode());
13677 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13678 for (unsigned i = 0; i < Iterations; ++i) {
13679 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13680 AddToWorklist(NewEst.getNode());
13682 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13683 AddToWorklist(NewEst.getNode());
13685 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13686 AddToWorklist(NewEst.getNode());
13688 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13689 AddToWorklist(Est.getNode());
13698 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13699 /// For the reciprocal sqrt, we need to find the zero of the function:
13700 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13702 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13703 /// As a result, we precompute A/2 prior to the iteration loop.
13704 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13705 unsigned Iterations) {
13706 EVT VT = Arg.getValueType();
13708 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13710 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13711 // this entire sequence requires only one FP constant.
13712 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13713 AddToWorklist(HalfArg.getNode());
13715 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13716 AddToWorklist(HalfArg.getNode());
13718 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13719 for (unsigned i = 0; i < Iterations; ++i) {
13720 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13721 AddToWorklist(NewEst.getNode());
13723 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13724 AddToWorklist(NewEst.getNode());
13726 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13727 AddToWorklist(NewEst.getNode());
13729 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13730 AddToWorklist(Est.getNode());
13735 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13736 /// For the reciprocal sqrt, we need to find the zero of the function:
13737 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13739 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13740 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13741 unsigned Iterations) {
13742 EVT VT = Arg.getValueType();
13744 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13745 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13747 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13748 for (unsigned i = 0; i < Iterations; ++i) {
13749 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13750 AddToWorklist(HalfEst.getNode());
13752 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13753 AddToWorklist(Est.getNode());
13755 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13756 AddToWorklist(Est.getNode());
13758 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13759 AddToWorklist(Est.getNode());
13761 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13762 AddToWorklist(Est.getNode());
13767 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13768 if (Level >= AfterLegalizeDAG)
13771 // Expose the DAG combiner to the target combiner implementations.
13772 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13773 unsigned Iterations = 0;
13774 bool UseOneConstNR = false;
13775 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13776 AddToWorklist(Est.getNode());
13778 Est = UseOneConstNR ?
13779 BuildRsqrtNROneConst(Op, Est, Iterations) :
13780 BuildRsqrtNRTwoConst(Op, Est, Iterations);
13788 /// Return true if base is a frame index, which is known not to alias with
13789 /// anything but itself. Provides base object and offset as results.
13790 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13791 const GlobalValue *&GV, const void *&CV) {
13792 // Assume it is a primitive operation.
13793 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13795 // If it's an adding a simple constant then integrate the offset.
13796 if (Base.getOpcode() == ISD::ADD) {
13797 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13798 Base = Base.getOperand(0);
13799 Offset += C->getZExtValue();
13803 // Return the underlying GlobalValue, and update the Offset. Return false
13804 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13805 // by multiple nodes with different offsets.
13806 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13807 GV = G->getGlobal();
13808 Offset += G->getOffset();
13812 // Return the underlying Constant value, and update the Offset. Return false
13813 // for ConstantSDNodes since the same constant pool entry may be represented
13814 // by multiple nodes with different offsets.
13815 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13816 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13817 : (const void *)C->getConstVal();
13818 Offset += C->getOffset();
13821 // If it's any of the following then it can't alias with anything but itself.
13822 return isa<FrameIndexSDNode>(Base);
13825 /// Return true if there is any possibility that the two addresses overlap.
13826 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13827 // If they are the same then they must be aliases.
13828 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13830 // If they are both volatile then they cannot be reordered.
13831 if (Op0->isVolatile() && Op1->isVolatile()) return true;
13833 // Gather base node and offset information.
13834 SDValue Base1, Base2;
13835 int64_t Offset1, Offset2;
13836 const GlobalValue *GV1, *GV2;
13837 const void *CV1, *CV2;
13838 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13839 Base1, Offset1, GV1, CV1);
13840 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13841 Base2, Offset2, GV2, CV2);
13843 // If they have a same base address then check to see if they overlap.
13844 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13845 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13846 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13848 // It is possible for different frame indices to alias each other, mostly
13849 // when tail call optimization reuses return address slots for arguments.
13850 // To catch this case, look up the actual index of frame indices to compute
13851 // the real alias relationship.
13852 if (isFrameIndex1 && isFrameIndex2) {
13853 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13854 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13855 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13856 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13857 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13860 // Otherwise, if we know what the bases are, and they aren't identical, then
13861 // we know they cannot alias.
13862 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13865 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13866 // compared to the size and offset of the access, we may be able to prove they
13867 // do not alias. This check is conservative for now to catch cases created by
13868 // splitting vector types.
13869 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13870 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13871 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13872 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13873 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13874 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13875 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13877 // There is no overlap between these relatively aligned accesses of similar
13878 // size, return no alias.
13879 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13880 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13884 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13886 : DAG.getSubtarget().useAA();
13888 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13889 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13893 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13894 // Use alias analysis information.
13895 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13896 Op1->getSrcValueOffset());
13897 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13898 Op0->getSrcValueOffset() - MinOffset;
13899 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13900 Op1->getSrcValueOffset() - MinOffset;
13901 AliasResult AAResult =
13902 AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
13903 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13904 MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
13905 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13906 if (AAResult == NoAlias)
13910 // Otherwise we have to assume they alias.
13914 /// Walk up chain skipping non-aliasing memory nodes,
13915 /// looking for aliasing nodes and adding them to the Aliases vector.
13916 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13917 SmallVectorImpl<SDValue> &Aliases) {
13918 SmallVector<SDValue, 8> Chains; // List of chains to visit.
13919 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
13921 // Get alias information for node.
13922 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13925 Chains.push_back(OriginalChain);
13926 unsigned Depth = 0;
13928 // Look at each chain and determine if it is an alias. If so, add it to the
13929 // aliases list. If not, then continue up the chain looking for the next
13931 while (!Chains.empty()) {
13932 SDValue Chain = Chains.pop_back_val();
13934 // For TokenFactor nodes, look at each operand and only continue up the
13935 // chain until we find two aliases. If we've seen two aliases, assume we'll
13936 // find more and revert to original chain since the xform is unlikely to be
13939 // FIXME: The depth check could be made to return the last non-aliasing
13940 // chain we found before we hit a tokenfactor rather than the original
13942 if (Depth > 6 || Aliases.size() == 2) {
13944 Aliases.push_back(OriginalChain);
13948 // Don't bother if we've been before.
13949 if (!Visited.insert(Chain.getNode()).second)
13952 switch (Chain.getOpcode()) {
13953 case ISD::EntryToken:
13954 // Entry token is ideal chain operand, but handled in FindBetterChain.
13959 // Get alias information for Chain.
13960 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13961 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13963 // If chain is alias then stop here.
13964 if (!(IsLoad && IsOpLoad) &&
13965 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13966 Aliases.push_back(Chain);
13968 // Look further up the chain.
13969 Chains.push_back(Chain.getOperand(0));
13975 case ISD::TokenFactor:
13976 // We have to check each of the operands of the token factor for "small"
13977 // token factors, so we queue them up. Adding the operands to the queue
13978 // (stack) in reverse order maintains the original order and increases the
13979 // likelihood that getNode will find a matching token factor (CSE.)
13980 if (Chain.getNumOperands() > 16) {
13981 Aliases.push_back(Chain);
13984 for (unsigned n = Chain.getNumOperands(); n;)
13985 Chains.push_back(Chain.getOperand(--n));
13990 // For all other instructions we will just have to take what we can get.
13991 Aliases.push_back(Chain);
13996 // We need to be careful here to also search for aliases through the
13997 // value operand of a store, etc. Consider the following situation:
13999 // L1 = load Token1, %52
14000 // S1 = store Token1, L1, %51
14001 // L2 = load Token1, %52+8
14002 // S2 = store Token1, L2, %51+8
14003 // Token2 = Token(S1, S2)
14004 // L3 = load Token2, %53
14005 // S3 = store Token2, L3, %52
14006 // L4 = load Token2, %53+8
14007 // S4 = store Token2, L4, %52+8
14008 // If we search for aliases of S3 (which loads address %52), and we look
14009 // only through the chain, then we'll miss the trivial dependence on L1
14010 // (which also loads from %52). We then might change all loads and
14011 // stores to use Token1 as their chain operand, which could result in
14012 // copying %53 into %52 before copying %52 into %51 (which should
14015 // The problem is, however, that searching for such data dependencies
14016 // can become expensive, and the cost is not directly related to the
14017 // chain depth. Instead, we'll rule out such configurations here by
14018 // insisting that we've visited all chain users (except for users
14019 // of the original chain, which is not necessary). When doing this,
14020 // we need to look through nodes we don't care about (otherwise, things
14021 // like register copies will interfere with trivial cases).
14023 SmallVector<const SDNode *, 16> Worklist;
14024 for (const SDNode *N : Visited)
14025 if (N != OriginalChain.getNode())
14026 Worklist.push_back(N);
14028 while (!Worklist.empty()) {
14029 const SDNode *M = Worklist.pop_back_val();
14031 // We have already visited M, and want to make sure we've visited any uses
14032 // of M that we care about. For uses that we've not visisted, and don't
14033 // care about, queue them to the worklist.
14035 for (SDNode::use_iterator UI = M->use_begin(),
14036 UIE = M->use_end(); UI != UIE; ++UI)
14037 if (UI.getUse().getValueType() == MVT::Other &&
14038 Visited.insert(*UI).second) {
14039 if (isa<MemSDNode>(*UI)) {
14040 // We've not visited this use, and we care about it (it could have an
14041 // ordering dependency with the original node).
14043 Aliases.push_back(OriginalChain);
14047 // We've not visited this use, but we don't care about it. Mark it as
14048 // visited and enqueue it to the worklist.
14049 Worklist.push_back(*UI);
14054 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14055 /// (aliasing node.)
14056 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14057 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
14059 // Accumulate all the aliases to this node.
14060 GatherAllAliases(N, OldChain, Aliases);
14062 // If no operands then chain to entry token.
14063 if (Aliases.size() == 0)
14064 return DAG.getEntryNode();
14066 // If a single operand then chain to it. We don't need to revisit it.
14067 if (Aliases.size() == 1)
14070 // Construct a custom tailored token factor.
14071 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14074 /// This is the entry point for the file.
14075 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14076 CodeGenOpt::Level OptLevel) {
14077 /// This is the main entry point to this class.
14078 DAGCombiner(*this, AA, OptLevel).Run(Level);