[llvm] [NFCI][IR] Add optional DataLayout argument to zero and null value related APIs (PR #183208)
Alexander Richardson via llvm-commits
llvm-commits at lists.llvm.org
Sat May 2 10:01:52 PDT 2026
================
@@ -71,25 +72,112 @@ bool Constant::isNegativeZeroValue() const {
return isNullValue();
}
-bool Constant::isNullValue() const {
- // 0 is null.
+// ConstantAggregateZero is always zero value. Whether it is also the null value
+// depends on whether the zero value is null value for each element type.
+static bool isZeroAggregateNullValue(Type *Ty, const DataLayout *DL) {
+ if (StructType *STy = dyn_cast<StructType>(Ty)) {
+ for (Type *EltTy : STy->elements()) {
+ if (!Constant::getZeroValue(EltTy, DL)->isNullValue(DL))
+ return false;
+ }
+ return true;
+ }
+
+ if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
+ if (ATy->getNumElements() == 0)
+ return true;
+ return Constant::getZeroValue(ATy->getElementType(), DL)->isNullValue(DL);
+ }
+
+ VectorType *VTy = cast<VectorType>(Ty);
+ return Constant::getZeroValue(VTy->getElementType(), DL)->isNullValue(DL);
+}
+
+template <typename AggregateType>
+static bool
+checkAllAggregateElements(const Constant *C, AggregateType *Ty,
+ const DataLayout *DL,
+ bool (Constant::*IsValue)(const DataLayout *) const) {
+ for (uint64_t I = 0, E = Ty->getNumElements(); I != E; ++I) {
+ Constant *Elt = C->getAggregateElement(I);
+ if (!Elt || !(Elt->*IsValue)(DL))
+ return false;
+ }
+ return true;
+}
+
+static bool
+checkAllAggregateElements(const Constant *C, const DataLayout *DL,
+ bool (Constant::*IsValue)(const DataLayout *) const) {
+ if (StructType *STy = dyn_cast<StructType>(C->getType()))
+ return checkAllAggregateElements(C, STy, DL, IsValue);
+
+ if (ArrayType *ATy = dyn_cast<ArrayType>(C->getType()))
+ return checkAllAggregateElements(C, ATy, DL, IsValue);
+
+ FixedVectorType *VTy = cast<FixedVectorType>(C->getType());
+ return checkAllAggregateElements(C, VTy, DL, IsValue);
+}
+
+bool Constant::isNullValue(const DataLayout *DL) const {
+ if (isa<UndefValue>(this))
+ return false;
+
+ if (isa<ConstantPointerNull>(this))
+ return true;
+
+ if (isa<ConstantAggregateZero>(this))
+ return isZeroAggregateNullValue(getType(), DL);
+
+ if (getType()->isAggregateType() || isa<FixedVectorType>(getType()))
+ return checkAllAggregateElements(this, DL, &Constant::isNullValue);
+
+ if (isa<ScalableVectorType>(getType())) {
+ if (Constant *Splat = getSplatValue())
+ return Splat->isNullValue(DL);
+ }
+
+ return isZeroValue(DL);
----------------
arichardson wrote:
I think longer term it would be good if we only allow this function to be used for pointer types (and vectors of pointers).
https://github.com/llvm/llvm-project/pull/183208
More information about the llvm-commits
mailing list