Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:28

0001 //===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file defines the isa<X>(), cast<X>(), dyn_cast<X>(),
0010 // cast_if_present<X>(), and dyn_cast_if_present<X>() templates.
0011 //
0012 //===----------------------------------------------------------------------===//
0013 
0014 #ifndef LLVM_SUPPORT_CASTING_H
0015 #define LLVM_SUPPORT_CASTING_H
0016 
0017 #include "llvm/Support/Compiler.h"
0018 #include "llvm/Support/type_traits.h"
0019 #include <cassert>
0020 #include <memory>
0021 #include <optional>
0022 #include <type_traits>
0023 
0024 namespace llvm {
0025 
0026 //===----------------------------------------------------------------------===//
0027 // simplify_type
0028 //===----------------------------------------------------------------------===//
0029 
0030 /// Define a template that can be specialized by smart pointers to reflect the
0031 /// fact that they are automatically dereferenced, and are not involved with the
0032 /// template selection process...  the default implementation is a noop.
0033 // TODO: rename this and/or replace it with other cast traits.
0034 template <typename From> struct simplify_type {
0035   using SimpleType = From; // The real type this represents...
0036 
0037   // An accessor to get the real value...
0038   static SimpleType &getSimplifiedValue(From &Val) { return Val; }
0039 };
0040 
0041 template <typename From> struct simplify_type<const From> {
0042   using NonConstSimpleType = typename simplify_type<From>::SimpleType;
0043   using SimpleType = typename add_const_past_pointer<NonConstSimpleType>::type;
0044   using RetType =
0045       typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
0046 
0047   static RetType getSimplifiedValue(const From &Val) {
0048     return simplify_type<From>::getSimplifiedValue(const_cast<From &>(Val));
0049   }
0050 };
0051 
0052 // TODO: add this namespace once everyone is switched to using the new
0053 //       interface.
0054 // namespace detail {
0055 
0056 //===----------------------------------------------------------------------===//
0057 // isa_impl
0058 //===----------------------------------------------------------------------===//
0059 
0060 // The core of the implementation of isa<X> is here; To and From should be
0061 // the names of classes.  This template can be specialized to customize the
0062 // implementation of isa<> without rewriting it from scratch.
0063 template <typename To, typename From, typename Enabler = void> struct isa_impl {
0064   static inline bool doit(const From &Val) { return To::classof(&Val); }
0065 };
0066 
0067 // Always allow upcasts, and perform no dynamic check for them.
0068 template <typename To, typename From>
0069 struct isa_impl<To, From, std::enable_if_t<std::is_base_of_v<To, From>>> {
0070   static inline bool doit(const From &) { return true; }
0071 };
0072 
0073 template <typename To, typename From> struct isa_impl_cl {
0074   static inline bool doit(const From &Val) {
0075     return isa_impl<To, From>::doit(Val);
0076   }
0077 };
0078 
0079 template <typename To, typename From> struct isa_impl_cl<To, const From> {
0080   static inline bool doit(const From &Val) {
0081     return isa_impl<To, From>::doit(Val);
0082   }
0083 };
0084 
0085 template <typename To, typename From>
0086 struct isa_impl_cl<To, const std::unique_ptr<From>> {
0087   static inline bool doit(const std::unique_ptr<From> &Val) {
0088     assert(Val && "isa<> used on a null pointer");
0089     return isa_impl_cl<To, From>::doit(*Val);
0090   }
0091 };
0092 
0093 template <typename To, typename From> struct isa_impl_cl<To, From *> {
0094   static inline bool doit(const From *Val) {
0095     assert(Val && "isa<> used on a null pointer");
0096     return isa_impl<To, From>::doit(*Val);
0097   }
0098 };
0099 
0100 template <typename To, typename From> struct isa_impl_cl<To, From *const> {
0101   static inline bool doit(const From *Val) {
0102     assert(Val && "isa<> used on a null pointer");
0103     return isa_impl<To, From>::doit(*Val);
0104   }
0105 };
0106 
0107 template <typename To, typename From> struct isa_impl_cl<To, const From *> {
0108   static inline bool doit(const From *Val) {
0109     assert(Val && "isa<> used on a null pointer");
0110     return isa_impl<To, From>::doit(*Val);
0111   }
0112 };
0113 
0114 template <typename To, typename From>
0115 struct isa_impl_cl<To, const From *const> {
0116   static inline bool doit(const From *Val) {
0117     assert(Val && "isa<> used on a null pointer");
0118     return isa_impl<To, From>::doit(*Val);
0119   }
0120 };
0121 
0122 template <typename To, typename From, typename SimpleFrom>
0123 struct isa_impl_wrap {
0124   // When From != SimplifiedType, we can simplify the type some more by using
0125   // the simplify_type template.
0126   static bool doit(const From &Val) {
0127     return isa_impl_wrap<To, SimpleFrom,
0128                          typename simplify_type<SimpleFrom>::SimpleType>::
0129         doit(simplify_type<const From>::getSimplifiedValue(Val));
0130   }
0131 };
0132 
0133 template <typename To, typename FromTy>
0134 struct isa_impl_wrap<To, FromTy, FromTy> {
0135   // When From == SimpleType, we are as simple as we are going to get.
0136   static bool doit(const FromTy &Val) {
0137     return isa_impl_cl<To, FromTy>::doit(Val);
0138   }
0139 };
0140 
0141 //===----------------------------------------------------------------------===//
0142 // cast_retty + cast_retty_impl
0143 //===----------------------------------------------------------------------===//
0144 
0145 template <class To, class From> struct cast_retty;
0146 
0147 // Calculate what type the 'cast' function should return, based on a requested
0148 // type of To and a source type of From.
0149 template <class To, class From> struct cast_retty_impl {
0150   using ret_type = To &; // Normal case, return Ty&
0151 };
0152 template <class To, class From> struct cast_retty_impl<To, const From> {
0153   using ret_type = const To &; // Normal case, return Ty&
0154 };
0155 
0156 template <class To, class From> struct cast_retty_impl<To, From *> {
0157   using ret_type = To *; // Pointer arg case, return Ty*
0158 };
0159 
0160 template <class To, class From> struct cast_retty_impl<To, const From *> {
0161   using ret_type = const To *; // Constant pointer arg case, return const Ty*
0162 };
0163 
0164 template <class To, class From> struct cast_retty_impl<To, const From *const> {
0165   using ret_type = const To *; // Constant pointer arg case, return const Ty*
0166 };
0167 
0168 template <class To, class From>
0169 struct cast_retty_impl<To, std::unique_ptr<From>> {
0170 private:
0171   using PointerType = typename cast_retty_impl<To, From *>::ret_type;
0172   using ResultType = std::remove_pointer_t<PointerType>;
0173 
0174 public:
0175   using ret_type = std::unique_ptr<ResultType>;
0176 };
0177 
0178 template <class To, class From, class SimpleFrom> struct cast_retty_wrap {
0179   // When the simplified type and the from type are not the same, use the type
0180   // simplifier to reduce the type, then reuse cast_retty_impl to get the
0181   // resultant type.
0182   using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
0183 };
0184 
0185 template <class To, class FromTy> struct cast_retty_wrap<To, FromTy, FromTy> {
0186   // When the simplified type is equal to the from type, use it directly.
0187   using ret_type = typename cast_retty_impl<To, FromTy>::ret_type;
0188 };
0189 
0190 template <class To, class From> struct cast_retty {
0191   using ret_type = typename cast_retty_wrap<
0192       To, From, typename simplify_type<From>::SimpleType>::ret_type;
0193 };
0194 
0195 //===----------------------------------------------------------------------===//
0196 // cast_convert_val
0197 //===----------------------------------------------------------------------===//
0198 
0199 // Ensure the non-simple values are converted using the simplify_type template
0200 // that may be specialized by smart pointers...
0201 //
0202 template <class To, class From, class SimpleFrom> struct cast_convert_val {
0203   // This is not a simple type, use the template to simplify it...
0204   static typename cast_retty<To, From>::ret_type doit(const From &Val) {
0205     return cast_convert_val<To, SimpleFrom,
0206                             typename simplify_type<SimpleFrom>::SimpleType>::
0207         doit(simplify_type<From>::getSimplifiedValue(const_cast<From &>(Val)));
0208   }
0209 };
0210 
0211 template <class To, class FromTy> struct cast_convert_val<To, FromTy, FromTy> {
0212   // If it's a reference, switch to a pointer to do the cast and then deref it.
0213   static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
0214     return *(std::remove_reference_t<typename cast_retty<To, FromTy>::ret_type>
0215                  *)&const_cast<FromTy &>(Val);
0216   }
0217 };
0218 
0219 template <class To, class FromTy>
0220 struct cast_convert_val<To, FromTy *, FromTy *> {
0221   // If it's a pointer, we can use c-style casting directly.
0222   static typename cast_retty<To, FromTy *>::ret_type doit(const FromTy *Val) {
0223     return (typename cast_retty<To, FromTy *>::ret_type) const_cast<FromTy *>(
0224         Val);
0225   }
0226 };
0227 
0228 //===----------------------------------------------------------------------===//
0229 // is_simple_type
0230 //===----------------------------------------------------------------------===//
0231 
0232 template <class X> struct is_simple_type {
0233   static const bool value =
0234       std::is_same_v<X, typename simplify_type<X>::SimpleType>;
0235 };
0236 
0237 // } // namespace detail
0238 
0239 //===----------------------------------------------------------------------===//
0240 // CastIsPossible
0241 //===----------------------------------------------------------------------===//
0242 
0243 /// This struct provides a way to check if a given cast is possible. It provides
0244 /// a static function called isPossible that is used to check if a cast can be
0245 /// performed. It should be overridden like this:
0246 ///
0247 /// template<> struct CastIsPossible<foo, bar> {
0248 ///   static inline bool isPossible(const bar &b) {
0249 ///     return bar.isFoo();
0250 ///   }
0251 /// };
0252 template <typename To, typename From, typename Enable = void>
0253 struct CastIsPossible {
0254   static inline bool isPossible(const From &f) {
0255     return isa_impl_wrap<
0256         To, const From,
0257         typename simplify_type<const From>::SimpleType>::doit(f);
0258   }
0259 };
0260 
0261 // Needed for optional unwrapping. This could be implemented with isa_impl, but
0262 // we want to implement things in the new method and move old implementations
0263 // over. In fact, some of the isa_impl templates should be moved over to
0264 // CastIsPossible.
0265 template <typename To, typename From>
0266 struct CastIsPossible<To, std::optional<From>> {
0267   static inline bool isPossible(const std::optional<From> &f) {
0268     assert(f && "CastIsPossible::isPossible called on a nullopt!");
0269     return isa_impl_wrap<
0270         To, const From,
0271         typename simplify_type<const From>::SimpleType>::doit(*f);
0272   }
0273 };
0274 
0275 /// Upcasting (from derived to base) and casting from a type to itself should
0276 /// always be possible.
0277 template <typename To, typename From>
0278 struct CastIsPossible<To, From, std::enable_if_t<std::is_base_of_v<To, From>>> {
0279   static inline bool isPossible(const From &f) { return true; }
0280 };
0281 
0282 //===----------------------------------------------------------------------===//
0283 // Cast traits
0284 //===----------------------------------------------------------------------===//
0285 
0286 /// All of these cast traits are meant to be implementations for useful casts
0287 /// that users may want to use that are outside the standard behavior. An
0288 /// example of how to use a special cast called `CastTrait` is:
0289 ///
0290 /// template<> struct CastInfo<foo, bar> : public CastTrait<foo, bar> {};
0291 ///
0292 /// Essentially, if your use case falls directly into one of the use cases
0293 /// supported by a given cast trait, simply inherit your special CastInfo
0294 /// directly from one of these to avoid having to reimplement the boilerplate
0295 /// `isPossible/castFailed/doCast/doCastIfPossible`. A cast trait can also
0296 /// provide a subset of those functions.
0297 
0298 /// This cast trait just provides castFailed for the specified `To` type to make
0299 /// CastInfo specializations more declarative. In order to use this, the target
0300 /// result type must be `To` and `To` must be constructible from `nullptr`.
0301 template <typename To> struct NullableValueCastFailed {
0302   static To castFailed() { return To(nullptr); }
0303 };
0304 
0305 /// This cast trait just provides the default implementation of doCastIfPossible
0306 /// to make CastInfo specializations more declarative. The `Derived` template
0307 /// parameter *must* be provided for forwarding castFailed and doCast.
0308 template <typename To, typename From, typename Derived>
0309 struct DefaultDoCastIfPossible {
0310   static To doCastIfPossible(From f) {
0311     if (!Derived::isPossible(f))
0312       return Derived::castFailed();
0313     return Derived::doCast(f);
0314   }
0315 };
0316 
0317 namespace detail {
0318 /// A helper to derive the type to use with `Self` for cast traits, when the
0319 /// provided CRTP derived type is allowed to be void.
0320 template <typename OptionalDerived, typename Default>
0321 using SelfType = std::conditional_t<std::is_same_v<OptionalDerived, void>,
0322                                     Default, OptionalDerived>;
0323 } // namespace detail
0324 
0325 /// This cast trait provides casting for the specific case of casting to a
0326 /// value-typed object from a pointer-typed object. Note that `To` must be
0327 /// nullable/constructible from a pointer to `From` to use this cast.
0328 template <typename To, typename From, typename Derived = void>
0329 struct ValueFromPointerCast
0330     : public CastIsPossible<To, From *>,
0331       public NullableValueCastFailed<To>,
0332       public DefaultDoCastIfPossible<
0333           To, From *,
0334           detail::SelfType<Derived, ValueFromPointerCast<To, From>>> {
0335   static inline To doCast(From *f) { return To(f); }
0336 };
0337 
0338 /// This cast trait provides std::unique_ptr casting. It has the semantics of
0339 /// moving the contents of the input unique_ptr into the output unique_ptr
0340 /// during the cast. It's also a good example of how to implement a move-only
0341 /// cast.
0342 template <typename To, typename From, typename Derived = void>
0343 struct UniquePtrCast : public CastIsPossible<To, From *> {
0344   using Self = detail::SelfType<Derived, UniquePtrCast<To, From>>;
0345   using CastResultType = std::unique_ptr<
0346       std::remove_reference_t<typename cast_retty<To, From>::ret_type>>;
0347 
0348   static inline CastResultType doCast(std::unique_ptr<From> &&f) {
0349     return CastResultType((typename CastResultType::element_type *)f.release());
0350   }
0351 
0352   static inline CastResultType castFailed() { return CastResultType(nullptr); }
0353 
0354   static inline CastResultType doCastIfPossible(std::unique_ptr<From> &f) {
0355     if (!Self::isPossible(f.get()))
0356       return castFailed();
0357     return doCast(std::move(f));
0358   }
0359 };
0360 
0361 /// This cast trait provides std::optional<T> casting. This means that if you
0362 /// have a value type, you can cast it to another value type and have dyn_cast
0363 /// return an std::optional<T>.
0364 template <typename To, typename From, typename Derived = void>
0365 struct OptionalValueCast
0366     : public CastIsPossible<To, From>,
0367       public DefaultDoCastIfPossible<
0368           std::optional<To>, From,
0369           detail::SelfType<Derived, OptionalValueCast<To, From>>> {
0370   static inline std::optional<To> castFailed() { return std::optional<To>{}; }
0371 
0372   static inline std::optional<To> doCast(const From &f) { return To(f); }
0373 };
0374 
0375 /// Provides a cast trait that strips `const` from types to make it easier to
0376 /// implement a const-version of a non-const cast. It just removes boilerplate
0377 /// and reduces the amount of code you as the user need to implement. You can
0378 /// use it like this:
0379 ///
0380 /// template<> struct CastInfo<foo, bar> {
0381 ///   ...verbose implementation...
0382 /// };
0383 ///
0384 /// template<> struct CastInfo<foo, const bar> : public
0385 ///        ConstStrippingForwardingCast<foo, const bar, CastInfo<foo, bar>> {};
0386 ///
0387 template <typename To, typename From, typename ForwardTo>
0388 struct ConstStrippingForwardingCast {
0389   // Remove the pointer if it exists, then we can get rid of consts/volatiles.
0390   using DecayedFrom = std::remove_cv_t<std::remove_pointer_t<From>>;
0391   // Now if it's a pointer, add it back. Otherwise, we want a ref.
0392   using NonConstFrom =
0393       std::conditional_t<std::is_pointer_v<From>, DecayedFrom *, DecayedFrom &>;
0394 
0395   static inline bool isPossible(const From &f) {
0396     return ForwardTo::isPossible(const_cast<NonConstFrom>(f));
0397   }
0398 
0399   static inline decltype(auto) castFailed() { return ForwardTo::castFailed(); }
0400 
0401   static inline decltype(auto) doCast(const From &f) {
0402     return ForwardTo::doCast(const_cast<NonConstFrom>(f));
0403   }
0404 
0405   static inline decltype(auto) doCastIfPossible(const From &f) {
0406     return ForwardTo::doCastIfPossible(const_cast<NonConstFrom>(f));
0407   }
0408 };
0409 
0410 /// Provides a cast trait that uses a defined pointer to pointer cast as a base
0411 /// for reference-to-reference casts. Note that it does not provide castFailed
0412 /// and doCastIfPossible because a pointer-to-pointer cast would likely just
0413 /// return `nullptr` which could cause nullptr dereference. You can use it like
0414 /// this:
0415 ///
0416 ///   template <> struct CastInfo<foo, bar *> { ... verbose implementation... };
0417 ///
0418 ///   template <>
0419 ///   struct CastInfo<foo, bar>
0420 ///       : public ForwardToPointerCast<foo, bar, CastInfo<foo, bar *>> {};
0421 ///
0422 template <typename To, typename From, typename ForwardTo>
0423 struct ForwardToPointerCast {
0424   static inline bool isPossible(const From &f) {
0425     return ForwardTo::isPossible(&f);
0426   }
0427 
0428   static inline decltype(auto) doCast(const From &f) {
0429     return *ForwardTo::doCast(&f);
0430   }
0431 };
0432 
0433 //===----------------------------------------------------------------------===//
0434 // CastInfo
0435 //===----------------------------------------------------------------------===//
0436 
0437 /// This struct provides a method for customizing the way a cast is performed.
0438 /// It inherits from CastIsPossible, to support the case of declaring many
0439 /// CastIsPossible specializations without having to specialize the full
0440 /// CastInfo.
0441 ///
0442 /// In order to specialize different behaviors, specify different functions in
0443 /// your CastInfo specialization.
0444 /// For isa<> customization, provide:
0445 ///
0446 ///   `static bool isPossible(const From &f)`
0447 ///
0448 /// For cast<> customization, provide:
0449 ///
0450 ///  `static To doCast(const From &f)`
0451 ///
0452 /// For dyn_cast<> and the *_if_present<> variants' customization, provide:
0453 ///
0454 ///  `static To castFailed()` and `static To doCastIfPossible(const From &f)`
0455 ///
0456 /// Your specialization might look something like this:
0457 ///
0458 ///  template<> struct CastInfo<foo, bar> : public CastIsPossible<foo, bar> {
0459 ///    static inline foo doCast(const bar &b) {
0460 ///      return foo(const_cast<bar &>(b));
0461 ///    }
0462 ///    static inline foo castFailed() { return foo(); }
0463 ///    static inline foo doCastIfPossible(const bar &b) {
0464 ///      if (!CastInfo<foo, bar>::isPossible(b))
0465 ///        return castFailed();
0466 ///      return doCast(b);
0467 ///    }
0468 ///  };
0469 
0470 // The default implementations of CastInfo don't use cast traits for now because
0471 // we need to specify types all over the place due to the current expected
0472 // casting behavior and the way cast_retty works. New use cases can and should
0473 // take advantage of the cast traits whenever possible!
0474 
0475 template <typename To, typename From, typename Enable = void>
0476 struct CastInfo : public CastIsPossible<To, From> {
0477   using Self = CastInfo<To, From, Enable>;
0478 
0479   using CastReturnType = typename cast_retty<To, From>::ret_type;
0480 
0481   static inline CastReturnType doCast(const From &f) {
0482     return cast_convert_val<
0483         To, From,
0484         typename simplify_type<From>::SimpleType>::doit(const_cast<From &>(f));
0485   }
0486 
0487   // This assumes that you can construct the cast return type from `nullptr`.
0488   // This is largely to support legacy use cases - if you don't want this
0489   // behavior you should specialize CastInfo for your use case.
0490   static inline CastReturnType castFailed() { return CastReturnType(nullptr); }
0491 
0492   static inline CastReturnType doCastIfPossible(const From &f) {
0493     if (!Self::isPossible(f))
0494       return castFailed();
0495     return doCast(f);
0496   }
0497 };
0498 
0499 /// This struct provides an overload for CastInfo where From has simplify_type
0500 /// defined. This simply forwards to the appropriate CastInfo with the
0501 /// simplified type/value, so you don't have to implement both.
0502 template <typename To, typename From>
0503 struct CastInfo<To, From, std::enable_if_t<!is_simple_type<From>::value>> {
0504   using Self = CastInfo<To, From>;
0505   using SimpleFrom = typename simplify_type<From>::SimpleType;
0506   using SimplifiedSelf = CastInfo<To, SimpleFrom>;
0507 
0508   static inline bool isPossible(From &f) {
0509     return SimplifiedSelf::isPossible(
0510         simplify_type<From>::getSimplifiedValue(f));
0511   }
0512 
0513   static inline decltype(auto) doCast(From &f) {
0514     return SimplifiedSelf::doCast(simplify_type<From>::getSimplifiedValue(f));
0515   }
0516 
0517   static inline decltype(auto) castFailed() {
0518     return SimplifiedSelf::castFailed();
0519   }
0520 
0521   static inline decltype(auto) doCastIfPossible(From &f) {
0522     return SimplifiedSelf::doCastIfPossible(
0523         simplify_type<From>::getSimplifiedValue(f));
0524   }
0525 };
0526 
0527 //===----------------------------------------------------------------------===//
0528 // Pre-specialized CastInfo
0529 //===----------------------------------------------------------------------===//
0530 
0531 /// Provide a CastInfo specialized for std::unique_ptr.
0532 template <typename To, typename From>
0533 struct CastInfo<To, std::unique_ptr<From>> : public UniquePtrCast<To, From> {};
0534 
0535 /// Provide a CastInfo specialized for std::optional<From>. It's assumed that if
0536 /// the input is std::optional<From> that the output can be std::optional<To>.
0537 /// If that's not the case, specialize CastInfo for your use case.
0538 template <typename To, typename From>
0539 struct CastInfo<To, std::optional<From>> : public OptionalValueCast<To, From> {
0540 };
0541 
0542 /// isa<X> - Return true if the parameter to the template is an instance of one
0543 /// of the template type arguments.  Used like this:
0544 ///
0545 ///  if (isa<Type>(myVal)) { ... }
0546 ///  if (isa<Type0, Type1, Type2>(myVal)) { ... }
0547 template <typename To, typename From>
0548 [[nodiscard]] inline bool isa(const From &Val) {
0549   return CastInfo<To, const From>::isPossible(Val);
0550 }
0551 
0552 template <typename First, typename Second, typename... Rest, typename From>
0553 [[nodiscard]] inline bool isa(const From &Val) {
0554   return isa<First>(Val) || isa<Second, Rest...>(Val);
0555 }
0556 
0557 /// cast<X> - Return the argument parameter cast to the specified type.  This
0558 /// casting operator asserts that the type is correct, so it does not return
0559 /// null on failure.  It does not allow a null argument (use cast_if_present for
0560 /// that). It is typically used like this:
0561 ///
0562 ///  cast<Instruction>(myVal)->getParent()
0563 
0564 template <typename To, typename From>
0565 [[nodiscard]] inline decltype(auto) cast(const From &Val) {
0566   assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!");
0567   return CastInfo<To, const From>::doCast(Val);
0568 }
0569 
0570 template <typename To, typename From>
0571 [[nodiscard]] inline decltype(auto) cast(From &Val) {
0572   assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!");
0573   return CastInfo<To, From>::doCast(Val);
0574 }
0575 
0576 template <typename To, typename From>
0577 [[nodiscard]] inline decltype(auto) cast(From *Val) {
0578   assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!");
0579   return CastInfo<To, From *>::doCast(Val);
0580 }
0581 
0582 template <typename To, typename From>
0583 [[nodiscard]] inline decltype(auto) cast(std::unique_ptr<From> &&Val) {
0584   assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!");
0585   return CastInfo<To, std::unique_ptr<From>>::doCast(std::move(Val));
0586 }
0587 
0588 //===----------------------------------------------------------------------===//
0589 // ValueIsPresent
0590 //===----------------------------------------------------------------------===//
0591 
0592 template <typename T>
0593 constexpr bool IsNullable =
0594     std::is_pointer_v<T> || std::is_constructible_v<T, std::nullptr_t>;
0595 
0596 /// ValueIsPresent provides a way to check if a value is, well, present. For
0597 /// pointers, this is the equivalent of checking against nullptr, for Optionals
0598 /// this is the equivalent of checking hasValue(). It also provides a method for
0599 /// unwrapping a value (think calling .value() on an optional).
0600 
0601 // Generic values can't *not* be present.
0602 template <typename T, typename Enable = void> struct ValueIsPresent {
0603   using UnwrappedType = T;
0604   static inline bool isPresent(const T &t) { return true; }
0605   static inline decltype(auto) unwrapValue(T &t) { return t; }
0606 };
0607 
0608 // Optional provides its own way to check if something is present.
0609 template <typename T> struct ValueIsPresent<std::optional<T>> {
0610   using UnwrappedType = T;
0611   static inline bool isPresent(const std::optional<T> &t) {
0612     return t.has_value();
0613   }
0614   static inline decltype(auto) unwrapValue(std::optional<T> &t) { return *t; }
0615 };
0616 
0617 // If something is "nullable" then we just compare it to nullptr to see if it
0618 // exists.
0619 template <typename T>
0620 struct ValueIsPresent<T, std::enable_if_t<IsNullable<T>>> {
0621   using UnwrappedType = T;
0622   static inline bool isPresent(const T &t) { return t != T(nullptr); }
0623   static inline decltype(auto) unwrapValue(T &t) { return t; }
0624 };
0625 
0626 namespace detail {
0627 // Convenience function we can use to check if a value is present. Because of
0628 // simplify_type, we have to call it on the simplified type for now.
0629 template <typename T> inline bool isPresent(const T &t) {
0630   return ValueIsPresent<typename simplify_type<T>::SimpleType>::isPresent(
0631       simplify_type<T>::getSimplifiedValue(const_cast<T &>(t)));
0632 }
0633 
0634 // Convenience function we can use to unwrap a value.
0635 template <typename T> inline decltype(auto) unwrapValue(T &t) {
0636   return ValueIsPresent<T>::unwrapValue(t);
0637 }
0638 } // namespace detail
0639 
0640 /// dyn_cast<X> - Return the argument parameter cast to the specified type. This
0641 /// casting operator returns null if the argument is of the wrong type, so it
0642 /// can be used to test for a type as well as cast if successful. The value
0643 /// passed in must be present, if not, use dyn_cast_if_present. This should be
0644 /// used in the context of an if statement like this:
0645 ///
0646 ///  if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
0647 
0648 template <typename To, typename From>
0649 [[nodiscard]] inline decltype(auto) dyn_cast(const From &Val) {
0650   assert(detail::isPresent(Val) && "dyn_cast on a non-existent value");
0651   return CastInfo<To, const From>::doCastIfPossible(Val);
0652 }
0653 
0654 template <typename To, typename From>
0655 [[nodiscard]] inline decltype(auto) dyn_cast(From &Val) {
0656   assert(detail::isPresent(Val) && "dyn_cast on a non-existent value");
0657   return CastInfo<To, From>::doCastIfPossible(Val);
0658 }
0659 
0660 template <typename To, typename From>
0661 [[nodiscard]] inline decltype(auto) dyn_cast(From *Val) {
0662   assert(detail::isPresent(Val) && "dyn_cast on a non-existent value");
0663   return CastInfo<To, From *>::doCastIfPossible(Val);
0664 }
0665 
0666 template <typename To, typename From>
0667 [[nodiscard]] inline decltype(auto) dyn_cast(std::unique_ptr<From> &Val) {
0668   assert(detail::isPresent(Val) && "dyn_cast on a non-existent value");
0669   return CastInfo<To, std::unique_ptr<From>>::doCastIfPossible(Val);
0670 }
0671 
0672 /// isa_and_present<X> - Functionally identical to isa, except that a null value
0673 /// is accepted.
0674 template <typename... X, class Y>
0675 [[nodiscard]] inline bool isa_and_present(const Y &Val) {
0676   if (!detail::isPresent(Val))
0677     return false;
0678   return isa<X...>(Val);
0679 }
0680 
0681 template <typename... X, class Y>
0682 [[nodiscard]] inline bool isa_and_nonnull(const Y &Val) {
0683   return isa_and_present<X...>(Val);
0684 }
0685 
0686 /// cast_if_present<X> - Functionally identical to cast, except that a null
0687 /// value is accepted.
0688 template <class X, class Y>
0689 [[nodiscard]] inline auto cast_if_present(const Y &Val) {
0690   if (!detail::isPresent(Val))
0691     return CastInfo<X, const Y>::castFailed();
0692   assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!");
0693   return cast<X>(detail::unwrapValue(Val));
0694 }
0695 
0696 template <class X, class Y> [[nodiscard]] inline auto cast_if_present(Y &Val) {
0697   if (!detail::isPresent(Val))
0698     return CastInfo<X, Y>::castFailed();
0699   assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!");
0700   return cast<X>(detail::unwrapValue(Val));
0701 }
0702 
0703 template <class X, class Y> [[nodiscard]] inline auto cast_if_present(Y *Val) {
0704   if (!detail::isPresent(Val))
0705     return CastInfo<X, Y *>::castFailed();
0706   assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!");
0707   return cast<X>(detail::unwrapValue(Val));
0708 }
0709 
0710 template <class X, class Y>
0711 [[nodiscard]] inline auto cast_if_present(std::unique_ptr<Y> &&Val) {
0712   if (!detail::isPresent(Val))
0713     return UniquePtrCast<X, Y>::castFailed();
0714   return UniquePtrCast<X, Y>::doCast(std::move(Val));
0715 }
0716 
0717 // Provide a forwarding from cast_or_null to cast_if_present for current
0718 // users. This is deprecated and will be removed in a future patch, use
0719 // cast_if_present instead.
0720 template <class X, class Y> auto cast_or_null(const Y &Val) {
0721   return cast_if_present<X>(Val);
0722 }
0723 
0724 template <class X, class Y> auto cast_or_null(Y &Val) {
0725   return cast_if_present<X>(Val);
0726 }
0727 
0728 template <class X, class Y> auto cast_or_null(Y *Val) {
0729   return cast_if_present<X>(Val);
0730 }
0731 
0732 template <class X, class Y> auto cast_or_null(std::unique_ptr<Y> &&Val) {
0733   return cast_if_present<X>(std::move(Val));
0734 }
0735 
0736 /// dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a
0737 /// null (or none in the case of optionals) value is accepted.
0738 template <class X, class Y> auto dyn_cast_if_present(const Y &Val) {
0739   if (!detail::isPresent(Val))
0740     return CastInfo<X, const Y>::castFailed();
0741   return CastInfo<X, const Y>::doCastIfPossible(detail::unwrapValue(Val));
0742 }
0743 
0744 template <class X, class Y> auto dyn_cast_if_present(Y &Val) {
0745   if (!detail::isPresent(Val))
0746     return CastInfo<X, Y>::castFailed();
0747   return CastInfo<X, Y>::doCastIfPossible(detail::unwrapValue(Val));
0748 }
0749 
0750 template <class X, class Y> auto dyn_cast_if_present(Y *Val) {
0751   if (!detail::isPresent(Val))
0752     return CastInfo<X, Y *>::castFailed();
0753   return CastInfo<X, Y *>::doCastIfPossible(detail::unwrapValue(Val));
0754 }
0755 
0756 // Forwards to dyn_cast_if_present to avoid breaking current users. This is
0757 // deprecated and will be removed in a future patch, use
0758 // dyn_cast_if_present instead.
0759 template <class X, class Y> auto dyn_cast_or_null(const Y &Val) {
0760   return dyn_cast_if_present<X>(Val);
0761 }
0762 
0763 template <class X, class Y> auto dyn_cast_or_null(Y &Val) {
0764   return dyn_cast_if_present<X>(Val);
0765 }
0766 
0767 template <class X, class Y> auto dyn_cast_or_null(Y *Val) {
0768   return dyn_cast_if_present<X>(Val);
0769 }
0770 
0771 /// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
0772 /// taking ownership of the input pointer iff isa<X>(Val) is true.  If the
0773 /// cast is successful, From refers to nullptr on exit and the casted value
0774 /// is returned.  If the cast is unsuccessful, the function returns nullptr
0775 /// and From is unchanged.
0776 template <class X, class Y>
0777 [[nodiscard]] inline typename CastInfo<X, std::unique_ptr<Y>>::CastResultType
0778 unique_dyn_cast(std::unique_ptr<Y> &Val) {
0779   if (!isa<X>(Val))
0780     return nullptr;
0781   return cast<X>(std::move(Val));
0782 }
0783 
0784 template <class X, class Y>
0785 [[nodiscard]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val) {
0786   return unique_dyn_cast<X, Y>(Val);
0787 }
0788 
0789 // unique_dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast,
0790 // except that a null value is accepted.
0791 template <class X, class Y>
0792 [[nodiscard]] inline typename CastInfo<X, std::unique_ptr<Y>>::CastResultType
0793 unique_dyn_cast_or_null(std::unique_ptr<Y> &Val) {
0794   if (!Val)
0795     return nullptr;
0796   return unique_dyn_cast<X, Y>(Val);
0797 }
0798 
0799 template <class X, class Y>
0800 [[nodiscard]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val) {
0801   return unique_dyn_cast_or_null<X, Y>(Val);
0802 }
0803 
0804 //===----------------------------------------------------------------------===//
0805 // Isa Predicates
0806 //===----------------------------------------------------------------------===//
0807 
0808 /// These are wrappers over isa* function that allow them to be used in generic
0809 /// algorithms such as `llvm:all_of`, `llvm::none_of`, etc. This is accomplished
0810 /// by exposing the isa* functions through function objects with a generic
0811 /// function call operator.
0812 
0813 namespace detail {
0814 template <typename... Types> struct IsaCheckPredicate {
0815   template <typename T> [[nodiscard]] bool operator()(const T &Val) const {
0816     return isa<Types...>(Val);
0817   }
0818 };
0819 
0820 template <typename... Types> struct IsaAndPresentCheckPredicate {
0821   template <typename T> [[nodiscard]] bool operator()(const T &Val) const {
0822     return isa_and_present<Types...>(Val);
0823   }
0824 };
0825 } // namespace detail
0826 
0827 /// Function object wrapper for the `llvm::isa` type check. The function call
0828 /// operator returns true when the value can be cast to any type in `Types`.
0829 /// Example:
0830 /// ```
0831 /// SmallVector<Type> myTypes = ...;
0832 /// if (llvm::all_of(myTypes, llvm::IsaPred<VectorType>))
0833 ///   ...
0834 /// ```
0835 template <typename... Types>
0836 inline constexpr detail::IsaCheckPredicate<Types...> IsaPred{};
0837 
0838 /// Function object wrapper for the `llvm::isa_and_present` type check. The
0839 /// function call operator returns true when the value can be cast to any type
0840 /// in `Types`, or if the value is not present (e.g., nullptr). Example:
0841 /// ```
0842 /// SmallVector<Type> myTypes = ...;
0843 /// if (llvm::all_of(myTypes, llvm::IsaAndPresentPred<VectorType>))
0844 ///   ...
0845 /// ```
0846 template <typename... Types>
0847 inline constexpr detail::IsaAndPresentCheckPredicate<Types...>
0848     IsaAndPresentPred{};
0849 
0850 } // end namespace llvm
0851 
0852 #endif // LLVM_SUPPORT_CASTING_H