[Alignment] Use Align for TargetLowering::MinStackArgumentAlignment
[llvm-core.git] / lib / CodeGen / SelectionDAG / SelectionDAG.cpp
blob203cb0b46a12029a858abdaff239d6fe2f8746f5
1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the SelectionDAG class.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/CodeGen/ISDOpcodes.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineConstantPool.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineMemOperand.h"
34 #include "llvm/CodeGen/RuntimeLibcalls.h"
35 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
36 #include "llvm/CodeGen/SelectionDAGNodes.h"
37 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
38 #include "llvm/CodeGen/TargetLowering.h"
39 #include "llvm/CodeGen/TargetRegisterInfo.h"
40 #include "llvm/CodeGen/TargetSubtargetInfo.h"
41 #include "llvm/CodeGen/ValueTypes.h"
42 #include "llvm/IR/Constant.h"
43 #include "llvm/IR/Constants.h"
44 #include "llvm/IR/DataLayout.h"
45 #include "llvm/IR/DebugInfoMetadata.h"
46 #include "llvm/IR/DebugLoc.h"
47 #include "llvm/IR/DerivedTypes.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/GlobalValue.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/IR/Type.h"
52 #include "llvm/IR/Value.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CodeGen.h"
55 #include "llvm/Support/Compiler.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/KnownBits.h"
59 #include "llvm/Support/MachineValueType.h"
60 #include "llvm/Support/ManagedStatic.h"
61 #include "llvm/Support/MathExtras.h"
62 #include "llvm/Support/Mutex.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/Target/TargetMachine.h"
65 #include "llvm/Target/TargetOptions.h"
66 #include <algorithm>
67 #include <cassert>
68 #include <cstdint>
69 #include <cstdlib>
70 #include <limits>
71 #include <set>
72 #include <string>
73 #include <utility>
74 #include <vector>
76 using namespace llvm;
78 /// makeVTList - Return an instance of the SDVTList struct initialized with the
79 /// specified members.
80 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
81 SDVTList Res = {VTs, NumVTs};
82 return Res;
85 // Default null implementations of the callbacks.
86 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
87 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
88 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
90 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
92 #define DEBUG_TYPE "selectiondag"
94 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
95 cl::Hidden, cl::init(true),
96 cl::desc("Gang up loads and stores generated by inlining of memcpy"));
98 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
99 cl::desc("Number limit for gluing ld/st of memcpy."),
100 cl::Hidden, cl::init(0));
102 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
103 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
106 //===----------------------------------------------------------------------===//
107 // ConstantFPSDNode Class
108 //===----------------------------------------------------------------------===//
110 /// isExactlyValue - We don't rely on operator== working on double values, as
111 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
112 /// As such, this method can be used to do an exact bit-for-bit comparison of
113 /// two floating point values.
114 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
115 return getValueAPF().bitwiseIsEqual(V);
118 bool ConstantFPSDNode::isValueValidForType(EVT VT,
119 const APFloat& Val) {
120 assert(VT.isFloatingPoint() && "Can only convert between FP types");
122 // convert modifies in place, so make a copy.
123 APFloat Val2 = APFloat(Val);
124 bool losesInfo;
125 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
126 APFloat::rmNearestTiesToEven,
127 &losesInfo);
128 return !losesInfo;
131 //===----------------------------------------------------------------------===//
132 // ISD Namespace
133 //===----------------------------------------------------------------------===//
135 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
136 auto *BV = dyn_cast<BuildVectorSDNode>(N);
137 if (!BV)
138 return false;
140 APInt SplatUndef;
141 unsigned SplatBitSize;
142 bool HasUndefs;
143 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
144 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
145 EltSize) &&
146 EltSize == SplatBitSize;
149 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
150 // specializations of the more general isConstantSplatVector()?
152 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
153 // Look through a bit convert.
154 while (N->getOpcode() == ISD::BITCAST)
155 N = N->getOperand(0).getNode();
157 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
159 unsigned i = 0, e = N->getNumOperands();
161 // Skip over all of the undef values.
162 while (i != e && N->getOperand(i).isUndef())
163 ++i;
165 // Do not accept an all-undef vector.
166 if (i == e) return false;
168 // Do not accept build_vectors that aren't all constants or which have non-~0
169 // elements. We have to be a bit careful here, as the type of the constant
170 // may not be the same as the type of the vector elements due to type
171 // legalization (the elements are promoted to a legal type for the target and
172 // a vector of a type may be legal when the base element type is not).
173 // We only want to check enough bits to cover the vector elements, because
174 // we care if the resultant vector is all ones, not whether the individual
175 // constants are.
176 SDValue NotZero = N->getOperand(i);
177 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
178 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
179 if (CN->getAPIntValue().countTrailingOnes() < EltSize)
180 return false;
181 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
182 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
183 return false;
184 } else
185 return false;
187 // Okay, we have at least one ~0 value, check to see if the rest match or are
188 // undefs. Even with the above element type twiddling, this should be OK, as
189 // the same type legalization should have applied to all the elements.
190 for (++i; i != e; ++i)
191 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
192 return false;
193 return true;
196 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
197 // Look through a bit convert.
198 while (N->getOpcode() == ISD::BITCAST)
199 N = N->getOperand(0).getNode();
201 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
203 bool IsAllUndef = true;
204 for (const SDValue &Op : N->op_values()) {
205 if (Op.isUndef())
206 continue;
207 IsAllUndef = false;
208 // Do not accept build_vectors that aren't all constants or which have non-0
209 // elements. We have to be a bit careful here, as the type of the constant
210 // may not be the same as the type of the vector elements due to type
211 // legalization (the elements are promoted to a legal type for the target
212 // and a vector of a type may be legal when the base element type is not).
213 // We only want to check enough bits to cover the vector elements, because
214 // we care if the resultant vector is all zeros, not whether the individual
215 // constants are.
216 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
217 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
218 if (CN->getAPIntValue().countTrailingZeros() < EltSize)
219 return false;
220 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
221 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
222 return false;
223 } else
224 return false;
227 // Do not accept an all-undef vector.
228 if (IsAllUndef)
229 return false;
230 return true;
233 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
234 if (N->getOpcode() != ISD::BUILD_VECTOR)
235 return false;
237 for (const SDValue &Op : N->op_values()) {
238 if (Op.isUndef())
239 continue;
240 if (!isa<ConstantSDNode>(Op))
241 return false;
243 return true;
246 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
247 if (N->getOpcode() != ISD::BUILD_VECTOR)
248 return false;
250 for (const SDValue &Op : N->op_values()) {
251 if (Op.isUndef())
252 continue;
253 if (!isa<ConstantFPSDNode>(Op))
254 return false;
256 return true;
259 bool ISD::allOperandsUndef(const SDNode *N) {
260 // Return false if the node has no operands.
261 // This is "logically inconsistent" with the definition of "all" but
262 // is probably the desired behavior.
263 if (N->getNumOperands() == 0)
264 return false;
265 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
268 bool ISD::matchUnaryPredicate(SDValue Op,
269 std::function<bool(ConstantSDNode *)> Match,
270 bool AllowUndefs) {
271 // FIXME: Add support for scalar UNDEF cases?
272 if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
273 return Match(Cst);
275 // FIXME: Add support for vector UNDEF cases?
276 if (ISD::BUILD_VECTOR != Op.getOpcode())
277 return false;
279 EVT SVT = Op.getValueType().getScalarType();
280 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
281 if (AllowUndefs && Op.getOperand(i).isUndef()) {
282 if (!Match(nullptr))
283 return false;
284 continue;
287 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
288 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
289 return false;
291 return true;
294 bool ISD::matchBinaryPredicate(
295 SDValue LHS, SDValue RHS,
296 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
297 bool AllowUndefs, bool AllowTypeMismatch) {
298 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
299 return false;
301 // TODO: Add support for scalar UNDEF cases?
302 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
303 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
304 return Match(LHSCst, RHSCst);
306 // TODO: Add support for vector UNDEF cases?
307 if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
308 ISD::BUILD_VECTOR != RHS.getOpcode())
309 return false;
311 EVT SVT = LHS.getValueType().getScalarType();
312 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
313 SDValue LHSOp = LHS.getOperand(i);
314 SDValue RHSOp = RHS.getOperand(i);
315 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
316 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
317 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
318 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
319 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
320 return false;
321 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
322 LHSOp.getValueType() != RHSOp.getValueType()))
323 return false;
324 if (!Match(LHSCst, RHSCst))
325 return false;
327 return true;
330 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
331 switch (ExtType) {
332 case ISD::EXTLOAD:
333 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
334 case ISD::SEXTLOAD:
335 return ISD::SIGN_EXTEND;
336 case ISD::ZEXTLOAD:
337 return ISD::ZERO_EXTEND;
338 default:
339 break;
342 llvm_unreachable("Invalid LoadExtType");
345 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
346 // To perform this operation, we just need to swap the L and G bits of the
347 // operation.
348 unsigned OldL = (Operation >> 2) & 1;
349 unsigned OldG = (Operation >> 1) & 1;
350 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
351 (OldL << 1) | // New G bit
352 (OldG << 2)); // New L bit.
355 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
356 unsigned Operation = Op;
357 if (isInteger)
358 Operation ^= 7; // Flip L, G, E bits, but not U.
359 else
360 Operation ^= 15; // Flip all of the condition bits.
362 if (Operation > ISD::SETTRUE2)
363 Operation &= ~8; // Don't let N and U bits get set.
365 return ISD::CondCode(Operation);
368 /// For an integer comparison, return 1 if the comparison is a signed operation
369 /// and 2 if the result is an unsigned comparison. Return zero if the operation
370 /// does not depend on the sign of the input (setne and seteq).
371 static int isSignedOp(ISD::CondCode Opcode) {
372 switch (Opcode) {
373 default: llvm_unreachable("Illegal integer setcc operation!");
374 case ISD::SETEQ:
375 case ISD::SETNE: return 0;
376 case ISD::SETLT:
377 case ISD::SETLE:
378 case ISD::SETGT:
379 case ISD::SETGE: return 1;
380 case ISD::SETULT:
381 case ISD::SETULE:
382 case ISD::SETUGT:
383 case ISD::SETUGE: return 2;
387 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
388 bool IsInteger) {
389 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
390 // Cannot fold a signed integer setcc with an unsigned integer setcc.
391 return ISD::SETCC_INVALID;
393 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
395 // If the N and U bits get set, then the resultant comparison DOES suddenly
396 // care about orderedness, and it is true when ordered.
397 if (Op > ISD::SETTRUE2)
398 Op &= ~16; // Clear the U bit if the N bit is set.
400 // Canonicalize illegal integer setcc's.
401 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
402 Op = ISD::SETNE;
404 return ISD::CondCode(Op);
407 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
408 bool IsInteger) {
409 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
410 // Cannot fold a signed setcc with an unsigned setcc.
411 return ISD::SETCC_INVALID;
413 // Combine all of the condition bits.
414 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
416 // Canonicalize illegal integer setcc's.
417 if (IsInteger) {
418 switch (Result) {
419 default: break;
420 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
421 case ISD::SETOEQ: // SETEQ & SETU[LG]E
422 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
423 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
424 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
428 return Result;
431 //===----------------------------------------------------------------------===//
432 // SDNode Profile Support
433 //===----------------------------------------------------------------------===//
435 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
436 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
437 ID.AddInteger(OpC);
440 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
441 /// solely with their pointer.
442 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
443 ID.AddPointer(VTList.VTs);
446 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
447 static void AddNodeIDOperands(FoldingSetNodeID &ID,
448 ArrayRef<SDValue> Ops) {
449 for (auto& Op : Ops) {
450 ID.AddPointer(Op.getNode());
451 ID.AddInteger(Op.getResNo());
455 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
456 static void AddNodeIDOperands(FoldingSetNodeID &ID,
457 ArrayRef<SDUse> Ops) {
458 for (auto& Op : Ops) {
459 ID.AddPointer(Op.getNode());
460 ID.AddInteger(Op.getResNo());
464 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
465 SDVTList VTList, ArrayRef<SDValue> OpList) {
466 AddNodeIDOpcode(ID, OpC);
467 AddNodeIDValueTypes(ID, VTList);
468 AddNodeIDOperands(ID, OpList);
471 /// If this is an SDNode with special info, add this info to the NodeID data.
472 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
473 switch (N->getOpcode()) {
474 case ISD::TargetExternalSymbol:
475 case ISD::ExternalSymbol:
476 case ISD::MCSymbol:
477 llvm_unreachable("Should only be used on nodes with operands");
478 default: break; // Normal nodes don't need extra info.
479 case ISD::TargetConstant:
480 case ISD::Constant: {
481 const ConstantSDNode *C = cast<ConstantSDNode>(N);
482 ID.AddPointer(C->getConstantIntValue());
483 ID.AddBoolean(C->isOpaque());
484 break;
486 case ISD::TargetConstantFP:
487 case ISD::ConstantFP:
488 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
489 break;
490 case ISD::TargetGlobalAddress:
491 case ISD::GlobalAddress:
492 case ISD::TargetGlobalTLSAddress:
493 case ISD::GlobalTLSAddress: {
494 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
495 ID.AddPointer(GA->getGlobal());
496 ID.AddInteger(GA->getOffset());
497 ID.AddInteger(GA->getTargetFlags());
498 break;
500 case ISD::BasicBlock:
501 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
502 break;
503 case ISD::Register:
504 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
505 break;
506 case ISD::RegisterMask:
507 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
508 break;
509 case ISD::SRCVALUE:
510 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
511 break;
512 case ISD::FrameIndex:
513 case ISD::TargetFrameIndex:
514 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
515 break;
516 case ISD::LIFETIME_START:
517 case ISD::LIFETIME_END:
518 if (cast<LifetimeSDNode>(N)->hasOffset()) {
519 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
520 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
522 break;
523 case ISD::JumpTable:
524 case ISD::TargetJumpTable:
525 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
526 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
527 break;
528 case ISD::ConstantPool:
529 case ISD::TargetConstantPool: {
530 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
531 ID.AddInteger(CP->getAlignment());
532 ID.AddInteger(CP->getOffset());
533 if (CP->isMachineConstantPoolEntry())
534 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
535 else
536 ID.AddPointer(CP->getConstVal());
537 ID.AddInteger(CP->getTargetFlags());
538 break;
540 case ISD::TargetIndex: {
541 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
542 ID.AddInteger(TI->getIndex());
543 ID.AddInteger(TI->getOffset());
544 ID.AddInteger(TI->getTargetFlags());
545 break;
547 case ISD::LOAD: {
548 const LoadSDNode *LD = cast<LoadSDNode>(N);
549 ID.AddInteger(LD->getMemoryVT().getRawBits());
550 ID.AddInteger(LD->getRawSubclassData());
551 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
552 break;
554 case ISD::STORE: {
555 const StoreSDNode *ST = cast<StoreSDNode>(N);
556 ID.AddInteger(ST->getMemoryVT().getRawBits());
557 ID.AddInteger(ST->getRawSubclassData());
558 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
559 break;
561 case ISD::MLOAD: {
562 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
563 ID.AddInteger(MLD->getMemoryVT().getRawBits());
564 ID.AddInteger(MLD->getRawSubclassData());
565 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
566 break;
568 case ISD::MSTORE: {
569 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
570 ID.AddInteger(MST->getMemoryVT().getRawBits());
571 ID.AddInteger(MST->getRawSubclassData());
572 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
573 break;
575 case ISD::MGATHER: {
576 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
577 ID.AddInteger(MG->getMemoryVT().getRawBits());
578 ID.AddInteger(MG->getRawSubclassData());
579 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
580 break;
582 case ISD::MSCATTER: {
583 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
584 ID.AddInteger(MS->getMemoryVT().getRawBits());
585 ID.AddInteger(MS->getRawSubclassData());
586 ID.AddInteger(MS->getPointerInfo().getAddrSpace());
587 break;
589 case ISD::ATOMIC_CMP_SWAP:
590 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
591 case ISD::ATOMIC_SWAP:
592 case ISD::ATOMIC_LOAD_ADD:
593 case ISD::ATOMIC_LOAD_SUB:
594 case ISD::ATOMIC_LOAD_AND:
595 case ISD::ATOMIC_LOAD_CLR:
596 case ISD::ATOMIC_LOAD_OR:
597 case ISD::ATOMIC_LOAD_XOR:
598 case ISD::ATOMIC_LOAD_NAND:
599 case ISD::ATOMIC_LOAD_MIN:
600 case ISD::ATOMIC_LOAD_MAX:
601 case ISD::ATOMIC_LOAD_UMIN:
602 case ISD::ATOMIC_LOAD_UMAX:
603 case ISD::ATOMIC_LOAD:
604 case ISD::ATOMIC_STORE: {
605 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
606 ID.AddInteger(AT->getMemoryVT().getRawBits());
607 ID.AddInteger(AT->getRawSubclassData());
608 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
609 break;
611 case ISD::PREFETCH: {
612 const MemSDNode *PF = cast<MemSDNode>(N);
613 ID.AddInteger(PF->getPointerInfo().getAddrSpace());
614 break;
616 case ISD::VECTOR_SHUFFLE: {
617 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
618 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
619 i != e; ++i)
620 ID.AddInteger(SVN->getMaskElt(i));
621 break;
623 case ISD::TargetBlockAddress:
624 case ISD::BlockAddress: {
625 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
626 ID.AddPointer(BA->getBlockAddress());
627 ID.AddInteger(BA->getOffset());
628 ID.AddInteger(BA->getTargetFlags());
629 break;
631 } // end switch (N->getOpcode())
633 // Target specific memory nodes could also have address spaces to check.
634 if (N->isTargetMemoryOpcode())
635 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
638 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
639 /// data.
640 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
641 AddNodeIDOpcode(ID, N->getOpcode());
642 // Add the return value info.
643 AddNodeIDValueTypes(ID, N->getVTList());
644 // Add the operand info.
645 AddNodeIDOperands(ID, N->ops());
647 // Handle SDNode leafs with special info.
648 AddNodeIDCustom(ID, N);
651 //===----------------------------------------------------------------------===//
652 // SelectionDAG Class
653 //===----------------------------------------------------------------------===//
655 /// doNotCSE - Return true if CSE should not be performed for this node.
656 static bool doNotCSE(SDNode *N) {
657 if (N->getValueType(0) == MVT::Glue)
658 return true; // Never CSE anything that produces a flag.
660 switch (N->getOpcode()) {
661 default: break;
662 case ISD::HANDLENODE:
663 case ISD::EH_LABEL:
664 return true; // Never CSE these nodes.
667 // Check that remaining values produced are not flags.
668 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
669 if (N->getValueType(i) == MVT::Glue)
670 return true; // Never CSE anything that produces a flag.
672 return false;
675 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
676 /// SelectionDAG.
677 void SelectionDAG::RemoveDeadNodes() {
678 // Create a dummy node (which is not added to allnodes), that adds a reference
679 // to the root node, preventing it from being deleted.
680 HandleSDNode Dummy(getRoot());
682 SmallVector<SDNode*, 128> DeadNodes;
684 // Add all obviously-dead nodes to the DeadNodes worklist.
685 for (SDNode &Node : allnodes())
686 if (Node.use_empty())
687 DeadNodes.push_back(&Node);
689 RemoveDeadNodes(DeadNodes);
691 // If the root changed (e.g. it was a dead load, update the root).
692 setRoot(Dummy.getValue());
695 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
696 /// given list, and any nodes that become unreachable as a result.
697 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
699 // Process the worklist, deleting the nodes and adding their uses to the
700 // worklist.
701 while (!DeadNodes.empty()) {
702 SDNode *N = DeadNodes.pop_back_val();
703 // Skip to next node if we've already managed to delete the node. This could
704 // happen if replacing a node causes a node previously added to the node to
705 // be deleted.
706 if (N->getOpcode() == ISD::DELETED_NODE)
707 continue;
709 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
710 DUL->NodeDeleted(N, nullptr);
712 // Take the node out of the appropriate CSE map.
713 RemoveNodeFromCSEMaps(N);
715 // Next, brutally remove the operand list. This is safe to do, as there are
716 // no cycles in the graph.
717 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
718 SDUse &Use = *I++;
719 SDNode *Operand = Use.getNode();
720 Use.set(SDValue());
722 // Now that we removed this operand, see if there are no uses of it left.
723 if (Operand->use_empty())
724 DeadNodes.push_back(Operand);
727 DeallocateNode(N);
731 void SelectionDAG::RemoveDeadNode(SDNode *N){
732 SmallVector<SDNode*, 16> DeadNodes(1, N);
734 // Create a dummy node that adds a reference to the root node, preventing
735 // it from being deleted. (This matters if the root is an operand of the
736 // dead node.)
737 HandleSDNode Dummy(getRoot());
739 RemoveDeadNodes(DeadNodes);
742 void SelectionDAG::DeleteNode(SDNode *N) {
743 // First take this out of the appropriate CSE map.
744 RemoveNodeFromCSEMaps(N);
746 // Finally, remove uses due to operands of this node, remove from the
747 // AllNodes list, and delete the node.
748 DeleteNodeNotInCSEMaps(N);
751 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
752 assert(N->getIterator() != AllNodes.begin() &&
753 "Cannot delete the entry node!");
754 assert(N->use_empty() && "Cannot delete a node that is not dead!");
756 // Drop all of the operands and decrement used node's use counts.
757 N->DropOperands();
759 DeallocateNode(N);
762 void SDDbgInfo::erase(const SDNode *Node) {
763 DbgValMapType::iterator I = DbgValMap.find(Node);
764 if (I == DbgValMap.end())
765 return;
766 for (auto &Val: I->second)
767 Val->setIsInvalidated();
768 DbgValMap.erase(I);
771 void SelectionDAG::DeallocateNode(SDNode *N) {
772 // If we have operands, deallocate them.
773 removeOperands(N);
775 NodeAllocator.Deallocate(AllNodes.remove(N));
777 // Set the opcode to DELETED_NODE to help catch bugs when node
778 // memory is reallocated.
779 // FIXME: There are places in SDag that have grown a dependency on the opcode
780 // value in the released node.
781 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
782 N->NodeType = ISD::DELETED_NODE;
784 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
785 // them and forget about that node.
786 DbgInfo->erase(N);
789 #ifndef NDEBUG
790 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
791 static void VerifySDNode(SDNode *N) {
792 switch (N->getOpcode()) {
793 default:
794 break;
795 case ISD::BUILD_PAIR: {
796 EVT VT = N->getValueType(0);
797 assert(N->getNumValues() == 1 && "Too many results!");
798 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
799 "Wrong return type!");
800 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
801 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
802 "Mismatched operand types!");
803 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
804 "Wrong operand type!");
805 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
806 "Wrong return type size");
807 break;
809 case ISD::BUILD_VECTOR: {
810 assert(N->getNumValues() == 1 && "Too many results!");
811 assert(N->getValueType(0).isVector() && "Wrong return type!");
812 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
813 "Wrong number of operands!");
814 EVT EltVT = N->getValueType(0).getVectorElementType();
815 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
816 assert((I->getValueType() == EltVT ||
817 (EltVT.isInteger() && I->getValueType().isInteger() &&
818 EltVT.bitsLE(I->getValueType()))) &&
819 "Wrong operand type!");
820 assert(I->getValueType() == N->getOperand(0).getValueType() &&
821 "Operands must all have the same type");
823 break;
827 #endif // NDEBUG
829 /// Insert a newly allocated node into the DAG.
831 /// Handles insertion into the all nodes list and CSE map, as well as
832 /// verification and other common operations when a new node is allocated.
833 void SelectionDAG::InsertNode(SDNode *N) {
834 AllNodes.push_back(N);
835 #ifndef NDEBUG
836 N->PersistentId = NextPersistentId++;
837 VerifySDNode(N);
838 #endif
839 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
840 DUL->NodeInserted(N);
843 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
844 /// correspond to it. This is useful when we're about to delete or repurpose
845 /// the node. We don't want future request for structurally identical nodes
846 /// to return N anymore.
847 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
848 bool Erased = false;
849 switch (N->getOpcode()) {
850 case ISD::HANDLENODE: return false; // noop.
851 case ISD::CONDCODE:
852 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
853 "Cond code doesn't exist!");
854 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
855 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
856 break;
857 case ISD::ExternalSymbol:
858 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
859 break;
860 case ISD::TargetExternalSymbol: {
861 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
862 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
863 ESN->getSymbol(), ESN->getTargetFlags()));
864 break;
866 case ISD::MCSymbol: {
867 auto *MCSN = cast<MCSymbolSDNode>(N);
868 Erased = MCSymbols.erase(MCSN->getMCSymbol());
869 break;
871 case ISD::VALUETYPE: {
872 EVT VT = cast<VTSDNode>(N)->getVT();
873 if (VT.isExtended()) {
874 Erased = ExtendedValueTypeNodes.erase(VT);
875 } else {
876 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
877 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
879 break;
881 default:
882 // Remove it from the CSE Map.
883 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
884 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
885 Erased = CSEMap.RemoveNode(N);
886 break;
888 #ifndef NDEBUG
889 // Verify that the node was actually in one of the CSE maps, unless it has a
890 // flag result (which cannot be CSE'd) or is one of the special cases that are
891 // not subject to CSE.
892 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
893 !N->isMachineOpcode() && !doNotCSE(N)) {
894 N->dump(this);
895 dbgs() << "\n";
896 llvm_unreachable("Node is not in map!");
898 #endif
899 return Erased;
902 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
903 /// maps and modified in place. Add it back to the CSE maps, unless an identical
904 /// node already exists, in which case transfer all its users to the existing
905 /// node. This transfer can potentially trigger recursive merging.
906 void
907 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
908 // For node types that aren't CSE'd, just act as if no identical node
909 // already exists.
910 if (!doNotCSE(N)) {
911 SDNode *Existing = CSEMap.GetOrInsertNode(N);
912 if (Existing != N) {
913 // If there was already an existing matching node, use ReplaceAllUsesWith
914 // to replace the dead one with the existing one. This can cause
915 // recursive merging of other unrelated nodes down the line.
916 ReplaceAllUsesWith(N, Existing);
918 // N is now dead. Inform the listeners and delete it.
919 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
920 DUL->NodeDeleted(N, Existing);
921 DeleteNodeNotInCSEMaps(N);
922 return;
926 // If the node doesn't already exist, we updated it. Inform listeners.
927 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
928 DUL->NodeUpdated(N);
931 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
932 /// were replaced with those specified. If this node is never memoized,
933 /// return null, otherwise return a pointer to the slot it would take. If a
934 /// node already exists with these operands, the slot will be non-null.
935 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
936 void *&InsertPos) {
937 if (doNotCSE(N))
938 return nullptr;
940 SDValue Ops[] = { Op };
941 FoldingSetNodeID ID;
942 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
943 AddNodeIDCustom(ID, N);
944 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
945 if (Node)
946 Node->intersectFlagsWith(N->getFlags());
947 return Node;
950 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
951 /// were replaced with those specified. If this node is never memoized,
952 /// return null, otherwise return a pointer to the slot it would take. If a
953 /// node already exists with these operands, the slot will be non-null.
954 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
955 SDValue Op1, SDValue Op2,
956 void *&InsertPos) {
957 if (doNotCSE(N))
958 return nullptr;
960 SDValue Ops[] = { Op1, Op2 };
961 FoldingSetNodeID ID;
962 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
963 AddNodeIDCustom(ID, N);
964 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
965 if (Node)
966 Node->intersectFlagsWith(N->getFlags());
967 return Node;
970 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
971 /// were replaced with those specified. If this node is never memoized,
972 /// return null, otherwise return a pointer to the slot it would take. If a
973 /// node already exists with these operands, the slot will be non-null.
974 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
975 void *&InsertPos) {
976 if (doNotCSE(N))
977 return nullptr;
979 FoldingSetNodeID ID;
980 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
981 AddNodeIDCustom(ID, N);
982 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
983 if (Node)
984 Node->intersectFlagsWith(N->getFlags());
985 return Node;
988 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
989 Type *Ty = VT == MVT::iPTR ?
990 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
991 VT.getTypeForEVT(*getContext());
993 return getDataLayout().getABITypeAlignment(Ty);
996 // EntryNode could meaningfully have debug info if we can find it...
997 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
998 : TM(tm), OptLevel(OL),
999 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1000 Root(getEntryNode()) {
1001 InsertNode(&EntryNode);
1002 DbgInfo = new SDDbgInfo();
1005 void SelectionDAG::init(MachineFunction &NewMF,
1006 OptimizationRemarkEmitter &NewORE,
1007 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1008 LegacyDivergenceAnalysis * Divergence) {
1009 MF = &NewMF;
1010 SDAGISelPass = PassPtr;
1011 ORE = &NewORE;
1012 TLI = getSubtarget().getTargetLowering();
1013 TSI = getSubtarget().getSelectionDAGInfo();
1014 LibInfo = LibraryInfo;
1015 Context = &MF->getFunction().getContext();
1016 DA = Divergence;
1019 SelectionDAG::~SelectionDAG() {
1020 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1021 allnodes_clear();
1022 OperandRecycler.clear(OperandAllocator);
1023 delete DbgInfo;
1026 void SelectionDAG::allnodes_clear() {
1027 assert(&*AllNodes.begin() == &EntryNode);
1028 AllNodes.remove(AllNodes.begin());
1029 while (!AllNodes.empty())
1030 DeallocateNode(&AllNodes.front());
1031 #ifndef NDEBUG
1032 NextPersistentId = 0;
1033 #endif
1036 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1037 void *&InsertPos) {
1038 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1039 if (N) {
1040 switch (N->getOpcode()) {
1041 default: break;
1042 case ISD::Constant:
1043 case ISD::ConstantFP:
1044 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1045 "debug location. Use another overload.");
1048 return N;
1051 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1052 const SDLoc &DL, void *&InsertPos) {
1053 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1054 if (N) {
1055 switch (N->getOpcode()) {
1056 case ISD::Constant:
1057 case ISD::ConstantFP:
1058 // Erase debug location from the node if the node is used at several
1059 // different places. Do not propagate one location to all uses as it
1060 // will cause a worse single stepping debugging experience.
1061 if (N->getDebugLoc() != DL.getDebugLoc())
1062 N->setDebugLoc(DebugLoc());
1063 break;
1064 default:
1065 // When the node's point of use is located earlier in the instruction
1066 // sequence than its prior point of use, update its debug info to the
1067 // earlier location.
1068 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1069 N->setDebugLoc(DL.getDebugLoc());
1070 break;
1073 return N;
1076 void SelectionDAG::clear() {
1077 allnodes_clear();
1078 OperandRecycler.clear(OperandAllocator);
1079 OperandAllocator.Reset();
1080 CSEMap.clear();
1082 ExtendedValueTypeNodes.clear();
1083 ExternalSymbols.clear();
1084 TargetExternalSymbols.clear();
1085 MCSymbols.clear();
1086 SDCallSiteDbgInfo.clear();
1087 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1088 static_cast<CondCodeSDNode*>(nullptr));
1089 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1090 static_cast<SDNode*>(nullptr));
1092 EntryNode.UseList = nullptr;
1093 InsertNode(&EntryNode);
1094 Root = getEntryNode();
1095 DbgInfo->clear();
1098 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1099 return VT.bitsGT(Op.getValueType())
1100 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1101 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1104 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1105 return VT.bitsGT(Op.getValueType()) ?
1106 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1107 getNode(ISD::TRUNCATE, DL, VT, Op);
1110 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1111 return VT.bitsGT(Op.getValueType()) ?
1112 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1113 getNode(ISD::TRUNCATE, DL, VT, Op);
1116 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1117 return VT.bitsGT(Op.getValueType()) ?
1118 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1119 getNode(ISD::TRUNCATE, DL, VT, Op);
1122 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1123 EVT OpVT) {
1124 if (VT.bitsLE(Op.getValueType()))
1125 return getNode(ISD::TRUNCATE, SL, VT, Op);
1127 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1128 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1131 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1132 assert(!VT.isVector() &&
1133 "getZeroExtendInReg should use the vector element type instead of "
1134 "the vector type!");
1135 if (Op.getValueType().getScalarType() == VT) return Op;
1136 unsigned BitWidth = Op.getScalarValueSizeInBits();
1137 APInt Imm = APInt::getLowBitsSet(BitWidth,
1138 VT.getSizeInBits());
1139 return getNode(ISD::AND, DL, Op.getValueType(), Op,
1140 getConstant(Imm, DL, Op.getValueType()));
1143 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1144 // Only unsigned pointer semantics are supported right now. In the future this
1145 // might delegate to TLI to check pointer signedness.
1146 return getZExtOrTrunc(Op, DL, VT);
1149 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1150 // Only unsigned pointer semantics are supported right now. In the future this
1151 // might delegate to TLI to check pointer signedness.
1152 return getZeroExtendInReg(Op, DL, VT);
1155 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1156 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1157 EVT EltVT = VT.getScalarType();
1158 SDValue NegOne =
1159 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1160 return getNode(ISD::XOR, DL, VT, Val, NegOne);
1163 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1164 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1165 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1168 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1169 EVT OpVT) {
1170 if (!V)
1171 return getConstant(0, DL, VT);
1173 switch (TLI->getBooleanContents(OpVT)) {
1174 case TargetLowering::ZeroOrOneBooleanContent:
1175 case TargetLowering::UndefinedBooleanContent:
1176 return getConstant(1, DL, VT);
1177 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1178 return getAllOnesConstant(DL, VT);
1180 llvm_unreachable("Unexpected boolean content enum!");
1183 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1184 bool isT, bool isO) {
1185 EVT EltVT = VT.getScalarType();
1186 assert((EltVT.getSizeInBits() >= 64 ||
1187 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1188 "getConstant with a uint64_t value that doesn't fit in the type!");
1189 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1192 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1193 bool isT, bool isO) {
1194 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1197 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1198 EVT VT, bool isT, bool isO) {
1199 assert(VT.isInteger() && "Cannot create FP integer constant!");
1201 EVT EltVT = VT.getScalarType();
1202 const ConstantInt *Elt = &Val;
1204 // In some cases the vector type is legal but the element type is illegal and
1205 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1206 // inserted value (the type does not need to match the vector element type).
1207 // Any extra bits introduced will be truncated away.
1208 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1209 TargetLowering::TypePromoteInteger) {
1210 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1211 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1212 Elt = ConstantInt::get(*getContext(), NewVal);
1214 // In other cases the element type is illegal and needs to be expanded, for
1215 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1216 // the value into n parts and use a vector type with n-times the elements.
1217 // Then bitcast to the type requested.
1218 // Legalizing constants too early makes the DAGCombiner's job harder so we
1219 // only legalize if the DAG tells us we must produce legal types.
1220 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1221 TLI->getTypeAction(*getContext(), EltVT) ==
1222 TargetLowering::TypeExpandInteger) {
1223 const APInt &NewVal = Elt->getValue();
1224 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1225 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1226 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1227 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1229 // Check the temporary vector is the correct size. If this fails then
1230 // getTypeToTransformTo() probably returned a type whose size (in bits)
1231 // isn't a power-of-2 factor of the requested type size.
1232 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1234 SmallVector<SDValue, 2> EltParts;
1235 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1236 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1237 .zextOrTrunc(ViaEltSizeInBits), DL,
1238 ViaEltVT, isT, isO));
1241 // EltParts is currently in little endian order. If we actually want
1242 // big-endian order then reverse it now.
1243 if (getDataLayout().isBigEndian())
1244 std::reverse(EltParts.begin(), EltParts.end());
1246 // The elements must be reversed when the element order is different
1247 // to the endianness of the elements (because the BITCAST is itself a
1248 // vector shuffle in this situation). However, we do not need any code to
1249 // perform this reversal because getConstant() is producing a vector
1250 // splat.
1251 // This situation occurs in MIPS MSA.
1253 SmallVector<SDValue, 8> Ops;
1254 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1255 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1257 SDValue V = getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1258 return V;
1261 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1262 "APInt size does not match type size!");
1263 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1264 FoldingSetNodeID ID;
1265 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1266 ID.AddPointer(Elt);
1267 ID.AddBoolean(isO);
1268 void *IP = nullptr;
1269 SDNode *N = nullptr;
1270 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1271 if (!VT.isVector())
1272 return SDValue(N, 0);
1274 if (!N) {
1275 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1276 CSEMap.InsertNode(N, IP);
1277 InsertNode(N);
1278 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1281 SDValue Result(N, 0);
1282 if (VT.isVector())
1283 Result = getSplatBuildVector(VT, DL, Result);
1285 return Result;
1288 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1289 bool isTarget) {
1290 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1293 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1294 const SDLoc &DL, bool LegalTypes) {
1295 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1296 return getConstant(Val, DL, ShiftVT);
1299 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1300 bool isTarget) {
1301 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1304 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1305 EVT VT, bool isTarget) {
1306 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1308 EVT EltVT = VT.getScalarType();
1310 // Do the map lookup using the actual bit pattern for the floating point
1311 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1312 // we don't have issues with SNANs.
1313 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1314 FoldingSetNodeID ID;
1315 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1316 ID.AddPointer(&V);
1317 void *IP = nullptr;
1318 SDNode *N = nullptr;
1319 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1320 if (!VT.isVector())
1321 return SDValue(N, 0);
1323 if (!N) {
1324 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1325 CSEMap.InsertNode(N, IP);
1326 InsertNode(N);
1329 SDValue Result(N, 0);
1330 if (VT.isVector())
1331 Result = getSplatBuildVector(VT, DL, Result);
1332 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1333 return Result;
1336 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1337 bool isTarget) {
1338 EVT EltVT = VT.getScalarType();
1339 if (EltVT == MVT::f32)
1340 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1341 else if (EltVT == MVT::f64)
1342 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1343 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1344 EltVT == MVT::f16) {
1345 bool Ignored;
1346 APFloat APF = APFloat(Val);
1347 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1348 &Ignored);
1349 return getConstantFP(APF, DL, VT, isTarget);
1350 } else
1351 llvm_unreachable("Unsupported type in getConstantFP");
1354 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1355 EVT VT, int64_t Offset, bool isTargetGA,
1356 unsigned TargetFlags) {
1357 assert((TargetFlags == 0 || isTargetGA) &&
1358 "Cannot set target flags on target-independent globals");
1360 // Truncate (with sign-extension) the offset value to the pointer size.
1361 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1362 if (BitWidth < 64)
1363 Offset = SignExtend64(Offset, BitWidth);
1365 unsigned Opc;
1366 if (GV->isThreadLocal())
1367 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1368 else
1369 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1371 FoldingSetNodeID ID;
1372 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1373 ID.AddPointer(GV);
1374 ID.AddInteger(Offset);
1375 ID.AddInteger(TargetFlags);
1376 void *IP = nullptr;
1377 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1378 return SDValue(E, 0);
1380 auto *N = newSDNode<GlobalAddressSDNode>(
1381 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1382 CSEMap.InsertNode(N, IP);
1383 InsertNode(N);
1384 return SDValue(N, 0);
1387 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1388 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1389 FoldingSetNodeID ID;
1390 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1391 ID.AddInteger(FI);
1392 void *IP = nullptr;
1393 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1394 return SDValue(E, 0);
1396 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1397 CSEMap.InsertNode(N, IP);
1398 InsertNode(N);
1399 return SDValue(N, 0);
1402 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1403 unsigned TargetFlags) {
1404 assert((TargetFlags == 0 || isTarget) &&
1405 "Cannot set target flags on target-independent jump tables");
1406 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1407 FoldingSetNodeID ID;
1408 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1409 ID.AddInteger(JTI);
1410 ID.AddInteger(TargetFlags);
1411 void *IP = nullptr;
1412 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1413 return SDValue(E, 0);
1415 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1416 CSEMap.InsertNode(N, IP);
1417 InsertNode(N);
1418 return SDValue(N, 0);
1421 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1422 unsigned Alignment, int Offset,
1423 bool isTarget,
1424 unsigned TargetFlags) {
1425 assert((TargetFlags == 0 || isTarget) &&
1426 "Cannot set target flags on target-independent globals");
1427 if (Alignment == 0)
1428 Alignment = MF->getFunction().hasOptSize()
1429 ? getDataLayout().getABITypeAlignment(C->getType())
1430 : getDataLayout().getPrefTypeAlignment(C->getType());
1431 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1432 FoldingSetNodeID ID;
1433 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1434 ID.AddInteger(Alignment);
1435 ID.AddInteger(Offset);
1436 ID.AddPointer(C);
1437 ID.AddInteger(TargetFlags);
1438 void *IP = nullptr;
1439 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1440 return SDValue(E, 0);
1442 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1443 TargetFlags);
1444 CSEMap.InsertNode(N, IP);
1445 InsertNode(N);
1446 return SDValue(N, 0);
1449 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1450 unsigned Alignment, int Offset,
1451 bool isTarget,
1452 unsigned TargetFlags) {
1453 assert((TargetFlags == 0 || isTarget) &&
1454 "Cannot set target flags on target-independent globals");
1455 if (Alignment == 0)
1456 Alignment = getDataLayout().getPrefTypeAlignment(C->getType());
1457 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1458 FoldingSetNodeID ID;
1459 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1460 ID.AddInteger(Alignment);
1461 ID.AddInteger(Offset);
1462 C->addSelectionDAGCSEId(ID);
1463 ID.AddInteger(TargetFlags);
1464 void *IP = nullptr;
1465 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1466 return SDValue(E, 0);
1468 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1469 TargetFlags);
1470 CSEMap.InsertNode(N, IP);
1471 InsertNode(N);
1472 return SDValue(N, 0);
1475 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1476 unsigned TargetFlags) {
1477 FoldingSetNodeID ID;
1478 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1479 ID.AddInteger(Index);
1480 ID.AddInteger(Offset);
1481 ID.AddInteger(TargetFlags);
1482 void *IP = nullptr;
1483 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1484 return SDValue(E, 0);
1486 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1487 CSEMap.InsertNode(N, IP);
1488 InsertNode(N);
1489 return SDValue(N, 0);
1492 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1493 FoldingSetNodeID ID;
1494 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1495 ID.AddPointer(MBB);
1496 void *IP = nullptr;
1497 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1498 return SDValue(E, 0);
1500 auto *N = newSDNode<BasicBlockSDNode>(MBB);
1501 CSEMap.InsertNode(N, IP);
1502 InsertNode(N);
1503 return SDValue(N, 0);
1506 SDValue SelectionDAG::getValueType(EVT VT) {
1507 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1508 ValueTypeNodes.size())
1509 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1511 SDNode *&N = VT.isExtended() ?
1512 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1514 if (N) return SDValue(N, 0);
1515 N = newSDNode<VTSDNode>(VT);
1516 InsertNode(N);
1517 return SDValue(N, 0);
1520 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1521 SDNode *&N = ExternalSymbols[Sym];
1522 if (N) return SDValue(N, 0);
1523 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1524 InsertNode(N);
1525 return SDValue(N, 0);
1528 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1529 SDNode *&N = MCSymbols[Sym];
1530 if (N)
1531 return SDValue(N, 0);
1532 N = newSDNode<MCSymbolSDNode>(Sym, VT);
1533 InsertNode(N);
1534 return SDValue(N, 0);
1537 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1538 unsigned TargetFlags) {
1539 SDNode *&N =
1540 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1541 if (N) return SDValue(N, 0);
1542 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1543 InsertNode(N);
1544 return SDValue(N, 0);
1547 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1548 if ((unsigned)Cond >= CondCodeNodes.size())
1549 CondCodeNodes.resize(Cond+1);
1551 if (!CondCodeNodes[Cond]) {
1552 auto *N = newSDNode<CondCodeSDNode>(Cond);
1553 CondCodeNodes[Cond] = N;
1554 InsertNode(N);
1557 return SDValue(CondCodeNodes[Cond], 0);
1560 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1561 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1562 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1563 std::swap(N1, N2);
1564 ShuffleVectorSDNode::commuteMask(M);
1567 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1568 SDValue N2, ArrayRef<int> Mask) {
1569 assert(VT.getVectorNumElements() == Mask.size() &&
1570 "Must have the same number of vector elements as mask elements!");
1571 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1572 "Invalid VECTOR_SHUFFLE");
1574 // Canonicalize shuffle undef, undef -> undef
1575 if (N1.isUndef() && N2.isUndef())
1576 return getUNDEF(VT);
1578 // Validate that all indices in Mask are within the range of the elements
1579 // input to the shuffle.
1580 int NElts = Mask.size();
1581 assert(llvm::all_of(Mask,
1582 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1583 "Index out of range");
1585 // Copy the mask so we can do any needed cleanup.
1586 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1588 // Canonicalize shuffle v, v -> v, undef
1589 if (N1 == N2) {
1590 N2 = getUNDEF(VT);
1591 for (int i = 0; i != NElts; ++i)
1592 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1595 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1596 if (N1.isUndef())
1597 commuteShuffle(N1, N2, MaskVec);
1599 if (TLI->hasVectorBlend()) {
1600 // If shuffling a splat, try to blend the splat instead. We do this here so
1601 // that even when this arises during lowering we don't have to re-handle it.
1602 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1603 BitVector UndefElements;
1604 SDValue Splat = BV->getSplatValue(&UndefElements);
1605 if (!Splat)
1606 return;
1608 for (int i = 0; i < NElts; ++i) {
1609 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1610 continue;
1612 // If this input comes from undef, mark it as such.
1613 if (UndefElements[MaskVec[i] - Offset]) {
1614 MaskVec[i] = -1;
1615 continue;
1618 // If we can blend a non-undef lane, use that instead.
1619 if (!UndefElements[i])
1620 MaskVec[i] = i + Offset;
1623 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1624 BlendSplat(N1BV, 0);
1625 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1626 BlendSplat(N2BV, NElts);
1629 // Canonicalize all index into lhs, -> shuffle lhs, undef
1630 // Canonicalize all index into rhs, -> shuffle rhs, undef
1631 bool AllLHS = true, AllRHS = true;
1632 bool N2Undef = N2.isUndef();
1633 for (int i = 0; i != NElts; ++i) {
1634 if (MaskVec[i] >= NElts) {
1635 if (N2Undef)
1636 MaskVec[i] = -1;
1637 else
1638 AllLHS = false;
1639 } else if (MaskVec[i] >= 0) {
1640 AllRHS = false;
1643 if (AllLHS && AllRHS)
1644 return getUNDEF(VT);
1645 if (AllLHS && !N2Undef)
1646 N2 = getUNDEF(VT);
1647 if (AllRHS) {
1648 N1 = getUNDEF(VT);
1649 commuteShuffle(N1, N2, MaskVec);
1651 // Reset our undef status after accounting for the mask.
1652 N2Undef = N2.isUndef();
1653 // Re-check whether both sides ended up undef.
1654 if (N1.isUndef() && N2Undef)
1655 return getUNDEF(VT);
1657 // If Identity shuffle return that node.
1658 bool Identity = true, AllSame = true;
1659 for (int i = 0; i != NElts; ++i) {
1660 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1661 if (MaskVec[i] != MaskVec[0]) AllSame = false;
1663 if (Identity && NElts)
1664 return N1;
1666 // Shuffling a constant splat doesn't change the result.
1667 if (N2Undef) {
1668 SDValue V = N1;
1670 // Look through any bitcasts. We check that these don't change the number
1671 // (and size) of elements and just changes their types.
1672 while (V.getOpcode() == ISD::BITCAST)
1673 V = V->getOperand(0);
1675 // A splat should always show up as a build vector node.
1676 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1677 BitVector UndefElements;
1678 SDValue Splat = BV->getSplatValue(&UndefElements);
1679 // If this is a splat of an undef, shuffling it is also undef.
1680 if (Splat && Splat.isUndef())
1681 return getUNDEF(VT);
1683 bool SameNumElts =
1684 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1686 // We only have a splat which can skip shuffles if there is a splatted
1687 // value and no undef lanes rearranged by the shuffle.
1688 if (Splat && UndefElements.none()) {
1689 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1690 // number of elements match or the value splatted is a zero constant.
1691 if (SameNumElts)
1692 return N1;
1693 if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1694 if (C->isNullValue())
1695 return N1;
1698 // If the shuffle itself creates a splat, build the vector directly.
1699 if (AllSame && SameNumElts) {
1700 EVT BuildVT = BV->getValueType(0);
1701 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1702 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1704 // We may have jumped through bitcasts, so the type of the
1705 // BUILD_VECTOR may not match the type of the shuffle.
1706 if (BuildVT != VT)
1707 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1708 return NewBV;
1713 FoldingSetNodeID ID;
1714 SDValue Ops[2] = { N1, N2 };
1715 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1716 for (int i = 0; i != NElts; ++i)
1717 ID.AddInteger(MaskVec[i]);
1719 void* IP = nullptr;
1720 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1721 return SDValue(E, 0);
1723 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1724 // SDNode doesn't have access to it. This memory will be "leaked" when
1725 // the node is deallocated, but recovered when the NodeAllocator is released.
1726 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1727 llvm::copy(MaskVec, MaskAlloc);
1729 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1730 dl.getDebugLoc(), MaskAlloc);
1731 createOperands(N, Ops);
1733 CSEMap.InsertNode(N, IP);
1734 InsertNode(N);
1735 SDValue V = SDValue(N, 0);
1736 NewSDValueDbgMsg(V, "Creating new node: ", this);
1737 return V;
1740 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1741 EVT VT = SV.getValueType(0);
1742 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1743 ShuffleVectorSDNode::commuteMask(MaskVec);
1745 SDValue Op0 = SV.getOperand(0);
1746 SDValue Op1 = SV.getOperand(1);
1747 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1750 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1751 FoldingSetNodeID ID;
1752 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1753 ID.AddInteger(RegNo);
1754 void *IP = nullptr;
1755 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1756 return SDValue(E, 0);
1758 auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1759 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1760 CSEMap.InsertNode(N, IP);
1761 InsertNode(N);
1762 return SDValue(N, 0);
1765 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1766 FoldingSetNodeID ID;
1767 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1768 ID.AddPointer(RegMask);
1769 void *IP = nullptr;
1770 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1771 return SDValue(E, 0);
1773 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1774 CSEMap.InsertNode(N, IP);
1775 InsertNode(N);
1776 return SDValue(N, 0);
1779 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1780 MCSymbol *Label) {
1781 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
1784 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
1785 SDValue Root, MCSymbol *Label) {
1786 FoldingSetNodeID ID;
1787 SDValue Ops[] = { Root };
1788 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
1789 ID.AddPointer(Label);
1790 void *IP = nullptr;
1791 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1792 return SDValue(E, 0);
1794 auto *N =
1795 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
1796 createOperands(N, Ops);
1798 CSEMap.InsertNode(N, IP);
1799 InsertNode(N);
1800 return SDValue(N, 0);
1803 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1804 int64_t Offset, bool isTarget,
1805 unsigned TargetFlags) {
1806 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1808 FoldingSetNodeID ID;
1809 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1810 ID.AddPointer(BA);
1811 ID.AddInteger(Offset);
1812 ID.AddInteger(TargetFlags);
1813 void *IP = nullptr;
1814 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1815 return SDValue(E, 0);
1817 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
1818 CSEMap.InsertNode(N, IP);
1819 InsertNode(N);
1820 return SDValue(N, 0);
1823 SDValue SelectionDAG::getSrcValue(const Value *V) {
1824 assert((!V || V->getType()->isPointerTy()) &&
1825 "SrcValue is not a pointer?");
1827 FoldingSetNodeID ID;
1828 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1829 ID.AddPointer(V);
1831 void *IP = nullptr;
1832 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1833 return SDValue(E, 0);
1835 auto *N = newSDNode<SrcValueSDNode>(V);
1836 CSEMap.InsertNode(N, IP);
1837 InsertNode(N);
1838 return SDValue(N, 0);
1841 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1842 FoldingSetNodeID ID;
1843 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1844 ID.AddPointer(MD);
1846 void *IP = nullptr;
1847 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1848 return SDValue(E, 0);
1850 auto *N = newSDNode<MDNodeSDNode>(MD);
1851 CSEMap.InsertNode(N, IP);
1852 InsertNode(N);
1853 return SDValue(N, 0);
1856 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
1857 if (VT == V.getValueType())
1858 return V;
1860 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
1863 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
1864 unsigned SrcAS, unsigned DestAS) {
1865 SDValue Ops[] = {Ptr};
1866 FoldingSetNodeID ID;
1867 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
1868 ID.AddInteger(SrcAS);
1869 ID.AddInteger(DestAS);
1871 void *IP = nullptr;
1872 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1873 return SDValue(E, 0);
1875 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
1876 VT, SrcAS, DestAS);
1877 createOperands(N, Ops);
1879 CSEMap.InsertNode(N, IP);
1880 InsertNode(N);
1881 return SDValue(N, 0);
1884 /// getShiftAmountOperand - Return the specified value casted to
1885 /// the target's desired shift amount type.
1886 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1887 EVT OpTy = Op.getValueType();
1888 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
1889 if (OpTy == ShTy || OpTy.isVector()) return Op;
1891 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
1894 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
1895 SDLoc dl(Node);
1896 const TargetLowering &TLI = getTargetLoweringInfo();
1897 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1898 EVT VT = Node->getValueType(0);
1899 SDValue Tmp1 = Node->getOperand(0);
1900 SDValue Tmp2 = Node->getOperand(1);
1901 const llvm::MaybeAlign MA(Node->getConstantOperandVal(3));
1903 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
1904 Tmp2, MachinePointerInfo(V));
1905 SDValue VAList = VAListLoad;
1907 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
1908 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1909 getConstant(MA->value() - 1, dl, VAList.getValueType()));
1911 VAList =
1912 getNode(ISD::AND, dl, VAList.getValueType(), VAList,
1913 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
1916 // Increment the pointer, VAList, to the next vaarg
1917 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1918 getConstant(getDataLayout().getTypeAllocSize(
1919 VT.getTypeForEVT(*getContext())),
1920 dl, VAList.getValueType()));
1921 // Store the incremented VAList to the legalized pointer
1922 Tmp1 =
1923 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
1924 // Load the actual argument out of the pointer VAList
1925 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
1928 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
1929 SDLoc dl(Node);
1930 const TargetLowering &TLI = getTargetLoweringInfo();
1931 // This defaults to loading a pointer from the input and storing it to the
1932 // output, returning the chain.
1933 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
1934 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
1935 SDValue Tmp1 =
1936 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
1937 Node->getOperand(2), MachinePointerInfo(VS));
1938 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
1939 MachinePointerInfo(VD));
1942 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1943 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1944 unsigned ByteSize = VT.getStoreSize();
1945 Type *Ty = VT.getTypeForEVT(*getContext());
1946 unsigned StackAlign =
1947 std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign);
1949 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
1950 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1953 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1954 unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
1955 Type *Ty1 = VT1.getTypeForEVT(*getContext());
1956 Type *Ty2 = VT2.getTypeForEVT(*getContext());
1957 const DataLayout &DL = getDataLayout();
1958 unsigned Align =
1959 std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2));
1961 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1962 int FrameIdx = MFI.CreateStackObject(Bytes, Align, false);
1963 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1966 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
1967 ISD::CondCode Cond, const SDLoc &dl) {
1968 EVT OpVT = N1.getValueType();
1970 // These setcc operations always fold.
1971 switch (Cond) {
1972 default: break;
1973 case ISD::SETFALSE:
1974 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
1975 case ISD::SETTRUE:
1976 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
1978 case ISD::SETOEQ:
1979 case ISD::SETOGT:
1980 case ISD::SETOGE:
1981 case ISD::SETOLT:
1982 case ISD::SETOLE:
1983 case ISD::SETONE:
1984 case ISD::SETO:
1985 case ISD::SETUO:
1986 case ISD::SETUEQ:
1987 case ISD::SETUNE:
1988 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
1989 break;
1992 if (OpVT.isInteger()) {
1993 // For EQ and NE, we can always pick a value for the undef to make the
1994 // predicate pass or fail, so we can return undef.
1995 // Matches behavior in llvm::ConstantFoldCompareInstruction.
1996 // icmp eq/ne X, undef -> undef.
1997 if ((N1.isUndef() || N2.isUndef()) &&
1998 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
1999 return getUNDEF(VT);
2001 // If both operands are undef, we can return undef for int comparison.
2002 // icmp undef, undef -> undef.
2003 if (N1.isUndef() && N2.isUndef())
2004 return getUNDEF(VT);
2006 // icmp X, X -> true/false
2007 // icmp X, undef -> true/false because undef could be X.
2008 if (N1 == N2)
2009 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2012 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2013 const APInt &C2 = N2C->getAPIntValue();
2014 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2015 const APInt &C1 = N1C->getAPIntValue();
2017 switch (Cond) {
2018 default: llvm_unreachable("Unknown integer setcc!");
2019 case ISD::SETEQ: return getBoolConstant(C1 == C2, dl, VT, OpVT);
2020 case ISD::SETNE: return getBoolConstant(C1 != C2, dl, VT, OpVT);
2021 case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
2022 case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
2023 case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
2024 case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
2025 case ISD::SETLT: return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
2026 case ISD::SETGT: return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
2027 case ISD::SETLE: return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
2028 case ISD::SETGE: return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
2033 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2034 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2036 if (N1CFP && N2CFP) {
2037 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2038 switch (Cond) {
2039 default: break;
2040 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2041 return getUNDEF(VT);
2042 LLVM_FALLTHROUGH;
2043 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2044 OpVT);
2045 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2046 return getUNDEF(VT);
2047 LLVM_FALLTHROUGH;
2048 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2049 R==APFloat::cmpLessThan, dl, VT,
2050 OpVT);
2051 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2052 return getUNDEF(VT);
2053 LLVM_FALLTHROUGH;
2054 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2055 OpVT);
2056 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2057 return getUNDEF(VT);
2058 LLVM_FALLTHROUGH;
2059 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2060 VT, OpVT);
2061 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2062 return getUNDEF(VT);
2063 LLVM_FALLTHROUGH;
2064 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2065 R==APFloat::cmpEqual, dl, VT,
2066 OpVT);
2067 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2068 return getUNDEF(VT);
2069 LLVM_FALLTHROUGH;
2070 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2071 R==APFloat::cmpEqual, dl, VT, OpVT);
2072 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2073 OpVT);
2074 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2075 OpVT);
2076 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2077 R==APFloat::cmpEqual, dl, VT,
2078 OpVT);
2079 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2080 OpVT);
2081 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2082 R==APFloat::cmpLessThan, dl, VT,
2083 OpVT);
2084 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2085 R==APFloat::cmpUnordered, dl, VT,
2086 OpVT);
2087 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2088 VT, OpVT);
2089 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2090 OpVT);
2092 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2093 // Ensure that the constant occurs on the RHS.
2094 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2095 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2096 return SDValue();
2097 return getSetCC(dl, VT, N2, N1, SwappedCond);
2098 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2099 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2100 // If an operand is known to be a nan (or undef that could be a nan), we can
2101 // fold it.
2102 // Choosing NaN for the undef will always make unordered comparison succeed
2103 // and ordered comparison fails.
2104 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2105 switch (ISD::getUnorderedFlavor(Cond)) {
2106 default:
2107 llvm_unreachable("Unknown flavor!");
2108 case 0: // Known false.
2109 return getBoolConstant(false, dl, VT, OpVT);
2110 case 1: // Known true.
2111 return getBoolConstant(true, dl, VT, OpVT);
2112 case 2: // Undefined.
2113 return getUNDEF(VT);
2117 // Could not fold it.
2118 return SDValue();
2121 /// See if the specified operand can be simplified with the knowledge that only
2122 /// the bits specified by DemandedBits are used.
2123 /// TODO: really we should be making this into the DAG equivalent of
2124 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2125 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2126 EVT VT = V.getValueType();
2127 APInt DemandedElts = VT.isVector()
2128 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2129 : APInt(1, 1);
2130 return GetDemandedBits(V, DemandedBits, DemandedElts);
2133 /// See if the specified operand can be simplified with the knowledge that only
2134 /// the bits specified by DemandedBits are used in the elements specified by
2135 /// DemandedElts.
2136 /// TODO: really we should be making this into the DAG equivalent of
2137 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2138 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2139 const APInt &DemandedElts) {
2140 switch (V.getOpcode()) {
2141 default:
2142 break;
2143 case ISD::Constant: {
2144 auto *CV = cast<ConstantSDNode>(V.getNode());
2145 assert(CV && "Const value should be ConstSDNode.");
2146 const APInt &CVal = CV->getAPIntValue();
2147 APInt NewVal = CVal & DemandedBits;
2148 if (NewVal != CVal)
2149 return getConstant(NewVal, SDLoc(V), V.getValueType());
2150 break;
2152 case ISD::OR:
2153 case ISD::XOR:
2154 case ISD::SIGN_EXTEND_INREG:
2155 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2156 *this, 0);
2157 case ISD::SRL:
2158 // Only look at single-use SRLs.
2159 if (!V.getNode()->hasOneUse())
2160 break;
2161 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2162 // See if we can recursively simplify the LHS.
2163 unsigned Amt = RHSC->getZExtValue();
2165 // Watch out for shift count overflow though.
2166 if (Amt >= DemandedBits.getBitWidth())
2167 break;
2168 APInt SrcDemandedBits = DemandedBits << Amt;
2169 if (SDValue SimplifyLHS =
2170 GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2171 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2172 V.getOperand(1));
2174 break;
2175 case ISD::AND: {
2176 // X & -1 -> X (ignoring bits which aren't demanded).
2177 // Also handle the case where masked out bits in X are known to be zero.
2178 if (ConstantSDNode *RHSC = isConstOrConstSplat(V.getOperand(1))) {
2179 const APInt &AndVal = RHSC->getAPIntValue();
2180 if (DemandedBits.isSubsetOf(AndVal) ||
2181 DemandedBits.isSubsetOf(computeKnownBits(V.getOperand(0)).Zero |
2182 AndVal))
2183 return V.getOperand(0);
2185 break;
2187 case ISD::ANY_EXTEND: {
2188 SDValue Src = V.getOperand(0);
2189 unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
2190 // Being conservative here - only peek through if we only demand bits in the
2191 // non-extended source (even though the extended bits are technically
2192 // undef).
2193 if (DemandedBits.getActiveBits() > SrcBitWidth)
2194 break;
2195 APInt SrcDemandedBits = DemandedBits.trunc(SrcBitWidth);
2196 if (SDValue DemandedSrc = GetDemandedBits(Src, SrcDemandedBits))
2197 return getNode(ISD::ANY_EXTEND, SDLoc(V), V.getValueType(), DemandedSrc);
2198 break;
2201 return SDValue();
2204 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2205 /// use this predicate to simplify operations downstream.
2206 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2207 unsigned BitWidth = Op.getScalarValueSizeInBits();
2208 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2211 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2212 /// this predicate to simplify operations downstream. Mask is known to be zero
2213 /// for bits that V cannot have.
2214 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2215 unsigned Depth) const {
2216 EVT VT = V.getValueType();
2217 APInt DemandedElts = VT.isVector()
2218 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2219 : APInt(1, 1);
2220 return MaskedValueIsZero(V, Mask, DemandedElts, Depth);
2223 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2224 /// DemandedElts. We use this predicate to simplify operations downstream.
2225 /// Mask is known to be zero for bits that V cannot have.
2226 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2227 const APInt &DemandedElts,
2228 unsigned Depth) const {
2229 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2232 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2233 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2234 unsigned Depth) const {
2235 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2238 /// isSplatValue - Return true if the vector V has the same value
2239 /// across all DemandedElts.
2240 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2241 APInt &UndefElts) {
2242 if (!DemandedElts)
2243 return false; // No demanded elts, better to assume we don't know anything.
2245 EVT VT = V.getValueType();
2246 assert(VT.isVector() && "Vector type expected");
2248 unsigned NumElts = VT.getVectorNumElements();
2249 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2250 UndefElts = APInt::getNullValue(NumElts);
2252 switch (V.getOpcode()) {
2253 case ISD::BUILD_VECTOR: {
2254 SDValue Scl;
2255 for (unsigned i = 0; i != NumElts; ++i) {
2256 SDValue Op = V.getOperand(i);
2257 if (Op.isUndef()) {
2258 UndefElts.setBit(i);
2259 continue;
2261 if (!DemandedElts[i])
2262 continue;
2263 if (Scl && Scl != Op)
2264 return false;
2265 Scl = Op;
2267 return true;
2269 case ISD::VECTOR_SHUFFLE: {
2270 // Check if this is a shuffle node doing a splat.
2271 // TODO: Do we need to handle shuffle(splat, undef, mask)?
2272 int SplatIndex = -1;
2273 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2274 for (int i = 0; i != (int)NumElts; ++i) {
2275 int M = Mask[i];
2276 if (M < 0) {
2277 UndefElts.setBit(i);
2278 continue;
2280 if (!DemandedElts[i])
2281 continue;
2282 if (0 <= SplatIndex && SplatIndex != M)
2283 return false;
2284 SplatIndex = M;
2286 return true;
2288 case ISD::EXTRACT_SUBVECTOR: {
2289 SDValue Src = V.getOperand(0);
2290 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(V.getOperand(1));
2291 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2292 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2293 // Offset the demanded elts by the subvector index.
2294 uint64_t Idx = SubIdx->getZExtValue();
2295 APInt UndefSrcElts;
2296 APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2297 if (isSplatValue(Src, DemandedSrc, UndefSrcElts)) {
2298 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2299 return true;
2302 break;
2304 case ISD::ADD:
2305 case ISD::SUB:
2306 case ISD::AND: {
2307 APInt UndefLHS, UndefRHS;
2308 SDValue LHS = V.getOperand(0);
2309 SDValue RHS = V.getOperand(1);
2310 if (isSplatValue(LHS, DemandedElts, UndefLHS) &&
2311 isSplatValue(RHS, DemandedElts, UndefRHS)) {
2312 UndefElts = UndefLHS | UndefRHS;
2313 return true;
2315 break;
2319 return false;
2322 /// Helper wrapper to main isSplatValue function.
2323 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2324 EVT VT = V.getValueType();
2325 assert(VT.isVector() && "Vector type expected");
2326 unsigned NumElts = VT.getVectorNumElements();
2328 APInt UndefElts;
2329 APInt DemandedElts = APInt::getAllOnesValue(NumElts);
2330 return isSplatValue(V, DemandedElts, UndefElts) &&
2331 (AllowUndefs || !UndefElts);
2334 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2335 V = peekThroughExtractSubvectors(V);
2337 EVT VT = V.getValueType();
2338 unsigned Opcode = V.getOpcode();
2339 switch (Opcode) {
2340 default: {
2341 APInt UndefElts;
2342 APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2343 if (isSplatValue(V, DemandedElts, UndefElts)) {
2344 // Handle case where all demanded elements are UNDEF.
2345 if (DemandedElts.isSubsetOf(UndefElts)) {
2346 SplatIdx = 0;
2347 return getUNDEF(VT);
2349 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2350 return V;
2352 break;
2354 case ISD::VECTOR_SHUFFLE: {
2355 // Check if this is a shuffle node doing a splat.
2356 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2357 // getTargetVShiftNode currently struggles without the splat source.
2358 auto *SVN = cast<ShuffleVectorSDNode>(V);
2359 if (!SVN->isSplat())
2360 break;
2361 int Idx = SVN->getSplatIndex();
2362 int NumElts = V.getValueType().getVectorNumElements();
2363 SplatIdx = Idx % NumElts;
2364 return V.getOperand(Idx / NumElts);
2368 return SDValue();
2371 SDValue SelectionDAG::getSplatValue(SDValue V) {
2372 int SplatIdx;
2373 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx))
2374 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V),
2375 SrcVector.getValueType().getScalarType(), SrcVector,
2376 getIntPtrConstant(SplatIdx, SDLoc(V)));
2377 return SDValue();
2380 /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
2381 /// is less than the element bit-width of the shift node, return it.
2382 static const APInt *getValidShiftAmountConstant(SDValue V) {
2383 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1))) {
2384 // Shifting more than the bitwidth is not valid.
2385 const APInt &ShAmt = SA->getAPIntValue();
2386 if (ShAmt.ult(V.getScalarValueSizeInBits()))
2387 return &ShAmt;
2389 return nullptr;
2392 /// Determine which bits of Op are known to be either zero or one and return
2393 /// them in Known. For vectors, the known bits are those that are shared by
2394 /// every vector element.
2395 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2396 EVT VT = Op.getValueType();
2397 APInt DemandedElts = VT.isVector()
2398 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2399 : APInt(1, 1);
2400 return computeKnownBits(Op, DemandedElts, Depth);
2403 /// Determine which bits of Op are known to be either zero or one and return
2404 /// them in Known. The DemandedElts argument allows us to only collect the known
2405 /// bits that are shared by the requested vector elements.
2406 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2407 unsigned Depth) const {
2408 unsigned BitWidth = Op.getScalarValueSizeInBits();
2410 KnownBits Known(BitWidth); // Don't know anything.
2412 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2413 // We know all of the bits for a constant!
2414 Known.One = C->getAPIntValue();
2415 Known.Zero = ~Known.One;
2416 return Known;
2418 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2419 // We know all of the bits for a constant fp!
2420 Known.One = C->getValueAPF().bitcastToAPInt();
2421 Known.Zero = ~Known.One;
2422 return Known;
2425 if (Depth >= 6)
2426 return Known; // Limit search depth.
2428 KnownBits Known2;
2429 unsigned NumElts = DemandedElts.getBitWidth();
2430 assert((!Op.getValueType().isVector() ||
2431 NumElts == Op.getValueType().getVectorNumElements()) &&
2432 "Unexpected vector size");
2434 if (!DemandedElts)
2435 return Known; // No demanded elts, better to assume we don't know anything.
2437 unsigned Opcode = Op.getOpcode();
2438 switch (Opcode) {
2439 case ISD::BUILD_VECTOR:
2440 // Collect the known bits that are shared by every demanded vector element.
2441 Known.Zero.setAllBits(); Known.One.setAllBits();
2442 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2443 if (!DemandedElts[i])
2444 continue;
2446 SDValue SrcOp = Op.getOperand(i);
2447 Known2 = computeKnownBits(SrcOp, Depth + 1);
2449 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2450 if (SrcOp.getValueSizeInBits() != BitWidth) {
2451 assert(SrcOp.getValueSizeInBits() > BitWidth &&
2452 "Expected BUILD_VECTOR implicit truncation");
2453 Known2 = Known2.trunc(BitWidth);
2456 // Known bits are the values that are shared by every demanded element.
2457 Known.One &= Known2.One;
2458 Known.Zero &= Known2.Zero;
2460 // If we don't know any bits, early out.
2461 if (Known.isUnknown())
2462 break;
2464 break;
2465 case ISD::VECTOR_SHUFFLE: {
2466 // Collect the known bits that are shared by every vector element referenced
2467 // by the shuffle.
2468 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2469 Known.Zero.setAllBits(); Known.One.setAllBits();
2470 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2471 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2472 for (unsigned i = 0; i != NumElts; ++i) {
2473 if (!DemandedElts[i])
2474 continue;
2476 int M = SVN->getMaskElt(i);
2477 if (M < 0) {
2478 // For UNDEF elements, we don't know anything about the common state of
2479 // the shuffle result.
2480 Known.resetAll();
2481 DemandedLHS.clearAllBits();
2482 DemandedRHS.clearAllBits();
2483 break;
2486 if ((unsigned)M < NumElts)
2487 DemandedLHS.setBit((unsigned)M % NumElts);
2488 else
2489 DemandedRHS.setBit((unsigned)M % NumElts);
2491 // Known bits are the values that are shared by every demanded element.
2492 if (!!DemandedLHS) {
2493 SDValue LHS = Op.getOperand(0);
2494 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2495 Known.One &= Known2.One;
2496 Known.Zero &= Known2.Zero;
2498 // If we don't know any bits, early out.
2499 if (Known.isUnknown())
2500 break;
2501 if (!!DemandedRHS) {
2502 SDValue RHS = Op.getOperand(1);
2503 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2504 Known.One &= Known2.One;
2505 Known.Zero &= Known2.Zero;
2507 break;
2509 case ISD::CONCAT_VECTORS: {
2510 // Split DemandedElts and test each of the demanded subvectors.
2511 Known.Zero.setAllBits(); Known.One.setAllBits();
2512 EVT SubVectorVT = Op.getOperand(0).getValueType();
2513 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2514 unsigned NumSubVectors = Op.getNumOperands();
2515 for (unsigned i = 0; i != NumSubVectors; ++i) {
2516 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2517 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2518 if (!!DemandedSub) {
2519 SDValue Sub = Op.getOperand(i);
2520 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2521 Known.One &= Known2.One;
2522 Known.Zero &= Known2.Zero;
2524 // If we don't know any bits, early out.
2525 if (Known.isUnknown())
2526 break;
2528 break;
2530 case ISD::INSERT_SUBVECTOR: {
2531 // If we know the element index, demand any elements from the subvector and
2532 // the remainder from the src its inserted into, otherwise demand them all.
2533 SDValue Src = Op.getOperand(0);
2534 SDValue Sub = Op.getOperand(1);
2535 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2536 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2537 if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
2538 Known.One.setAllBits();
2539 Known.Zero.setAllBits();
2540 uint64_t Idx = SubIdx->getZExtValue();
2541 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2542 if (!!DemandedSubElts) {
2543 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2544 if (Known.isUnknown())
2545 break; // early-out.
2547 APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
2548 APInt DemandedSrcElts = DemandedElts & ~SubMask;
2549 if (!!DemandedSrcElts) {
2550 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2551 Known.One &= Known2.One;
2552 Known.Zero &= Known2.Zero;
2554 } else {
2555 Known = computeKnownBits(Sub, Depth + 1);
2556 if (Known.isUnknown())
2557 break; // early-out.
2558 Known2 = computeKnownBits(Src, Depth + 1);
2559 Known.One &= Known2.One;
2560 Known.Zero &= Known2.Zero;
2562 break;
2564 case ISD::EXTRACT_SUBVECTOR: {
2565 // If we know the element index, just demand that subvector elements,
2566 // otherwise demand them all.
2567 SDValue Src = Op.getOperand(0);
2568 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2569 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2570 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2571 // Offset the demanded elts by the subvector index.
2572 uint64_t Idx = SubIdx->getZExtValue();
2573 APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2574 Known = computeKnownBits(Src, DemandedSrc, Depth + 1);
2575 } else {
2576 Known = computeKnownBits(Src, Depth + 1);
2578 break;
2580 case ISD::SCALAR_TO_VECTOR: {
2581 // We know about scalar_to_vector as much as we know about it source,
2582 // which becomes the first element of otherwise unknown vector.
2583 if (DemandedElts != 1)
2584 break;
2586 SDValue N0 = Op.getOperand(0);
2587 Known = computeKnownBits(N0, Depth + 1);
2588 if (N0.getValueSizeInBits() != BitWidth)
2589 Known = Known.trunc(BitWidth);
2591 break;
2593 case ISD::BITCAST: {
2594 SDValue N0 = Op.getOperand(0);
2595 EVT SubVT = N0.getValueType();
2596 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2598 // Ignore bitcasts from unsupported types.
2599 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2600 break;
2602 // Fast handling of 'identity' bitcasts.
2603 if (BitWidth == SubBitWidth) {
2604 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2605 break;
2608 bool IsLE = getDataLayout().isLittleEndian();
2610 // Bitcast 'small element' vector to 'large element' scalar/vector.
2611 if ((BitWidth % SubBitWidth) == 0) {
2612 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2614 // Collect known bits for the (larger) output by collecting the known
2615 // bits from each set of sub elements and shift these into place.
2616 // We need to separately call computeKnownBits for each set of
2617 // sub elements as the knownbits for each is likely to be different.
2618 unsigned SubScale = BitWidth / SubBitWidth;
2619 APInt SubDemandedElts(NumElts * SubScale, 0);
2620 for (unsigned i = 0; i != NumElts; ++i)
2621 if (DemandedElts[i])
2622 SubDemandedElts.setBit(i * SubScale);
2624 for (unsigned i = 0; i != SubScale; ++i) {
2625 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2626 Depth + 1);
2627 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2628 Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts);
2629 Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts);
2633 // Bitcast 'large element' scalar/vector to 'small element' vector.
2634 if ((SubBitWidth % BitWidth) == 0) {
2635 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2637 // Collect known bits for the (smaller) output by collecting the known
2638 // bits from the overlapping larger input elements and extracting the
2639 // sub sections we actually care about.
2640 unsigned SubScale = SubBitWidth / BitWidth;
2641 APInt SubDemandedElts(NumElts / SubScale, 0);
2642 for (unsigned i = 0; i != NumElts; ++i)
2643 if (DemandedElts[i])
2644 SubDemandedElts.setBit(i / SubScale);
2646 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2648 Known.Zero.setAllBits(); Known.One.setAllBits();
2649 for (unsigned i = 0; i != NumElts; ++i)
2650 if (DemandedElts[i]) {
2651 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
2652 unsigned Offset = (Shifts % SubScale) * BitWidth;
2653 Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2654 Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2655 // If we don't know any bits, early out.
2656 if (Known.isUnknown())
2657 break;
2660 break;
2662 case ISD::AND:
2663 // If either the LHS or the RHS are Zero, the result is zero.
2664 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2665 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2667 // Output known-1 bits are only known if set in both the LHS & RHS.
2668 Known.One &= Known2.One;
2669 // Output known-0 are known to be clear if zero in either the LHS | RHS.
2670 Known.Zero |= Known2.Zero;
2671 break;
2672 case ISD::OR:
2673 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2674 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2676 // Output known-0 bits are only known if clear in both the LHS & RHS.
2677 Known.Zero &= Known2.Zero;
2678 // Output known-1 are known to be set if set in either the LHS | RHS.
2679 Known.One |= Known2.One;
2680 break;
2681 case ISD::XOR: {
2682 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2683 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2685 // Output known-0 bits are known if clear or set in both the LHS & RHS.
2686 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
2687 // Output known-1 are known to be set if set in only one of the LHS, RHS.
2688 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
2689 Known.Zero = KnownZeroOut;
2690 break;
2692 case ISD::MUL: {
2693 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2694 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2696 // If low bits are zero in either operand, output low known-0 bits.
2697 // Also compute a conservative estimate for high known-0 bits.
2698 // More trickiness is possible, but this is sufficient for the
2699 // interesting case of alignment computation.
2700 unsigned TrailZ = Known.countMinTrailingZeros() +
2701 Known2.countMinTrailingZeros();
2702 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
2703 Known2.countMinLeadingZeros(),
2704 BitWidth) - BitWidth;
2706 Known.resetAll();
2707 Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
2708 Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
2709 break;
2711 case ISD::UDIV: {
2712 // For the purposes of computing leading zeros we can conservatively
2713 // treat a udiv as a logical right shift by the power of 2 known to
2714 // be less than the denominator.
2715 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2716 unsigned LeadZ = Known2.countMinLeadingZeros();
2718 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2719 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
2720 if (RHSMaxLeadingZeros != BitWidth)
2721 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
2723 Known.Zero.setHighBits(LeadZ);
2724 break;
2726 case ISD::SELECT:
2727 case ISD::VSELECT:
2728 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2729 // If we don't know any bits, early out.
2730 if (Known.isUnknown())
2731 break;
2732 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
2734 // Only known if known in both the LHS and RHS.
2735 Known.One &= Known2.One;
2736 Known.Zero &= Known2.Zero;
2737 break;
2738 case ISD::SELECT_CC:
2739 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
2740 // If we don't know any bits, early out.
2741 if (Known.isUnknown())
2742 break;
2743 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2745 // Only known if known in both the LHS and RHS.
2746 Known.One &= Known2.One;
2747 Known.Zero &= Known2.Zero;
2748 break;
2749 case ISD::SMULO:
2750 case ISD::UMULO:
2751 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
2752 if (Op.getResNo() != 1)
2753 break;
2754 // The boolean result conforms to getBooleanContents.
2755 // If we know the result of a setcc has the top bits zero, use this info.
2756 // We know that we have an integer-based boolean since these operations
2757 // are only available for integer.
2758 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2759 TargetLowering::ZeroOrOneBooleanContent &&
2760 BitWidth > 1)
2761 Known.Zero.setBitsFrom(1);
2762 break;
2763 case ISD::SETCC:
2764 // If we know the result of a setcc has the top bits zero, use this info.
2765 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2766 TargetLowering::ZeroOrOneBooleanContent &&
2767 BitWidth > 1)
2768 Known.Zero.setBitsFrom(1);
2769 break;
2770 case ISD::SHL:
2771 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2772 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2773 unsigned Shift = ShAmt->getZExtValue();
2774 Known.Zero <<= Shift;
2775 Known.One <<= Shift;
2776 // Low bits are known zero.
2777 Known.Zero.setLowBits(Shift);
2779 break;
2780 case ISD::SRL:
2781 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2782 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2783 unsigned Shift = ShAmt->getZExtValue();
2784 Known.Zero.lshrInPlace(Shift);
2785 Known.One.lshrInPlace(Shift);
2786 // High bits are known zero.
2787 Known.Zero.setHighBits(Shift);
2788 } else if (auto *BV = dyn_cast<BuildVectorSDNode>(Op.getOperand(1))) {
2789 // If the shift amount is a vector of constants see if we can bound
2790 // the number of upper zero bits.
2791 unsigned ShiftAmountMin = BitWidth;
2792 for (unsigned i = 0; i != BV->getNumOperands(); ++i) {
2793 if (auto *C = dyn_cast<ConstantSDNode>(BV->getOperand(i))) {
2794 const APInt &ShAmt = C->getAPIntValue();
2795 if (ShAmt.ult(BitWidth)) {
2796 ShiftAmountMin = std::min<unsigned>(ShiftAmountMin,
2797 ShAmt.getZExtValue());
2798 continue;
2801 // Don't know anything.
2802 ShiftAmountMin = 0;
2803 break;
2806 Known.Zero.setHighBits(ShiftAmountMin);
2808 break;
2809 case ISD::SRA:
2810 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2811 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2812 unsigned Shift = ShAmt->getZExtValue();
2813 // Sign extend known zero/one bit (else is unknown).
2814 Known.Zero.ashrInPlace(Shift);
2815 Known.One.ashrInPlace(Shift);
2817 break;
2818 case ISD::FSHL:
2819 case ISD::FSHR:
2820 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
2821 unsigned Amt = C->getAPIntValue().urem(BitWidth);
2823 // For fshl, 0-shift returns the 1st arg.
2824 // For fshr, 0-shift returns the 2nd arg.
2825 if (Amt == 0) {
2826 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
2827 DemandedElts, Depth + 1);
2828 break;
2831 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
2832 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
2833 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2834 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2835 if (Opcode == ISD::FSHL) {
2836 Known.One <<= Amt;
2837 Known.Zero <<= Amt;
2838 Known2.One.lshrInPlace(BitWidth - Amt);
2839 Known2.Zero.lshrInPlace(BitWidth - Amt);
2840 } else {
2841 Known.One <<= BitWidth - Amt;
2842 Known.Zero <<= BitWidth - Amt;
2843 Known2.One.lshrInPlace(Amt);
2844 Known2.Zero.lshrInPlace(Amt);
2846 Known.One |= Known2.One;
2847 Known.Zero |= Known2.Zero;
2849 break;
2850 case ISD::SIGN_EXTEND_INREG: {
2851 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2852 unsigned EBits = EVT.getScalarSizeInBits();
2854 // Sign extension. Compute the demanded bits in the result that are not
2855 // present in the input.
2856 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2858 APInt InSignMask = APInt::getSignMask(EBits);
2859 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2861 // If the sign extended bits are demanded, we know that the sign
2862 // bit is demanded.
2863 InSignMask = InSignMask.zext(BitWidth);
2864 if (NewBits.getBoolValue())
2865 InputDemandedBits |= InSignMask;
2867 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2868 Known.One &= InputDemandedBits;
2869 Known.Zero &= InputDemandedBits;
2871 // If the sign bit of the input is known set or clear, then we know the
2872 // top bits of the result.
2873 if (Known.Zero.intersects(InSignMask)) { // Input sign bit known clear
2874 Known.Zero |= NewBits;
2875 Known.One &= ~NewBits;
2876 } else if (Known.One.intersects(InSignMask)) { // Input sign bit known set
2877 Known.One |= NewBits;
2878 Known.Zero &= ~NewBits;
2879 } else { // Input sign bit unknown
2880 Known.Zero &= ~NewBits;
2881 Known.One &= ~NewBits;
2883 break;
2885 case ISD::CTTZ:
2886 case ISD::CTTZ_ZERO_UNDEF: {
2887 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2888 // If we have a known 1, its position is our upper bound.
2889 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2890 unsigned LowBits = Log2_32(PossibleTZ) + 1;
2891 Known.Zero.setBitsFrom(LowBits);
2892 break;
2894 case ISD::CTLZ:
2895 case ISD::CTLZ_ZERO_UNDEF: {
2896 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2897 // If we have a known 1, its position is our upper bound.
2898 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2899 unsigned LowBits = Log2_32(PossibleLZ) + 1;
2900 Known.Zero.setBitsFrom(LowBits);
2901 break;
2903 case ISD::CTPOP: {
2904 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2905 // If we know some of the bits are zero, they can't be one.
2906 unsigned PossibleOnes = Known2.countMaxPopulation();
2907 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
2908 break;
2910 case ISD::LOAD: {
2911 LoadSDNode *LD = cast<LoadSDNode>(Op);
2912 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
2913 if (ISD::isNON_EXTLoad(LD) && Cst) {
2914 // Determine any common known bits from the loaded constant pool value.
2915 Type *CstTy = Cst->getType();
2916 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
2917 // If its a vector splat, then we can (quickly) reuse the scalar path.
2918 // NOTE: We assume all elements match and none are UNDEF.
2919 if (CstTy->isVectorTy()) {
2920 if (const Constant *Splat = Cst->getSplatValue()) {
2921 Cst = Splat;
2922 CstTy = Cst->getType();
2925 // TODO - do we need to handle different bitwidths?
2926 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
2927 // Iterate across all vector elements finding common known bits.
2928 Known.One.setAllBits();
2929 Known.Zero.setAllBits();
2930 for (unsigned i = 0; i != NumElts; ++i) {
2931 if (!DemandedElts[i])
2932 continue;
2933 if (Constant *Elt = Cst->getAggregateElement(i)) {
2934 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
2935 const APInt &Value = CInt->getValue();
2936 Known.One &= Value;
2937 Known.Zero &= ~Value;
2938 continue;
2940 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
2941 APInt Value = CFP->getValueAPF().bitcastToAPInt();
2942 Known.One &= Value;
2943 Known.Zero &= ~Value;
2944 continue;
2947 Known.One.clearAllBits();
2948 Known.Zero.clearAllBits();
2949 break;
2951 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
2952 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
2953 const APInt &Value = CInt->getValue();
2954 Known.One = Value;
2955 Known.Zero = ~Value;
2956 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
2957 APInt Value = CFP->getValueAPF().bitcastToAPInt();
2958 Known.One = Value;
2959 Known.Zero = ~Value;
2963 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2964 // If this is a ZEXTLoad and we are looking at the loaded value.
2965 EVT VT = LD->getMemoryVT();
2966 unsigned MemBits = VT.getScalarSizeInBits();
2967 Known.Zero.setBitsFrom(MemBits);
2968 } else if (const MDNode *Ranges = LD->getRanges()) {
2969 if (LD->getExtensionType() == ISD::NON_EXTLOAD)
2970 computeKnownBitsFromRangeMetadata(*Ranges, Known);
2972 break;
2974 case ISD::ZERO_EXTEND_VECTOR_INREG: {
2975 EVT InVT = Op.getOperand(0).getValueType();
2976 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
2977 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
2978 Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
2979 break;
2981 case ISD::ZERO_EXTEND: {
2982 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2983 Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
2984 break;
2986 case ISD::SIGN_EXTEND_VECTOR_INREG: {
2987 EVT InVT = Op.getOperand(0).getValueType();
2988 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
2989 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
2990 // If the sign bit is known to be zero or one, then sext will extend
2991 // it to the top bits, else it will just zext.
2992 Known = Known.sext(BitWidth);
2993 break;
2995 case ISD::SIGN_EXTEND: {
2996 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2997 // If the sign bit is known to be zero or one, then sext will extend
2998 // it to the top bits, else it will just zext.
2999 Known = Known.sext(BitWidth);
3000 break;
3002 case ISD::ANY_EXTEND: {
3003 Known = computeKnownBits(Op.getOperand(0), Depth+1);
3004 Known = Known.zext(BitWidth, false /* ExtendedBitsAreKnownZero */);
3005 break;
3007 case ISD::TRUNCATE: {
3008 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3009 Known = Known.trunc(BitWidth);
3010 break;
3012 case ISD::AssertZext: {
3013 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3014 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3015 Known = computeKnownBits(Op.getOperand(0), Depth+1);
3016 Known.Zero |= (~InMask);
3017 Known.One &= (~Known.Zero);
3018 break;
3020 case ISD::FGETSIGN:
3021 // All bits are zero except the low bit.
3022 Known.Zero.setBitsFrom(1);
3023 break;
3024 case ISD::USUBO:
3025 case ISD::SSUBO:
3026 if (Op.getResNo() == 1) {
3027 // If we know the result of a setcc has the top bits zero, use this info.
3028 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3029 TargetLowering::ZeroOrOneBooleanContent &&
3030 BitWidth > 1)
3031 Known.Zero.setBitsFrom(1);
3032 break;
3034 LLVM_FALLTHROUGH;
3035 case ISD::SUB:
3036 case ISD::SUBC: {
3037 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3038 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3039 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3040 Known, Known2);
3041 break;
3043 case ISD::UADDO:
3044 case ISD::SADDO:
3045 case ISD::ADDCARRY:
3046 if (Op.getResNo() == 1) {
3047 // If we know the result of a setcc has the top bits zero, use this info.
3048 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3049 TargetLowering::ZeroOrOneBooleanContent &&
3050 BitWidth > 1)
3051 Known.Zero.setBitsFrom(1);
3052 break;
3054 LLVM_FALLTHROUGH;
3055 case ISD::ADD:
3056 case ISD::ADDC:
3057 case ISD::ADDE: {
3058 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3060 // With ADDE and ADDCARRY, a carry bit may be added in.
3061 KnownBits Carry(1);
3062 if (Opcode == ISD::ADDE)
3063 // Can't track carry from glue, set carry to unknown.
3064 Carry.resetAll();
3065 else if (Opcode == ISD::ADDCARRY)
3066 // TODO: Compute known bits for the carry operand. Not sure if it is worth
3067 // the trouble (how often will we find a known carry bit). And I haven't
3068 // tested this very much yet, but something like this might work:
3069 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3070 // Carry = Carry.zextOrTrunc(1, false);
3071 Carry.resetAll();
3072 else
3073 Carry.setAllZero();
3075 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3076 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3077 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3078 break;
3080 case ISD::SREM:
3081 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
3082 const APInt &RA = Rem->getAPIntValue().abs();
3083 if (RA.isPowerOf2()) {
3084 APInt LowBits = RA - 1;
3085 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3087 // The low bits of the first operand are unchanged by the srem.
3088 Known.Zero = Known2.Zero & LowBits;
3089 Known.One = Known2.One & LowBits;
3091 // If the first operand is non-negative or has all low bits zero, then
3092 // the upper bits are all zero.
3093 if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
3094 Known.Zero |= ~LowBits;
3096 // If the first operand is negative and not all low bits are zero, then
3097 // the upper bits are all one.
3098 if (Known2.isNegative() && LowBits.intersects(Known2.One))
3099 Known.One |= ~LowBits;
3100 assert((Known.Zero & Known.One) == 0&&"Bits known to be one AND zero?");
3103 break;
3104 case ISD::UREM: {
3105 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
3106 const APInt &RA = Rem->getAPIntValue();
3107 if (RA.isPowerOf2()) {
3108 APInt LowBits = (RA - 1);
3109 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3111 // The upper bits are all zero, the lower ones are unchanged.
3112 Known.Zero = Known2.Zero | ~LowBits;
3113 Known.One = Known2.One & LowBits;
3114 break;
3118 // Since the result is less than or equal to either operand, any leading
3119 // zero bits in either operand must also exist in the result.
3120 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3121 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3123 uint32_t Leaders =
3124 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
3125 Known.resetAll();
3126 Known.Zero.setHighBits(Leaders);
3127 break;
3129 case ISD::EXTRACT_ELEMENT: {
3130 Known = computeKnownBits(Op.getOperand(0), Depth+1);
3131 const unsigned Index = Op.getConstantOperandVal(1);
3132 const unsigned EltBitWidth = Op.getValueSizeInBits();
3134 // Remove low part of known bits mask
3135 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3136 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3138 // Remove high part of known bit mask
3139 Known = Known.trunc(EltBitWidth);
3140 break;
3142 case ISD::EXTRACT_VECTOR_ELT: {
3143 SDValue InVec = Op.getOperand(0);
3144 SDValue EltNo = Op.getOperand(1);
3145 EVT VecVT = InVec.getValueType();
3146 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3147 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3148 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3149 // anything about the extended bits.
3150 if (BitWidth > EltBitWidth)
3151 Known = Known.trunc(EltBitWidth);
3152 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3153 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) {
3154 // If we know the element index, just demand that vector element.
3155 unsigned Idx = ConstEltNo->getZExtValue();
3156 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
3157 Known = computeKnownBits(InVec, DemandedElt, Depth + 1);
3158 } else {
3159 // Unknown element index, so ignore DemandedElts and demand them all.
3160 Known = computeKnownBits(InVec, Depth + 1);
3162 if (BitWidth > EltBitWidth)
3163 Known = Known.zext(BitWidth, false /* => any extend */);
3164 break;
3166 case ISD::INSERT_VECTOR_ELT: {
3167 SDValue InVec = Op.getOperand(0);
3168 SDValue InVal = Op.getOperand(1);
3169 SDValue EltNo = Op.getOperand(2);
3171 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3172 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3173 // If we know the element index, split the demand between the
3174 // source vector and the inserted element.
3175 Known.Zero = Known.One = APInt::getAllOnesValue(BitWidth);
3176 unsigned EltIdx = CEltNo->getZExtValue();
3178 // If we demand the inserted element then add its common known bits.
3179 if (DemandedElts[EltIdx]) {
3180 Known2 = computeKnownBits(InVal, Depth + 1);
3181 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
3182 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
3185 // If we demand the source vector then add its common known bits, ensuring
3186 // that we don't demand the inserted element.
3187 APInt VectorElts = DemandedElts & ~(APInt::getOneBitSet(NumElts, EltIdx));
3188 if (!!VectorElts) {
3189 Known2 = computeKnownBits(InVec, VectorElts, Depth + 1);
3190 Known.One &= Known2.One;
3191 Known.Zero &= Known2.Zero;
3193 } else {
3194 // Unknown element index, so ignore DemandedElts and demand them all.
3195 Known = computeKnownBits(InVec, Depth + 1);
3196 Known2 = computeKnownBits(InVal, Depth + 1);
3197 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
3198 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
3200 break;
3202 case ISD::BITREVERSE: {
3203 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3204 Known.Zero = Known2.Zero.reverseBits();
3205 Known.One = Known2.One.reverseBits();
3206 break;
3208 case ISD::BSWAP: {
3209 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3210 Known.Zero = Known2.Zero.byteSwap();
3211 Known.One = Known2.One.byteSwap();
3212 break;
3214 case ISD::ABS: {
3215 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3217 // If the source's MSB is zero then we know the rest of the bits already.
3218 if (Known2.isNonNegative()) {
3219 Known.Zero = Known2.Zero;
3220 Known.One = Known2.One;
3221 break;
3224 // We only know that the absolute values's MSB will be zero iff there is
3225 // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
3226 Known2.One.clearSignBit();
3227 if (Known2.One.getBoolValue()) {
3228 Known.Zero = APInt::getSignMask(BitWidth);
3229 break;
3231 break;
3233 case ISD::UMIN: {
3234 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3235 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3237 // UMIN - we know that the result will have the maximum of the
3238 // known zero leading bits of the inputs.
3239 unsigned LeadZero = Known.countMinLeadingZeros();
3240 LeadZero = std::max(LeadZero, Known2.countMinLeadingZeros());
3242 Known.Zero &= Known2.Zero;
3243 Known.One &= Known2.One;
3244 Known.Zero.setHighBits(LeadZero);
3245 break;
3247 case ISD::UMAX: {
3248 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3249 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3251 // UMAX - we know that the result will have the maximum of the
3252 // known one leading bits of the inputs.
3253 unsigned LeadOne = Known.countMinLeadingOnes();
3254 LeadOne = std::max(LeadOne, Known2.countMinLeadingOnes());
3256 Known.Zero &= Known2.Zero;
3257 Known.One &= Known2.One;
3258 Known.One.setHighBits(LeadOne);
3259 break;
3261 case ISD::SMIN:
3262 case ISD::SMAX: {
3263 // If we have a clamp pattern, we know that the number of sign bits will be
3264 // the minimum of the clamp min/max range.
3265 bool IsMax = (Opcode == ISD::SMAX);
3266 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3267 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3268 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3269 CstHigh =
3270 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3271 if (CstLow && CstHigh) {
3272 if (!IsMax)
3273 std::swap(CstLow, CstHigh);
3275 const APInt &ValueLow = CstLow->getAPIntValue();
3276 const APInt &ValueHigh = CstHigh->getAPIntValue();
3277 if (ValueLow.sle(ValueHigh)) {
3278 unsigned LowSignBits = ValueLow.getNumSignBits();
3279 unsigned HighSignBits = ValueHigh.getNumSignBits();
3280 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3281 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3282 Known.One.setHighBits(MinSignBits);
3283 break;
3285 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3286 Known.Zero.setHighBits(MinSignBits);
3287 break;
3292 // Fallback - just get the shared known bits of the operands.
3293 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3294 if (Known.isUnknown()) break; // Early-out
3295 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3296 Known.Zero &= Known2.Zero;
3297 Known.One &= Known2.One;
3298 break;
3300 case ISD::FrameIndex:
3301 case ISD::TargetFrameIndex:
3302 TLI->computeKnownBitsForFrameIndex(Op, Known, DemandedElts, *this, Depth);
3303 break;
3305 default:
3306 if (Opcode < ISD::BUILTIN_OP_END)
3307 break;
3308 LLVM_FALLTHROUGH;
3309 case ISD::INTRINSIC_WO_CHAIN:
3310 case ISD::INTRINSIC_W_CHAIN:
3311 case ISD::INTRINSIC_VOID:
3312 // Allow the target to implement this method for its nodes.
3313 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3314 break;
3317 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3318 return Known;
3321 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3322 SDValue N1) const {
3323 // X + 0 never overflow
3324 if (isNullConstant(N1))
3325 return OFK_Never;
3327 KnownBits N1Known = computeKnownBits(N1);
3328 if (N1Known.Zero.getBoolValue()) {
3329 KnownBits N0Known = computeKnownBits(N0);
3331 bool overflow;
3332 (void)(~N0Known.Zero).uadd_ov(~N1Known.Zero, overflow);
3333 if (!overflow)
3334 return OFK_Never;
3337 // mulhi + 1 never overflow
3338 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3339 (~N1Known.Zero & 0x01) == ~N1Known.Zero)
3340 return OFK_Never;
3342 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3343 KnownBits N0Known = computeKnownBits(N0);
3345 if ((~N0Known.Zero & 0x01) == ~N0Known.Zero)
3346 return OFK_Never;
3349 return OFK_Sometime;
3352 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3353 EVT OpVT = Val.getValueType();
3354 unsigned BitWidth = OpVT.getScalarSizeInBits();
3356 // Is the constant a known power of 2?
3357 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3358 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3360 // A left-shift of a constant one will have exactly one bit set because
3361 // shifting the bit off the end is undefined.
3362 if (Val.getOpcode() == ISD::SHL) {
3363 auto *C = isConstOrConstSplat(Val.getOperand(0));
3364 if (C && C->getAPIntValue() == 1)
3365 return true;
3368 // Similarly, a logical right-shift of a constant sign-bit will have exactly
3369 // one bit set.
3370 if (Val.getOpcode() == ISD::SRL) {
3371 auto *C = isConstOrConstSplat(Val.getOperand(0));
3372 if (C && C->getAPIntValue().isSignMask())
3373 return true;
3376 // Are all operands of a build vector constant powers of two?
3377 if (Val.getOpcode() == ISD::BUILD_VECTOR)
3378 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3379 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3380 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3381 return false;
3383 return true;
3385 // More could be done here, though the above checks are enough
3386 // to handle some common cases.
3388 // Fall back to computeKnownBits to catch other known cases.
3389 KnownBits Known = computeKnownBits(Val);
3390 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3393 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3394 EVT VT = Op.getValueType();
3395 APInt DemandedElts = VT.isVector()
3396 ? APInt::getAllOnesValue(VT.getVectorNumElements())
3397 : APInt(1, 1);
3398 return ComputeNumSignBits(Op, DemandedElts, Depth);
3401 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3402 unsigned Depth) const {
3403 EVT VT = Op.getValueType();
3404 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3405 unsigned VTBits = VT.getScalarSizeInBits();
3406 unsigned NumElts = DemandedElts.getBitWidth();
3407 unsigned Tmp, Tmp2;
3408 unsigned FirstAnswer = 1;
3410 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3411 const APInt &Val = C->getAPIntValue();
3412 return Val.getNumSignBits();
3415 if (Depth >= 6)
3416 return 1; // Limit search depth.
3418 if (!DemandedElts)
3419 return 1; // No demanded elts, better to assume we don't know anything.
3421 unsigned Opcode = Op.getOpcode();
3422 switch (Opcode) {
3423 default: break;
3424 case ISD::AssertSext:
3425 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3426 return VTBits-Tmp+1;
3427 case ISD::AssertZext:
3428 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3429 return VTBits-Tmp;
3431 case ISD::BUILD_VECTOR:
3432 Tmp = VTBits;
3433 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3434 if (!DemandedElts[i])
3435 continue;
3437 SDValue SrcOp = Op.getOperand(i);
3438 Tmp2 = ComputeNumSignBits(Op.getOperand(i), Depth + 1);
3440 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3441 if (SrcOp.getValueSizeInBits() != VTBits) {
3442 assert(SrcOp.getValueSizeInBits() > VTBits &&
3443 "Expected BUILD_VECTOR implicit truncation");
3444 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3445 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3447 Tmp = std::min(Tmp, Tmp2);
3449 return Tmp;
3451 case ISD::VECTOR_SHUFFLE: {
3452 // Collect the minimum number of sign bits that are shared by every vector
3453 // element referenced by the shuffle.
3454 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3455 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3456 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3457 for (unsigned i = 0; i != NumElts; ++i) {
3458 int M = SVN->getMaskElt(i);
3459 if (!DemandedElts[i])
3460 continue;
3461 // For UNDEF elements, we don't know anything about the common state of
3462 // the shuffle result.
3463 if (M < 0)
3464 return 1;
3465 if ((unsigned)M < NumElts)
3466 DemandedLHS.setBit((unsigned)M % NumElts);
3467 else
3468 DemandedRHS.setBit((unsigned)M % NumElts);
3470 Tmp = std::numeric_limits<unsigned>::max();
3471 if (!!DemandedLHS)
3472 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3473 if (!!DemandedRHS) {
3474 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3475 Tmp = std::min(Tmp, Tmp2);
3477 // If we don't know anything, early out and try computeKnownBits fall-back.
3478 if (Tmp == 1)
3479 break;
3480 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3481 return Tmp;
3484 case ISD::BITCAST: {
3485 SDValue N0 = Op.getOperand(0);
3486 EVT SrcVT = N0.getValueType();
3487 unsigned SrcBits = SrcVT.getScalarSizeInBits();
3489 // Ignore bitcasts from unsupported types..
3490 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3491 break;
3493 // Fast handling of 'identity' bitcasts.
3494 if (VTBits == SrcBits)
3495 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3497 bool IsLE = getDataLayout().isLittleEndian();
3499 // Bitcast 'large element' scalar/vector to 'small element' vector.
3500 if ((SrcBits % VTBits) == 0) {
3501 assert(VT.isVector() && "Expected bitcast to vector");
3503 unsigned Scale = SrcBits / VTBits;
3504 APInt SrcDemandedElts(NumElts / Scale, 0);
3505 for (unsigned i = 0; i != NumElts; ++i)
3506 if (DemandedElts[i])
3507 SrcDemandedElts.setBit(i / Scale);
3509 // Fast case - sign splat can be simply split across the small elements.
3510 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3511 if (Tmp == SrcBits)
3512 return VTBits;
3514 // Slow case - determine how far the sign extends into each sub-element.
3515 Tmp2 = VTBits;
3516 for (unsigned i = 0; i != NumElts; ++i)
3517 if (DemandedElts[i]) {
3518 unsigned SubOffset = i % Scale;
3519 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3520 SubOffset = SubOffset * VTBits;
3521 if (Tmp <= SubOffset)
3522 return 1;
3523 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3525 return Tmp2;
3527 break;
3530 case ISD::SIGN_EXTEND:
3531 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3532 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3533 case ISD::SIGN_EXTEND_INREG:
3534 // Max of the input and what this extends.
3535 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3536 Tmp = VTBits-Tmp+1;
3537 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3538 return std::max(Tmp, Tmp2);
3539 case ISD::SIGN_EXTEND_VECTOR_INREG: {
3540 SDValue Src = Op.getOperand(0);
3541 EVT SrcVT = Src.getValueType();
3542 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3543 Tmp = VTBits - SrcVT.getScalarSizeInBits();
3544 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3547 case ISD::SRA:
3548 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3549 // SRA X, C -> adds C sign bits.
3550 if (ConstantSDNode *C =
3551 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3552 APInt ShiftVal = C->getAPIntValue();
3553 ShiftVal += Tmp;
3554 Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
3556 return Tmp;
3557 case ISD::SHL:
3558 if (ConstantSDNode *C =
3559 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3560 // shl destroys sign bits.
3561 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3562 if (C->getAPIntValue().uge(VTBits) || // Bad shift.
3563 C->getAPIntValue().uge(Tmp)) break; // Shifted all sign bits out.
3564 return Tmp - C->getZExtValue();
3566 break;
3567 case ISD::AND:
3568 case ISD::OR:
3569 case ISD::XOR: // NOT is handled here.
3570 // Logical binary ops preserve the number of sign bits at the worst.
3571 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3572 if (Tmp != 1) {
3573 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3574 FirstAnswer = std::min(Tmp, Tmp2);
3575 // We computed what we know about the sign bits as our first
3576 // answer. Now proceed to the generic code that uses
3577 // computeKnownBits, and pick whichever answer is better.
3579 break;
3581 case ISD::SELECT:
3582 case ISD::VSELECT:
3583 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3584 if (Tmp == 1) return 1; // Early out.
3585 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3586 return std::min(Tmp, Tmp2);
3587 case ISD::SELECT_CC:
3588 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3589 if (Tmp == 1) return 1; // Early out.
3590 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3591 return std::min(Tmp, Tmp2);
3593 case ISD::SMIN:
3594 case ISD::SMAX: {
3595 // If we have a clamp pattern, we know that the number of sign bits will be
3596 // the minimum of the clamp min/max range.
3597 bool IsMax = (Opcode == ISD::SMAX);
3598 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3599 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3600 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3601 CstHigh =
3602 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3603 if (CstLow && CstHigh) {
3604 if (!IsMax)
3605 std::swap(CstLow, CstHigh);
3606 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3607 Tmp = CstLow->getAPIntValue().getNumSignBits();
3608 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3609 return std::min(Tmp, Tmp2);
3613 // Fallback - just get the minimum number of sign bits of the operands.
3614 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3615 if (Tmp == 1)
3616 return 1; // Early out.
3617 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3618 return std::min(Tmp, Tmp2);
3620 case ISD::UMIN:
3621 case ISD::UMAX:
3622 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3623 if (Tmp == 1)
3624 return 1; // Early out.
3625 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3626 return std::min(Tmp, Tmp2);
3627 case ISD::SADDO:
3628 case ISD::UADDO:
3629 case ISD::SSUBO:
3630 case ISD::USUBO:
3631 case ISD::SMULO:
3632 case ISD::UMULO:
3633 if (Op.getResNo() != 1)
3634 break;
3635 // The boolean result conforms to getBooleanContents. Fall through.
3636 // If setcc returns 0/-1, all bits are sign bits.
3637 // We know that we have an integer-based boolean since these operations
3638 // are only available for integer.
3639 if (TLI->getBooleanContents(VT.isVector(), false) ==
3640 TargetLowering::ZeroOrNegativeOneBooleanContent)
3641 return VTBits;
3642 break;
3643 case ISD::SETCC:
3644 // If setcc returns 0/-1, all bits are sign bits.
3645 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3646 TargetLowering::ZeroOrNegativeOneBooleanContent)
3647 return VTBits;
3648 break;
3649 case ISD::ROTL:
3650 case ISD::ROTR:
3651 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3652 unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3654 // Handle rotate right by N like a rotate left by 32-N.
3655 if (Opcode == ISD::ROTR)
3656 RotAmt = (VTBits - RotAmt) % VTBits;
3658 // If we aren't rotating out all of the known-in sign bits, return the
3659 // number that are left. This handles rotl(sext(x), 1) for example.
3660 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3661 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3663 break;
3664 case ISD::ADD:
3665 case ISD::ADDC:
3666 // Add can have at most one carry bit. Thus we know that the output
3667 // is, at worst, one more bit than the inputs.
3668 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3669 if (Tmp == 1) return 1; // Early out.
3671 // Special case decrementing a value (ADD X, -1):
3672 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3673 if (CRHS->isAllOnesValue()) {
3674 KnownBits Known = computeKnownBits(Op.getOperand(0), Depth+1);
3676 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3677 // sign bits set.
3678 if ((Known.Zero | 1).isAllOnesValue())
3679 return VTBits;
3681 // If we are subtracting one from a positive number, there is no carry
3682 // out of the result.
3683 if (Known.isNonNegative())
3684 return Tmp;
3687 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3688 if (Tmp2 == 1) return 1;
3689 return std::min(Tmp, Tmp2)-1;
3691 case ISD::SUB:
3692 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3693 if (Tmp2 == 1) return 1;
3695 // Handle NEG.
3696 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
3697 if (CLHS->isNullValue()) {
3698 KnownBits Known = computeKnownBits(Op.getOperand(1), Depth+1);
3699 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3700 // sign bits set.
3701 if ((Known.Zero | 1).isAllOnesValue())
3702 return VTBits;
3704 // If the input is known to be positive (the sign bit is known clear),
3705 // the output of the NEG has the same number of sign bits as the input.
3706 if (Known.isNonNegative())
3707 return Tmp2;
3709 // Otherwise, we treat this like a SUB.
3712 // Sub can have at most one carry bit. Thus we know that the output
3713 // is, at worst, one more bit than the inputs.
3714 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3715 if (Tmp == 1) return 1; // Early out.
3716 return std::min(Tmp, Tmp2)-1;
3717 case ISD::MUL: {
3718 // The output of the Mul can be at most twice the valid bits in the inputs.
3719 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3720 if (SignBitsOp0 == 1)
3721 break;
3722 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3723 if (SignBitsOp1 == 1)
3724 break;
3725 unsigned OutValidBits =
3726 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
3727 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
3729 case ISD::TRUNCATE: {
3730 // Check if the sign bits of source go down as far as the truncated value.
3731 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3732 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3733 if (NumSrcSignBits > (NumSrcBits - VTBits))
3734 return NumSrcSignBits - (NumSrcBits - VTBits);
3735 break;
3737 case ISD::EXTRACT_ELEMENT: {
3738 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3739 const int BitWidth = Op.getValueSizeInBits();
3740 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3742 // Get reverse index (starting from 1), Op1 value indexes elements from
3743 // little end. Sign starts at big end.
3744 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3746 // If the sign portion ends in our element the subtraction gives correct
3747 // result. Otherwise it gives either negative or > bitwidth result
3748 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3750 case ISD::INSERT_VECTOR_ELT: {
3751 SDValue InVec = Op.getOperand(0);
3752 SDValue InVal = Op.getOperand(1);
3753 SDValue EltNo = Op.getOperand(2);
3755 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3756 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3757 // If we know the element index, split the demand between the
3758 // source vector and the inserted element.
3759 unsigned EltIdx = CEltNo->getZExtValue();
3761 // If we demand the inserted element then get its sign bits.
3762 Tmp = std::numeric_limits<unsigned>::max();
3763 if (DemandedElts[EltIdx]) {
3764 // TODO - handle implicit truncation of inserted elements.
3765 if (InVal.getScalarValueSizeInBits() != VTBits)
3766 break;
3767 Tmp = ComputeNumSignBits(InVal, Depth + 1);
3770 // If we demand the source vector then get its sign bits, and determine
3771 // the minimum.
3772 APInt VectorElts = DemandedElts;
3773 VectorElts.clearBit(EltIdx);
3774 if (!!VectorElts) {
3775 Tmp2 = ComputeNumSignBits(InVec, VectorElts, Depth + 1);
3776 Tmp = std::min(Tmp, Tmp2);
3778 } else {
3779 // Unknown element index, so ignore DemandedElts and demand them all.
3780 Tmp = ComputeNumSignBits(InVec, Depth + 1);
3781 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3782 Tmp = std::min(Tmp, Tmp2);
3784 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3785 return Tmp;
3787 case ISD::EXTRACT_VECTOR_ELT: {
3788 SDValue InVec = Op.getOperand(0);
3789 SDValue EltNo = Op.getOperand(1);
3790 EVT VecVT = InVec.getValueType();
3791 const unsigned BitWidth = Op.getValueSizeInBits();
3792 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3793 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3795 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3796 // anything about sign bits. But if the sizes match we can derive knowledge
3797 // about sign bits from the vector operand.
3798 if (BitWidth != EltBitWidth)
3799 break;
3801 // If we know the element index, just demand that vector element, else for
3802 // an unknown element index, ignore DemandedElts and demand them all.
3803 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3804 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3805 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3806 DemandedSrcElts =
3807 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3809 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3811 case ISD::EXTRACT_SUBVECTOR: {
3812 // If we know the element index, just demand that subvector elements,
3813 // otherwise demand them all.
3814 SDValue Src = Op.getOperand(0);
3815 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
3816 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3817 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
3818 // Offset the demanded elts by the subvector index.
3819 uint64_t Idx = SubIdx->getZExtValue();
3820 APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
3821 return ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
3823 return ComputeNumSignBits(Src, Depth + 1);
3825 case ISD::CONCAT_VECTORS: {
3826 // Determine the minimum number of sign bits across all demanded
3827 // elts of the input vectors. Early out if the result is already 1.
3828 Tmp = std::numeric_limits<unsigned>::max();
3829 EVT SubVectorVT = Op.getOperand(0).getValueType();
3830 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3831 unsigned NumSubVectors = Op.getNumOperands();
3832 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
3833 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
3834 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
3835 if (!DemandedSub)
3836 continue;
3837 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
3838 Tmp = std::min(Tmp, Tmp2);
3840 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3841 return Tmp;
3843 case ISD::INSERT_SUBVECTOR: {
3844 // If we know the element index, demand any elements from the subvector and
3845 // the remainder from the src its inserted into, otherwise demand them all.
3846 SDValue Src = Op.getOperand(0);
3847 SDValue Sub = Op.getOperand(1);
3848 auto *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3849 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3850 if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
3851 Tmp = std::numeric_limits<unsigned>::max();
3852 uint64_t Idx = SubIdx->getZExtValue();
3853 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3854 if (!!DemandedSubElts) {
3855 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
3856 if (Tmp == 1) return 1; // early-out
3858 APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
3859 APInt DemandedSrcElts = DemandedElts & ~SubMask;
3860 if (!!DemandedSrcElts) {
3861 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
3862 Tmp = std::min(Tmp, Tmp2);
3864 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3865 return Tmp;
3868 // Not able to determine the index so just assume worst case.
3869 Tmp = ComputeNumSignBits(Sub, Depth + 1);
3870 if (Tmp == 1) return 1; // early-out
3871 Tmp2 = ComputeNumSignBits(Src, Depth + 1);
3872 Tmp = std::min(Tmp, Tmp2);
3873 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3874 return Tmp;
3878 // If we are looking at the loaded value of the SDNode.
3879 if (Op.getResNo() == 0) {
3880 // Handle LOADX separately here. EXTLOAD case will fallthrough.
3881 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
3882 unsigned ExtType = LD->getExtensionType();
3883 switch (ExtType) {
3884 default: break;
3885 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
3886 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3887 return VTBits - Tmp + 1;
3888 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
3889 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3890 return VTBits - Tmp;
3891 case ISD::NON_EXTLOAD:
3892 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
3893 // We only need to handle vectors - computeKnownBits should handle
3894 // scalar cases.
3895 Type *CstTy = Cst->getType();
3896 if (CstTy->isVectorTy() &&
3897 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
3898 Tmp = VTBits;
3899 for (unsigned i = 0; i != NumElts; ++i) {
3900 if (!DemandedElts[i])
3901 continue;
3902 if (Constant *Elt = Cst->getAggregateElement(i)) {
3903 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3904 const APInt &Value = CInt->getValue();
3905 Tmp = std::min(Tmp, Value.getNumSignBits());
3906 continue;
3908 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3909 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3910 Tmp = std::min(Tmp, Value.getNumSignBits());
3911 continue;
3914 // Unknown type. Conservatively assume no bits match sign bit.
3915 return 1;
3917 return Tmp;
3920 break;
3925 // Allow the target to implement this method for its nodes.
3926 if (Opcode >= ISD::BUILTIN_OP_END ||
3927 Opcode == ISD::INTRINSIC_WO_CHAIN ||
3928 Opcode == ISD::INTRINSIC_W_CHAIN ||
3929 Opcode == ISD::INTRINSIC_VOID) {
3930 unsigned NumBits =
3931 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
3932 if (NumBits > 1)
3933 FirstAnswer = std::max(FirstAnswer, NumBits);
3936 // Finally, if we can prove that the top bits of the result are 0's or 1's,
3937 // use this information.
3938 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
3940 APInt Mask;
3941 if (Known.isNonNegative()) { // sign bit is 0
3942 Mask = Known.Zero;
3943 } else if (Known.isNegative()) { // sign bit is 1;
3944 Mask = Known.One;
3945 } else {
3946 // Nothing known.
3947 return FirstAnswer;
3950 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
3951 // the number of identical bits in the top of the input value.
3952 Mask = ~Mask;
3953 Mask <<= Mask.getBitWidth()-VTBits;
3954 // Return # leading zeros. We use 'min' here in case Val was zero before
3955 // shifting. We don't want to return '64' as for an i32 "0".
3956 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
3959 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
3960 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
3961 !isa<ConstantSDNode>(Op.getOperand(1)))
3962 return false;
3964 if (Op.getOpcode() == ISD::OR &&
3965 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
3966 return false;
3968 return true;
3971 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
3972 // If we're told that NaNs won't happen, assume they won't.
3973 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
3974 return true;
3976 if (Depth >= 6)
3977 return false; // Limit search depth.
3979 // TODO: Handle vectors.
3980 // If the value is a constant, we can obviously see if it is a NaN or not.
3981 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
3982 return !C->getValueAPF().isNaN() ||
3983 (SNaN && !C->getValueAPF().isSignaling());
3986 unsigned Opcode = Op.getOpcode();
3987 switch (Opcode) {
3988 case ISD::FADD:
3989 case ISD::FSUB:
3990 case ISD::FMUL:
3991 case ISD::FDIV:
3992 case ISD::FREM:
3993 case ISD::FSIN:
3994 case ISD::FCOS: {
3995 if (SNaN)
3996 return true;
3997 // TODO: Need isKnownNeverInfinity
3998 return false;
4000 case ISD::FCANONICALIZE:
4001 case ISD::FEXP:
4002 case ISD::FEXP2:
4003 case ISD::FTRUNC:
4004 case ISD::FFLOOR:
4005 case ISD::FCEIL:
4006 case ISD::FROUND:
4007 case ISD::FRINT:
4008 case ISD::FNEARBYINT: {
4009 if (SNaN)
4010 return true;
4011 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4013 case ISD::FABS:
4014 case ISD::FNEG:
4015 case ISD::FCOPYSIGN: {
4016 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4018 case ISD::SELECT:
4019 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4020 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4021 case ISD::FP_EXTEND:
4022 case ISD::FP_ROUND: {
4023 if (SNaN)
4024 return true;
4025 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4027 case ISD::SINT_TO_FP:
4028 case ISD::UINT_TO_FP:
4029 return true;
4030 case ISD::FMA:
4031 case ISD::FMAD: {
4032 if (SNaN)
4033 return true;
4034 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4035 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4036 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4038 case ISD::FSQRT: // Need is known positive
4039 case ISD::FLOG:
4040 case ISD::FLOG2:
4041 case ISD::FLOG10:
4042 case ISD::FPOWI:
4043 case ISD::FPOW: {
4044 if (SNaN)
4045 return true;
4046 // TODO: Refine on operand
4047 return false;
4049 case ISD::FMINNUM:
4050 case ISD::FMAXNUM: {
4051 // Only one needs to be known not-nan, since it will be returned if the
4052 // other ends up being one.
4053 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4054 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4056 case ISD::FMINNUM_IEEE:
4057 case ISD::FMAXNUM_IEEE: {
4058 if (SNaN)
4059 return true;
4060 // This can return a NaN if either operand is an sNaN, or if both operands
4061 // are NaN.
4062 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4063 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4064 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4065 isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4067 case ISD::FMINIMUM:
4068 case ISD::FMAXIMUM: {
4069 // TODO: Does this quiet or return the origina NaN as-is?
4070 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4071 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4073 case ISD::EXTRACT_VECTOR_ELT: {
4074 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4076 default:
4077 if (Opcode >= ISD::BUILTIN_OP_END ||
4078 Opcode == ISD::INTRINSIC_WO_CHAIN ||
4079 Opcode == ISD::INTRINSIC_W_CHAIN ||
4080 Opcode == ISD::INTRINSIC_VOID) {
4081 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4084 return false;
4088 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4089 assert(Op.getValueType().isFloatingPoint() &&
4090 "Floating point type expected");
4092 // If the value is a constant, we can obviously see if it is a zero or not.
4093 // TODO: Add BuildVector support.
4094 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4095 return !C->isZero();
4096 return false;
4099 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4100 assert(!Op.getValueType().isFloatingPoint() &&
4101 "Floating point types unsupported - use isKnownNeverZeroFloat");
4103 // If the value is a constant, we can obviously see if it is a zero or not.
4104 if (ISD::matchUnaryPredicate(
4105 Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
4106 return true;
4108 // TODO: Recognize more cases here.
4109 switch (Op.getOpcode()) {
4110 default: break;
4111 case ISD::OR:
4112 if (isKnownNeverZero(Op.getOperand(1)) ||
4113 isKnownNeverZero(Op.getOperand(0)))
4114 return true;
4115 break;
4118 return false;
4121 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4122 // Check the obvious case.
4123 if (A == B) return true;
4125 // For for negative and positive zero.
4126 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4127 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4128 if (CA->isZero() && CB->isZero()) return true;
4130 // Otherwise they may not be equal.
4131 return false;
4134 // FIXME: unify with llvm::haveNoCommonBitsSet.
4135 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4136 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4137 assert(A.getValueType() == B.getValueType() &&
4138 "Values must have the same type");
4139 return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue();
4142 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4143 ArrayRef<SDValue> Ops,
4144 SelectionDAG &DAG) {
4145 int NumOps = Ops.size();
4146 assert(NumOps != 0 && "Can't build an empty vector!");
4147 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4148 "Incorrect element count in BUILD_VECTOR!");
4150 // BUILD_VECTOR of UNDEFs is UNDEF.
4151 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4152 return DAG.getUNDEF(VT);
4154 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4155 SDValue IdentitySrc;
4156 bool IsIdentity = true;
4157 for (int i = 0; i != NumOps; ++i) {
4158 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4159 Ops[i].getOperand(0).getValueType() != VT ||
4160 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4161 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4162 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4163 IsIdentity = false;
4164 break;
4166 IdentitySrc = Ops[i].getOperand(0);
4168 if (IsIdentity)
4169 return IdentitySrc;
4171 return SDValue();
4174 /// Try to simplify vector concatenation to an input value, undef, or build
4175 /// vector.
4176 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4177 ArrayRef<SDValue> Ops,
4178 SelectionDAG &DAG) {
4179 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4180 assert(llvm::all_of(Ops,
4181 [Ops](SDValue Op) {
4182 return Ops[0].getValueType() == Op.getValueType();
4183 }) &&
4184 "Concatenation of vectors with inconsistent value types!");
4185 assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
4186 VT.getVectorNumElements() &&
4187 "Incorrect element count in vector concatenation!");
4189 if (Ops.size() == 1)
4190 return Ops[0];
4192 // Concat of UNDEFs is UNDEF.
4193 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4194 return DAG.getUNDEF(VT);
4196 // Scan the operands and look for extract operations from a single source
4197 // that correspond to insertion at the same location via this concatenation:
4198 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4199 SDValue IdentitySrc;
4200 bool IsIdentity = true;
4201 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4202 SDValue Op = Ops[i];
4203 unsigned IdentityIndex = i * Op.getValueType().getVectorNumElements();
4204 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4205 Op.getOperand(0).getValueType() != VT ||
4206 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4207 !isa<ConstantSDNode>(Op.getOperand(1)) ||
4208 Op.getConstantOperandVal(1) != IdentityIndex) {
4209 IsIdentity = false;
4210 break;
4212 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4213 "Unexpected identity source vector for concat of extracts");
4214 IdentitySrc = Op.getOperand(0);
4216 if (IsIdentity) {
4217 assert(IdentitySrc && "Failed to set source vector of extracts");
4218 return IdentitySrc;
4221 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4222 // simplified to one big BUILD_VECTOR.
4223 // FIXME: Add support for SCALAR_TO_VECTOR as well.
4224 EVT SVT = VT.getScalarType();
4225 SmallVector<SDValue, 16> Elts;
4226 for (SDValue Op : Ops) {
4227 EVT OpVT = Op.getValueType();
4228 if (Op.isUndef())
4229 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4230 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4231 Elts.append(Op->op_begin(), Op->op_end());
4232 else
4233 return SDValue();
4236 // BUILD_VECTOR requires all inputs to be of the same type, find the
4237 // maximum type and extend them all.
4238 for (SDValue Op : Elts)
4239 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4241 if (SVT.bitsGT(VT.getScalarType()))
4242 for (SDValue &Op : Elts)
4243 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4244 ? DAG.getZExtOrTrunc(Op, DL, SVT)
4245 : DAG.getSExtOrTrunc(Op, DL, SVT);
4247 SDValue V = DAG.getBuildVector(VT, DL, Elts);
4248 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4249 return V;
4252 /// Gets or creates the specified node.
4253 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4254 FoldingSetNodeID ID;
4255 AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4256 void *IP = nullptr;
4257 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4258 return SDValue(E, 0);
4260 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4261 getVTList(VT));
4262 CSEMap.InsertNode(N, IP);
4264 InsertNode(N);
4265 SDValue V = SDValue(N, 0);
4266 NewSDValueDbgMsg(V, "Creating new node: ", this);
4267 return V;
4270 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4271 SDValue Operand, const SDNodeFlags Flags) {
4272 // Constant fold unary operations with an integer constant operand. Even
4273 // opaque constant will be folded, because the folding of unary operations
4274 // doesn't create new constants with different values. Nevertheless, the
4275 // opaque flag is preserved during folding to prevent future folding with
4276 // other constants.
4277 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4278 const APInt &Val = C->getAPIntValue();
4279 switch (Opcode) {
4280 default: break;
4281 case ISD::SIGN_EXTEND:
4282 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4283 C->isTargetOpcode(), C->isOpaque());
4284 case ISD::TRUNCATE:
4285 if (C->isOpaque())
4286 break;
4287 LLVM_FALLTHROUGH;
4288 case ISD::ANY_EXTEND:
4289 case ISD::ZERO_EXTEND:
4290 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4291 C->isTargetOpcode(), C->isOpaque());
4292 case ISD::UINT_TO_FP:
4293 case ISD::SINT_TO_FP: {
4294 APFloat apf(EVTToAPFloatSemantics(VT),
4295 APInt::getNullValue(VT.getSizeInBits()));
4296 (void)apf.convertFromAPInt(Val,
4297 Opcode==ISD::SINT_TO_FP,
4298 APFloat::rmNearestTiesToEven);
4299 return getConstantFP(apf, DL, VT);
4301 case ISD::BITCAST:
4302 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4303 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4304 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4305 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4306 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4307 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4308 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4309 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4310 break;
4311 case ISD::ABS:
4312 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4313 C->isOpaque());
4314 case ISD::BITREVERSE:
4315 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4316 C->isOpaque());
4317 case ISD::BSWAP:
4318 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4319 C->isOpaque());
4320 case ISD::CTPOP:
4321 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4322 C->isOpaque());
4323 case ISD::CTLZ:
4324 case ISD::CTLZ_ZERO_UNDEF:
4325 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4326 C->isOpaque());
4327 case ISD::CTTZ:
4328 case ISD::CTTZ_ZERO_UNDEF:
4329 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4330 C->isOpaque());
4331 case ISD::FP16_TO_FP: {
4332 bool Ignored;
4333 APFloat FPV(APFloat::IEEEhalf(),
4334 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4336 // This can return overflow, underflow, or inexact; we don't care.
4337 // FIXME need to be more flexible about rounding mode.
4338 (void)FPV.convert(EVTToAPFloatSemantics(VT),
4339 APFloat::rmNearestTiesToEven, &Ignored);
4340 return getConstantFP(FPV, DL, VT);
4345 // Constant fold unary operations with a floating point constant operand.
4346 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4347 APFloat V = C->getValueAPF(); // make copy
4348 switch (Opcode) {
4349 case ISD::FNEG:
4350 V.changeSign();
4351 return getConstantFP(V, DL, VT);
4352 case ISD::FABS:
4353 V.clearSign();
4354 return getConstantFP(V, DL, VT);
4355 case ISD::FCEIL: {
4356 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4357 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4358 return getConstantFP(V, DL, VT);
4359 break;
4361 case ISD::FTRUNC: {
4362 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4363 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4364 return getConstantFP(V, DL, VT);
4365 break;
4367 case ISD::FFLOOR: {
4368 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4369 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4370 return getConstantFP(V, DL, VT);
4371 break;
4373 case ISD::FP_EXTEND: {
4374 bool ignored;
4375 // This can return overflow, underflow, or inexact; we don't care.
4376 // FIXME need to be more flexible about rounding mode.
4377 (void)V.convert(EVTToAPFloatSemantics(VT),
4378 APFloat::rmNearestTiesToEven, &ignored);
4379 return getConstantFP(V, DL, VT);
4381 case ISD::FP_TO_SINT:
4382 case ISD::FP_TO_UINT: {
4383 bool ignored;
4384 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4385 // FIXME need to be more flexible about rounding mode.
4386 APFloat::opStatus s =
4387 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4388 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4389 break;
4390 return getConstant(IntVal, DL, VT);
4392 case ISD::BITCAST:
4393 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4394 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4395 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4396 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4397 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4398 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4399 break;
4400 case ISD::FP_TO_FP16: {
4401 bool Ignored;
4402 // This can return overflow, underflow, or inexact; we don't care.
4403 // FIXME need to be more flexible about rounding mode.
4404 (void)V.convert(APFloat::IEEEhalf(),
4405 APFloat::rmNearestTiesToEven, &Ignored);
4406 return getConstant(V.bitcastToAPInt(), DL, VT);
4411 // Constant fold unary operations with a vector integer or float operand.
4412 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
4413 if (BV->isConstant()) {
4414 switch (Opcode) {
4415 default:
4416 // FIXME: Entirely reasonable to perform folding of other unary
4417 // operations here as the need arises.
4418 break;
4419 case ISD::FNEG:
4420 case ISD::FABS:
4421 case ISD::FCEIL:
4422 case ISD::FTRUNC:
4423 case ISD::FFLOOR:
4424 case ISD::FP_EXTEND:
4425 case ISD::FP_TO_SINT:
4426 case ISD::FP_TO_UINT:
4427 case ISD::TRUNCATE:
4428 case ISD::ANY_EXTEND:
4429 case ISD::ZERO_EXTEND:
4430 case ISD::SIGN_EXTEND:
4431 case ISD::UINT_TO_FP:
4432 case ISD::SINT_TO_FP:
4433 case ISD::ABS:
4434 case ISD::BITREVERSE:
4435 case ISD::BSWAP:
4436 case ISD::CTLZ:
4437 case ISD::CTLZ_ZERO_UNDEF:
4438 case ISD::CTTZ:
4439 case ISD::CTTZ_ZERO_UNDEF:
4440 case ISD::CTPOP: {
4441 SDValue Ops = { Operand };
4442 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4443 return Fold;
4449 unsigned OpOpcode = Operand.getNode()->getOpcode();
4450 switch (Opcode) {
4451 case ISD::TokenFactor:
4452 case ISD::MERGE_VALUES:
4453 case ISD::CONCAT_VECTORS:
4454 return Operand; // Factor, merge or concat of one node? No need.
4455 case ISD::BUILD_VECTOR: {
4456 // Attempt to simplify BUILD_VECTOR.
4457 SDValue Ops[] = {Operand};
4458 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4459 return V;
4460 break;
4462 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4463 case ISD::FP_EXTEND:
4464 assert(VT.isFloatingPoint() &&
4465 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4466 if (Operand.getValueType() == VT) return Operand; // noop conversion.
4467 assert((!VT.isVector() ||
4468 VT.getVectorNumElements() ==
4469 Operand.getValueType().getVectorNumElements()) &&
4470 "Vector element count mismatch!");
4471 assert(Operand.getValueType().bitsLT(VT) &&
4472 "Invalid fpext node, dst < src!");
4473 if (Operand.isUndef())
4474 return getUNDEF(VT);
4475 break;
4476 case ISD::FP_TO_SINT:
4477 case ISD::FP_TO_UINT:
4478 if (Operand.isUndef())
4479 return getUNDEF(VT);
4480 break;
4481 case ISD::SINT_TO_FP:
4482 case ISD::UINT_TO_FP:
4483 // [us]itofp(undef) = 0, because the result value is bounded.
4484 if (Operand.isUndef())
4485 return getConstantFP(0.0, DL, VT);
4486 break;
4487 case ISD::SIGN_EXTEND:
4488 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4489 "Invalid SIGN_EXTEND!");
4490 assert(VT.isVector() == Operand.getValueType().isVector() &&
4491 "SIGN_EXTEND result type type should be vector iff the operand "
4492 "type is vector!");
4493 if (Operand.getValueType() == VT) return Operand; // noop extension
4494 assert((!VT.isVector() ||
4495 VT.getVectorNumElements() ==
4496 Operand.getValueType().getVectorNumElements()) &&
4497 "Vector element count mismatch!");
4498 assert(Operand.getValueType().bitsLT(VT) &&
4499 "Invalid sext node, dst < src!");
4500 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4501 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4502 else if (OpOpcode == ISD::UNDEF)
4503 // sext(undef) = 0, because the top bits will all be the same.
4504 return getConstant(0, DL, VT);
4505 break;
4506 case ISD::ZERO_EXTEND:
4507 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4508 "Invalid ZERO_EXTEND!");
4509 assert(VT.isVector() == Operand.getValueType().isVector() &&
4510 "ZERO_EXTEND result type type should be vector iff the operand "
4511 "type is vector!");
4512 if (Operand.getValueType() == VT) return Operand; // noop extension
4513 assert((!VT.isVector() ||
4514 VT.getVectorNumElements() ==
4515 Operand.getValueType().getVectorNumElements()) &&
4516 "Vector element count mismatch!");
4517 assert(Operand.getValueType().bitsLT(VT) &&
4518 "Invalid zext node, dst < src!");
4519 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
4520 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4521 else if (OpOpcode == ISD::UNDEF)
4522 // zext(undef) = 0, because the top bits will be zero.
4523 return getConstant(0, DL, VT);
4524 break;
4525 case ISD::ANY_EXTEND:
4526 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4527 "Invalid ANY_EXTEND!");
4528 assert(VT.isVector() == Operand.getValueType().isVector() &&
4529 "ANY_EXTEND result type type should be vector iff the operand "
4530 "type is vector!");
4531 if (Operand.getValueType() == VT) return Operand; // noop extension
4532 assert((!VT.isVector() ||
4533 VT.getVectorNumElements() ==
4534 Operand.getValueType().getVectorNumElements()) &&
4535 "Vector element count mismatch!");
4536 assert(Operand.getValueType().bitsLT(VT) &&
4537 "Invalid anyext node, dst < src!");
4539 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4540 OpOpcode == ISD::ANY_EXTEND)
4541 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
4542 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4543 else if (OpOpcode == ISD::UNDEF)
4544 return getUNDEF(VT);
4546 // (ext (trunc x)) -> x
4547 if (OpOpcode == ISD::TRUNCATE) {
4548 SDValue OpOp = Operand.getOperand(0);
4549 if (OpOp.getValueType() == VT) {
4550 transferDbgValues(Operand, OpOp);
4551 return OpOp;
4554 break;
4555 case ISD::TRUNCATE:
4556 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4557 "Invalid TRUNCATE!");
4558 assert(VT.isVector() == Operand.getValueType().isVector() &&
4559 "TRUNCATE result type type should be vector iff the operand "
4560 "type is vector!");
4561 if (Operand.getValueType() == VT) return Operand; // noop truncate
4562 assert((!VT.isVector() ||
4563 VT.getVectorNumElements() ==
4564 Operand.getValueType().getVectorNumElements()) &&
4565 "Vector element count mismatch!");
4566 assert(Operand.getValueType().bitsGT(VT) &&
4567 "Invalid truncate node, src < dst!");
4568 if (OpOpcode == ISD::TRUNCATE)
4569 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4570 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4571 OpOpcode == ISD::ANY_EXTEND) {
4572 // If the source is smaller than the dest, we still need an extend.
4573 if (Operand.getOperand(0).getValueType().getScalarType()
4574 .bitsLT(VT.getScalarType()))
4575 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4576 if (Operand.getOperand(0).getValueType().bitsGT(VT))
4577 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4578 return Operand.getOperand(0);
4580 if (OpOpcode == ISD::UNDEF)
4581 return getUNDEF(VT);
4582 break;
4583 case ISD::ANY_EXTEND_VECTOR_INREG:
4584 case ISD::ZERO_EXTEND_VECTOR_INREG:
4585 case ISD::SIGN_EXTEND_VECTOR_INREG:
4586 assert(VT.isVector() && "This DAG node is restricted to vector types.");
4587 assert(Operand.getValueType().bitsLE(VT) &&
4588 "The input must be the same size or smaller than the result.");
4589 assert(VT.getVectorNumElements() <
4590 Operand.getValueType().getVectorNumElements() &&
4591 "The destination vector type must have fewer lanes than the input.");
4592 break;
4593 case ISD::ABS:
4594 assert(VT.isInteger() && VT == Operand.getValueType() &&
4595 "Invalid ABS!");
4596 if (OpOpcode == ISD::UNDEF)
4597 return getUNDEF(VT);
4598 break;
4599 case ISD::BSWAP:
4600 assert(VT.isInteger() && VT == Operand.getValueType() &&
4601 "Invalid BSWAP!");
4602 assert((VT.getScalarSizeInBits() % 16 == 0) &&
4603 "BSWAP types must be a multiple of 16 bits!");
4604 if (OpOpcode == ISD::UNDEF)
4605 return getUNDEF(VT);
4606 break;
4607 case ISD::BITREVERSE:
4608 assert(VT.isInteger() && VT == Operand.getValueType() &&
4609 "Invalid BITREVERSE!");
4610 if (OpOpcode == ISD::UNDEF)
4611 return getUNDEF(VT);
4612 break;
4613 case ISD::BITCAST:
4614 // Basic sanity checking.
4615 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4616 "Cannot BITCAST between types of different sizes!");
4617 if (VT == Operand.getValueType()) return Operand; // noop conversion.
4618 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
4619 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4620 if (OpOpcode == ISD::UNDEF)
4621 return getUNDEF(VT);
4622 break;
4623 case ISD::SCALAR_TO_VECTOR:
4624 assert(VT.isVector() && !Operand.getValueType().isVector() &&
4625 (VT.getVectorElementType() == Operand.getValueType() ||
4626 (VT.getVectorElementType().isInteger() &&
4627 Operand.getValueType().isInteger() &&
4628 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4629 "Illegal SCALAR_TO_VECTOR node!");
4630 if (OpOpcode == ISD::UNDEF)
4631 return getUNDEF(VT);
4632 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4633 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4634 isa<ConstantSDNode>(Operand.getOperand(1)) &&
4635 Operand.getConstantOperandVal(1) == 0 &&
4636 Operand.getOperand(0).getValueType() == VT)
4637 return Operand.getOperand(0);
4638 break;
4639 case ISD::FNEG:
4640 // Negation of an unknown bag of bits is still completely undefined.
4641 if (OpOpcode == ISD::UNDEF)
4642 return getUNDEF(VT);
4644 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
4645 if ((getTarget().Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros()) &&
4646 OpOpcode == ISD::FSUB)
4647 return getNode(ISD::FSUB, DL, VT, Operand.getOperand(1),
4648 Operand.getOperand(0), Flags);
4649 if (OpOpcode == ISD::FNEG) // --X -> X
4650 return Operand.getOperand(0);
4651 break;
4652 case ISD::FABS:
4653 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
4654 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
4655 break;
4658 SDNode *N;
4659 SDVTList VTs = getVTList(VT);
4660 SDValue Ops[] = {Operand};
4661 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
4662 FoldingSetNodeID ID;
4663 AddNodeIDNode(ID, Opcode, VTs, Ops);
4664 void *IP = nullptr;
4665 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4666 E->intersectFlagsWith(Flags);
4667 return SDValue(E, 0);
4670 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4671 N->setFlags(Flags);
4672 createOperands(N, Ops);
4673 CSEMap.InsertNode(N, IP);
4674 } else {
4675 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4676 createOperands(N, Ops);
4679 InsertNode(N);
4680 SDValue V = SDValue(N, 0);
4681 NewSDValueDbgMsg(V, "Creating new node: ", this);
4682 return V;
4685 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
4686 const APInt &C2) {
4687 switch (Opcode) {
4688 case ISD::ADD: return std::make_pair(C1 + C2, true);
4689 case ISD::SUB: return std::make_pair(C1 - C2, true);
4690 case ISD::MUL: return std::make_pair(C1 * C2, true);
4691 case ISD::AND: return std::make_pair(C1 & C2, true);
4692 case ISD::OR: return std::make_pair(C1 | C2, true);
4693 case ISD::XOR: return std::make_pair(C1 ^ C2, true);
4694 case ISD::SHL: return std::make_pair(C1 << C2, true);
4695 case ISD::SRL: return std::make_pair(C1.lshr(C2), true);
4696 case ISD::SRA: return std::make_pair(C1.ashr(C2), true);
4697 case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
4698 case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
4699 case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
4700 case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
4701 case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
4702 case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
4703 case ISD::SADDSAT: return std::make_pair(C1.sadd_sat(C2), true);
4704 case ISD::UADDSAT: return std::make_pair(C1.uadd_sat(C2), true);
4705 case ISD::SSUBSAT: return std::make_pair(C1.ssub_sat(C2), true);
4706 case ISD::USUBSAT: return std::make_pair(C1.usub_sat(C2), true);
4707 case ISD::UDIV:
4708 if (!C2.getBoolValue())
4709 break;
4710 return std::make_pair(C1.udiv(C2), true);
4711 case ISD::UREM:
4712 if (!C2.getBoolValue())
4713 break;
4714 return std::make_pair(C1.urem(C2), true);
4715 case ISD::SDIV:
4716 if (!C2.getBoolValue())
4717 break;
4718 return std::make_pair(C1.sdiv(C2), true);
4719 case ISD::SREM:
4720 if (!C2.getBoolValue())
4721 break;
4722 return std::make_pair(C1.srem(C2), true);
4724 return std::make_pair(APInt(1, 0), false);
4727 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
4728 EVT VT, const ConstantSDNode *C1,
4729 const ConstantSDNode *C2) {
4730 if (C1->isOpaque() || C2->isOpaque())
4731 return SDValue();
4733 std::pair<APInt, bool> Folded = FoldValue(Opcode, C1->getAPIntValue(),
4734 C2->getAPIntValue());
4735 if (!Folded.second)
4736 return SDValue();
4737 return getConstant(Folded.first, DL, VT);
4740 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
4741 const GlobalAddressSDNode *GA,
4742 const SDNode *N2) {
4743 if (GA->getOpcode() != ISD::GlobalAddress)
4744 return SDValue();
4745 if (!TLI->isOffsetFoldingLegal(GA))
4746 return SDValue();
4747 auto *C2 = dyn_cast<ConstantSDNode>(N2);
4748 if (!C2)
4749 return SDValue();
4750 int64_t Offset = C2->getSExtValue();
4751 switch (Opcode) {
4752 case ISD::ADD: break;
4753 case ISD::SUB: Offset = -uint64_t(Offset); break;
4754 default: return SDValue();
4756 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
4757 GA->getOffset() + uint64_t(Offset));
4760 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
4761 switch (Opcode) {
4762 case ISD::SDIV:
4763 case ISD::UDIV:
4764 case ISD::SREM:
4765 case ISD::UREM: {
4766 // If a divisor is zero/undef or any element of a divisor vector is
4767 // zero/undef, the whole op is undef.
4768 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
4769 SDValue Divisor = Ops[1];
4770 if (Divisor.isUndef() || isNullConstant(Divisor))
4771 return true;
4773 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
4774 llvm::any_of(Divisor->op_values(),
4775 [](SDValue V) { return V.isUndef() ||
4776 isNullConstant(V); });
4777 // TODO: Handle signed overflow.
4779 // TODO: Handle oversized shifts.
4780 default:
4781 return false;
4785 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
4786 EVT VT, SDNode *N1, SDNode *N2) {
4787 // If the opcode is a target-specific ISD node, there's nothing we can
4788 // do here and the operand rules may not line up with the below, so
4789 // bail early.
4790 if (Opcode >= ISD::BUILTIN_OP_END)
4791 return SDValue();
4793 if (isUndef(Opcode, {SDValue(N1, 0), SDValue(N2, 0)}))
4794 return getUNDEF(VT);
4796 // Handle the case of two scalars.
4797 if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
4798 if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
4799 SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, C1, C2);
4800 assert((!Folded || !VT.isVector()) &&
4801 "Can't fold vectors ops with scalar operands");
4802 return Folded;
4806 // fold (add Sym, c) -> Sym+c
4807 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
4808 return FoldSymbolOffset(Opcode, VT, GA, N2);
4809 if (TLI->isCommutativeBinOp(Opcode))
4810 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
4811 return FoldSymbolOffset(Opcode, VT, GA, N1);
4813 // For vectors, extract each constant element and fold them individually.
4814 // Either input may be an undef value.
4815 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
4816 if (!BV1 && !N1->isUndef())
4817 return SDValue();
4818 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
4819 if (!BV2 && !N2->isUndef())
4820 return SDValue();
4821 // If both operands are undef, that's handled the same way as scalars.
4822 if (!BV1 && !BV2)
4823 return SDValue();
4825 assert((!BV1 || !BV2 || BV1->getNumOperands() == BV2->getNumOperands()) &&
4826 "Vector binop with different number of elements in operands?");
4828 EVT SVT = VT.getScalarType();
4829 EVT LegalSVT = SVT;
4830 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
4831 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
4832 if (LegalSVT.bitsLT(SVT))
4833 return SDValue();
4835 SmallVector<SDValue, 4> Outputs;
4836 unsigned NumOps = BV1 ? BV1->getNumOperands() : BV2->getNumOperands();
4837 for (unsigned I = 0; I != NumOps; ++I) {
4838 SDValue V1 = BV1 ? BV1->getOperand(I) : getUNDEF(SVT);
4839 SDValue V2 = BV2 ? BV2->getOperand(I) : getUNDEF(SVT);
4840 if (SVT.isInteger()) {
4841 if (V1->getValueType(0).bitsGT(SVT))
4842 V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
4843 if (V2->getValueType(0).bitsGT(SVT))
4844 V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
4847 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
4848 return SDValue();
4850 // Fold one vector element.
4851 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
4852 if (LegalSVT != SVT)
4853 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4855 // Scalar folding only succeeded if the result is a constant or UNDEF.
4856 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4857 ScalarResult.getOpcode() != ISD::ConstantFP)
4858 return SDValue();
4859 Outputs.push_back(ScalarResult);
4862 assert(VT.getVectorNumElements() == Outputs.size() &&
4863 "Vector size mismatch!");
4865 // We may have a vector type but a scalar result. Create a splat.
4866 Outputs.resize(VT.getVectorNumElements(), Outputs.back());
4868 // Build a big vector out of the scalar elements we generated.
4869 return getBuildVector(VT, SDLoc(), Outputs);
4872 // TODO: Merge with FoldConstantArithmetic
4873 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
4874 const SDLoc &DL, EVT VT,
4875 ArrayRef<SDValue> Ops,
4876 const SDNodeFlags Flags) {
4877 // If the opcode is a target-specific ISD node, there's nothing we can
4878 // do here and the operand rules may not line up with the below, so
4879 // bail early.
4880 if (Opcode >= ISD::BUILTIN_OP_END)
4881 return SDValue();
4883 if (isUndef(Opcode, Ops))
4884 return getUNDEF(VT);
4886 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
4887 if (!VT.isVector())
4888 return SDValue();
4890 unsigned NumElts = VT.getVectorNumElements();
4892 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
4893 return !Op.getValueType().isVector() ||
4894 Op.getValueType().getVectorNumElements() == NumElts;
4897 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
4898 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
4899 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
4900 (BV && BV->isConstant());
4903 // All operands must be vector types with the same number of elements as
4904 // the result type and must be either UNDEF or a build vector of constant
4905 // or UNDEF scalars.
4906 if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
4907 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
4908 return SDValue();
4910 // If we are comparing vectors, then the result needs to be a i1 boolean
4911 // that is then sign-extended back to the legal result type.
4912 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
4914 // Find legal integer scalar type for constant promotion and
4915 // ensure that its scalar size is at least as large as source.
4916 EVT LegalSVT = VT.getScalarType();
4917 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
4918 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
4919 if (LegalSVT.bitsLT(VT.getScalarType()))
4920 return SDValue();
4923 // Constant fold each scalar lane separately.
4924 SmallVector<SDValue, 4> ScalarResults;
4925 for (unsigned i = 0; i != NumElts; i++) {
4926 SmallVector<SDValue, 4> ScalarOps;
4927 for (SDValue Op : Ops) {
4928 EVT InSVT = Op.getValueType().getScalarType();
4929 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
4930 if (!InBV) {
4931 // We've checked that this is UNDEF or a constant of some kind.
4932 if (Op.isUndef())
4933 ScalarOps.push_back(getUNDEF(InSVT));
4934 else
4935 ScalarOps.push_back(Op);
4936 continue;
4939 SDValue ScalarOp = InBV->getOperand(i);
4940 EVT ScalarVT = ScalarOp.getValueType();
4942 // Build vector (integer) scalar operands may need implicit
4943 // truncation - do this before constant folding.
4944 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
4945 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
4947 ScalarOps.push_back(ScalarOp);
4950 // Constant fold the scalar operands.
4951 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
4953 // Legalize the (integer) scalar constant if necessary.
4954 if (LegalSVT != SVT)
4955 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4957 // Scalar folding only succeeded if the result is a constant or UNDEF.
4958 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4959 ScalarResult.getOpcode() != ISD::ConstantFP)
4960 return SDValue();
4961 ScalarResults.push_back(ScalarResult);
4964 SDValue V = getBuildVector(VT, DL, ScalarResults);
4965 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
4966 return V;
4969 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
4970 EVT VT, SDValue N1, SDValue N2) {
4971 // TODO: We don't do any constant folding for strict FP opcodes here, but we
4972 // should. That will require dealing with a potentially non-default
4973 // rounding mode, checking the "opStatus" return value from the APFloat
4974 // math calculations, and possibly other variations.
4975 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
4976 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
4977 if (N1CFP && N2CFP) {
4978 APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
4979 switch (Opcode) {
4980 case ISD::FADD:
4981 C1.add(C2, APFloat::rmNearestTiesToEven);
4982 return getConstantFP(C1, DL, VT);
4983 case ISD::FSUB:
4984 C1.subtract(C2, APFloat::rmNearestTiesToEven);
4985 return getConstantFP(C1, DL, VT);
4986 case ISD::FMUL:
4987 C1.multiply(C2, APFloat::rmNearestTiesToEven);
4988 return getConstantFP(C1, DL, VT);
4989 case ISD::FDIV:
4990 C1.divide(C2, APFloat::rmNearestTiesToEven);
4991 return getConstantFP(C1, DL, VT);
4992 case ISD::FREM:
4993 C1.mod(C2);
4994 return getConstantFP(C1, DL, VT);
4995 case ISD::FCOPYSIGN:
4996 C1.copySign(C2);
4997 return getConstantFP(C1, DL, VT);
4998 default: break;
5001 if (N1CFP && Opcode == ISD::FP_ROUND) {
5002 APFloat C1 = N1CFP->getValueAPF(); // make copy
5003 bool Unused;
5004 // This can return overflow, underflow, or inexact; we don't care.
5005 // FIXME need to be more flexible about rounding mode.
5006 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5007 &Unused);
5008 return getConstantFP(C1, DL, VT);
5011 switch (Opcode) {
5012 case ISD::FADD:
5013 case ISD::FSUB:
5014 case ISD::FMUL:
5015 case ISD::FDIV:
5016 case ISD::FREM:
5017 // If both operands are undef, the result is undef. If 1 operand is undef,
5018 // the result is NaN. This should match the behavior of the IR optimizer.
5019 if (N1.isUndef() && N2.isUndef())
5020 return getUNDEF(VT);
5021 if (N1.isUndef() || N2.isUndef())
5022 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5024 return SDValue();
5027 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5028 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5029 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5030 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5031 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5032 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5034 // Canonicalize constant to RHS if commutative.
5035 if (TLI->isCommutativeBinOp(Opcode)) {
5036 if (N1C && !N2C) {
5037 std::swap(N1C, N2C);
5038 std::swap(N1, N2);
5039 } else if (N1CFP && !N2CFP) {
5040 std::swap(N1CFP, N2CFP);
5041 std::swap(N1, N2);
5045 switch (Opcode) {
5046 default: break;
5047 case ISD::TokenFactor:
5048 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5049 N2.getValueType() == MVT::Other && "Invalid token factor!");
5050 // Fold trivial token factors.
5051 if (N1.getOpcode() == ISD::EntryToken) return N2;
5052 if (N2.getOpcode() == ISD::EntryToken) return N1;
5053 if (N1 == N2) return N1;
5054 break;
5055 case ISD::BUILD_VECTOR: {
5056 // Attempt to simplify BUILD_VECTOR.
5057 SDValue Ops[] = {N1, N2};
5058 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5059 return V;
5060 break;
5062 case ISD::CONCAT_VECTORS: {
5063 SDValue Ops[] = {N1, N2};
5064 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5065 return V;
5066 break;
5068 case ISD::AND:
5069 assert(VT.isInteger() && "This operator does not apply to FP types!");
5070 assert(N1.getValueType() == N2.getValueType() &&
5071 N1.getValueType() == VT && "Binary operator types must match!");
5072 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
5073 // worth handling here.
5074 if (N2C && N2C->isNullValue())
5075 return N2;
5076 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
5077 return N1;
5078 break;
5079 case ISD::OR:
5080 case ISD::XOR:
5081 case ISD::ADD:
5082 case ISD::SUB:
5083 assert(VT.isInteger() && "This operator does not apply to FP types!");
5084 assert(N1.getValueType() == N2.getValueType() &&
5085 N1.getValueType() == VT && "Binary operator types must match!");
5086 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
5087 // it's worth handling here.
5088 if (N2C && N2C->isNullValue())
5089 return N1;
5090 break;
5091 case ISD::UDIV:
5092 case ISD::UREM:
5093 case ISD::MULHU:
5094 case ISD::MULHS:
5095 case ISD::MUL:
5096 case ISD::SDIV:
5097 case ISD::SREM:
5098 case ISD::SMIN:
5099 case ISD::SMAX:
5100 case ISD::UMIN:
5101 case ISD::UMAX:
5102 case ISD::SADDSAT:
5103 case ISD::SSUBSAT:
5104 case ISD::UADDSAT:
5105 case ISD::USUBSAT:
5106 assert(VT.isInteger() && "This operator does not apply to FP types!");
5107 assert(N1.getValueType() == N2.getValueType() &&
5108 N1.getValueType() == VT && "Binary operator types must match!");
5109 break;
5110 case ISD::FADD:
5111 case ISD::FSUB:
5112 case ISD::FMUL:
5113 case ISD::FDIV:
5114 case ISD::FREM:
5115 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5116 assert(N1.getValueType() == N2.getValueType() &&
5117 N1.getValueType() == VT && "Binary operator types must match!");
5118 if (SDValue V = simplifyFPBinop(Opcode, N1, N2))
5119 return V;
5120 break;
5121 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
5122 assert(N1.getValueType() == VT &&
5123 N1.getValueType().isFloatingPoint() &&
5124 N2.getValueType().isFloatingPoint() &&
5125 "Invalid FCOPYSIGN!");
5126 break;
5127 case ISD::SHL:
5128 case ISD::SRA:
5129 case ISD::SRL:
5130 if (SDValue V = simplifyShift(N1, N2))
5131 return V;
5132 LLVM_FALLTHROUGH;
5133 case ISD::ROTL:
5134 case ISD::ROTR:
5135 assert(VT == N1.getValueType() &&
5136 "Shift operators return type must be the same as their first arg");
5137 assert(VT.isInteger() && N2.getValueType().isInteger() &&
5138 "Shifts only work on integers");
5139 assert((!VT.isVector() || VT == N2.getValueType()) &&
5140 "Vector shift amounts must be in the same as their first arg");
5141 // Verify that the shift amount VT is big enough to hold valid shift
5142 // amounts. This catches things like trying to shift an i1024 value by an
5143 // i8, which is easy to fall into in generic code that uses
5144 // TLI.getShiftAmount().
5145 assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) &&
5146 "Invalid use of small shift amount with oversized value!");
5148 // Always fold shifts of i1 values so the code generator doesn't need to
5149 // handle them. Since we know the size of the shift has to be less than the
5150 // size of the value, the shift/rotate count is guaranteed to be zero.
5151 if (VT == MVT::i1)
5152 return N1;
5153 if (N2C && N2C->isNullValue())
5154 return N1;
5155 break;
5156 case ISD::FP_ROUND:
5157 assert(VT.isFloatingPoint() &&
5158 N1.getValueType().isFloatingPoint() &&
5159 VT.bitsLE(N1.getValueType()) &&
5160 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5161 "Invalid FP_ROUND!");
5162 if (N1.getValueType() == VT) return N1; // noop conversion.
5163 break;
5164 case ISD::AssertSext:
5165 case ISD::AssertZext: {
5166 EVT EVT = cast<VTSDNode>(N2)->getVT();
5167 assert(VT == N1.getValueType() && "Not an inreg extend!");
5168 assert(VT.isInteger() && EVT.isInteger() &&
5169 "Cannot *_EXTEND_INREG FP types");
5170 assert(!EVT.isVector() &&
5171 "AssertSExt/AssertZExt type should be the vector element type "
5172 "rather than the vector type!");
5173 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5174 if (VT.getScalarType() == EVT) return N1; // noop assertion.
5175 break;
5177 case ISD::SIGN_EXTEND_INREG: {
5178 EVT EVT = cast<VTSDNode>(N2)->getVT();
5179 assert(VT == N1.getValueType() && "Not an inreg extend!");
5180 assert(VT.isInteger() && EVT.isInteger() &&
5181 "Cannot *_EXTEND_INREG FP types");
5182 assert(EVT.isVector() == VT.isVector() &&
5183 "SIGN_EXTEND_INREG type should be vector iff the operand "
5184 "type is vector!");
5185 assert((!EVT.isVector() ||
5186 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
5187 "Vector element counts must match in SIGN_EXTEND_INREG");
5188 assert(EVT.bitsLE(VT) && "Not extending!");
5189 if (EVT == VT) return N1; // Not actually extending
5191 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5192 unsigned FromBits = EVT.getScalarSizeInBits();
5193 Val <<= Val.getBitWidth() - FromBits;
5194 Val.ashrInPlace(Val.getBitWidth() - FromBits);
5195 return getConstant(Val, DL, ConstantVT);
5198 if (N1C) {
5199 const APInt &Val = N1C->getAPIntValue();
5200 return SignExtendInReg(Val, VT);
5202 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5203 SmallVector<SDValue, 8> Ops;
5204 llvm::EVT OpVT = N1.getOperand(0).getValueType();
5205 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5206 SDValue Op = N1.getOperand(i);
5207 if (Op.isUndef()) {
5208 Ops.push_back(getUNDEF(OpVT));
5209 continue;
5211 ConstantSDNode *C = cast<ConstantSDNode>(Op);
5212 APInt Val = C->getAPIntValue();
5213 Ops.push_back(SignExtendInReg(Val, OpVT));
5215 return getBuildVector(VT, DL, Ops);
5217 break;
5219 case ISD::EXTRACT_VECTOR_ELT:
5220 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5221 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5222 element type of the vector.");
5224 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
5225 if (N1.isUndef())
5226 return getUNDEF(VT);
5228 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
5229 if (N2C && N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5230 return getUNDEF(VT);
5232 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5233 // expanding copies of large vectors from registers.
5234 if (N2C &&
5235 N1.getOpcode() == ISD::CONCAT_VECTORS &&
5236 N1.getNumOperands() > 0) {
5237 unsigned Factor =
5238 N1.getOperand(0).getValueType().getVectorNumElements();
5239 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5240 N1.getOperand(N2C->getZExtValue() / Factor),
5241 getConstant(N2C->getZExtValue() % Factor, DL,
5242 N2.getValueType()));
5245 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
5246 // expanding large vector constants.
5247 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
5248 SDValue Elt = N1.getOperand(N2C->getZExtValue());
5250 if (VT != Elt.getValueType())
5251 // If the vector element type is not legal, the BUILD_VECTOR operands
5252 // are promoted and implicitly truncated, and the result implicitly
5253 // extended. Make that explicit here.
5254 Elt = getAnyExtOrTrunc(Elt, DL, VT);
5256 return Elt;
5259 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5260 // operations are lowered to scalars.
5261 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5262 // If the indices are the same, return the inserted element else
5263 // if the indices are known different, extract the element from
5264 // the original vector.
5265 SDValue N1Op2 = N1.getOperand(2);
5266 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5268 if (N1Op2C && N2C) {
5269 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5270 if (VT == N1.getOperand(1).getValueType())
5271 return N1.getOperand(1);
5272 else
5273 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5276 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5280 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5281 // when vector types are scalarized and v1iX is legal.
5282 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx)
5283 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5284 N1.getValueType().getVectorNumElements() == 1) {
5285 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5286 N1.getOperand(1));
5288 break;
5289 case ISD::EXTRACT_ELEMENT:
5290 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5291 assert(!N1.getValueType().isVector() && !VT.isVector() &&
5292 (N1.getValueType().isInteger() == VT.isInteger()) &&
5293 N1.getValueType() != VT &&
5294 "Wrong types for EXTRACT_ELEMENT!");
5296 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5297 // 64-bit integers into 32-bit parts. Instead of building the extract of
5298 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5299 if (N1.getOpcode() == ISD::BUILD_PAIR)
5300 return N1.getOperand(N2C->getZExtValue());
5302 // EXTRACT_ELEMENT of a constant int is also very common.
5303 if (N1C) {
5304 unsigned ElementSize = VT.getSizeInBits();
5305 unsigned Shift = ElementSize * N2C->getZExtValue();
5306 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
5307 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
5309 break;
5310 case ISD::EXTRACT_SUBVECTOR:
5311 if (VT.isSimple() && N1.getValueType().isSimple()) {
5312 assert(VT.isVector() && N1.getValueType().isVector() &&
5313 "Extract subvector VTs must be a vectors!");
5314 assert(VT.getVectorElementType() ==
5315 N1.getValueType().getVectorElementType() &&
5316 "Extract subvector VTs must have the same element type!");
5317 assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
5318 "Extract subvector must be from larger vector to smaller vector!");
5320 if (N2C) {
5321 assert((VT.getVectorNumElements() + N2C->getZExtValue()
5322 <= N1.getValueType().getVectorNumElements())
5323 && "Extract subvector overflow!");
5326 // Trivial extraction.
5327 if (VT.getSimpleVT() == N1.getSimpleValueType())
5328 return N1;
5330 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5331 if (N1.isUndef())
5332 return getUNDEF(VT);
5334 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5335 // the concat have the same type as the extract.
5336 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
5337 N1.getNumOperands() > 0 &&
5338 VT == N1.getOperand(0).getValueType()) {
5339 unsigned Factor = VT.getVectorNumElements();
5340 return N1.getOperand(N2C->getZExtValue() / Factor);
5343 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5344 // during shuffle legalization.
5345 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5346 VT == N1.getOperand(1).getValueType())
5347 return N1.getOperand(1);
5349 break;
5352 // Perform trivial constant folding.
5353 if (SDValue SV =
5354 FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
5355 return SV;
5357 if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5358 return V;
5360 // Canonicalize an UNDEF to the RHS, even over a constant.
5361 if (N1.isUndef()) {
5362 if (TLI->isCommutativeBinOp(Opcode)) {
5363 std::swap(N1, N2);
5364 } else {
5365 switch (Opcode) {
5366 case ISD::SIGN_EXTEND_INREG:
5367 case ISD::SUB:
5368 return getUNDEF(VT); // fold op(undef, arg2) -> undef
5369 case ISD::UDIV:
5370 case ISD::SDIV:
5371 case ISD::UREM:
5372 case ISD::SREM:
5373 case ISD::SSUBSAT:
5374 case ISD::USUBSAT:
5375 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
5380 // Fold a bunch of operators when the RHS is undef.
5381 if (N2.isUndef()) {
5382 switch (Opcode) {
5383 case ISD::XOR:
5384 if (N1.isUndef())
5385 // Handle undef ^ undef -> 0 special case. This is a common
5386 // idiom (misuse).
5387 return getConstant(0, DL, VT);
5388 LLVM_FALLTHROUGH;
5389 case ISD::ADD:
5390 case ISD::SUB:
5391 case ISD::UDIV:
5392 case ISD::SDIV:
5393 case ISD::UREM:
5394 case ISD::SREM:
5395 return getUNDEF(VT); // fold op(arg1, undef) -> undef
5396 case ISD::MUL:
5397 case ISD::AND:
5398 case ISD::SSUBSAT:
5399 case ISD::USUBSAT:
5400 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
5401 case ISD::OR:
5402 case ISD::SADDSAT:
5403 case ISD::UADDSAT:
5404 return getAllOnesConstant(DL, VT);
5408 // Memoize this node if possible.
5409 SDNode *N;
5410 SDVTList VTs = getVTList(VT);
5411 SDValue Ops[] = {N1, N2};
5412 if (VT != MVT::Glue) {
5413 FoldingSetNodeID ID;
5414 AddNodeIDNode(ID, Opcode, VTs, Ops);
5415 void *IP = nullptr;
5416 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5417 E->intersectFlagsWith(Flags);
5418 return SDValue(E, 0);
5421 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5422 N->setFlags(Flags);
5423 createOperands(N, Ops);
5424 CSEMap.InsertNode(N, IP);
5425 } else {
5426 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5427 createOperands(N, Ops);
5430 InsertNode(N);
5431 SDValue V = SDValue(N, 0);
5432 NewSDValueDbgMsg(V, "Creating new node: ", this);
5433 return V;
5436 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5437 SDValue N1, SDValue N2, SDValue N3,
5438 const SDNodeFlags Flags) {
5439 // Perform various simplifications.
5440 switch (Opcode) {
5441 case ISD::FMA: {
5442 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5443 assert(N1.getValueType() == VT && N2.getValueType() == VT &&
5444 N3.getValueType() == VT && "FMA types must match!");
5445 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5446 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5447 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
5448 if (N1CFP && N2CFP && N3CFP) {
5449 APFloat V1 = N1CFP->getValueAPF();
5450 const APFloat &V2 = N2CFP->getValueAPF();
5451 const APFloat &V3 = N3CFP->getValueAPF();
5452 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
5453 return getConstantFP(V1, DL, VT);
5455 break;
5457 case ISD::BUILD_VECTOR: {
5458 // Attempt to simplify BUILD_VECTOR.
5459 SDValue Ops[] = {N1, N2, N3};
5460 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5461 return V;
5462 break;
5464 case ISD::CONCAT_VECTORS: {
5465 SDValue Ops[] = {N1, N2, N3};
5466 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5467 return V;
5468 break;
5470 case ISD::SETCC: {
5471 assert(VT.isInteger() && "SETCC result type must be an integer!");
5472 assert(N1.getValueType() == N2.getValueType() &&
5473 "SETCC operands must have the same type!");
5474 assert(VT.isVector() == N1.getValueType().isVector() &&
5475 "SETCC type should be vector iff the operand type is vector!");
5476 assert((!VT.isVector() ||
5477 VT.getVectorNumElements() == N1.getValueType().getVectorNumElements()) &&
5478 "SETCC vector element counts must match!");
5479 // Use FoldSetCC to simplify SETCC's.
5480 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
5481 return V;
5482 // Vector constant folding.
5483 SDValue Ops[] = {N1, N2, N3};
5484 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
5485 NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
5486 return V;
5488 break;
5490 case ISD::SELECT:
5491 case ISD::VSELECT:
5492 if (SDValue V = simplifySelect(N1, N2, N3))
5493 return V;
5494 break;
5495 case ISD::VECTOR_SHUFFLE:
5496 llvm_unreachable("should use getVectorShuffle constructor!");
5497 case ISD::INSERT_VECTOR_ELT: {
5498 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
5499 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF
5500 if (N3C && N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
5501 return getUNDEF(VT);
5502 break;
5504 case ISD::INSERT_SUBVECTOR: {
5505 // Inserting undef into undef is still undef.
5506 if (N1.isUndef() && N2.isUndef())
5507 return getUNDEF(VT);
5508 SDValue Index = N3;
5509 if (VT.isSimple() && N1.getValueType().isSimple()
5510 && N2.getValueType().isSimple()) {
5511 assert(VT.isVector() && N1.getValueType().isVector() &&
5512 N2.getValueType().isVector() &&
5513 "Insert subvector VTs must be a vectors");
5514 assert(VT == N1.getValueType() &&
5515 "Dest and insert subvector source types must match!");
5516 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
5517 "Insert subvector must be from smaller vector to larger vector!");
5518 if (isa<ConstantSDNode>(Index)) {
5519 assert((N2.getValueType().getVectorNumElements() +
5520 cast<ConstantSDNode>(Index)->getZExtValue()
5521 <= VT.getVectorNumElements())
5522 && "Insert subvector overflow!");
5525 // Trivial insertion.
5526 if (VT.getSimpleVT() == N2.getSimpleValueType())
5527 return N2;
5529 // If this is an insert of an extracted vector into an undef vector, we
5530 // can just use the input to the extract.
5531 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5532 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
5533 return N2.getOperand(0);
5535 break;
5537 case ISD::BITCAST:
5538 // Fold bit_convert nodes from a type to themselves.
5539 if (N1.getValueType() == VT)
5540 return N1;
5541 break;
5544 // Memoize node if it doesn't produce a flag.
5545 SDNode *N;
5546 SDVTList VTs = getVTList(VT);
5547 SDValue Ops[] = {N1, N2, N3};
5548 if (VT != MVT::Glue) {
5549 FoldingSetNodeID ID;
5550 AddNodeIDNode(ID, Opcode, VTs, Ops);
5551 void *IP = nullptr;
5552 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5553 E->intersectFlagsWith(Flags);
5554 return SDValue(E, 0);
5557 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5558 N->setFlags(Flags);
5559 createOperands(N, Ops);
5560 CSEMap.InsertNode(N, IP);
5561 } else {
5562 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5563 createOperands(N, Ops);
5566 InsertNode(N);
5567 SDValue V = SDValue(N, 0);
5568 NewSDValueDbgMsg(V, "Creating new node: ", this);
5569 return V;
5572 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5573 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
5574 SDValue Ops[] = { N1, N2, N3, N4 };
5575 return getNode(Opcode, DL, VT, Ops);
5578 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5579 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
5580 SDValue N5) {
5581 SDValue Ops[] = { N1, N2, N3, N4, N5 };
5582 return getNode(Opcode, DL, VT, Ops);
5585 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
5586 /// the incoming stack arguments to be loaded from the stack.
5587 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
5588 SmallVector<SDValue, 8> ArgChains;
5590 // Include the original chain at the beginning of the list. When this is
5591 // used by target LowerCall hooks, this helps legalize find the
5592 // CALLSEQ_BEGIN node.
5593 ArgChains.push_back(Chain);
5595 // Add a chain value for each stack argument.
5596 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
5597 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
5598 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
5599 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
5600 if (FI->getIndex() < 0)
5601 ArgChains.push_back(SDValue(L, 1));
5603 // Build a tokenfactor for all the chains.
5604 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
5607 /// getMemsetValue - Vectorized representation of the memset value
5608 /// operand.
5609 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
5610 const SDLoc &dl) {
5611 assert(!Value.isUndef());
5613 unsigned NumBits = VT.getScalarSizeInBits();
5614 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
5615 assert(C->getAPIntValue().getBitWidth() == 8);
5616 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
5617 if (VT.isInteger()) {
5618 bool IsOpaque = VT.getSizeInBits() > 64 ||
5619 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
5620 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
5622 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
5623 VT);
5626 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
5627 EVT IntVT = VT.getScalarType();
5628 if (!IntVT.isInteger())
5629 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
5631 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
5632 if (NumBits > 8) {
5633 // Use a multiplication with 0x010101... to extend the input to the
5634 // required length.
5635 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
5636 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
5637 DAG.getConstant(Magic, dl, IntVT));
5640 if (VT != Value.getValueType() && !VT.isInteger())
5641 Value = DAG.getBitcast(VT.getScalarType(), Value);
5642 if (VT != Value.getValueType())
5643 Value = DAG.getSplatBuildVector(VT, dl, Value);
5645 return Value;
5648 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
5649 /// used when a memcpy is turned into a memset when the source is a constant
5650 /// string ptr.
5651 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
5652 const TargetLowering &TLI,
5653 const ConstantDataArraySlice &Slice) {
5654 // Handle vector with all elements zero.
5655 if (Slice.Array == nullptr) {
5656 if (VT.isInteger())
5657 return DAG.getConstant(0, dl, VT);
5658 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
5659 return DAG.getConstantFP(0.0, dl, VT);
5660 else if (VT.isVector()) {
5661 unsigned NumElts = VT.getVectorNumElements();
5662 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5663 return DAG.getNode(ISD::BITCAST, dl, VT,
5664 DAG.getConstant(0, dl,
5665 EVT::getVectorVT(*DAG.getContext(),
5666 EltVT, NumElts)));
5667 } else
5668 llvm_unreachable("Expected type!");
5671 assert(!VT.isVector() && "Can't handle vector type here!");
5672 unsigned NumVTBits = VT.getSizeInBits();
5673 unsigned NumVTBytes = NumVTBits / 8;
5674 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
5676 APInt Val(NumVTBits, 0);
5677 if (DAG.getDataLayout().isLittleEndian()) {
5678 for (unsigned i = 0; i != NumBytes; ++i)
5679 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
5680 } else {
5681 for (unsigned i = 0; i != NumBytes; ++i)
5682 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
5685 // If the "cost" of materializing the integer immediate is less than the cost
5686 // of a load, then it is cost effective to turn the load into the immediate.
5687 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
5688 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
5689 return DAG.getConstant(Val, dl, VT);
5690 return SDValue(nullptr, 0);
5693 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
5694 const SDLoc &DL) {
5695 EVT VT = Base.getValueType();
5696 return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
5699 /// Returns true if memcpy source is constant data.
5700 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
5701 uint64_t SrcDelta = 0;
5702 GlobalAddressSDNode *G = nullptr;
5703 if (Src.getOpcode() == ISD::GlobalAddress)
5704 G = cast<GlobalAddressSDNode>(Src);
5705 else if (Src.getOpcode() == ISD::ADD &&
5706 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
5707 Src.getOperand(1).getOpcode() == ISD::Constant) {
5708 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
5709 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
5711 if (!G)
5712 return false;
5714 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
5715 SrcDelta + G->getOffset());
5718 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
5719 // On Darwin, -Os means optimize for size without hurting performance, so
5720 // only really optimize for size when -Oz (MinSize) is used.
5721 if (MF.getTarget().getTargetTriple().isOSDarwin())
5722 return MF.getFunction().hasMinSize();
5723 return MF.getFunction().hasOptSize();
5726 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
5727 SmallVector<SDValue, 32> &OutChains, unsigned From,
5728 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
5729 SmallVector<SDValue, 16> &OutStoreChains) {
5730 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
5731 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
5732 SmallVector<SDValue, 16> GluedLoadChains;
5733 for (unsigned i = From; i < To; ++i) {
5734 OutChains.push_back(OutLoadChains[i]);
5735 GluedLoadChains.push_back(OutLoadChains[i]);
5738 // Chain for all loads.
5739 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5740 GluedLoadChains);
5742 for (unsigned i = From; i < To; ++i) {
5743 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
5744 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
5745 ST->getBasePtr(), ST->getMemoryVT(),
5746 ST->getMemOperand());
5747 OutChains.push_back(NewStore);
5751 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5752 SDValue Chain, SDValue Dst, SDValue Src,
5753 uint64_t Size, unsigned Align,
5754 bool isVol, bool AlwaysInline,
5755 MachinePointerInfo DstPtrInfo,
5756 MachinePointerInfo SrcPtrInfo) {
5757 // Turn a memcpy of undef to nop.
5758 // FIXME: We need to honor volatile even is Src is undef.
5759 if (Src.isUndef())
5760 return Chain;
5762 // Expand memcpy to a series of load and store ops if the size operand falls
5763 // below a certain threshold.
5764 // TODO: In the AlwaysInline case, if the size is big then generate a loop
5765 // rather than maybe a humongous number of loads and stores.
5766 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5767 const DataLayout &DL = DAG.getDataLayout();
5768 LLVMContext &C = *DAG.getContext();
5769 std::vector<EVT> MemOps;
5770 bool DstAlignCanChange = false;
5771 MachineFunction &MF = DAG.getMachineFunction();
5772 MachineFrameInfo &MFI = MF.getFrameInfo();
5773 bool OptSize = shouldLowerMemFuncForSize(MF);
5774 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5775 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5776 DstAlignCanChange = true;
5777 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5778 if (Align > SrcAlign)
5779 SrcAlign = Align;
5780 ConstantDataArraySlice Slice;
5781 bool CopyFromConstant = isMemSrcFromConstant(Src, Slice);
5782 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
5783 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
5785 if (!TLI.findOptimalMemOpLowering(
5786 MemOps, Limit, Size, (DstAlignCanChange ? 0 : Align),
5787 (isZeroConstant ? 0 : SrcAlign), /*IsMemset=*/false,
5788 /*ZeroMemset=*/false, /*MemcpyStrSrc=*/CopyFromConstant,
5789 /*AllowOverlap=*/!isVol, DstPtrInfo.getAddrSpace(),
5790 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
5791 return SDValue();
5793 if (DstAlignCanChange) {
5794 Type *Ty = MemOps[0].getTypeForEVT(C);
5795 unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
5797 // Don't promote to an alignment that would require dynamic stack
5798 // realignment.
5799 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
5800 if (!TRI->needsStackRealignment(MF))
5801 while (NewAlign > Align &&
5802 DL.exceedsNaturalStackAlignment(llvm::Align(NewAlign)))
5803 NewAlign /= 2;
5805 if (NewAlign > Align) {
5806 // Give the stack frame object a larger alignment if needed.
5807 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5808 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5809 Align = NewAlign;
5813 MachineMemOperand::Flags MMOFlags =
5814 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5815 SmallVector<SDValue, 16> OutLoadChains;
5816 SmallVector<SDValue, 16> OutStoreChains;
5817 SmallVector<SDValue, 32> OutChains;
5818 unsigned NumMemOps = MemOps.size();
5819 uint64_t SrcOff = 0, DstOff = 0;
5820 for (unsigned i = 0; i != NumMemOps; ++i) {
5821 EVT VT = MemOps[i];
5822 unsigned VTSize = VT.getSizeInBits() / 8;
5823 SDValue Value, Store;
5825 if (VTSize > Size) {
5826 // Issuing an unaligned load / store pair that overlaps with the previous
5827 // pair. Adjust the offset accordingly.
5828 assert(i == NumMemOps-1 && i != 0);
5829 SrcOff -= VTSize - Size;
5830 DstOff -= VTSize - Size;
5833 if (CopyFromConstant &&
5834 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
5835 // It's unlikely a store of a vector immediate can be done in a single
5836 // instruction. It would require a load from a constantpool first.
5837 // We only handle zero vectors here.
5838 // FIXME: Handle other cases where store of vector immediate is done in
5839 // a single instruction.
5840 ConstantDataArraySlice SubSlice;
5841 if (SrcOff < Slice.Length) {
5842 SubSlice = Slice;
5843 SubSlice.move(SrcOff);
5844 } else {
5845 // This is an out-of-bounds access and hence UB. Pretend we read zero.
5846 SubSlice.Array = nullptr;
5847 SubSlice.Offset = 0;
5848 SubSlice.Length = VTSize;
5850 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
5851 if (Value.getNode()) {
5852 Store = DAG.getStore(Chain, dl, Value,
5853 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5854 DstPtrInfo.getWithOffset(DstOff), Align,
5855 MMOFlags);
5856 OutChains.push_back(Store);
5860 if (!Store.getNode()) {
5861 // The type might not be legal for the target. This should only happen
5862 // if the type is smaller than a legal type, as on PPC, so the right
5863 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
5864 // to Load/Store if NVT==VT.
5865 // FIXME does the case above also need this?
5866 EVT NVT = TLI.getTypeToTransformTo(C, VT);
5867 assert(NVT.bitsGE(VT));
5869 bool isDereferenceable =
5870 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
5871 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
5872 if (isDereferenceable)
5873 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
5875 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
5876 DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5877 SrcPtrInfo.getWithOffset(SrcOff), VT,
5878 MinAlign(SrcAlign, SrcOff), SrcMMOFlags);
5879 OutLoadChains.push_back(Value.getValue(1));
5881 Store = DAG.getTruncStore(
5882 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5883 DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
5884 OutStoreChains.push_back(Store);
5886 SrcOff += VTSize;
5887 DstOff += VTSize;
5888 Size -= VTSize;
5891 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
5892 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
5893 unsigned NumLdStInMemcpy = OutStoreChains.size();
5895 if (NumLdStInMemcpy) {
5896 // It may be that memcpy might be converted to memset if it's memcpy
5897 // of constants. In such a case, we won't have loads and stores, but
5898 // just stores. In the absence of loads, there is nothing to gang up.
5899 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
5900 // If target does not care, just leave as it.
5901 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
5902 OutChains.push_back(OutLoadChains[i]);
5903 OutChains.push_back(OutStoreChains[i]);
5905 } else {
5906 // Ld/St less than/equal limit set by target.
5907 if (NumLdStInMemcpy <= GluedLdStLimit) {
5908 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
5909 NumLdStInMemcpy, OutLoadChains,
5910 OutStoreChains);
5911 } else {
5912 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
5913 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
5914 unsigned GlueIter = 0;
5916 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
5917 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
5918 unsigned IndexTo = NumLdStInMemcpy - GlueIter;
5920 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
5921 OutLoadChains, OutStoreChains);
5922 GlueIter += GluedLdStLimit;
5925 // Residual ld/st.
5926 if (RemainingLdStInMemcpy) {
5927 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
5928 RemainingLdStInMemcpy, OutLoadChains,
5929 OutStoreChains);
5934 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5937 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5938 SDValue Chain, SDValue Dst, SDValue Src,
5939 uint64_t Size, unsigned Align,
5940 bool isVol, bool AlwaysInline,
5941 MachinePointerInfo DstPtrInfo,
5942 MachinePointerInfo SrcPtrInfo) {
5943 // Turn a memmove of undef to nop.
5944 // FIXME: We need to honor volatile even is Src is undef.
5945 if (Src.isUndef())
5946 return Chain;
5948 // Expand memmove to a series of load and store ops if the size operand falls
5949 // below a certain threshold.
5950 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5951 const DataLayout &DL = DAG.getDataLayout();
5952 LLVMContext &C = *DAG.getContext();
5953 std::vector<EVT> MemOps;
5954 bool DstAlignCanChange = false;
5955 MachineFunction &MF = DAG.getMachineFunction();
5956 MachineFrameInfo &MFI = MF.getFrameInfo();
5957 bool OptSize = shouldLowerMemFuncForSize(MF);
5958 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5959 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5960 DstAlignCanChange = true;
5961 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5962 if (Align > SrcAlign)
5963 SrcAlign = Align;
5964 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
5965 // FIXME: `AllowOverlap` should really be `!isVol` but there is a bug in
5966 // findOptimalMemOpLowering. Meanwhile, setting it to `false` produces the
5967 // correct code.
5968 bool AllowOverlap = false;
5969 if (!TLI.findOptimalMemOpLowering(
5970 MemOps, Limit, Size, (DstAlignCanChange ? 0 : Align), SrcAlign,
5971 /*IsMemset=*/false, /*ZeroMemset=*/false, /*MemcpyStrSrc=*/false,
5972 AllowOverlap, DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
5973 MF.getFunction().getAttributes()))
5974 return SDValue();
5976 if (DstAlignCanChange) {
5977 Type *Ty = MemOps[0].getTypeForEVT(C);
5978 unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
5979 if (NewAlign > Align) {
5980 // Give the stack frame object a larger alignment if needed.
5981 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5982 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5983 Align = NewAlign;
5987 MachineMemOperand::Flags MMOFlags =
5988 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5989 uint64_t SrcOff = 0, DstOff = 0;
5990 SmallVector<SDValue, 8> LoadValues;
5991 SmallVector<SDValue, 8> LoadChains;
5992 SmallVector<SDValue, 8> OutChains;
5993 unsigned NumMemOps = MemOps.size();
5994 for (unsigned i = 0; i < NumMemOps; i++) {
5995 EVT VT = MemOps[i];
5996 unsigned VTSize = VT.getSizeInBits() / 8;
5997 SDValue Value;
5999 bool isDereferenceable =
6000 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6001 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6002 if (isDereferenceable)
6003 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6005 Value =
6006 DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
6007 SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, SrcMMOFlags);
6008 LoadValues.push_back(Value);
6009 LoadChains.push_back(Value.getValue(1));
6010 SrcOff += VTSize;
6012 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6013 OutChains.clear();
6014 for (unsigned i = 0; i < NumMemOps; i++) {
6015 EVT VT = MemOps[i];
6016 unsigned VTSize = VT.getSizeInBits() / 8;
6017 SDValue Store;
6019 Store = DAG.getStore(Chain, dl, LoadValues[i],
6020 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
6021 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
6022 OutChains.push_back(Store);
6023 DstOff += VTSize;
6026 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6029 /// Lower the call to 'memset' intrinsic function into a series of store
6030 /// operations.
6032 /// \param DAG Selection DAG where lowered code is placed.
6033 /// \param dl Link to corresponding IR location.
6034 /// \param Chain Control flow dependency.
6035 /// \param Dst Pointer to destination memory location.
6036 /// \param Src Value of byte to write into the memory.
6037 /// \param Size Number of bytes to write.
6038 /// \param Align Alignment of the destination in bytes.
6039 /// \param isVol True if destination is volatile.
6040 /// \param DstPtrInfo IR information on the memory pointer.
6041 /// \returns New head in the control flow, if lowering was successful, empty
6042 /// SDValue otherwise.
6044 /// The function tries to replace 'llvm.memset' intrinsic with several store
6045 /// operations and value calculation code. This is usually profitable for small
6046 /// memory size.
6047 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6048 SDValue Chain, SDValue Dst, SDValue Src,
6049 uint64_t Size, unsigned Align, bool isVol,
6050 MachinePointerInfo DstPtrInfo) {
6051 // Turn a memset of undef to nop.
6052 // FIXME: We need to honor volatile even is Src is undef.
6053 if (Src.isUndef())
6054 return Chain;
6056 // Expand memset to a series of load/store ops if the size operand
6057 // falls below a certain threshold.
6058 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6059 std::vector<EVT> MemOps;
6060 bool DstAlignCanChange = false;
6061 MachineFunction &MF = DAG.getMachineFunction();
6062 MachineFrameInfo &MFI = MF.getFrameInfo();
6063 bool OptSize = shouldLowerMemFuncForSize(MF);
6064 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6065 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6066 DstAlignCanChange = true;
6067 bool IsZeroVal =
6068 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
6069 if (!TLI.findOptimalMemOpLowering(
6070 MemOps, TLI.getMaxStoresPerMemset(OptSize), Size,
6071 (DstAlignCanChange ? 0 : Align), 0, /*IsMemset=*/true,
6072 /*ZeroMemset=*/IsZeroVal, /*MemcpyStrSrc=*/false,
6073 /*AllowOverlap=*/!isVol, DstPtrInfo.getAddrSpace(), ~0u,
6074 MF.getFunction().getAttributes()))
6075 return SDValue();
6077 if (DstAlignCanChange) {
6078 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6079 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
6080 if (NewAlign > Align) {
6081 // Give the stack frame object a larger alignment if needed.
6082 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
6083 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6084 Align = NewAlign;
6088 SmallVector<SDValue, 8> OutChains;
6089 uint64_t DstOff = 0;
6090 unsigned NumMemOps = MemOps.size();
6092 // Find the largest store and generate the bit pattern for it.
6093 EVT LargestVT = MemOps[0];
6094 for (unsigned i = 1; i < NumMemOps; i++)
6095 if (MemOps[i].bitsGT(LargestVT))
6096 LargestVT = MemOps[i];
6097 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6099 for (unsigned i = 0; i < NumMemOps; i++) {
6100 EVT VT = MemOps[i];
6101 unsigned VTSize = VT.getSizeInBits() / 8;
6102 if (VTSize > Size) {
6103 // Issuing an unaligned load / store pair that overlaps with the previous
6104 // pair. Adjust the offset accordingly.
6105 assert(i == NumMemOps-1 && i != 0);
6106 DstOff -= VTSize - Size;
6109 // If this store is smaller than the largest store see whether we can get
6110 // the smaller value for free with a truncate.
6111 SDValue Value = MemSetValue;
6112 if (VT.bitsLT(LargestVT)) {
6113 if (!LargestVT.isVector() && !VT.isVector() &&
6114 TLI.isTruncateFree(LargestVT, VT))
6115 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6116 else
6117 Value = getMemsetValue(Src, VT, DAG, dl);
6119 assert(Value.getValueType() == VT && "Value with wrong type.");
6120 SDValue Store = DAG.getStore(
6121 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
6122 DstPtrInfo.getWithOffset(DstOff), Align,
6123 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
6124 OutChains.push_back(Store);
6125 DstOff += VT.getSizeInBits() / 8;
6126 Size -= VTSize;
6129 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6132 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6133 unsigned AS) {
6134 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6135 // pointer operands can be losslessly bitcasted to pointers of address space 0
6136 if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
6137 report_fatal_error("cannot lower memory intrinsic in address space " +
6138 Twine(AS));
6142 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6143 SDValue Src, SDValue Size, unsigned Align,
6144 bool isVol, bool AlwaysInline, bool isTailCall,
6145 MachinePointerInfo DstPtrInfo,
6146 MachinePointerInfo SrcPtrInfo) {
6147 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
6149 // Check to see if we should lower the memcpy to loads and stores first.
6150 // For cases within the target-specified limits, this is the best choice.
6151 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6152 if (ConstantSize) {
6153 // Memcpy with size zero? Just return the original chain.
6154 if (ConstantSize->isNullValue())
6155 return Chain;
6157 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6158 ConstantSize->getZExtValue(),Align,
6159 isVol, false, DstPtrInfo, SrcPtrInfo);
6160 if (Result.getNode())
6161 return Result;
6164 // Then check to see if we should lower the memcpy with target-specific
6165 // code. If the target chooses to do this, this is the next best.
6166 if (TSI) {
6167 SDValue Result = TSI->EmitTargetCodeForMemcpy(
6168 *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
6169 DstPtrInfo, SrcPtrInfo);
6170 if (Result.getNode())
6171 return Result;
6174 // If we really need inline code and the target declined to provide it,
6175 // use a (potentially long) sequence of loads and stores.
6176 if (AlwaysInline) {
6177 assert(ConstantSize && "AlwaysInline requires a constant size!");
6178 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6179 ConstantSize->getZExtValue(), Align, isVol,
6180 true, DstPtrInfo, SrcPtrInfo);
6183 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6184 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6186 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6187 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6188 // respect volatile, so they may do things like read or write memory
6189 // beyond the given memory regions. But fixing this isn't easy, and most
6190 // people don't care.
6192 // Emit a library call.
6193 TargetLowering::ArgListTy Args;
6194 TargetLowering::ArgListEntry Entry;
6195 Entry.Ty = Type::getInt8PtrTy(*getContext());
6196 Entry.Node = Dst; Args.push_back(Entry);
6197 Entry.Node = Src; Args.push_back(Entry);
6199 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6200 Entry.Node = Size; Args.push_back(Entry);
6201 // FIXME: pass in SDLoc
6202 TargetLowering::CallLoweringInfo CLI(*this);
6203 CLI.setDebugLoc(dl)
6204 .setChain(Chain)
6205 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6206 Dst.getValueType().getTypeForEVT(*getContext()),
6207 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6208 TLI->getPointerTy(getDataLayout())),
6209 std::move(Args))
6210 .setDiscardResult()
6211 .setTailCall(isTailCall);
6213 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6214 return CallResult.second;
6217 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6218 SDValue Dst, unsigned DstAlign,
6219 SDValue Src, unsigned SrcAlign,
6220 SDValue Size, Type *SizeTy,
6221 unsigned ElemSz, bool isTailCall,
6222 MachinePointerInfo DstPtrInfo,
6223 MachinePointerInfo SrcPtrInfo) {
6224 // Emit a library call.
6225 TargetLowering::ArgListTy Args;
6226 TargetLowering::ArgListEntry Entry;
6227 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6228 Entry.Node = Dst;
6229 Args.push_back(Entry);
6231 Entry.Node = Src;
6232 Args.push_back(Entry);
6234 Entry.Ty = SizeTy;
6235 Entry.Node = Size;
6236 Args.push_back(Entry);
6238 RTLIB::Libcall LibraryCall =
6239 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6240 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6241 report_fatal_error("Unsupported element size");
6243 TargetLowering::CallLoweringInfo CLI(*this);
6244 CLI.setDebugLoc(dl)
6245 .setChain(Chain)
6246 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6247 Type::getVoidTy(*getContext()),
6248 getExternalSymbol(TLI->getLibcallName(LibraryCall),
6249 TLI->getPointerTy(getDataLayout())),
6250 std::move(Args))
6251 .setDiscardResult()
6252 .setTailCall(isTailCall);
6254 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6255 return CallResult.second;
6258 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6259 SDValue Src, SDValue Size, unsigned Align,
6260 bool isVol, bool isTailCall,
6261 MachinePointerInfo DstPtrInfo,
6262 MachinePointerInfo SrcPtrInfo) {
6263 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
6265 // Check to see if we should lower the memmove to loads and stores first.
6266 // For cases within the target-specified limits, this is the best choice.
6267 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6268 if (ConstantSize) {
6269 // Memmove with size zero? Just return the original chain.
6270 if (ConstantSize->isNullValue())
6271 return Chain;
6273 SDValue Result =
6274 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
6275 ConstantSize->getZExtValue(), Align, isVol,
6276 false, DstPtrInfo, SrcPtrInfo);
6277 if (Result.getNode())
6278 return Result;
6281 // Then check to see if we should lower the memmove with target-specific
6282 // code. If the target chooses to do this, this is the next best.
6283 if (TSI) {
6284 SDValue Result = TSI->EmitTargetCodeForMemmove(
6285 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
6286 if (Result.getNode())
6287 return Result;
6290 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6291 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6293 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6294 // not be safe. See memcpy above for more details.
6296 // Emit a library call.
6297 TargetLowering::ArgListTy Args;
6298 TargetLowering::ArgListEntry Entry;
6299 Entry.Ty = Type::getInt8PtrTy(*getContext());
6300 Entry.Node = Dst; Args.push_back(Entry);
6301 Entry.Node = Src; Args.push_back(Entry);
6303 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6304 Entry.Node = Size; Args.push_back(Entry);
6305 // FIXME: pass in SDLoc
6306 TargetLowering::CallLoweringInfo CLI(*this);
6307 CLI.setDebugLoc(dl)
6308 .setChain(Chain)
6309 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6310 Dst.getValueType().getTypeForEVT(*getContext()),
6311 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6312 TLI->getPointerTy(getDataLayout())),
6313 std::move(Args))
6314 .setDiscardResult()
6315 .setTailCall(isTailCall);
6317 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6318 return CallResult.second;
6321 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6322 SDValue Dst, unsigned DstAlign,
6323 SDValue Src, unsigned SrcAlign,
6324 SDValue Size, Type *SizeTy,
6325 unsigned ElemSz, bool isTailCall,
6326 MachinePointerInfo DstPtrInfo,
6327 MachinePointerInfo SrcPtrInfo) {
6328 // Emit a library call.
6329 TargetLowering::ArgListTy Args;
6330 TargetLowering::ArgListEntry Entry;
6331 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6332 Entry.Node = Dst;
6333 Args.push_back(Entry);
6335 Entry.Node = Src;
6336 Args.push_back(Entry);
6338 Entry.Ty = SizeTy;
6339 Entry.Node = Size;
6340 Args.push_back(Entry);
6342 RTLIB::Libcall LibraryCall =
6343 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6344 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6345 report_fatal_error("Unsupported element size");
6347 TargetLowering::CallLoweringInfo CLI(*this);
6348 CLI.setDebugLoc(dl)
6349 .setChain(Chain)
6350 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6351 Type::getVoidTy(*getContext()),
6352 getExternalSymbol(TLI->getLibcallName(LibraryCall),
6353 TLI->getPointerTy(getDataLayout())),
6354 std::move(Args))
6355 .setDiscardResult()
6356 .setTailCall(isTailCall);
6358 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6359 return CallResult.second;
6362 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
6363 SDValue Src, SDValue Size, unsigned Align,
6364 bool isVol, bool isTailCall,
6365 MachinePointerInfo DstPtrInfo) {
6366 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
6368 // Check to see if we should lower the memset to stores first.
6369 // For cases within the target-specified limits, this is the best choice.
6370 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6371 if (ConstantSize) {
6372 // Memset with size zero? Just return the original chain.
6373 if (ConstantSize->isNullValue())
6374 return Chain;
6376 SDValue Result =
6377 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
6378 Align, isVol, DstPtrInfo);
6380 if (Result.getNode())
6381 return Result;
6384 // Then check to see if we should lower the memset with target-specific
6385 // code. If the target chooses to do this, this is the next best.
6386 if (TSI) {
6387 SDValue Result = TSI->EmitTargetCodeForMemset(
6388 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
6389 if (Result.getNode())
6390 return Result;
6393 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6395 // Emit a library call.
6396 TargetLowering::ArgListTy Args;
6397 TargetLowering::ArgListEntry Entry;
6398 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
6399 Args.push_back(Entry);
6400 Entry.Node = Src;
6401 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
6402 Args.push_back(Entry);
6403 Entry.Node = Size;
6404 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6405 Args.push_back(Entry);
6407 // FIXME: pass in SDLoc
6408 TargetLowering::CallLoweringInfo CLI(*this);
6409 CLI.setDebugLoc(dl)
6410 .setChain(Chain)
6411 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
6412 Dst.getValueType().getTypeForEVT(*getContext()),
6413 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
6414 TLI->getPointerTy(getDataLayout())),
6415 std::move(Args))
6416 .setDiscardResult()
6417 .setTailCall(isTailCall);
6419 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6420 return CallResult.second;
6423 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
6424 SDValue Dst, unsigned DstAlign,
6425 SDValue Value, SDValue Size, Type *SizeTy,
6426 unsigned ElemSz, bool isTailCall,
6427 MachinePointerInfo DstPtrInfo) {
6428 // Emit a library call.
6429 TargetLowering::ArgListTy Args;
6430 TargetLowering::ArgListEntry Entry;
6431 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6432 Entry.Node = Dst;
6433 Args.push_back(Entry);
6435 Entry.Ty = Type::getInt8Ty(*getContext());
6436 Entry.Node = Value;
6437 Args.push_back(Entry);
6439 Entry.Ty = SizeTy;
6440 Entry.Node = Size;
6441 Args.push_back(Entry);
6443 RTLIB::Libcall LibraryCall =
6444 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6445 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6446 report_fatal_error("Unsupported element size");
6448 TargetLowering::CallLoweringInfo CLI(*this);
6449 CLI.setDebugLoc(dl)
6450 .setChain(Chain)
6451 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6452 Type::getVoidTy(*getContext()),
6453 getExternalSymbol(TLI->getLibcallName(LibraryCall),
6454 TLI->getPointerTy(getDataLayout())),
6455 std::move(Args))
6456 .setDiscardResult()
6457 .setTailCall(isTailCall);
6459 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6460 return CallResult.second;
6463 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6464 SDVTList VTList, ArrayRef<SDValue> Ops,
6465 MachineMemOperand *MMO) {
6466 FoldingSetNodeID ID;
6467 ID.AddInteger(MemVT.getRawBits());
6468 AddNodeIDNode(ID, Opcode, VTList, Ops);
6469 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6470 void* IP = nullptr;
6471 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6472 cast<AtomicSDNode>(E)->refineAlignment(MMO);
6473 return SDValue(E, 0);
6476 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6477 VTList, MemVT, MMO);
6478 createOperands(N, Ops);
6480 CSEMap.InsertNode(N, IP);
6481 InsertNode(N);
6482 return SDValue(N, 0);
6485 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
6486 EVT MemVT, SDVTList VTs, SDValue Chain,
6487 SDValue Ptr, SDValue Cmp, SDValue Swp,
6488 MachineMemOperand *MMO) {
6489 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
6490 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
6491 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
6493 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
6494 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6497 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6498 SDValue Chain, SDValue Ptr, SDValue Val,
6499 MachineMemOperand *MMO) {
6500 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
6501 Opcode == ISD::ATOMIC_LOAD_SUB ||
6502 Opcode == ISD::ATOMIC_LOAD_AND ||
6503 Opcode == ISD::ATOMIC_LOAD_CLR ||
6504 Opcode == ISD::ATOMIC_LOAD_OR ||
6505 Opcode == ISD::ATOMIC_LOAD_XOR ||
6506 Opcode == ISD::ATOMIC_LOAD_NAND ||
6507 Opcode == ISD::ATOMIC_LOAD_MIN ||
6508 Opcode == ISD::ATOMIC_LOAD_MAX ||
6509 Opcode == ISD::ATOMIC_LOAD_UMIN ||
6510 Opcode == ISD::ATOMIC_LOAD_UMAX ||
6511 Opcode == ISD::ATOMIC_LOAD_FADD ||
6512 Opcode == ISD::ATOMIC_LOAD_FSUB ||
6513 Opcode == ISD::ATOMIC_SWAP ||
6514 Opcode == ISD::ATOMIC_STORE) &&
6515 "Invalid Atomic Op");
6517 EVT VT = Val.getValueType();
6519 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
6520 getVTList(VT, MVT::Other);
6521 SDValue Ops[] = {Chain, Ptr, Val};
6522 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6525 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6526 EVT VT, SDValue Chain, SDValue Ptr,
6527 MachineMemOperand *MMO) {
6528 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
6530 SDVTList VTs = getVTList(VT, MVT::Other);
6531 SDValue Ops[] = {Chain, Ptr};
6532 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6535 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
6536 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
6537 if (Ops.size() == 1)
6538 return Ops[0];
6540 SmallVector<EVT, 4> VTs;
6541 VTs.reserve(Ops.size());
6542 for (unsigned i = 0; i < Ops.size(); ++i)
6543 VTs.push_back(Ops[i].getValueType());
6544 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
6547 SDValue SelectionDAG::getMemIntrinsicNode(
6548 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
6549 EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align,
6550 MachineMemOperand::Flags Flags, unsigned Size, const AAMDNodes &AAInfo) {
6551 if (Align == 0) // Ensure that codegen never sees alignment 0
6552 Align = getEVTAlignment(MemVT);
6554 if (!Size)
6555 Size = MemVT.getStoreSize();
6557 MachineFunction &MF = getMachineFunction();
6558 MachineMemOperand *MMO =
6559 MF.getMachineMemOperand(PtrInfo, Flags, Size, Align, AAInfo);
6561 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
6564 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
6565 SDVTList VTList,
6566 ArrayRef<SDValue> Ops, EVT MemVT,
6567 MachineMemOperand *MMO) {
6568 assert((Opcode == ISD::INTRINSIC_VOID ||
6569 Opcode == ISD::INTRINSIC_W_CHAIN ||
6570 Opcode == ISD::PREFETCH ||
6571 Opcode == ISD::LIFETIME_START ||
6572 Opcode == ISD::LIFETIME_END ||
6573 ((int)Opcode <= std::numeric_limits<int>::max() &&
6574 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
6575 "Opcode is not a memory-accessing opcode!");
6577 // Memoize the node unless it returns a flag.
6578 MemIntrinsicSDNode *N;
6579 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6580 FoldingSetNodeID ID;
6581 AddNodeIDNode(ID, Opcode, VTList, Ops);
6582 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
6583 Opcode, dl.getIROrder(), VTList, MemVT, MMO));
6584 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6585 void *IP = nullptr;
6586 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6587 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
6588 return SDValue(E, 0);
6591 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6592 VTList, MemVT, MMO);
6593 createOperands(N, Ops);
6595 CSEMap.InsertNode(N, IP);
6596 } else {
6597 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6598 VTList, MemVT, MMO);
6599 createOperands(N, Ops);
6601 InsertNode(N);
6602 SDValue V(N, 0);
6603 NewSDValueDbgMsg(V, "Creating new node: ", this);
6604 return V;
6607 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
6608 SDValue Chain, int FrameIndex,
6609 int64_t Size, int64_t Offset) {
6610 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
6611 const auto VTs = getVTList(MVT::Other);
6612 SDValue Ops[2] = {
6613 Chain,
6614 getFrameIndex(FrameIndex,
6615 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
6616 true)};
6618 FoldingSetNodeID ID;
6619 AddNodeIDNode(ID, Opcode, VTs, Ops);
6620 ID.AddInteger(FrameIndex);
6621 ID.AddInteger(Size);
6622 ID.AddInteger(Offset);
6623 void *IP = nullptr;
6624 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
6625 return SDValue(E, 0);
6627 LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
6628 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
6629 createOperands(N, Ops);
6630 CSEMap.InsertNode(N, IP);
6631 InsertNode(N);
6632 SDValue V(N, 0);
6633 NewSDValueDbgMsg(V, "Creating new node: ", this);
6634 return V;
6637 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
6638 /// MachinePointerInfo record from it. This is particularly useful because the
6639 /// code generator has many cases where it doesn't bother passing in a
6640 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
6641 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
6642 SelectionDAG &DAG, SDValue Ptr,
6643 int64_t Offset = 0) {
6644 // If this is FI+Offset, we can model it.
6645 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
6646 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
6647 FI->getIndex(), Offset);
6649 // If this is (FI+Offset1)+Offset2, we can model it.
6650 if (Ptr.getOpcode() != ISD::ADD ||
6651 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
6652 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
6653 return Info;
6655 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6656 return MachinePointerInfo::getFixedStack(
6657 DAG.getMachineFunction(), FI,
6658 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
6661 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
6662 /// MachinePointerInfo record from it. This is particularly useful because the
6663 /// code generator has many cases where it doesn't bother passing in a
6664 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
6665 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
6666 SelectionDAG &DAG, SDValue Ptr,
6667 SDValue OffsetOp) {
6668 // If the 'Offset' value isn't a constant, we can't handle this.
6669 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
6670 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
6671 if (OffsetOp.isUndef())
6672 return InferPointerInfo(Info, DAG, Ptr);
6673 return Info;
6676 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
6677 EVT VT, const SDLoc &dl, SDValue Chain,
6678 SDValue Ptr, SDValue Offset,
6679 MachinePointerInfo PtrInfo, EVT MemVT,
6680 unsigned Alignment,
6681 MachineMemOperand::Flags MMOFlags,
6682 const AAMDNodes &AAInfo, const MDNode *Ranges) {
6683 assert(Chain.getValueType() == MVT::Other &&
6684 "Invalid chain type");
6685 if (Alignment == 0) // Ensure that codegen never sees alignment 0
6686 Alignment = getEVTAlignment(MemVT);
6688 MMOFlags |= MachineMemOperand::MOLoad;
6689 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
6690 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
6691 // clients.
6692 if (PtrInfo.V.isNull())
6693 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
6695 MachineFunction &MF = getMachineFunction();
6696 MachineMemOperand *MMO = MF.getMachineMemOperand(
6697 PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
6698 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
6701 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
6702 EVT VT, const SDLoc &dl, SDValue Chain,
6703 SDValue Ptr, SDValue Offset, EVT MemVT,
6704 MachineMemOperand *MMO) {
6705 if (VT == MemVT) {
6706 ExtType = ISD::NON_EXTLOAD;
6707 } else if (ExtType == ISD::NON_EXTLOAD) {
6708 assert(VT == MemVT && "Non-extending load from different memory type!");
6709 } else {
6710 // Extending load.
6711 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
6712 "Should only be an extending load, not truncating!");
6713 assert(VT.isInteger() == MemVT.isInteger() &&
6714 "Cannot convert from FP to Int or Int -> FP!");
6715 assert(VT.isVector() == MemVT.isVector() &&
6716 "Cannot use an ext load to convert to or from a vector!");
6717 assert((!VT.isVector() ||
6718 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
6719 "Cannot use an ext load to change the number of vector elements!");
6722 bool Indexed = AM != ISD::UNINDEXED;
6723 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
6725 SDVTList VTs = Indexed ?
6726 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
6727 SDValue Ops[] = { Chain, Ptr, Offset };
6728 FoldingSetNodeID ID;
6729 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
6730 ID.AddInteger(MemVT.getRawBits());
6731 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
6732 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
6733 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6734 void *IP = nullptr;
6735 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6736 cast<LoadSDNode>(E)->refineAlignment(MMO);
6737 return SDValue(E, 0);
6739 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
6740 ExtType, MemVT, MMO);
6741 createOperands(N, Ops);
6743 CSEMap.InsertNode(N, IP);
6744 InsertNode(N);
6745 SDValue V(N, 0);
6746 NewSDValueDbgMsg(V, "Creating new node: ", this);
6747 return V;
6750 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6751 SDValue Ptr, MachinePointerInfo PtrInfo,
6752 unsigned Alignment,
6753 MachineMemOperand::Flags MMOFlags,
6754 const AAMDNodes &AAInfo, const MDNode *Ranges) {
6755 SDValue Undef = getUNDEF(Ptr.getValueType());
6756 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
6757 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
6760 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6761 SDValue Ptr, MachineMemOperand *MMO) {
6762 SDValue Undef = getUNDEF(Ptr.getValueType());
6763 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
6764 VT, MMO);
6767 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
6768 EVT VT, SDValue Chain, SDValue Ptr,
6769 MachinePointerInfo PtrInfo, EVT MemVT,
6770 unsigned Alignment,
6771 MachineMemOperand::Flags MMOFlags,
6772 const AAMDNodes &AAInfo) {
6773 SDValue Undef = getUNDEF(Ptr.getValueType());
6774 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
6775 MemVT, Alignment, MMOFlags, AAInfo);
6778 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
6779 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
6780 MachineMemOperand *MMO) {
6781 SDValue Undef = getUNDEF(Ptr.getValueType());
6782 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
6783 MemVT, MMO);
6786 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
6787 SDValue Base, SDValue Offset,
6788 ISD::MemIndexedMode AM) {
6789 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
6790 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
6791 // Don't propagate the invariant or dereferenceable flags.
6792 auto MMOFlags =
6793 LD->getMemOperand()->getFlags() &
6794 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
6795 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
6796 LD->getChain(), Base, Offset, LD->getPointerInfo(),
6797 LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
6798 LD->getAAInfo());
6801 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6802 SDValue Ptr, MachinePointerInfo PtrInfo,
6803 unsigned Alignment,
6804 MachineMemOperand::Flags MMOFlags,
6805 const AAMDNodes &AAInfo) {
6806 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
6807 if (Alignment == 0) // Ensure that codegen never sees alignment 0
6808 Alignment = getEVTAlignment(Val.getValueType());
6810 MMOFlags |= MachineMemOperand::MOStore;
6811 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
6813 if (PtrInfo.V.isNull())
6814 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
6816 MachineFunction &MF = getMachineFunction();
6817 MachineMemOperand *MMO = MF.getMachineMemOperand(
6818 PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
6819 return getStore(Chain, dl, Val, Ptr, MMO);
6822 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6823 SDValue Ptr, MachineMemOperand *MMO) {
6824 assert(Chain.getValueType() == MVT::Other &&
6825 "Invalid chain type");
6826 EVT VT = Val.getValueType();
6827 SDVTList VTs = getVTList(MVT::Other);
6828 SDValue Undef = getUNDEF(Ptr.getValueType());
6829 SDValue Ops[] = { Chain, Val, Ptr, Undef };
6830 FoldingSetNodeID ID;
6831 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6832 ID.AddInteger(VT.getRawBits());
6833 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
6834 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
6835 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6836 void *IP = nullptr;
6837 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6838 cast<StoreSDNode>(E)->refineAlignment(MMO);
6839 return SDValue(E, 0);
6841 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6842 ISD::UNINDEXED, false, VT, MMO);
6843 createOperands(N, Ops);
6845 CSEMap.InsertNode(N, IP);
6846 InsertNode(N);
6847 SDValue V(N, 0);
6848 NewSDValueDbgMsg(V, "Creating new node: ", this);
6849 return V;
6852 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6853 SDValue Ptr, MachinePointerInfo PtrInfo,
6854 EVT SVT, unsigned Alignment,
6855 MachineMemOperand::Flags MMOFlags,
6856 const AAMDNodes &AAInfo) {
6857 assert(Chain.getValueType() == MVT::Other &&
6858 "Invalid chain type");
6859 if (Alignment == 0) // Ensure that codegen never sees alignment 0
6860 Alignment = getEVTAlignment(SVT);
6862 MMOFlags |= MachineMemOperand::MOStore;
6863 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
6865 if (PtrInfo.V.isNull())
6866 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
6868 MachineFunction &MF = getMachineFunction();
6869 MachineMemOperand *MMO = MF.getMachineMemOperand(
6870 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
6871 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
6874 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6875 SDValue Ptr, EVT SVT,
6876 MachineMemOperand *MMO) {
6877 EVT VT = Val.getValueType();
6879 assert(Chain.getValueType() == MVT::Other &&
6880 "Invalid chain type");
6881 if (VT == SVT)
6882 return getStore(Chain, dl, Val, Ptr, MMO);
6884 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
6885 "Should only be a truncating store, not extending!");
6886 assert(VT.isInteger() == SVT.isInteger() &&
6887 "Can't do FP-INT conversion!");
6888 assert(VT.isVector() == SVT.isVector() &&
6889 "Cannot use trunc store to convert to or from a vector!");
6890 assert((!VT.isVector() ||
6891 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
6892 "Cannot use trunc store to change the number of vector elements!");
6894 SDVTList VTs = getVTList(MVT::Other);
6895 SDValue Undef = getUNDEF(Ptr.getValueType());
6896 SDValue Ops[] = { Chain, Val, Ptr, Undef };
6897 FoldingSetNodeID ID;
6898 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6899 ID.AddInteger(SVT.getRawBits());
6900 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
6901 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
6902 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6903 void *IP = nullptr;
6904 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6905 cast<StoreSDNode>(E)->refineAlignment(MMO);
6906 return SDValue(E, 0);
6908 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6909 ISD::UNINDEXED, true, SVT, MMO);
6910 createOperands(N, Ops);
6912 CSEMap.InsertNode(N, IP);
6913 InsertNode(N);
6914 SDValue V(N, 0);
6915 NewSDValueDbgMsg(V, "Creating new node: ", this);
6916 return V;
6919 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
6920 SDValue Base, SDValue Offset,
6921 ISD::MemIndexedMode AM) {
6922 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
6923 assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
6924 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
6925 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
6926 FoldingSetNodeID ID;
6927 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6928 ID.AddInteger(ST->getMemoryVT().getRawBits());
6929 ID.AddInteger(ST->getRawSubclassData());
6930 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
6931 void *IP = nullptr;
6932 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
6933 return SDValue(E, 0);
6935 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
6936 ST->isTruncatingStore(), ST->getMemoryVT(),
6937 ST->getMemOperand());
6938 createOperands(N, Ops);
6940 CSEMap.InsertNode(N, IP);
6941 InsertNode(N);
6942 SDValue V(N, 0);
6943 NewSDValueDbgMsg(V, "Creating new node: ", this);
6944 return V;
6947 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6948 SDValue Ptr, SDValue Mask, SDValue PassThru,
6949 EVT MemVT, MachineMemOperand *MMO,
6950 ISD::LoadExtType ExtTy, bool isExpanding) {
6951 SDVTList VTs = getVTList(VT, MVT::Other);
6952 SDValue Ops[] = { Chain, Ptr, Mask, PassThru };
6953 FoldingSetNodeID ID;
6954 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
6955 ID.AddInteger(MemVT.getRawBits());
6956 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
6957 dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
6958 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6959 void *IP = nullptr;
6960 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6961 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
6962 return SDValue(E, 0);
6964 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6965 ExtTy, isExpanding, MemVT, MMO);
6966 createOperands(N, Ops);
6968 CSEMap.InsertNode(N, IP);
6969 InsertNode(N);
6970 SDValue V(N, 0);
6971 NewSDValueDbgMsg(V, "Creating new node: ", this);
6972 return V;
6975 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
6976 SDValue Val, SDValue Ptr, SDValue Mask,
6977 EVT MemVT, MachineMemOperand *MMO,
6978 bool IsTruncating, bool IsCompressing) {
6979 assert(Chain.getValueType() == MVT::Other &&
6980 "Invalid chain type");
6981 SDVTList VTs = getVTList(MVT::Other);
6982 SDValue Ops[] = { Chain, Val, Ptr, Mask };
6983 FoldingSetNodeID ID;
6984 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
6985 ID.AddInteger(MemVT.getRawBits());
6986 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
6987 dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
6988 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6989 void *IP = nullptr;
6990 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6991 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
6992 return SDValue(E, 0);
6994 auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6995 IsTruncating, IsCompressing, MemVT, MMO);
6996 createOperands(N, Ops);
6998 CSEMap.InsertNode(N, IP);
6999 InsertNode(N);
7000 SDValue V(N, 0);
7001 NewSDValueDbgMsg(V, "Creating new node: ", this);
7002 return V;
7005 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
7006 ArrayRef<SDValue> Ops,
7007 MachineMemOperand *MMO,
7008 ISD::MemIndexType IndexType) {
7009 assert(Ops.size() == 6 && "Incompatible number of operands");
7011 FoldingSetNodeID ID;
7012 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
7013 ID.AddInteger(VT.getRawBits());
7014 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
7015 dl.getIROrder(), VTs, VT, MMO, IndexType));
7016 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7017 void *IP = nullptr;
7018 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7019 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
7020 return SDValue(E, 0);
7023 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7024 VTs, VT, MMO, IndexType);
7025 createOperands(N, Ops);
7027 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
7028 "Incompatible type of the PassThru value in MaskedGatherSDNode");
7029 assert(N->getMask().getValueType().getVectorNumElements() ==
7030 N->getValueType(0).getVectorNumElements() &&
7031 "Vector width mismatch between mask and data");
7032 assert(N->getIndex().getValueType().getVectorNumElements() >=
7033 N->getValueType(0).getVectorNumElements() &&
7034 "Vector width mismatch between index and data");
7035 assert(isa<ConstantSDNode>(N->getScale()) &&
7036 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7037 "Scale should be a constant power of 2");
7039 CSEMap.InsertNode(N, IP);
7040 InsertNode(N);
7041 SDValue V(N, 0);
7042 NewSDValueDbgMsg(V, "Creating new node: ", this);
7043 return V;
7046 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
7047 ArrayRef<SDValue> Ops,
7048 MachineMemOperand *MMO,
7049 ISD::MemIndexType IndexType) {
7050 assert(Ops.size() == 6 && "Incompatible number of operands");
7052 FoldingSetNodeID ID;
7053 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
7054 ID.AddInteger(VT.getRawBits());
7055 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
7056 dl.getIROrder(), VTs, VT, MMO, IndexType));
7057 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7058 void *IP = nullptr;
7059 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7060 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
7061 return SDValue(E, 0);
7063 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7064 VTs, VT, MMO, IndexType);
7065 createOperands(N, Ops);
7067 assert(N->getMask().getValueType().getVectorNumElements() ==
7068 N->getValue().getValueType().getVectorNumElements() &&
7069 "Vector width mismatch between mask and data");
7070 assert(N->getIndex().getValueType().getVectorNumElements() >=
7071 N->getValue().getValueType().getVectorNumElements() &&
7072 "Vector width mismatch between index and data");
7073 assert(isa<ConstantSDNode>(N->getScale()) &&
7074 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7075 "Scale should be a constant power of 2");
7077 CSEMap.InsertNode(N, IP);
7078 InsertNode(N);
7079 SDValue V(N, 0);
7080 NewSDValueDbgMsg(V, "Creating new node: ", this);
7081 return V;
7084 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
7085 // select undef, T, F --> T (if T is a constant), otherwise F
7086 // select, ?, undef, F --> F
7087 // select, ?, T, undef --> T
7088 if (Cond.isUndef())
7089 return isConstantValueOfAnyType(T) ? T : F;
7090 if (T.isUndef())
7091 return F;
7092 if (F.isUndef())
7093 return T;
7095 // select true, T, F --> T
7096 // select false, T, F --> F
7097 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
7098 return CondC->isNullValue() ? F : T;
7100 // TODO: This should simplify VSELECT with constant condition using something
7101 // like this (but check boolean contents to be complete?):
7102 // if (ISD::isBuildVectorAllOnes(Cond.getNode()))
7103 // return T;
7104 // if (ISD::isBuildVectorAllZeros(Cond.getNode()))
7105 // return F;
7107 // select ?, T, T --> T
7108 if (T == F)
7109 return T;
7111 return SDValue();
7114 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
7115 // shift undef, Y --> 0 (can always assume that the undef value is 0)
7116 if (X.isUndef())
7117 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
7118 // shift X, undef --> undef (because it may shift by the bitwidth)
7119 if (Y.isUndef())
7120 return getUNDEF(X.getValueType());
7122 // shift 0, Y --> 0
7123 // shift X, 0 --> X
7124 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
7125 return X;
7127 // shift X, C >= bitwidth(X) --> undef
7128 // All vector elements must be too big (or undef) to avoid partial undefs.
7129 auto isShiftTooBig = [X](ConstantSDNode *Val) {
7130 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
7132 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
7133 return getUNDEF(X.getValueType());
7135 return SDValue();
7138 // TODO: Use fast-math-flags to enable more simplifications.
7139 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y) {
7140 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
7141 if (!YC)
7142 return SDValue();
7144 // X + -0.0 --> X
7145 if (Opcode == ISD::FADD)
7146 if (YC->getValueAPF().isNegZero())
7147 return X;
7149 // X - +0.0 --> X
7150 if (Opcode == ISD::FSUB)
7151 if (YC->getValueAPF().isPosZero())
7152 return X;
7154 // X * 1.0 --> X
7155 // X / 1.0 --> X
7156 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
7157 if (YC->getValueAPF().isExactlyValue(1.0))
7158 return X;
7160 return SDValue();
7163 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
7164 SDValue Ptr, SDValue SV, unsigned Align) {
7165 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
7166 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
7169 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7170 ArrayRef<SDUse> Ops) {
7171 switch (Ops.size()) {
7172 case 0: return getNode(Opcode, DL, VT);
7173 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
7174 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
7175 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
7176 default: break;
7179 // Copy from an SDUse array into an SDValue array for use with
7180 // the regular getNode logic.
7181 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
7182 return getNode(Opcode, DL, VT, NewOps);
7185 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7186 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7187 unsigned NumOps = Ops.size();
7188 switch (NumOps) {
7189 case 0: return getNode(Opcode, DL, VT);
7190 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
7191 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
7192 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
7193 default: break;
7196 switch (Opcode) {
7197 default: break;
7198 case ISD::BUILD_VECTOR:
7199 // Attempt to simplify BUILD_VECTOR.
7200 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7201 return V;
7202 break;
7203 case ISD::CONCAT_VECTORS:
7204 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
7205 return V;
7206 break;
7207 case ISD::SELECT_CC:
7208 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
7209 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
7210 "LHS and RHS of condition must have same type!");
7211 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7212 "True and False arms of SelectCC must have same type!");
7213 assert(Ops[2].getValueType() == VT &&
7214 "select_cc node must be of same type as true and false value!");
7215 break;
7216 case ISD::BR_CC:
7217 assert(NumOps == 5 && "BR_CC takes 5 operands!");
7218 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7219 "LHS/RHS of comparison should match types!");
7220 break;
7223 // Memoize nodes.
7224 SDNode *N;
7225 SDVTList VTs = getVTList(VT);
7227 if (VT != MVT::Glue) {
7228 FoldingSetNodeID ID;
7229 AddNodeIDNode(ID, Opcode, VTs, Ops);
7230 void *IP = nullptr;
7232 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7233 return SDValue(E, 0);
7235 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7236 createOperands(N, Ops);
7238 CSEMap.InsertNode(N, IP);
7239 } else {
7240 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7241 createOperands(N, Ops);
7244 InsertNode(N);
7245 SDValue V(N, 0);
7246 NewSDValueDbgMsg(V, "Creating new node: ", this);
7247 return V;
7250 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7251 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
7252 return getNode(Opcode, DL, getVTList(ResultTys), Ops);
7255 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7256 ArrayRef<SDValue> Ops) {
7257 if (VTList.NumVTs == 1)
7258 return getNode(Opcode, DL, VTList.VTs[0], Ops);
7260 #if 0
7261 switch (Opcode) {
7262 // FIXME: figure out how to safely handle things like
7263 // int foo(int x) { return 1 << (x & 255); }
7264 // int bar() { return foo(256); }
7265 case ISD::SRA_PARTS:
7266 case ISD::SRL_PARTS:
7267 case ISD::SHL_PARTS:
7268 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7269 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
7270 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7271 else if (N3.getOpcode() == ISD::AND)
7272 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
7273 // If the and is only masking out bits that cannot effect the shift,
7274 // eliminate the and.
7275 unsigned NumBits = VT.getScalarSizeInBits()*2;
7276 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
7277 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7279 break;
7281 #endif
7283 // Memoize the node unless it returns a flag.
7284 SDNode *N;
7285 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7286 FoldingSetNodeID ID;
7287 AddNodeIDNode(ID, Opcode, VTList, Ops);
7288 void *IP = nullptr;
7289 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7290 return SDValue(E, 0);
7292 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7293 createOperands(N, Ops);
7294 CSEMap.InsertNode(N, IP);
7295 } else {
7296 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7297 createOperands(N, Ops);
7299 InsertNode(N);
7300 SDValue V(N, 0);
7301 NewSDValueDbgMsg(V, "Creating new node: ", this);
7302 return V;
7305 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7306 SDVTList VTList) {
7307 return getNode(Opcode, DL, VTList, None);
7310 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7311 SDValue N1) {
7312 SDValue Ops[] = { N1 };
7313 return getNode(Opcode, DL, VTList, Ops);
7316 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7317 SDValue N1, SDValue N2) {
7318 SDValue Ops[] = { N1, N2 };
7319 return getNode(Opcode, DL, VTList, Ops);
7322 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7323 SDValue N1, SDValue N2, SDValue N3) {
7324 SDValue Ops[] = { N1, N2, N3 };
7325 return getNode(Opcode, DL, VTList, Ops);
7328 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7329 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
7330 SDValue Ops[] = { N1, N2, N3, N4 };
7331 return getNode(Opcode, DL, VTList, Ops);
7334 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7335 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
7336 SDValue N5) {
7337 SDValue Ops[] = { N1, N2, N3, N4, N5 };
7338 return getNode(Opcode, DL, VTList, Ops);
7341 SDVTList SelectionDAG::getVTList(EVT VT) {
7342 return makeVTList(SDNode::getValueTypeList(VT), 1);
7345 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
7346 FoldingSetNodeID ID;
7347 ID.AddInteger(2U);
7348 ID.AddInteger(VT1.getRawBits());
7349 ID.AddInteger(VT2.getRawBits());
7351 void *IP = nullptr;
7352 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7353 if (!Result) {
7354 EVT *Array = Allocator.Allocate<EVT>(2);
7355 Array[0] = VT1;
7356 Array[1] = VT2;
7357 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
7358 VTListMap.InsertNode(Result, IP);
7360 return Result->getSDVTList();
7363 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
7364 FoldingSetNodeID ID;
7365 ID.AddInteger(3U);
7366 ID.AddInteger(VT1.getRawBits());
7367 ID.AddInteger(VT2.getRawBits());
7368 ID.AddInteger(VT3.getRawBits());
7370 void *IP = nullptr;
7371 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7372 if (!Result) {
7373 EVT *Array = Allocator.Allocate<EVT>(3);
7374 Array[0] = VT1;
7375 Array[1] = VT2;
7376 Array[2] = VT3;
7377 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
7378 VTListMap.InsertNode(Result, IP);
7380 return Result->getSDVTList();
7383 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
7384 FoldingSetNodeID ID;
7385 ID.AddInteger(4U);
7386 ID.AddInteger(VT1.getRawBits());
7387 ID.AddInteger(VT2.getRawBits());
7388 ID.AddInteger(VT3.getRawBits());
7389 ID.AddInteger(VT4.getRawBits());
7391 void *IP = nullptr;
7392 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7393 if (!Result) {
7394 EVT *Array = Allocator.Allocate<EVT>(4);
7395 Array[0] = VT1;
7396 Array[1] = VT2;
7397 Array[2] = VT3;
7398 Array[3] = VT4;
7399 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
7400 VTListMap.InsertNode(Result, IP);
7402 return Result->getSDVTList();
7405 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
7406 unsigned NumVTs = VTs.size();
7407 FoldingSetNodeID ID;
7408 ID.AddInteger(NumVTs);
7409 for (unsigned index = 0; index < NumVTs; index++) {
7410 ID.AddInteger(VTs[index].getRawBits());
7413 void *IP = nullptr;
7414 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7415 if (!Result) {
7416 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
7417 llvm::copy(VTs, Array);
7418 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
7419 VTListMap.InsertNode(Result, IP);
7421 return Result->getSDVTList();
7425 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
7426 /// specified operands. If the resultant node already exists in the DAG,
7427 /// this does not modify the specified node, instead it returns the node that
7428 /// already exists. If the resultant node does not exist in the DAG, the
7429 /// input node is returned. As a degenerate case, if you specify the same
7430 /// input operands as the node already has, the input node is returned.
7431 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
7432 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
7434 // Check to see if there is no change.
7435 if (Op == N->getOperand(0)) return N;
7437 // See if the modified node already exists.
7438 void *InsertPos = nullptr;
7439 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
7440 return Existing;
7442 // Nope it doesn't. Remove the node from its current place in the maps.
7443 if (InsertPos)
7444 if (!RemoveNodeFromCSEMaps(N))
7445 InsertPos = nullptr;
7447 // Now we update the operands.
7448 N->OperandList[0].set(Op);
7450 updateDivergence(N);
7451 // If this gets put into a CSE map, add it.
7452 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7453 return N;
7456 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
7457 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
7459 // Check to see if there is no change.
7460 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
7461 return N; // No operands changed, just return the input node.
7463 // See if the modified node already exists.
7464 void *InsertPos = nullptr;
7465 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
7466 return Existing;
7468 // Nope it doesn't. Remove the node from its current place in the maps.
7469 if (InsertPos)
7470 if (!RemoveNodeFromCSEMaps(N))
7471 InsertPos = nullptr;
7473 // Now we update the operands.
7474 if (N->OperandList[0] != Op1)
7475 N->OperandList[0].set(Op1);
7476 if (N->OperandList[1] != Op2)
7477 N->OperandList[1].set(Op2);
7479 updateDivergence(N);
7480 // If this gets put into a CSE map, add it.
7481 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7482 return N;
7485 SDNode *SelectionDAG::
7486 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
7487 SDValue Ops[] = { Op1, Op2, Op3 };
7488 return UpdateNodeOperands(N, Ops);
7491 SDNode *SelectionDAG::
7492 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
7493 SDValue Op3, SDValue Op4) {
7494 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
7495 return UpdateNodeOperands(N, Ops);
7498 SDNode *SelectionDAG::
7499 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
7500 SDValue Op3, SDValue Op4, SDValue Op5) {
7501 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
7502 return UpdateNodeOperands(N, Ops);
7505 SDNode *SelectionDAG::
7506 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
7507 unsigned NumOps = Ops.size();
7508 assert(N->getNumOperands() == NumOps &&
7509 "Update with wrong number of operands");
7511 // If no operands changed just return the input node.
7512 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
7513 return N;
7515 // See if the modified node already exists.
7516 void *InsertPos = nullptr;
7517 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
7518 return Existing;
7520 // Nope it doesn't. Remove the node from its current place in the maps.
7521 if (InsertPos)
7522 if (!RemoveNodeFromCSEMaps(N))
7523 InsertPos = nullptr;
7525 // Now we update the operands.
7526 for (unsigned i = 0; i != NumOps; ++i)
7527 if (N->OperandList[i] != Ops[i])
7528 N->OperandList[i].set(Ops[i]);
7530 updateDivergence(N);
7531 // If this gets put into a CSE map, add it.
7532 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7533 return N;
7536 /// DropOperands - Release the operands and set this node to have
7537 /// zero operands.
7538 void SDNode::DropOperands() {
7539 // Unlike the code in MorphNodeTo that does this, we don't need to
7540 // watch for dead nodes here.
7541 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
7542 SDUse &Use = *I++;
7543 Use.set(SDValue());
7547 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
7548 ArrayRef<MachineMemOperand *> NewMemRefs) {
7549 if (NewMemRefs.empty()) {
7550 N->clearMemRefs();
7551 return;
7554 // Check if we can avoid allocating by storing a single reference directly.
7555 if (NewMemRefs.size() == 1) {
7556 N->MemRefs = NewMemRefs[0];
7557 N->NumMemRefs = 1;
7558 return;
7561 MachineMemOperand **MemRefsBuffer =
7562 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
7563 llvm::copy(NewMemRefs, MemRefsBuffer);
7564 N->MemRefs = MemRefsBuffer;
7565 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
7568 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
7569 /// machine opcode.
7571 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7572 EVT VT) {
7573 SDVTList VTs = getVTList(VT);
7574 return SelectNodeTo(N, MachineOpc, VTs, None);
7577 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7578 EVT VT, SDValue Op1) {
7579 SDVTList VTs = getVTList(VT);
7580 SDValue Ops[] = { Op1 };
7581 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7584 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7585 EVT VT, SDValue Op1,
7586 SDValue Op2) {
7587 SDVTList VTs = getVTList(VT);
7588 SDValue Ops[] = { Op1, Op2 };
7589 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7592 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7593 EVT VT, SDValue Op1,
7594 SDValue Op2, SDValue Op3) {
7595 SDVTList VTs = getVTList(VT);
7596 SDValue Ops[] = { Op1, Op2, Op3 };
7597 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7600 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7601 EVT VT, ArrayRef<SDValue> Ops) {
7602 SDVTList VTs = getVTList(VT);
7603 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7606 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7607 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
7608 SDVTList VTs = getVTList(VT1, VT2);
7609 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7612 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7613 EVT VT1, EVT VT2) {
7614 SDVTList VTs = getVTList(VT1, VT2);
7615 return SelectNodeTo(N, MachineOpc, VTs, None);
7618 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7619 EVT VT1, EVT VT2, EVT VT3,
7620 ArrayRef<SDValue> Ops) {
7621 SDVTList VTs = getVTList(VT1, VT2, VT3);
7622 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7625 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7626 EVT VT1, EVT VT2,
7627 SDValue Op1, SDValue Op2) {
7628 SDVTList VTs = getVTList(VT1, VT2);
7629 SDValue Ops[] = { Op1, Op2 };
7630 return SelectNodeTo(N, MachineOpc, VTs, Ops);
7633 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7634 SDVTList VTs,ArrayRef<SDValue> Ops) {
7635 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
7636 // Reset the NodeID to -1.
7637 New->setNodeId(-1);
7638 if (New != N) {
7639 ReplaceAllUsesWith(N, New);
7640 RemoveDeadNode(N);
7642 return New;
7645 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
7646 /// the line number information on the merged node since it is not possible to
7647 /// preserve the information that operation is associated with multiple lines.
7648 /// This will make the debugger working better at -O0, were there is a higher
7649 /// probability having other instructions associated with that line.
7651 /// For IROrder, we keep the smaller of the two
7652 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
7653 DebugLoc NLoc = N->getDebugLoc();
7654 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
7655 N->setDebugLoc(DebugLoc());
7657 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
7658 N->setIROrder(Order);
7659 return N;
7662 /// MorphNodeTo - This *mutates* the specified node to have the specified
7663 /// return type, opcode, and operands.
7665 /// Note that MorphNodeTo returns the resultant node. If there is already a
7666 /// node of the specified opcode and operands, it returns that node instead of
7667 /// the current one. Note that the SDLoc need not be the same.
7669 /// Using MorphNodeTo is faster than creating a new node and swapping it in
7670 /// with ReplaceAllUsesWith both because it often avoids allocating a new
7671 /// node, and because it doesn't require CSE recalculation for any of
7672 /// the node's users.
7674 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
7675 /// As a consequence it isn't appropriate to use from within the DAG combiner or
7676 /// the legalizer which maintain worklists that would need to be updated when
7677 /// deleting things.
7678 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
7679 SDVTList VTs, ArrayRef<SDValue> Ops) {
7680 // If an identical node already exists, use it.
7681 void *IP = nullptr;
7682 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
7683 FoldingSetNodeID ID;
7684 AddNodeIDNode(ID, Opc, VTs, Ops);
7685 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
7686 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
7689 if (!RemoveNodeFromCSEMaps(N))
7690 IP = nullptr;
7692 // Start the morphing.
7693 N->NodeType = Opc;
7694 N->ValueList = VTs.VTs;
7695 N->NumValues = VTs.NumVTs;
7697 // Clear the operands list, updating used nodes to remove this from their
7698 // use list. Keep track of any operands that become dead as a result.
7699 SmallPtrSet<SDNode*, 16> DeadNodeSet;
7700 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
7701 SDUse &Use = *I++;
7702 SDNode *Used = Use.getNode();
7703 Use.set(SDValue());
7704 if (Used->use_empty())
7705 DeadNodeSet.insert(Used);
7708 // For MachineNode, initialize the memory references information.
7709 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
7710 MN->clearMemRefs();
7712 // Swap for an appropriately sized array from the recycler.
7713 removeOperands(N);
7714 createOperands(N, Ops);
7716 // Delete any nodes that are still dead after adding the uses for the
7717 // new operands.
7718 if (!DeadNodeSet.empty()) {
7719 SmallVector<SDNode *, 16> DeadNodes;
7720 for (SDNode *N : DeadNodeSet)
7721 if (N->use_empty())
7722 DeadNodes.push_back(N);
7723 RemoveDeadNodes(DeadNodes);
7726 if (IP)
7727 CSEMap.InsertNode(N, IP); // Memoize the new node.
7728 return N;
7731 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
7732 unsigned OrigOpc = Node->getOpcode();
7733 unsigned NewOpc;
7734 switch (OrigOpc) {
7735 default:
7736 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
7737 case ISD::STRICT_FADD: NewOpc = ISD::FADD; break;
7738 case ISD::STRICT_FSUB: NewOpc = ISD::FSUB; break;
7739 case ISD::STRICT_FMUL: NewOpc = ISD::FMUL; break;
7740 case ISD::STRICT_FDIV: NewOpc = ISD::FDIV; break;
7741 case ISD::STRICT_FREM: NewOpc = ISD::FREM; break;
7742 case ISD::STRICT_FMA: NewOpc = ISD::FMA; break;
7743 case ISD::STRICT_FSQRT: NewOpc = ISD::FSQRT; break;
7744 case ISD::STRICT_FPOW: NewOpc = ISD::FPOW; break;
7745 case ISD::STRICT_FPOWI: NewOpc = ISD::FPOWI; break;
7746 case ISD::STRICT_FSIN: NewOpc = ISD::FSIN; break;
7747 case ISD::STRICT_FCOS: NewOpc = ISD::FCOS; break;
7748 case ISD::STRICT_FEXP: NewOpc = ISD::FEXP; break;
7749 case ISD::STRICT_FEXP2: NewOpc = ISD::FEXP2; break;
7750 case ISD::STRICT_FLOG: NewOpc = ISD::FLOG; break;
7751 case ISD::STRICT_FLOG10: NewOpc = ISD::FLOG10; break;
7752 case ISD::STRICT_FLOG2: NewOpc = ISD::FLOG2; break;
7753 case ISD::STRICT_FRINT: NewOpc = ISD::FRINT; break;
7754 case ISD::STRICT_FNEARBYINT: NewOpc = ISD::FNEARBYINT; break;
7755 case ISD::STRICT_FMAXNUM: NewOpc = ISD::FMAXNUM; break;
7756 case ISD::STRICT_FMINNUM: NewOpc = ISD::FMINNUM; break;
7757 case ISD::STRICT_FCEIL: NewOpc = ISD::FCEIL; break;
7758 case ISD::STRICT_FFLOOR: NewOpc = ISD::FFLOOR; break;
7759 case ISD::STRICT_FROUND: NewOpc = ISD::FROUND; break;
7760 case ISD::STRICT_FTRUNC: NewOpc = ISD::FTRUNC; break;
7761 case ISD::STRICT_FP_ROUND: NewOpc = ISD::FP_ROUND; break;
7762 case ISD::STRICT_FP_EXTEND: NewOpc = ISD::FP_EXTEND; break;
7763 case ISD::STRICT_FP_TO_SINT: NewOpc = ISD::FP_TO_SINT; break;
7764 case ISD::STRICT_FP_TO_UINT: NewOpc = ISD::FP_TO_UINT; break;
7767 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
7769 // We're taking this node out of the chain, so we need to re-link things.
7770 SDValue InputChain = Node->getOperand(0);
7771 SDValue OutputChain = SDValue(Node, 1);
7772 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
7774 SmallVector<SDValue, 3> Ops;
7775 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
7776 Ops.push_back(Node->getOperand(i));
7778 SDVTList VTs = getVTList(Node->getValueType(0));
7779 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
7781 // MorphNodeTo can operate in two ways: if an existing node with the
7782 // specified operands exists, it can just return it. Otherwise, it
7783 // updates the node in place to have the requested operands.
7784 if (Res == Node) {
7785 // If we updated the node in place, reset the node ID. To the isel,
7786 // this should be just like a newly allocated machine node.
7787 Res->setNodeId(-1);
7788 } else {
7789 ReplaceAllUsesWith(Node, Res);
7790 RemoveDeadNode(Node);
7793 return Res;
7796 /// getMachineNode - These are used for target selectors to create a new node
7797 /// with specified return type(s), MachineInstr opcode, and operands.
7799 /// Note that getMachineNode returns the resultant node. If there is already a
7800 /// node of the specified opcode and operands, it returns that node instead of
7801 /// the current one.
7802 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7803 EVT VT) {
7804 SDVTList VTs = getVTList(VT);
7805 return getMachineNode(Opcode, dl, VTs, None);
7808 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7809 EVT VT, SDValue Op1) {
7810 SDVTList VTs = getVTList(VT);
7811 SDValue Ops[] = { Op1 };
7812 return getMachineNode(Opcode, dl, VTs, Ops);
7815 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7816 EVT VT, SDValue Op1, SDValue Op2) {
7817 SDVTList VTs = getVTList(VT);
7818 SDValue Ops[] = { Op1, Op2 };
7819 return getMachineNode(Opcode, dl, VTs, Ops);
7822 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7823 EVT VT, SDValue Op1, SDValue Op2,
7824 SDValue Op3) {
7825 SDVTList VTs = getVTList(VT);
7826 SDValue Ops[] = { Op1, Op2, Op3 };
7827 return getMachineNode(Opcode, dl, VTs, Ops);
7830 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7831 EVT VT, ArrayRef<SDValue> Ops) {
7832 SDVTList VTs = getVTList(VT);
7833 return getMachineNode(Opcode, dl, VTs, Ops);
7836 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7837 EVT VT1, EVT VT2, SDValue Op1,
7838 SDValue Op2) {
7839 SDVTList VTs = getVTList(VT1, VT2);
7840 SDValue Ops[] = { Op1, Op2 };
7841 return getMachineNode(Opcode, dl, VTs, Ops);
7844 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7845 EVT VT1, EVT VT2, SDValue Op1,
7846 SDValue Op2, SDValue Op3) {
7847 SDVTList VTs = getVTList(VT1, VT2);
7848 SDValue Ops[] = { Op1, Op2, Op3 };
7849 return getMachineNode(Opcode, dl, VTs, Ops);
7852 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7853 EVT VT1, EVT VT2,
7854 ArrayRef<SDValue> Ops) {
7855 SDVTList VTs = getVTList(VT1, VT2);
7856 return getMachineNode(Opcode, dl, VTs, Ops);
7859 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7860 EVT VT1, EVT VT2, EVT VT3,
7861 SDValue Op1, SDValue Op2) {
7862 SDVTList VTs = getVTList(VT1, VT2, VT3);
7863 SDValue Ops[] = { Op1, Op2 };
7864 return getMachineNode(Opcode, dl, VTs, Ops);
7867 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7868 EVT VT1, EVT VT2, EVT VT3,
7869 SDValue Op1, SDValue Op2,
7870 SDValue Op3) {
7871 SDVTList VTs = getVTList(VT1, VT2, VT3);
7872 SDValue Ops[] = { Op1, Op2, Op3 };
7873 return getMachineNode(Opcode, dl, VTs, Ops);
7876 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7877 EVT VT1, EVT VT2, EVT VT3,
7878 ArrayRef<SDValue> Ops) {
7879 SDVTList VTs = getVTList(VT1, VT2, VT3);
7880 return getMachineNode(Opcode, dl, VTs, Ops);
7883 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7884 ArrayRef<EVT> ResultTys,
7885 ArrayRef<SDValue> Ops) {
7886 SDVTList VTs = getVTList(ResultTys);
7887 return getMachineNode(Opcode, dl, VTs, Ops);
7890 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
7891 SDVTList VTs,
7892 ArrayRef<SDValue> Ops) {
7893 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
7894 MachineSDNode *N;
7895 void *IP = nullptr;
7897 if (DoCSE) {
7898 FoldingSetNodeID ID;
7899 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
7900 IP = nullptr;
7901 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
7902 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
7906 // Allocate a new MachineSDNode.
7907 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7908 createOperands(N, Ops);
7910 if (DoCSE)
7911 CSEMap.InsertNode(N, IP);
7913 InsertNode(N);
7914 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
7915 return N;
7918 /// getTargetExtractSubreg - A convenience function for creating
7919 /// TargetOpcode::EXTRACT_SUBREG nodes.
7920 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
7921 SDValue Operand) {
7922 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
7923 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
7924 VT, Operand, SRIdxVal);
7925 return SDValue(Subreg, 0);
7928 /// getTargetInsertSubreg - A convenience function for creating
7929 /// TargetOpcode::INSERT_SUBREG nodes.
7930 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
7931 SDValue Operand, SDValue Subreg) {
7932 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
7933 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
7934 VT, Operand, Subreg, SRIdxVal);
7935 return SDValue(Result, 0);
7938 /// getNodeIfExists - Get the specified node if it's already available, or
7939 /// else return NULL.
7940 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
7941 ArrayRef<SDValue> Ops,
7942 const SDNodeFlags Flags) {
7943 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
7944 FoldingSetNodeID ID;
7945 AddNodeIDNode(ID, Opcode, VTList, Ops);
7946 void *IP = nullptr;
7947 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
7948 E->intersectFlagsWith(Flags);
7949 return E;
7952 return nullptr;
7955 /// getDbgValue - Creates a SDDbgValue node.
7957 /// SDNode
7958 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
7959 SDNode *N, unsigned R, bool IsIndirect,
7960 const DebugLoc &DL, unsigned O) {
7961 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7962 "Expected inlined-at fields to agree");
7963 return new (DbgInfo->getAlloc())
7964 SDDbgValue(Var, Expr, N, R, IsIndirect, DL, O);
7967 /// Constant
7968 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
7969 DIExpression *Expr,
7970 const Value *C,
7971 const DebugLoc &DL, unsigned O) {
7972 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7973 "Expected inlined-at fields to agree");
7974 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, DL, O);
7977 /// FrameIndex
7978 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
7979 DIExpression *Expr, unsigned FI,
7980 bool IsIndirect,
7981 const DebugLoc &DL,
7982 unsigned O) {
7983 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7984 "Expected inlined-at fields to agree");
7985 return new (DbgInfo->getAlloc())
7986 SDDbgValue(Var, Expr, FI, IsIndirect, DL, O, SDDbgValue::FRAMEIX);
7989 /// VReg
7990 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var,
7991 DIExpression *Expr,
7992 unsigned VReg, bool IsIndirect,
7993 const DebugLoc &DL, unsigned O) {
7994 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7995 "Expected inlined-at fields to agree");
7996 return new (DbgInfo->getAlloc())
7997 SDDbgValue(Var, Expr, VReg, IsIndirect, DL, O, SDDbgValue::VREG);
8000 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
8001 unsigned OffsetInBits, unsigned SizeInBits,
8002 bool InvalidateDbg) {
8003 SDNode *FromNode = From.getNode();
8004 SDNode *ToNode = To.getNode();
8005 assert(FromNode && ToNode && "Can't modify dbg values");
8007 // PR35338
8008 // TODO: assert(From != To && "Redundant dbg value transfer");
8009 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
8010 if (From == To || FromNode == ToNode)
8011 return;
8013 if (!FromNode->getHasDebugValue())
8014 return;
8016 SmallVector<SDDbgValue *, 2> ClonedDVs;
8017 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
8018 if (Dbg->getKind() != SDDbgValue::SDNODE || Dbg->isInvalidated())
8019 continue;
8021 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
8023 // Just transfer the dbg value attached to From.
8024 if (Dbg->getResNo() != From.getResNo())
8025 continue;
8027 DIVariable *Var = Dbg->getVariable();
8028 auto *Expr = Dbg->getExpression();
8029 // If a fragment is requested, update the expression.
8030 if (SizeInBits) {
8031 // When splitting a larger (e.g., sign-extended) value whose
8032 // lower bits are described with an SDDbgValue, do not attempt
8033 // to transfer the SDDbgValue to the upper bits.
8034 if (auto FI = Expr->getFragmentInfo())
8035 if (OffsetInBits + SizeInBits > FI->SizeInBits)
8036 continue;
8037 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
8038 SizeInBits);
8039 if (!Fragment)
8040 continue;
8041 Expr = *Fragment;
8043 // Clone the SDDbgValue and move it to To.
8044 SDDbgValue *Clone =
8045 getDbgValue(Var, Expr, ToNode, To.getResNo(), Dbg->isIndirect(),
8046 Dbg->getDebugLoc(), Dbg->getOrder());
8047 ClonedDVs.push_back(Clone);
8049 if (InvalidateDbg) {
8050 // Invalidate value and indicate the SDDbgValue should not be emitted.
8051 Dbg->setIsInvalidated();
8052 Dbg->setIsEmitted();
8056 for (SDDbgValue *Dbg : ClonedDVs)
8057 AddDbgValue(Dbg, ToNode, false);
8060 void SelectionDAG::salvageDebugInfo(SDNode &N) {
8061 if (!N.getHasDebugValue())
8062 return;
8064 SmallVector<SDDbgValue *, 2> ClonedDVs;
8065 for (auto DV : GetDbgValues(&N)) {
8066 if (DV->isInvalidated())
8067 continue;
8068 switch (N.getOpcode()) {
8069 default:
8070 break;
8071 case ISD::ADD:
8072 SDValue N0 = N.getOperand(0);
8073 SDValue N1 = N.getOperand(1);
8074 if (!isConstantIntBuildVectorOrConstantInt(N0) &&
8075 isConstantIntBuildVectorOrConstantInt(N1)) {
8076 uint64_t Offset = N.getConstantOperandVal(1);
8077 // Rewrite an ADD constant node into a DIExpression. Since we are
8078 // performing arithmetic to compute the variable's *value* in the
8079 // DIExpression, we need to mark the expression with a
8080 // DW_OP_stack_value.
8081 auto *DIExpr = DV->getExpression();
8082 DIExpr =
8083 DIExpression::prepend(DIExpr, DIExpression::StackValue, Offset);
8084 SDDbgValue *Clone =
8085 getDbgValue(DV->getVariable(), DIExpr, N0.getNode(), N0.getResNo(),
8086 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder());
8087 ClonedDVs.push_back(Clone);
8088 DV->setIsInvalidated();
8089 DV->setIsEmitted();
8090 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
8091 N0.getNode()->dumprFull(this);
8092 dbgs() << " into " << *DIExpr << '\n');
8097 for (SDDbgValue *Dbg : ClonedDVs)
8098 AddDbgValue(Dbg, Dbg->getSDNode(), false);
8101 /// Creates a SDDbgLabel node.
8102 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
8103 const DebugLoc &DL, unsigned O) {
8104 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
8105 "Expected inlined-at fields to agree");
8106 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
8109 namespace {
8111 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
8112 /// pointed to by a use iterator is deleted, increment the use iterator
8113 /// so that it doesn't dangle.
8115 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
8116 SDNode::use_iterator &UI;
8117 SDNode::use_iterator &UE;
8119 void NodeDeleted(SDNode *N, SDNode *E) override {
8120 // Increment the iterator as needed.
8121 while (UI != UE && N == *UI)
8122 ++UI;
8125 public:
8126 RAUWUpdateListener(SelectionDAG &d,
8127 SDNode::use_iterator &ui,
8128 SDNode::use_iterator &ue)
8129 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
8132 } // end anonymous namespace
8134 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8135 /// This can cause recursive merging of nodes in the DAG.
8137 /// This version assumes From has a single result value.
8139 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
8140 SDNode *From = FromN.getNode();
8141 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
8142 "Cannot replace with this method!");
8143 assert(From != To.getNode() && "Cannot replace uses of with self");
8145 // Preserve Debug Values
8146 transferDbgValues(FromN, To);
8148 // Iterate over all the existing uses of From. New uses will be added
8149 // to the beginning of the use list, which we avoid visiting.
8150 // This specifically avoids visiting uses of From that arise while the
8151 // replacement is happening, because any such uses would be the result
8152 // of CSE: If an existing node looks like From after one of its operands
8153 // is replaced by To, we don't want to replace of all its users with To
8154 // too. See PR3018 for more info.
8155 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8156 RAUWUpdateListener Listener(*this, UI, UE);
8157 while (UI != UE) {
8158 SDNode *User = *UI;
8160 // This node is about to morph, remove its old self from the CSE maps.
8161 RemoveNodeFromCSEMaps(User);
8163 // A user can appear in a use list multiple times, and when this
8164 // happens the uses are usually next to each other in the list.
8165 // To help reduce the number of CSE recomputations, process all
8166 // the uses of this user that we can find this way.
8167 do {
8168 SDUse &Use = UI.getUse();
8169 ++UI;
8170 Use.set(To);
8171 if (To->isDivergent() != From->isDivergent())
8172 updateDivergence(User);
8173 } while (UI != UE && *UI == User);
8174 // Now that we have modified User, add it back to the CSE maps. If it
8175 // already exists there, recursively merge the results together.
8176 AddModifiedNodeToCSEMaps(User);
8179 // If we just RAUW'd the root, take note.
8180 if (FromN == getRoot())
8181 setRoot(To);
8184 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8185 /// This can cause recursive merging of nodes in the DAG.
8187 /// This version assumes that for each value of From, there is a
8188 /// corresponding value in To in the same position with the same type.
8190 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
8191 #ifndef NDEBUG
8192 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8193 assert((!From->hasAnyUseOfValue(i) ||
8194 From->getValueType(i) == To->getValueType(i)) &&
8195 "Cannot use this version of ReplaceAllUsesWith!");
8196 #endif
8198 // Handle the trivial case.
8199 if (From == To)
8200 return;
8202 // Preserve Debug Info. Only do this if there's a use.
8203 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8204 if (From->hasAnyUseOfValue(i)) {
8205 assert((i < To->getNumValues()) && "Invalid To location");
8206 transferDbgValues(SDValue(From, i), SDValue(To, i));
8209 // Iterate over just the existing users of From. See the comments in
8210 // the ReplaceAllUsesWith above.
8211 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8212 RAUWUpdateListener Listener(*this, UI, UE);
8213 while (UI != UE) {
8214 SDNode *User = *UI;
8216 // This node is about to morph, remove its old self from the CSE maps.
8217 RemoveNodeFromCSEMaps(User);
8219 // A user can appear in a use list multiple times, and when this
8220 // happens the uses are usually next to each other in the list.
8221 // To help reduce the number of CSE recomputations, process all
8222 // the uses of this user that we can find this way.
8223 do {
8224 SDUse &Use = UI.getUse();
8225 ++UI;
8226 Use.setNode(To);
8227 if (To->isDivergent() != From->isDivergent())
8228 updateDivergence(User);
8229 } while (UI != UE && *UI == User);
8231 // Now that we have modified User, add it back to the CSE maps. If it
8232 // already exists there, recursively merge the results together.
8233 AddModifiedNodeToCSEMaps(User);
8236 // If we just RAUW'd the root, take note.
8237 if (From == getRoot().getNode())
8238 setRoot(SDValue(To, getRoot().getResNo()));
8241 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8242 /// This can cause recursive merging of nodes in the DAG.
8244 /// This version can replace From with any result values. To must match the
8245 /// number and types of values returned by From.
8246 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
8247 if (From->getNumValues() == 1) // Handle the simple case efficiently.
8248 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
8250 // Preserve Debug Info.
8251 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8252 transferDbgValues(SDValue(From, i), To[i]);
8254 // Iterate over just the existing users of From. See the comments in
8255 // the ReplaceAllUsesWith above.
8256 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8257 RAUWUpdateListener Listener(*this, UI, UE);
8258 while (UI != UE) {
8259 SDNode *User = *UI;
8261 // This node is about to morph, remove its old self from the CSE maps.
8262 RemoveNodeFromCSEMaps(User);
8264 // A user can appear in a use list multiple times, and when this happens the
8265 // uses are usually next to each other in the list. To help reduce the
8266 // number of CSE and divergence recomputations, process all the uses of this
8267 // user that we can find this way.
8268 bool To_IsDivergent = false;
8269 do {
8270 SDUse &Use = UI.getUse();
8271 const SDValue &ToOp = To[Use.getResNo()];
8272 ++UI;
8273 Use.set(ToOp);
8274 To_IsDivergent |= ToOp->isDivergent();
8275 } while (UI != UE && *UI == User);
8277 if (To_IsDivergent != From->isDivergent())
8278 updateDivergence(User);
8280 // Now that we have modified User, add it back to the CSE maps. If it
8281 // already exists there, recursively merge the results together.
8282 AddModifiedNodeToCSEMaps(User);
8285 // If we just RAUW'd the root, take note.
8286 if (From == getRoot().getNode())
8287 setRoot(SDValue(To[getRoot().getResNo()]));
8290 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
8291 /// uses of other values produced by From.getNode() alone. The Deleted
8292 /// vector is handled the same way as for ReplaceAllUsesWith.
8293 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
8294 // Handle the really simple, really trivial case efficiently.
8295 if (From == To) return;
8297 // Handle the simple, trivial, case efficiently.
8298 if (From.getNode()->getNumValues() == 1) {
8299 ReplaceAllUsesWith(From, To);
8300 return;
8303 // Preserve Debug Info.
8304 transferDbgValues(From, To);
8306 // Iterate over just the existing users of From. See the comments in
8307 // the ReplaceAllUsesWith above.
8308 SDNode::use_iterator UI = From.getNode()->use_begin(),
8309 UE = From.getNode()->use_end();
8310 RAUWUpdateListener Listener(*this, UI, UE);
8311 while (UI != UE) {
8312 SDNode *User = *UI;
8313 bool UserRemovedFromCSEMaps = false;
8315 // A user can appear in a use list multiple times, and when this
8316 // happens the uses are usually next to each other in the list.
8317 // To help reduce the number of CSE recomputations, process all
8318 // the uses of this user that we can find this way.
8319 do {
8320 SDUse &Use = UI.getUse();
8322 // Skip uses of different values from the same node.
8323 if (Use.getResNo() != From.getResNo()) {
8324 ++UI;
8325 continue;
8328 // If this node hasn't been modified yet, it's still in the CSE maps,
8329 // so remove its old self from the CSE maps.
8330 if (!UserRemovedFromCSEMaps) {
8331 RemoveNodeFromCSEMaps(User);
8332 UserRemovedFromCSEMaps = true;
8335 ++UI;
8336 Use.set(To);
8337 if (To->isDivergent() != From->isDivergent())
8338 updateDivergence(User);
8339 } while (UI != UE && *UI == User);
8340 // We are iterating over all uses of the From node, so if a use
8341 // doesn't use the specific value, no changes are made.
8342 if (!UserRemovedFromCSEMaps)
8343 continue;
8345 // Now that we have modified User, add it back to the CSE maps. If it
8346 // already exists there, recursively merge the results together.
8347 AddModifiedNodeToCSEMaps(User);
8350 // If we just RAUW'd the root, take note.
8351 if (From == getRoot())
8352 setRoot(To);
8355 namespace {
8357 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
8358 /// to record information about a use.
8359 struct UseMemo {
8360 SDNode *User;
8361 unsigned Index;
8362 SDUse *Use;
8365 /// operator< - Sort Memos by User.
8366 bool operator<(const UseMemo &L, const UseMemo &R) {
8367 return (intptr_t)L.User < (intptr_t)R.User;
8370 } // end anonymous namespace
8372 void SelectionDAG::updateDivergence(SDNode * N)
8374 if (TLI->isSDNodeAlwaysUniform(N))
8375 return;
8376 bool IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
8377 for (auto &Op : N->ops()) {
8378 if (Op.Val.getValueType() != MVT::Other)
8379 IsDivergent |= Op.getNode()->isDivergent();
8381 if (N->SDNodeBits.IsDivergent != IsDivergent) {
8382 N->SDNodeBits.IsDivergent = IsDivergent;
8383 for (auto U : N->uses()) {
8384 updateDivergence(U);
8389 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
8390 DenseMap<SDNode *, unsigned> Degree;
8391 Order.reserve(AllNodes.size());
8392 for (auto &N : allnodes()) {
8393 unsigned NOps = N.getNumOperands();
8394 Degree[&N] = NOps;
8395 if (0 == NOps)
8396 Order.push_back(&N);
8398 for (size_t I = 0; I != Order.size(); ++I) {
8399 SDNode *N = Order[I];
8400 for (auto U : N->uses()) {
8401 unsigned &UnsortedOps = Degree[U];
8402 if (0 == --UnsortedOps)
8403 Order.push_back(U);
8408 #ifndef NDEBUG
8409 void SelectionDAG::VerifyDAGDiverence() {
8410 std::vector<SDNode *> TopoOrder;
8411 CreateTopologicalOrder(TopoOrder);
8412 const TargetLowering &TLI = getTargetLoweringInfo();
8413 DenseMap<const SDNode *, bool> DivergenceMap;
8414 for (auto &N : allnodes()) {
8415 DivergenceMap[&N] = false;
8417 for (auto N : TopoOrder) {
8418 bool IsDivergent = DivergenceMap[N];
8419 bool IsSDNodeDivergent = TLI.isSDNodeSourceOfDivergence(N, FLI, DA);
8420 for (auto &Op : N->ops()) {
8421 if (Op.Val.getValueType() != MVT::Other)
8422 IsSDNodeDivergent |= DivergenceMap[Op.getNode()];
8424 if (!IsDivergent && IsSDNodeDivergent && !TLI.isSDNodeAlwaysUniform(N)) {
8425 DivergenceMap[N] = true;
8428 for (auto &N : allnodes()) {
8429 (void)N;
8430 assert(DivergenceMap[&N] == N.isDivergent() &&
8431 "Divergence bit inconsistency detected\n");
8434 #endif
8436 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
8437 /// uses of other values produced by From.getNode() alone. The same value
8438 /// may appear in both the From and To list. The Deleted vector is
8439 /// handled the same way as for ReplaceAllUsesWith.
8440 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
8441 const SDValue *To,
8442 unsigned Num){
8443 // Handle the simple, trivial case efficiently.
8444 if (Num == 1)
8445 return ReplaceAllUsesOfValueWith(*From, *To);
8447 transferDbgValues(*From, *To);
8449 // Read up all the uses and make records of them. This helps
8450 // processing new uses that are introduced during the
8451 // replacement process.
8452 SmallVector<UseMemo, 4> Uses;
8453 for (unsigned i = 0; i != Num; ++i) {
8454 unsigned FromResNo = From[i].getResNo();
8455 SDNode *FromNode = From[i].getNode();
8456 for (SDNode::use_iterator UI = FromNode->use_begin(),
8457 E = FromNode->use_end(); UI != E; ++UI) {
8458 SDUse &Use = UI.getUse();
8459 if (Use.getResNo() == FromResNo) {
8460 UseMemo Memo = { *UI, i, &Use };
8461 Uses.push_back(Memo);
8466 // Sort the uses, so that all the uses from a given User are together.
8467 llvm::sort(Uses);
8469 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
8470 UseIndex != UseIndexEnd; ) {
8471 // We know that this user uses some value of From. If it is the right
8472 // value, update it.
8473 SDNode *User = Uses[UseIndex].User;
8475 // This node is about to morph, remove its old self from the CSE maps.
8476 RemoveNodeFromCSEMaps(User);
8478 // The Uses array is sorted, so all the uses for a given User
8479 // are next to each other in the list.
8480 // To help reduce the number of CSE recomputations, process all
8481 // the uses of this user that we can find this way.
8482 do {
8483 unsigned i = Uses[UseIndex].Index;
8484 SDUse &Use = *Uses[UseIndex].Use;
8485 ++UseIndex;
8487 Use.set(To[i]);
8488 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
8490 // Now that we have modified User, add it back to the CSE maps. If it
8491 // already exists there, recursively merge the results together.
8492 AddModifiedNodeToCSEMaps(User);
8496 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
8497 /// based on their topological order. It returns the maximum id and a vector
8498 /// of the SDNodes* in assigned order by reference.
8499 unsigned SelectionDAG::AssignTopologicalOrder() {
8500 unsigned DAGSize = 0;
8502 // SortedPos tracks the progress of the algorithm. Nodes before it are
8503 // sorted, nodes after it are unsorted. When the algorithm completes
8504 // it is at the end of the list.
8505 allnodes_iterator SortedPos = allnodes_begin();
8507 // Visit all the nodes. Move nodes with no operands to the front of
8508 // the list immediately. Annotate nodes that do have operands with their
8509 // operand count. Before we do this, the Node Id fields of the nodes
8510 // may contain arbitrary values. After, the Node Id fields for nodes
8511 // before SortedPos will contain the topological sort index, and the
8512 // Node Id fields for nodes At SortedPos and after will contain the
8513 // count of outstanding operands.
8514 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
8515 SDNode *N = &*I++;
8516 checkForCycles(N, this);
8517 unsigned Degree = N->getNumOperands();
8518 if (Degree == 0) {
8519 // A node with no uses, add it to the result array immediately.
8520 N->setNodeId(DAGSize++);
8521 allnodes_iterator Q(N);
8522 if (Q != SortedPos)
8523 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
8524 assert(SortedPos != AllNodes.end() && "Overran node list");
8525 ++SortedPos;
8526 } else {
8527 // Temporarily use the Node Id as scratch space for the degree count.
8528 N->setNodeId(Degree);
8532 // Visit all the nodes. As we iterate, move nodes into sorted order,
8533 // such that by the time the end is reached all nodes will be sorted.
8534 for (SDNode &Node : allnodes()) {
8535 SDNode *N = &Node;
8536 checkForCycles(N, this);
8537 // N is in sorted position, so all its uses have one less operand
8538 // that needs to be sorted.
8539 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8540 UI != UE; ++UI) {
8541 SDNode *P = *UI;
8542 unsigned Degree = P->getNodeId();
8543 assert(Degree != 0 && "Invalid node degree");
8544 --Degree;
8545 if (Degree == 0) {
8546 // All of P's operands are sorted, so P may sorted now.
8547 P->setNodeId(DAGSize++);
8548 if (P->getIterator() != SortedPos)
8549 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
8550 assert(SortedPos != AllNodes.end() && "Overran node list");
8551 ++SortedPos;
8552 } else {
8553 // Update P's outstanding operand count.
8554 P->setNodeId(Degree);
8557 if (Node.getIterator() == SortedPos) {
8558 #ifndef NDEBUG
8559 allnodes_iterator I(N);
8560 SDNode *S = &*++I;
8561 dbgs() << "Overran sorted position:\n";
8562 S->dumprFull(this); dbgs() << "\n";
8563 dbgs() << "Checking if this is due to cycles\n";
8564 checkForCycles(this, true);
8565 #endif
8566 llvm_unreachable(nullptr);
8570 assert(SortedPos == AllNodes.end() &&
8571 "Topological sort incomplete!");
8572 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
8573 "First node in topological sort is not the entry token!");
8574 assert(AllNodes.front().getNodeId() == 0 &&
8575 "First node in topological sort has non-zero id!");
8576 assert(AllNodes.front().getNumOperands() == 0 &&
8577 "First node in topological sort has operands!");
8578 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
8579 "Last node in topologic sort has unexpected id!");
8580 assert(AllNodes.back().use_empty() &&
8581 "Last node in topologic sort has users!");
8582 assert(DAGSize == allnodes_size() && "Node count mismatch!");
8583 return DAGSize;
8586 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
8587 /// value is produced by SD.
8588 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
8589 if (SD) {
8590 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
8591 SD->setHasDebugValue(true);
8593 DbgInfo->add(DB, SD, isParameter);
8596 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) {
8597 DbgInfo->add(DB);
8600 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
8601 SDValue NewMemOp) {
8602 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
8603 // The new memory operation must have the same position as the old load in
8604 // terms of memory dependency. Create a TokenFactor for the old load and new
8605 // memory operation and update uses of the old load's output chain to use that
8606 // TokenFactor.
8607 SDValue OldChain = SDValue(OldLoad, 1);
8608 SDValue NewChain = SDValue(NewMemOp.getNode(), 1);
8609 if (OldChain == NewChain || !OldLoad->hasAnyUseOfValue(1))
8610 return NewChain;
8612 SDValue TokenFactor =
8613 getNode(ISD::TokenFactor, SDLoc(OldLoad), MVT::Other, OldChain, NewChain);
8614 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
8615 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain);
8616 return TokenFactor;
8619 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
8620 Function **OutFunction) {
8621 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
8623 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8624 auto *Module = MF->getFunction().getParent();
8625 auto *Function = Module->getFunction(Symbol);
8627 if (OutFunction != nullptr)
8628 *OutFunction = Function;
8630 if (Function != nullptr) {
8631 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
8632 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
8635 std::string ErrorStr;
8636 raw_string_ostream ErrorFormatter(ErrorStr);
8638 ErrorFormatter << "Undefined external symbol ";
8639 ErrorFormatter << '"' << Symbol << '"';
8640 ErrorFormatter.flush();
8642 report_fatal_error(ErrorStr);
8645 //===----------------------------------------------------------------------===//
8646 // SDNode Class
8647 //===----------------------------------------------------------------------===//
8649 bool llvm::isNullConstant(SDValue V) {
8650 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8651 return Const != nullptr && Const->isNullValue();
8654 bool llvm::isNullFPConstant(SDValue V) {
8655 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
8656 return Const != nullptr && Const->isZero() && !Const->isNegative();
8659 bool llvm::isAllOnesConstant(SDValue V) {
8660 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8661 return Const != nullptr && Const->isAllOnesValue();
8664 bool llvm::isOneConstant(SDValue V) {
8665 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8666 return Const != nullptr && Const->isOne();
8669 SDValue llvm::peekThroughBitcasts(SDValue V) {
8670 while (V.getOpcode() == ISD::BITCAST)
8671 V = V.getOperand(0);
8672 return V;
8675 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
8676 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
8677 V = V.getOperand(0);
8678 return V;
8681 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
8682 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8683 V = V.getOperand(0);
8684 return V;
8687 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
8688 if (V.getOpcode() != ISD::XOR)
8689 return false;
8690 V = peekThroughBitcasts(V.getOperand(1));
8691 unsigned NumBits = V.getScalarValueSizeInBits();
8692 ConstantSDNode *C =
8693 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
8694 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
8697 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
8698 bool AllowTruncation) {
8699 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
8700 return CN;
8702 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8703 BitVector UndefElements;
8704 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
8706 // BuildVectors can truncate their operands. Ignore that case here unless
8707 // AllowTruncation is set.
8708 if (CN && (UndefElements.none() || AllowUndefs)) {
8709 EVT CVT = CN->getValueType(0);
8710 EVT NSVT = N.getValueType().getScalarType();
8711 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
8712 if (AllowTruncation || (CVT == NSVT))
8713 return CN;
8717 return nullptr;
8720 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
8721 bool AllowUndefs,
8722 bool AllowTruncation) {
8723 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
8724 return CN;
8726 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8727 BitVector UndefElements;
8728 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
8730 // BuildVectors can truncate their operands. Ignore that case here unless
8731 // AllowTruncation is set.
8732 if (CN && (UndefElements.none() || AllowUndefs)) {
8733 EVT CVT = CN->getValueType(0);
8734 EVT NSVT = N.getValueType().getScalarType();
8735 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
8736 if (AllowTruncation || (CVT == NSVT))
8737 return CN;
8741 return nullptr;
8744 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
8745 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
8746 return CN;
8748 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8749 BitVector UndefElements;
8750 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
8751 if (CN && (UndefElements.none() || AllowUndefs))
8752 return CN;
8755 return nullptr;
8758 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
8759 const APInt &DemandedElts,
8760 bool AllowUndefs) {
8761 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
8762 return CN;
8764 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8765 BitVector UndefElements;
8766 ConstantFPSDNode *CN =
8767 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
8768 if (CN && (UndefElements.none() || AllowUndefs))
8769 return CN;
8772 return nullptr;
8775 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
8776 // TODO: may want to use peekThroughBitcast() here.
8777 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
8778 return C && C->isNullValue();
8781 bool llvm::isOneOrOneSplat(SDValue N) {
8782 // TODO: may want to use peekThroughBitcast() here.
8783 unsigned BitWidth = N.getScalarValueSizeInBits();
8784 ConstantSDNode *C = isConstOrConstSplat(N);
8785 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
8788 bool llvm::isAllOnesOrAllOnesSplat(SDValue N) {
8789 N = peekThroughBitcasts(N);
8790 unsigned BitWidth = N.getScalarValueSizeInBits();
8791 ConstantSDNode *C = isConstOrConstSplat(N);
8792 return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
8795 HandleSDNode::~HandleSDNode() {
8796 DropOperands();
8799 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
8800 const DebugLoc &DL,
8801 const GlobalValue *GA, EVT VT,
8802 int64_t o, unsigned TF)
8803 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
8804 TheGlobal = GA;
8807 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
8808 EVT VT, unsigned SrcAS,
8809 unsigned DestAS)
8810 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
8811 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
8813 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
8814 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
8815 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
8816 MemSDNodeBits.IsVolatile = MMO->isVolatile();
8817 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
8818 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
8819 MemSDNodeBits.IsInvariant = MMO->isInvariant();
8821 // We check here that the size of the memory operand fits within the size of
8822 // the MMO. This is because the MMO might indicate only a possible address
8823 // range instead of specifying the affected memory addresses precisely.
8824 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
8827 /// Profile - Gather unique data for the node.
8829 void SDNode::Profile(FoldingSetNodeID &ID) const {
8830 AddNodeIDNode(ID, this);
8833 namespace {
8835 struct EVTArray {
8836 std::vector<EVT> VTs;
8838 EVTArray() {
8839 VTs.reserve(MVT::LAST_VALUETYPE);
8840 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
8841 VTs.push_back(MVT((MVT::SimpleValueType)i));
8845 } // end anonymous namespace
8847 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
8848 static ManagedStatic<EVTArray> SimpleVTArray;
8849 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
8851 /// getValueTypeList - Return a pointer to the specified value type.
8853 const EVT *SDNode::getValueTypeList(EVT VT) {
8854 if (VT.isExtended()) {
8855 sys::SmartScopedLock<true> Lock(*VTMutex);
8856 return &(*EVTs->insert(VT).first);
8857 } else {
8858 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
8859 "Value type out of range!");
8860 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
8864 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
8865 /// indicated value. This method ignores uses of other values defined by this
8866 /// operation.
8867 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
8868 assert(Value < getNumValues() && "Bad value!");
8870 // TODO: Only iterate over uses of a given value of the node
8871 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
8872 if (UI.getUse().getResNo() == Value) {
8873 if (NUses == 0)
8874 return false;
8875 --NUses;
8879 // Found exactly the right number of uses?
8880 return NUses == 0;
8883 /// hasAnyUseOfValue - Return true if there are any use of the indicated
8884 /// value. This method ignores uses of other values defined by this operation.
8885 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
8886 assert(Value < getNumValues() && "Bad value!");
8888 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
8889 if (UI.getUse().getResNo() == Value)
8890 return true;
8892 return false;
8895 /// isOnlyUserOf - Return true if this node is the only use of N.
8896 bool SDNode::isOnlyUserOf(const SDNode *N) const {
8897 bool Seen = false;
8898 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
8899 SDNode *User = *I;
8900 if (User == this)
8901 Seen = true;
8902 else
8903 return false;
8906 return Seen;
8909 /// Return true if the only users of N are contained in Nodes.
8910 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
8911 bool Seen = false;
8912 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
8913 SDNode *User = *I;
8914 if (llvm::any_of(Nodes,
8915 [&User](const SDNode *Node) { return User == Node; }))
8916 Seen = true;
8917 else
8918 return false;
8921 return Seen;
8924 /// isOperand - Return true if this node is an operand of N.
8925 bool SDValue::isOperandOf(const SDNode *N) const {
8926 return any_of(N->op_values(), [this](SDValue Op) { return *this == Op; });
8929 bool SDNode::isOperandOf(const SDNode *N) const {
8930 return any_of(N->op_values(),
8931 [this](SDValue Op) { return this == Op.getNode(); });
8934 /// reachesChainWithoutSideEffects - Return true if this operand (which must
8935 /// be a chain) reaches the specified operand without crossing any
8936 /// side-effecting instructions on any chain path. In practice, this looks
8937 /// through token factors and non-volatile loads. In order to remain efficient,
8938 /// this only looks a couple of nodes in, it does not do an exhaustive search.
8940 /// Note that we only need to examine chains when we're searching for
8941 /// side-effects; SelectionDAG requires that all side-effects are represented
8942 /// by chains, even if another operand would force a specific ordering. This
8943 /// constraint is necessary to allow transformations like splitting loads.
8944 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
8945 unsigned Depth) const {
8946 if (*this == Dest) return true;
8948 // Don't search too deeply, we just want to be able to see through
8949 // TokenFactor's etc.
8950 if (Depth == 0) return false;
8952 // If this is a token factor, all inputs to the TF happen in parallel.
8953 if (getOpcode() == ISD::TokenFactor) {
8954 // First, try a shallow search.
8955 if (is_contained((*this)->ops(), Dest)) {
8956 // We found the chain we want as an operand of this TokenFactor.
8957 // Essentially, we reach the chain without side-effects if we could
8958 // serialize the TokenFactor into a simple chain of operations with
8959 // Dest as the last operation. This is automatically true if the
8960 // chain has one use: there are no other ordering constraints.
8961 // If the chain has more than one use, we give up: some other
8962 // use of Dest might force a side-effect between Dest and the current
8963 // node.
8964 if (Dest.hasOneUse())
8965 return true;
8967 // Next, try a deep search: check whether every operand of the TokenFactor
8968 // reaches Dest.
8969 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
8970 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
8974 // Loads don't have side effects, look through them.
8975 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
8976 if (!Ld->isVolatile())
8977 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
8979 return false;
8982 bool SDNode::hasPredecessor(const SDNode *N) const {
8983 SmallPtrSet<const SDNode *, 32> Visited;
8984 SmallVector<const SDNode *, 16> Worklist;
8985 Worklist.push_back(this);
8986 return hasPredecessorHelper(N, Visited, Worklist);
8989 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
8990 this->Flags.intersectWith(Flags);
8993 SDValue
8994 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
8995 ArrayRef<ISD::NodeType> CandidateBinOps,
8996 bool AllowPartials) {
8997 // The pattern must end in an extract from index 0.
8998 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8999 !isNullConstant(Extract->getOperand(1)))
9000 return SDValue();
9002 // Match against one of the candidate binary ops.
9003 SDValue Op = Extract->getOperand(0);
9004 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
9005 return Op.getOpcode() == unsigned(BinOp);
9007 return SDValue();
9009 // Floating-point reductions may require relaxed constraints on the final step
9010 // of the reduction because they may reorder intermediate operations.
9011 unsigned CandidateBinOp = Op.getOpcode();
9012 if (Op.getValueType().isFloatingPoint()) {
9013 SDNodeFlags Flags = Op->getFlags();
9014 switch (CandidateBinOp) {
9015 case ISD::FADD:
9016 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
9017 return SDValue();
9018 break;
9019 default:
9020 llvm_unreachable("Unhandled FP opcode for binop reduction");
9024 // Matching failed - attempt to see if we did enough stages that a partial
9025 // reduction from a subvector is possible.
9026 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
9027 if (!AllowPartials || !Op)
9028 return SDValue();
9029 EVT OpVT = Op.getValueType();
9030 EVT OpSVT = OpVT.getScalarType();
9031 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
9032 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
9033 return SDValue();
9034 BinOp = (ISD::NodeType)CandidateBinOp;
9035 return getNode(
9036 ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
9037 getConstant(0, SDLoc(Op), TLI->getVectorIdxTy(getDataLayout())));
9040 // At each stage, we're looking for something that looks like:
9041 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
9042 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
9043 // i32 undef, i32 undef, i32 undef, i32 undef>
9044 // %a = binop <8 x i32> %op, %s
9045 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
9046 // we expect something like:
9047 // <4,5,6,7,u,u,u,u>
9048 // <2,3,u,u,u,u,u,u>
9049 // <1,u,u,u,u,u,u,u>
9050 // While a partial reduction match would be:
9051 // <2,3,u,u,u,u,u,u>
9052 // <1,u,u,u,u,u,u,u>
9053 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
9054 SDValue PrevOp;
9055 for (unsigned i = 0; i < Stages; ++i) {
9056 unsigned MaskEnd = (1 << i);
9058 if (Op.getOpcode() != CandidateBinOp)
9059 return PartialReduction(PrevOp, MaskEnd);
9061 SDValue Op0 = Op.getOperand(0);
9062 SDValue Op1 = Op.getOperand(1);
9064 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
9065 if (Shuffle) {
9066 Op = Op1;
9067 } else {
9068 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
9069 Op = Op0;
9072 // The first operand of the shuffle should be the same as the other operand
9073 // of the binop.
9074 if (!Shuffle || Shuffle->getOperand(0) != Op)
9075 return PartialReduction(PrevOp, MaskEnd);
9077 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
9078 for (int Index = 0; Index < (int)MaskEnd; ++Index)
9079 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
9080 return PartialReduction(PrevOp, MaskEnd);
9082 PrevOp = Op;
9085 BinOp = (ISD::NodeType)CandidateBinOp;
9086 return Op;
9089 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
9090 assert(N->getNumValues() == 1 &&
9091 "Can't unroll a vector with multiple results!");
9093 EVT VT = N->getValueType(0);
9094 unsigned NE = VT.getVectorNumElements();
9095 EVT EltVT = VT.getVectorElementType();
9096 SDLoc dl(N);
9098 SmallVector<SDValue, 8> Scalars;
9099 SmallVector<SDValue, 4> Operands(N->getNumOperands());
9101 // If ResNE is 0, fully unroll the vector op.
9102 if (ResNE == 0)
9103 ResNE = NE;
9104 else if (NE > ResNE)
9105 NE = ResNE;
9107 unsigned i;
9108 for (i= 0; i != NE; ++i) {
9109 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
9110 SDValue Operand = N->getOperand(j);
9111 EVT OperandVT = Operand.getValueType();
9112 if (OperandVT.isVector()) {
9113 // A vector operand; extract a single element.
9114 EVT OperandEltVT = OperandVT.getVectorElementType();
9115 Operands[j] =
9116 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
9117 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
9118 } else {
9119 // A scalar operand; just use it as is.
9120 Operands[j] = Operand;
9124 switch (N->getOpcode()) {
9125 default: {
9126 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
9127 N->getFlags()));
9128 break;
9130 case ISD::VSELECT:
9131 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
9132 break;
9133 case ISD::SHL:
9134 case ISD::SRA:
9135 case ISD::SRL:
9136 case ISD::ROTL:
9137 case ISD::ROTR:
9138 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
9139 getShiftAmountOperand(Operands[0].getValueType(),
9140 Operands[1])));
9141 break;
9142 case ISD::SIGN_EXTEND_INREG: {
9143 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
9144 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
9145 Operands[0],
9146 getValueType(ExtVT)));
9151 for (; i < ResNE; ++i)
9152 Scalars.push_back(getUNDEF(EltVT));
9154 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
9155 return getBuildVector(VecVT, dl, Scalars);
9158 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
9159 SDNode *N, unsigned ResNE) {
9160 unsigned Opcode = N->getOpcode();
9161 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
9162 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
9163 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
9164 "Expected an overflow opcode");
9166 EVT ResVT = N->getValueType(0);
9167 EVT OvVT = N->getValueType(1);
9168 EVT ResEltVT = ResVT.getVectorElementType();
9169 EVT OvEltVT = OvVT.getVectorElementType();
9170 SDLoc dl(N);
9172 // If ResNE is 0, fully unroll the vector op.
9173 unsigned NE = ResVT.getVectorNumElements();
9174 if (ResNE == 0)
9175 ResNE = NE;
9176 else if (NE > ResNE)
9177 NE = ResNE;
9179 SmallVector<SDValue, 8> LHSScalars;
9180 SmallVector<SDValue, 8> RHSScalars;
9181 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
9182 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
9184 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
9185 SDVTList VTs = getVTList(ResEltVT, SVT);
9186 SmallVector<SDValue, 8> ResScalars;
9187 SmallVector<SDValue, 8> OvScalars;
9188 for (unsigned i = 0; i < NE; ++i) {
9189 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
9190 SDValue Ov =
9191 getSelect(dl, OvEltVT, Res.getValue(1),
9192 getBoolConstant(true, dl, OvEltVT, ResVT),
9193 getConstant(0, dl, OvEltVT));
9195 ResScalars.push_back(Res);
9196 OvScalars.push_back(Ov);
9199 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
9200 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
9202 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
9203 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
9204 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
9205 getBuildVector(NewOvVT, dl, OvScalars));
9208 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
9209 LoadSDNode *Base,
9210 unsigned Bytes,
9211 int Dist) const {
9212 if (LD->isVolatile() || Base->isVolatile())
9213 return false;
9214 if (LD->isIndexed() || Base->isIndexed())
9215 return false;
9216 if (LD->getChain() != Base->getChain())
9217 return false;
9218 EVT VT = LD->getValueType(0);
9219 if (VT.getSizeInBits() / 8 != Bytes)
9220 return false;
9222 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
9223 auto LocDecomp = BaseIndexOffset::match(LD, *this);
9225 int64_t Offset = 0;
9226 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
9227 return (Dist * Bytes == Offset);
9228 return false;
9231 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
9232 /// it cannot be inferred.
9233 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
9234 // If this is a GlobalAddress + cst, return the alignment.
9235 const GlobalValue *GV;
9236 int64_t GVOffset = 0;
9237 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
9238 unsigned IdxWidth = getDataLayout().getIndexTypeSizeInBits(GV->getType());
9239 KnownBits Known(IdxWidth);
9240 llvm::computeKnownBits(GV, Known, getDataLayout());
9241 unsigned AlignBits = Known.countMinTrailingZeros();
9242 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
9243 if (Align)
9244 return MinAlign(Align, GVOffset);
9247 // If this is a direct reference to a stack slot, use information about the
9248 // stack slot's alignment.
9249 int FrameIdx = INT_MIN;
9250 int64_t FrameOffset = 0;
9251 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
9252 FrameIdx = FI->getIndex();
9253 } else if (isBaseWithConstantOffset(Ptr) &&
9254 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
9255 // Handle FI+Cst
9256 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
9257 FrameOffset = Ptr.getConstantOperandVal(1);
9260 if (FrameIdx != INT_MIN) {
9261 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
9262 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
9263 FrameOffset);
9264 return FIInfoAlign;
9267 return 0;
9270 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
9271 /// which is split (or expanded) into two not necessarily identical pieces.
9272 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
9273 // Currently all types are split in half.
9274 EVT LoVT, HiVT;
9275 if (!VT.isVector())
9276 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
9277 else
9278 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
9280 return std::make_pair(LoVT, HiVT);
9283 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
9284 /// low/high part.
9285 std::pair<SDValue, SDValue>
9286 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
9287 const EVT &HiVT) {
9288 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
9289 N.getValueType().getVectorNumElements() &&
9290 "More vector elements requested than available!");
9291 SDValue Lo, Hi;
9292 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
9293 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
9294 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
9295 getConstant(LoVT.getVectorNumElements(), DL,
9296 TLI->getVectorIdxTy(getDataLayout())));
9297 return std::make_pair(Lo, Hi);
9300 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
9301 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
9302 EVT VT = N.getValueType();
9303 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
9304 NextPowerOf2(VT.getVectorNumElements()));
9305 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
9306 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
9309 void SelectionDAG::ExtractVectorElements(SDValue Op,
9310 SmallVectorImpl<SDValue> &Args,
9311 unsigned Start, unsigned Count) {
9312 EVT VT = Op.getValueType();
9313 if (Count == 0)
9314 Count = VT.getVectorNumElements();
9316 EVT EltVT = VT.getVectorElementType();
9317 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
9318 SDLoc SL(Op);
9319 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
9320 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9321 Op, getConstant(i, SL, IdxTy)));
9325 // getAddressSpace - Return the address space this GlobalAddress belongs to.
9326 unsigned GlobalAddressSDNode::getAddressSpace() const {
9327 return getGlobal()->getType()->getAddressSpace();
9330 Type *ConstantPoolSDNode::getType() const {
9331 if (isMachineConstantPoolEntry())
9332 return Val.MachineCPVal->getType();
9333 return Val.ConstVal->getType();
9336 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
9337 unsigned &SplatBitSize,
9338 bool &HasAnyUndefs,
9339 unsigned MinSplatBits,
9340 bool IsBigEndian) const {
9341 EVT VT = getValueType(0);
9342 assert(VT.isVector() && "Expected a vector type");
9343 unsigned VecWidth = VT.getSizeInBits();
9344 if (MinSplatBits > VecWidth)
9345 return false;
9347 // FIXME: The widths are based on this node's type, but build vectors can
9348 // truncate their operands.
9349 SplatValue = APInt(VecWidth, 0);
9350 SplatUndef = APInt(VecWidth, 0);
9352 // Get the bits. Bits with undefined values (when the corresponding element
9353 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
9354 // in SplatValue. If any of the values are not constant, give up and return
9355 // false.
9356 unsigned int NumOps = getNumOperands();
9357 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
9358 unsigned EltWidth = VT.getScalarSizeInBits();
9360 for (unsigned j = 0; j < NumOps; ++j) {
9361 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
9362 SDValue OpVal = getOperand(i);
9363 unsigned BitPos = j * EltWidth;
9365 if (OpVal.isUndef())
9366 SplatUndef.setBits(BitPos, BitPos + EltWidth);
9367 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
9368 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
9369 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
9370 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
9371 else
9372 return false;
9375 // The build_vector is all constants or undefs. Find the smallest element
9376 // size that splats the vector.
9377 HasAnyUndefs = (SplatUndef != 0);
9379 // FIXME: This does not work for vectors with elements less than 8 bits.
9380 while (VecWidth > 8) {
9381 unsigned HalfSize = VecWidth / 2;
9382 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
9383 APInt LowValue = SplatValue.trunc(HalfSize);
9384 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
9385 APInt LowUndef = SplatUndef.trunc(HalfSize);
9387 // If the two halves do not match (ignoring undef bits), stop here.
9388 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
9389 MinSplatBits > HalfSize)
9390 break;
9392 SplatValue = HighValue | LowValue;
9393 SplatUndef = HighUndef & LowUndef;
9395 VecWidth = HalfSize;
9398 SplatBitSize = VecWidth;
9399 return true;
9402 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
9403 BitVector *UndefElements) const {
9404 if (UndefElements) {
9405 UndefElements->clear();
9406 UndefElements->resize(getNumOperands());
9408 assert(getNumOperands() == DemandedElts.getBitWidth() &&
9409 "Unexpected vector size");
9410 if (!DemandedElts)
9411 return SDValue();
9412 SDValue Splatted;
9413 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
9414 if (!DemandedElts[i])
9415 continue;
9416 SDValue Op = getOperand(i);
9417 if (Op.isUndef()) {
9418 if (UndefElements)
9419 (*UndefElements)[i] = true;
9420 } else if (!Splatted) {
9421 Splatted = Op;
9422 } else if (Splatted != Op) {
9423 return SDValue();
9427 if (!Splatted) {
9428 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
9429 assert(getOperand(FirstDemandedIdx).isUndef() &&
9430 "Can only have a splat without a constant for all undefs.");
9431 return getOperand(FirstDemandedIdx);
9434 return Splatted;
9437 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
9438 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
9439 return getSplatValue(DemandedElts, UndefElements);
9442 ConstantSDNode *
9443 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
9444 BitVector *UndefElements) const {
9445 return dyn_cast_or_null<ConstantSDNode>(
9446 getSplatValue(DemandedElts, UndefElements));
9449 ConstantSDNode *
9450 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
9451 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
9454 ConstantFPSDNode *
9455 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
9456 BitVector *UndefElements) const {
9457 return dyn_cast_or_null<ConstantFPSDNode>(
9458 getSplatValue(DemandedElts, UndefElements));
9461 ConstantFPSDNode *
9462 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
9463 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
9466 int32_t
9467 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
9468 uint32_t BitWidth) const {
9469 if (ConstantFPSDNode *CN =
9470 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
9471 bool IsExact;
9472 APSInt IntVal(BitWidth);
9473 const APFloat &APF = CN->getValueAPF();
9474 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
9475 APFloat::opOK ||
9476 !IsExact)
9477 return -1;
9479 return IntVal.exactLogBase2();
9481 return -1;
9484 bool BuildVectorSDNode::isConstant() const {
9485 for (const SDValue &Op : op_values()) {
9486 unsigned Opc = Op.getOpcode();
9487 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
9488 return false;
9490 return true;
9493 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
9494 // Find the first non-undef value in the shuffle mask.
9495 unsigned i, e;
9496 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
9497 /* search */;
9499 // If all elements are undefined, this shuffle can be considered a splat
9500 // (although it should eventually get simplified away completely).
9501 if (i == e)
9502 return true;
9504 // Make sure all remaining elements are either undef or the same as the first
9505 // non-undef value.
9506 for (int Idx = Mask[i]; i != e; ++i)
9507 if (Mask[i] >= 0 && Mask[i] != Idx)
9508 return false;
9509 return true;
9512 // Returns the SDNode if it is a constant integer BuildVector
9513 // or constant integer.
9514 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
9515 if (isa<ConstantSDNode>(N))
9516 return N.getNode();
9517 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
9518 return N.getNode();
9519 // Treat a GlobalAddress supporting constant offset folding as a
9520 // constant integer.
9521 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
9522 if (GA->getOpcode() == ISD::GlobalAddress &&
9523 TLI->isOffsetFoldingLegal(GA))
9524 return GA;
9525 return nullptr;
9528 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
9529 if (isa<ConstantFPSDNode>(N))
9530 return N.getNode();
9532 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
9533 return N.getNode();
9535 return nullptr;
9538 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
9539 assert(!Node->OperandList && "Node already has operands");
9540 assert(SDNode::getMaxNumOperands() >= Vals.size() &&
9541 "too many operands to fit into SDNode");
9542 SDUse *Ops = OperandRecycler.allocate(
9543 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
9545 bool IsDivergent = false;
9546 for (unsigned I = 0; I != Vals.size(); ++I) {
9547 Ops[I].setUser(Node);
9548 Ops[I].setInitial(Vals[I]);
9549 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
9550 IsDivergent = IsDivergent || Ops[I].getNode()->isDivergent();
9552 Node->NumOperands = Vals.size();
9553 Node->OperandList = Ops;
9554 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
9555 if (!TLI->isSDNodeAlwaysUniform(Node))
9556 Node->SDNodeBits.IsDivergent = IsDivergent;
9557 checkForCycles(Node);
9560 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
9561 SmallVectorImpl<SDValue> &Vals) {
9562 size_t Limit = SDNode::getMaxNumOperands();
9563 while (Vals.size() > Limit) {
9564 unsigned SliceIdx = Vals.size() - Limit;
9565 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
9566 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
9567 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
9568 Vals.emplace_back(NewTF);
9570 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
9573 #ifndef NDEBUG
9574 static void checkForCyclesHelper(const SDNode *N,
9575 SmallPtrSetImpl<const SDNode*> &Visited,
9576 SmallPtrSetImpl<const SDNode*> &Checked,
9577 const llvm::SelectionDAG *DAG) {
9578 // If this node has already been checked, don't check it again.
9579 if (Checked.count(N))
9580 return;
9582 // If a node has already been visited on this depth-first walk, reject it as
9583 // a cycle.
9584 if (!Visited.insert(N).second) {
9585 errs() << "Detected cycle in SelectionDAG\n";
9586 dbgs() << "Offending node:\n";
9587 N->dumprFull(DAG); dbgs() << "\n";
9588 abort();
9591 for (const SDValue &Op : N->op_values())
9592 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
9594 Checked.insert(N);
9595 Visited.erase(N);
9597 #endif
9599 void llvm::checkForCycles(const llvm::SDNode *N,
9600 const llvm::SelectionDAG *DAG,
9601 bool force) {
9602 #ifndef NDEBUG
9603 bool check = force;
9604 #ifdef EXPENSIVE_CHECKS
9605 check = true;
9606 #endif // EXPENSIVE_CHECKS
9607 if (check) {
9608 assert(N && "Checking nonexistent SDNode");
9609 SmallPtrSet<const SDNode*, 32> visited;
9610 SmallPtrSet<const SDNode*, 32> checked;
9611 checkForCyclesHelper(N, visited, checked, DAG);
9613 #endif // !NDEBUG
9616 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
9617 checkForCycles(DAG->getRoot().getNode(), DAG, force);