ComparisonCategories.cpp 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. //===- ComparisonCategories.cpp - Three Way Comparison Data -----*- C++ -*-===//
  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 file defines the Comparison Category enum and data types, which
  10. // store the types and expressions needed to support operator<=>
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/ComparisonCategories.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Decl.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/Type.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. using namespace clang;
  20. Optional<ComparisonCategoryType>
  21. clang::getComparisonCategoryForBuiltinCmp(QualType T) {
  22. using CCT = ComparisonCategoryType;
  23. if (T->isIntegralOrEnumerationType())
  24. return CCT::StrongOrdering;
  25. if (T->isRealFloatingType())
  26. return CCT::PartialOrdering;
  27. // C++2a [expr.spaceship]p8: If the composite pointer type is an object
  28. // pointer type, p <=> q is of type std::strong_ordering.
  29. // Note: this assumes neither operand is a null pointer constant.
  30. if (T->isObjectPointerType())
  31. return CCT::StrongOrdering;
  32. // TODO: Extend support for operator<=> to ObjC types.
  33. return llvm::None;
  34. }
  35. bool ComparisonCategoryInfo::ValueInfo::hasValidIntValue() const {
  36. assert(VD && "must have var decl");
  37. if (!VD->isUsableInConstantExpressions(VD->getASTContext()))
  38. return false;
  39. // Before we attempt to get the value of the first field, ensure that we
  40. // actually have one (and only one) field.
  41. auto *Record = VD->getType()->getAsCXXRecordDecl();
  42. if (std::distance(Record->field_begin(), Record->field_end()) != 1 ||
  43. !Record->field_begin()->getType()->isIntegralOrEnumerationType())
  44. return false;
  45. return true;
  46. }
  47. /// Attempt to determine the integer value used to represent the comparison
  48. /// category result by evaluating the initializer for the specified VarDecl as
  49. /// a constant expression and retrieving the value of the class's first
  50. /// (and only) field.
  51. ///
  52. /// Note: The STL types are expected to have the form:
  53. /// struct X { T value; };
  54. /// where T is an integral or enumeration type.
  55. llvm::APSInt ComparisonCategoryInfo::ValueInfo::getIntValue() const {
  56. assert(hasValidIntValue() && "must have a valid value");
  57. return VD->evaluateValue()->getStructField(0).getInt();
  58. }
  59. ComparisonCategoryInfo::ValueInfo *ComparisonCategoryInfo::lookupValueInfo(
  60. ComparisonCategoryResult ValueKind) const {
  61. // Check if we already have a cache entry for this value.
  62. auto It = llvm::find_if(
  63. Objects, [&](ValueInfo const &Info) { return Info.Kind == ValueKind; });
  64. if (It != Objects.end())
  65. return &(*It);
  66. // We don't have a cached result. Lookup the variable declaration and create
  67. // a new entry representing it.
  68. DeclContextLookupResult Lookup = Record->getCanonicalDecl()->lookup(
  69. &Ctx.Idents.get(ComparisonCategories::getResultString(ValueKind)));
  70. if (Lookup.empty() || !isa<VarDecl>(Lookup.front()))
  71. return nullptr;
  72. Objects.emplace_back(ValueKind, cast<VarDecl>(Lookup.front()));
  73. return &Objects.back();
  74. }
  75. static const NamespaceDecl *lookupStdNamespace(const ASTContext &Ctx,
  76. NamespaceDecl *&StdNS) {
  77. if (!StdNS) {
  78. DeclContextLookupResult Lookup =
  79. Ctx.getTranslationUnitDecl()->lookup(&Ctx.Idents.get("std"));
  80. if (!Lookup.empty())
  81. StdNS = dyn_cast<NamespaceDecl>(Lookup.front());
  82. }
  83. return StdNS;
  84. }
  85. static CXXRecordDecl *lookupCXXRecordDecl(const ASTContext &Ctx,
  86. const NamespaceDecl *StdNS,
  87. ComparisonCategoryType Kind) {
  88. StringRef Name = ComparisonCategories::getCategoryString(Kind);
  89. DeclContextLookupResult Lookup = StdNS->lookup(&Ctx.Idents.get(Name));
  90. if (!Lookup.empty())
  91. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Lookup.front()))
  92. return RD;
  93. return nullptr;
  94. }
  95. const ComparisonCategoryInfo *
  96. ComparisonCategories::lookupInfo(ComparisonCategoryType Kind) const {
  97. auto It = Data.find(static_cast<char>(Kind));
  98. if (It != Data.end())
  99. return &It->second;
  100. if (const NamespaceDecl *NS = lookupStdNamespace(Ctx, StdNS))
  101. if (CXXRecordDecl *RD = lookupCXXRecordDecl(Ctx, NS, Kind))
  102. return &Data.try_emplace((char)Kind, Ctx, RD, Kind).first->second;
  103. return nullptr;
  104. }
  105. const ComparisonCategoryInfo *
  106. ComparisonCategories::lookupInfoForType(QualType Ty) const {
  107. assert(!Ty.isNull() && "type must be non-null");
  108. using CCT = ComparisonCategoryType;
  109. auto *RD = Ty->getAsCXXRecordDecl();
  110. if (!RD)
  111. return nullptr;
  112. // Check to see if we have information for the specified type cached.
  113. const auto *CanonRD = RD->getCanonicalDecl();
  114. for (auto &KV : Data) {
  115. const ComparisonCategoryInfo &Info = KV.second;
  116. if (CanonRD == Info.Record->getCanonicalDecl())
  117. return &Info;
  118. }
  119. if (!RD->getEnclosingNamespaceContext()->isStdNamespace())
  120. return nullptr;
  121. // If not, check to see if the decl names a type in namespace std with a name
  122. // matching one of the comparison category types.
  123. for (unsigned I = static_cast<unsigned>(CCT::First),
  124. End = static_cast<unsigned>(CCT::Last);
  125. I <= End; ++I) {
  126. CCT Kind = static_cast<CCT>(I);
  127. // We've found the comparison category type. Build a new cache entry for
  128. // it.
  129. if (getCategoryString(Kind) == RD->getName())
  130. return &Data.try_emplace((char)Kind, Ctx, RD, Kind).first->second;
  131. }
  132. // We've found nothing. This isn't a comparison category type.
  133. return nullptr;
  134. }
  135. const ComparisonCategoryInfo &ComparisonCategories::getInfoForType(QualType Ty) const {
  136. const ComparisonCategoryInfo *Info = lookupInfoForType(Ty);
  137. assert(Info && "info for comparison category not found");
  138. return *Info;
  139. }
  140. QualType ComparisonCategoryInfo::getType() const {
  141. assert(Record);
  142. return QualType(Record->getTypeForDecl(), 0);
  143. }
  144. StringRef ComparisonCategories::getCategoryString(ComparisonCategoryType Kind) {
  145. using CCKT = ComparisonCategoryType;
  146. switch (Kind) {
  147. case CCKT::PartialOrdering:
  148. return "partial_ordering";
  149. case CCKT::WeakOrdering:
  150. return "weak_ordering";
  151. case CCKT::StrongOrdering:
  152. return "strong_ordering";
  153. }
  154. llvm_unreachable("unhandled cases in switch");
  155. }
  156. StringRef ComparisonCategories::getResultString(ComparisonCategoryResult Kind) {
  157. using CCVT = ComparisonCategoryResult;
  158. switch (Kind) {
  159. case CCVT::Equal:
  160. return "equal";
  161. case CCVT::Equivalent:
  162. return "equivalent";
  163. case CCVT::Less:
  164. return "less";
  165. case CCVT::Greater:
  166. return "greater";
  167. case CCVT::Unordered:
  168. return "unordered";
  169. }
  170. llvm_unreachable("unhandled case in switch");
  171. }
  172. std::vector<ComparisonCategoryResult>
  173. ComparisonCategories::getPossibleResultsForType(ComparisonCategoryType Type) {
  174. using CCT = ComparisonCategoryType;
  175. using CCR = ComparisonCategoryResult;
  176. std::vector<CCR> Values;
  177. Values.reserve(4);
  178. bool IsStrong = Type == CCT::StrongOrdering;
  179. Values.push_back(IsStrong ? CCR::Equal : CCR::Equivalent);
  180. Values.push_back(CCR::Less);
  181. Values.push_back(CCR::Greater);
  182. if (Type == CCT::PartialOrdering)
  183. Values.push_back(CCR::Unordered);
  184. return Values;
  185. }