types.cc 45.4 KB
Newer Older
1 2 3 4
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
#include "src/torque/types.h"

7 8 9
#include <cmath>
#include <iostream>

10
#include "src/base/bits.h"
11
#include "src/base/optional.h"
12
#include "src/torque/ast.h"
13
#include "src/torque/declarable.h"
14
#include "src/torque/global-context.h"
15
#include "src/torque/source-positions.h"
16
#include "src/torque/type-oracle.h"
17
#include "src/torque/type-visitor.h"
18 19 20 21 22

namespace v8 {
namespace internal {
namespace torque {

23 24
// This custom copy constructor doesn't copy aliases_ and id_ because they
// should be distinct for each type.
25 26 27 28 29 30
Type::Type(const Type& other) V8_NOEXCEPT
    : TypeBase(other),
      parent_(other.parent_),
      aliases_(),
      id_(TypeOracle::FreshTypeId()),
      constexpr_version_(other.constexpr_version_) {}
31 32 33 34 35
Type::Type(TypeBase::Kind kind, const Type* parent,
           MaybeSpecializationKey specialized_from)
    : TypeBase(kind),
      parent_(parent),
      id_(TypeOracle::FreshTypeId()),
36 37
      specialized_from_(specialized_from),
      constexpr_version_(nullptr) {}
38

39
std::string Type::ToString() const {
40 41
  if (aliases_.size() == 0)
    return ComputeName(ToExplicitString(), GetSpecializedFrom());
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
  if (aliases_.size() == 1) return *aliases_.begin();
  std::stringstream result;
  int i = 0;
  for (const std::string& alias : aliases_) {
    if (i == 0) {
      result << alias << " (aka. ";
    } else if (i == 1) {
      result << alias;
    } else {
      result << ", " << alias;
    }
    ++i;
  }
  result << ")";
  return result.str();
}

59
std::string Type::SimpleName() const {
60 61 62 63 64 65 66 67 68 69
  if (aliases_.empty()) {
    std::stringstream result;
    result << SimpleNameImpl();
    if (GetSpecializedFrom()) {
      for (const Type* t : GetSpecializedFrom()->specialized_types) {
        result << "_" << t->SimpleName();
      }
    }
    return result.str();
  }
70 71 72
  return *aliases_.begin();
}

73 74 75
// TODO(danno): HandlifiedCppTypeName should be used universally in Torque
// where the C++ type of a Torque object is required.
std::string Type::HandlifiedCppTypeName() const {
76 77
  if (IsSubtypeOf(TypeOracle::GetSmiType())) return "int";
  if (IsSubtypeOf(TypeOracle::GetTaggedType())) {
78
    return "Handle<" + UnhandlifiedCppTypeName() + ">";
79
  } else {
80
    return UnhandlifiedCppTypeName();
81 82 83
  }
}

84 85 86 87 88 89
std::string Type::UnhandlifiedCppTypeName() const {
  if (IsSubtypeOf(TypeOracle::GetSmiType())) return "int";
  if (this == TypeOracle::GetObjectType()) return "Object";
  return GetConstexprGeneratedTypeName();
}

90
bool Type::IsSubtypeOf(const Type* supertype) const {
91
  if (supertype->IsTopType()) return true;
92
  if (IsNever()) return true;
93 94 95
  if (const UnionType* union_type = UnionType::DynamicCast(supertype)) {
    return union_type->IsSupertypeOf(this);
  }
96 97 98 99 100 101 102 103
  const Type* subtype = this;
  while (subtype != nullptr) {
    if (subtype == supertype) return true;
    subtype = subtype->parent();
  }
  return false;
}

104 105 106 107 108 109 110 111 112
std::string Type::GetConstexprGeneratedTypeName() const {
  const Type* constexpr_version = ConstexprVersion();
  if (constexpr_version == nullptr) {
    Error("Type '", ToString(), "' requires a constexpr representation");
    return "";
  }
  return constexpr_version->GetGeneratedTypeName();
}

113 114
base::Optional<const ClassType*> Type::ClassSupertype() const {
  for (const Type* t = this; t != nullptr; t = t->parent()) {
115 116 117
    if (auto* class_type = ClassType::DynamicCast(t)) {
      return class_type;
    }
118 119 120 121
  }
  return base::nullopt;
}

122 123 124 125 126 127 128 129 130
base::Optional<const StructType*> Type::StructSupertype() const {
  for (const Type* t = this; t != nullptr; t = t->parent()) {
    if (auto* struct_type = StructType::DynamicCast(t)) {
      return struct_type;
    }
  }
  return base::nullopt;
}

131 132 133 134 135 136 137 138 139
base::Optional<const AggregateType*> Type::AggregateSupertype() const {
  for (const Type* t = this; t != nullptr; t = t->parent()) {
    if (auto* aggregate_type = AggregateType::DynamicCast(t)) {
      return aggregate_type;
    }
  }
  return base::nullopt;
}

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
// static
const Type* Type::CommonSupertype(const Type* a, const Type* b) {
  int diff = a->Depth() - b->Depth();
  const Type* a_supertype = a;
  const Type* b_supertype = b;
  for (; diff > 0; --diff) a_supertype = a_supertype->parent();
  for (; diff < 0; ++diff) b_supertype = b_supertype->parent();
  while (a_supertype && b_supertype) {
    if (a_supertype == b_supertype) return a_supertype;
    a_supertype = a_supertype->parent();
    b_supertype = b_supertype->parent();
  }
  ReportError("types " + a->ToString() + " and " + b->ToString() +
              " have no common supertype");
}

int Type::Depth() const {
  int result = 0;
  for (const Type* current = parent_; current; current = current->parent_) {
    ++result;
  }
  return result;
}

164 165 166 167 168
bool Type::IsAbstractName(const std::string& name) const {
  if (!IsAbstractType()) return false;
  return AbstractType::cast(this)->name() == name;
}

169 170
std::string Type::GetGeneratedTypeName() const {
  std::string result = GetGeneratedTypeNameImpl();
171
  if (result.empty() || result == "TNode<>") {
172 173 174 175 176 177 178 179
    ReportError("Generated type is required for type '", ToString(),
                "'. Use 'generates' clause in definition.");
  }
  return result;
}

std::string Type::GetGeneratedTNodeTypeName() const {
  std::string result = GetGeneratedTNodeTypeNameImpl();
180
  if (result.empty() || IsConstexpr()) {
181 182 183 184 185 186
    ReportError("Generated TNode type is required for type '", ToString(),
                "'. Use 'generates' clause in definition.");
  }
  return result;
}

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
std::string AbstractType::GetGeneratedTypeNameImpl() const {
  // A special case that is not very well represented by the "generates"
  // syntax in the .tq files: Lazy<T> represents a std::function that
  // produces a TNode of the wrapped type.
  if (base::Optional<const Type*> type_wrapped_in_lazy =
          Type::MatchUnaryGeneric(this, TypeOracle::GetLazyGeneric())) {
    DCHECK(!IsConstexpr());
    return "std::function<" + (*type_wrapped_in_lazy)->GetGeneratedTypeName() +
           "()>";
  }

  if (generated_type_.empty()) {
    return parent()->GetGeneratedTypeName();
  }
  return IsConstexpr() ? generated_type_ : "TNode<" + generated_type_ + ">";
}

204
std::string AbstractType::GetGeneratedTNodeTypeNameImpl() const {
205
  if (generated_type_.empty()) return parent()->GetGeneratedTNodeTypeName();
206
  return generated_type_;
207 208
}

209 210 211
std::vector<TypeChecker> AbstractType::GetTypeCheckers() const {
  if (UseParentTypeChecker()) return parent()->GetTypeCheckers();
  std::string type_name = name();
212 213
  if (auto strong_type =
          Type::MatchUnaryGeneric(this, TypeOracle::GetWeakGeneric())) {
214 215 216
    auto strong_runtime_types = (*strong_type)->GetTypeCheckers();
    std::vector<TypeChecker> result;
    for (const TypeChecker& type : strong_runtime_types) {
217 218 219 220 221 222 223 224 225 226
      // Generic parameter in Weak<T> should have already been checked to
      // extend HeapObject, so it couldn't itself be another weak type.
      DCHECK(type.weak_ref_to.empty());
      result.push_back({type_name, type.type});
    }
    return result;
  }
  return {{type_name, ""}};
}

227
std::string BuiltinPointerType::ToExplicitString() const {
228 229
  std::stringstream result;
  result << "builtin (";
230 231
  PrintCommaSeparatedList(result, parameter_types_);
  result << ") => " << *return_type_;
232 233 234
  return result.str();
}

235
std::string BuiltinPointerType::SimpleNameImpl() const {
236
  std::stringstream result;
237
  result << "BuiltinPointer";
238
  for (const Type* t : parameter_types_) {
239
    result << "_" << t->SimpleName();
240
  }
241
  result << "_" << return_type_->SimpleName();
242 243 244
  return result.str();
}

245 246 247 248 249 250 251 252 253
std::string UnionType::ToExplicitString() const {
  std::stringstream result;
  result << "(";
  bool first = true;
  for (const Type* t : types_) {
    if (!first) {
      result << " | ";
    }
    first = false;
254
    result << *t;
255 256 257 258 259
  }
  result << ")";
  return result.str();
}

260
std::string UnionType::SimpleNameImpl() const {
261
  std::stringstream result;
262
  bool first = true;
263
  for (const Type* t : types_) {
264 265 266 267 268
    if (!first) {
      result << "_OR_";
    }
    first = false;
    result << t->SimpleName();
269 270 271 272
  }
  return result.str();
}

273
std::string UnionType::GetGeneratedTNodeTypeNameImpl() const {
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
  if (types_.size() <= 3) {
    std::set<std::string> members;
    for (const Type* t : types_) {
      members.insert(t->GetGeneratedTNodeTypeName());
    }
    if (members == std::set<std::string>{"Smi", "HeapNumber"}) {
      return "Number";
    }
    if (members == std::set<std::string>{"Smi", "HeapNumber", "BigInt"}) {
      return "Numeric";
    }
  }
  return parent()->GetGeneratedTNodeTypeName();
}

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
void UnionType::RecomputeParent() {
  const Type* parent = nullptr;
  for (const Type* t : types_) {
    if (parent == nullptr) {
      parent = t;
    } else {
      parent = CommonSupertype(parent, t);
    }
  }
  set_parent(parent);
}

void UnionType::Subtract(const Type* t) {
  for (auto it = types_.begin(); it != types_.end();) {
    if ((*it)->IsSubtypeOf(t)) {
      it = types_.erase(it);
    } else {
      ++it;
    }
  }
  if (types_.size() == 0) types_.insert(TypeOracle::GetNeverType());
  RecomputeParent();
}

const Type* SubtractType(const Type* a, const Type* b) {
  UnionType result = UnionType::FromType(a);
  result.Subtract(b);
  return TypeOracle::GetUnionType(result);
}

319 320 321 322
std::string BitFieldStructType::ToExplicitString() const {
  return "bitfield struct " + name();
}

323 324 325 326 327 328 329 330 331
const BitField& BitFieldStructType::LookupField(const std::string& name) const {
  for (const BitField& field : fields_) {
    if (field.name_and_type.name == name) {
      return field;
    }
  }
  ReportError("Couldn't find bitfield ", name);
}

332
void AggregateType::CheckForDuplicateFields() const {
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
  // Check the aggregate hierarchy and currently defined class for duplicate
  // field declarations.
  auto hierarchy = GetHierarchy();
  std::map<std::string, const AggregateType*> field_names;
  for (const AggregateType* aggregate_type : hierarchy) {
    for (const Field& field : aggregate_type->fields()) {
      const std::string& field_name = field.name_and_type.name;
      auto i = field_names.find(field_name);
      if (i != field_names.end()) {
        CurrentSourcePosition::Scope current_source_position(field.pos);
        std::string aggregate_type_name =
            aggregate_type->IsClassType() ? "class" : "struct";
        if (i->second == this) {
          ReportError(aggregate_type_name, " '", name(),
                      "' declares a field with the name '", field_name,
                      "' more than once");
        } else {
          ReportError(aggregate_type_name, " '", name(),
                      "' declares a field with the name '", field_name,
                      "' that masks an inherited field from class '",
                      i->second->name(), "'");
        }
      }
      field_names[field_name] = aggregate_type;
    }
  }
}

361 362
std::vector<const AggregateType*> AggregateType::GetHierarchy() const {
  if (!is_finalized_) Finalize();
363 364 365 366 367 368 369 370 371 372 373 374 375
  std::vector<const AggregateType*> hierarchy;
  const AggregateType* current_container_type = this;
  while (current_container_type != nullptr) {
    hierarchy.push_back(current_container_type);
    current_container_type =
        current_container_type->IsClassType()
            ? ClassType::cast(current_container_type)->GetSuperClass()
            : nullptr;
  }
  std::reverse(hierarchy.begin(), hierarchy.end());
  return hierarchy;
}

376
bool AggregateType::HasField(const std::string& name) const {
377
  if (!is_finalized_) Finalize();
378 379 380 381 382 383 384 385 386 387 388
  for (auto& field : fields_) {
    if (field.name_and_type.name == name) return true;
  }
  if (parent() != nullptr) {
    if (auto parent_class = ClassType::DynamicCast(parent())) {
      return parent_class->HasField(name);
    }
  }
  return false;
}

389
const Field& AggregateType::LookupFieldInternal(const std::string& name) const {
390 391 392 393 394 395 396 397
  for (auto& field : fields_) {
    if (field.name_and_type.name == name) return field;
  }
  if (parent() != nullptr) {
    if (auto parent_class = ClassType::DynamicCast(parent())) {
      return parent_class->LookupField(name);
    }
  }
398
  ReportError("no field ", name, " found in ", this->ToString());
399 400
}

401 402 403 404 405
const Field& AggregateType::LookupField(const std::string& name) const {
  if (!is_finalized_) Finalize();
  return LookupFieldInternal(name);
}

406 407
StructType::StructType(Namespace* nspace, const StructDeclaration* decl,
                       MaybeSpecializationKey specialized_from)
408 409 410
    : AggregateType(Kind::kStructType, nullptr, nspace, decl->name->value,
                    specialized_from),
      decl_(decl) {
411 412 413 414 415 416 417 418
  if (decl->flags & StructFlag::kExport) {
    generated_type_name_ = "TorqueStruct" + name();
  } else {
    generated_type_name_ =
        GlobalContext::MakeUniqueName("TorqueStruct" + SimpleName());
  }
}

419
std::string StructType::GetGeneratedTypeNameImpl() const {
420
  return generated_type_name_;
421 422
}

423 424
size_t StructType::PackedSize() const {
  size_t result = 0;
425 426
  for (const Field& field : fields()) {
    result += std::get<0>(field.GetFieldSizeInformation());
427 428 429 430
  }
  return result;
}

431 432 433 434
StructType::Classification StructType::ClassifyContents() const {
  Classification result = ClassificationFlag::kEmpty;
  for (const Field& struct_field : fields()) {
    const Type* field_type = struct_field.name_and_type.type;
435 436 437 438
    if (field_type->IsSubtypeOf(TypeOracle::GetStrongTaggedType())) {
      result |= ClassificationFlag::kStrongTagged;
    } else if (field_type->IsSubtypeOf(TypeOracle::GetTaggedType())) {
      result |= ClassificationFlag::kWeakTagged;
439 440
    } else if (auto field_as_struct = field_type->StructSupertype()) {
      result |= (*field_as_struct)->ClassifyContents();
441 442 443 444 445 446 447
    } else {
      result |= ClassificationFlag::kUntagged;
    }
  }
  return result;
}

448
// static
449 450
std::string Type::ComputeName(const std::string& basename,
                              MaybeSpecializationKey specialized_from) {
451
  if (!specialized_from) return basename;
452 453 454 455 456 457
  if (specialized_from->generic == TypeOracle::GetConstReferenceGeneric()) {
    return torque::ToString("const &", *specialized_from->specialized_types[0]);
  }
  if (specialized_from->generic == TypeOracle::GetMutableReferenceGeneric()) {
    return torque::ToString("&", *specialized_from->specialized_types[0]);
  }
458 459 460
  std::stringstream s;
  s << basename << "<";
  bool first = true;
461
  for (auto t : specialized_from->specialized_types) {
462 463 464 465 466 467 468 469
    if (!first) {
      s << ", ";
    }
    s << t->ToString();
    first = false;
  }
  s << ">";
  return s.str();
470 471
}

472
std::string StructType::SimpleNameImpl() const { return decl_->name->value; }
473 474

// static
475 476
base::Optional<const Type*> Type::MatchUnaryGeneric(const Type* type,
                                                    GenericType* generic) {
477
  DCHECK_EQ(generic->generic_parameters().size(), 1);
478
  if (!type->GetSpecializedFrom()) {
479 480
    return base::nullopt;
  }
481
  auto& key = type->GetSpecializedFrom().value();
482 483 484 485 486 487
  if (key.generic != generic || key.specialized_types.size() != 1) {
    return base::nullopt;
  }
  return {key.specialized_types[0]};
}

488
std::vector<Method*> AggregateType::Methods(const std::string& name) const {
489
  if (!is_finalized_) Finalize();
490 491
  std::vector<Method*> result;
  std::copy_if(methods_.begin(), methods_.end(), std::back_inserter(result),
492
               [name](Macro* macro) { return macro->ReadableName() == name; });
493 494 495 496 497
  if (result.empty() && parent() != nullptr) {
    if (auto aggregate_parent = parent()->AggregateSupertype()) {
      return (*aggregate_parent)->Methods(name);
    }
  }
498 499 500
  return result;
}

501
std::string StructType::ToExplicitString() const { return "struct " + name(); }
502

503 504 505 506 507 508 509 510 511 512 513
void StructType::Finalize() const {
  if (is_finalized_) return;
  {
    CurrentScope::Scope scope_activator(nspace());
    CurrentSourcePosition::Scope position_activator(decl_->pos);
    TypeVisitor::VisitStructMethods(const_cast<StructType*>(this), decl_);
  }
  is_finalized_ = true;
  CheckForDuplicateFields();
}

514
ClassType::ClassType(const Type* parent, Namespace* nspace,
515
                     const std::string& name, ClassFlags flags,
516 517
                     const std::string& generates, const ClassDeclaration* decl,
                     const TypeAlias* alias)
518
    : AggregateType(Kind::kClassType, parent, nspace, name),
519
      size_(ResidueClass::Unknown()),
520
      flags_(flags),
521 522
      generates_(generates),
      decl_(decl),
523
      alias_(alias) {}
524

525
std::string ClassType::GetGeneratedTNodeTypeNameImpl() const {
526
  return generates_;
527 528
}

529
std::string ClassType::GetGeneratedTypeNameImpl() const {
530
  return IsConstexpr() ? GetGeneratedTNodeTypeName()
531
                       : "TNode<" + GetGeneratedTNodeTypeName() + ">";
532 533
}

534
std::string ClassType::ToExplicitString() const { return "class " + name(); }
535

536
bool ClassType::AllowInstantiation() const {
537
  return (!IsExtern() || nspace()->IsDefaultNamespace()) && !IsAbstract();
538 539
}

540 541 542 543 544 545 546 547 548 549
void ClassType::Finalize() const {
  if (is_finalized_) return;
  CurrentScope::Scope scope_activator(alias_->ParentScope());
  CurrentSourcePosition::Scope position_activator(decl_->pos);
  TypeVisitor::VisitClassFieldsAndMethods(const_cast<ClassType*>(this),
                                          this->decl_);
  is_finalized_ = true;
  CheckForDuplicateFields();
}

550 551 552 553 554 555 556 557 558 559 560
std::vector<Field> ClassType::ComputeAllFields() const {
  std::vector<Field> all_fields;
  const ClassType* super_class = this->GetSuperClass();
  if (super_class) {
    all_fields = super_class->ComputeAllFields();
  }
  const std::vector<Field>& fields = this->fields();
  all_fields.insert(all_fields.end(), fields.begin(), fields.end());
  return all_fields;
}

561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
std::vector<Field> ClassType::ComputeHeaderFields() const {
  std::vector<Field> result;
  for (Field& field : ComputeAllFields()) {
    if (field.index) break;
    DCHECK(*field.offset < header_size());
    result.push_back(std::move(field));
  }
  return result;
}

std::vector<Field> ClassType::ComputeArrayFields() const {
  std::vector<Field> result;
  for (Field& field : ComputeAllFields()) {
    if (!field.index) {
      DCHECK(*field.offset < header_size());
      continue;
    }
    result.push_back(std::move(field));
  }
  return result;
}

void ClassType::InitializeInstanceTypes(
    base::Optional<int> own, base::Optional<std::pair<int, int>> range) const {
  DCHECK(!own_instance_type_.has_value());
  DCHECK(!instance_type_range_.has_value());
  own_instance_type_ = own;
  instance_type_range_ = range;
}

base::Optional<int> ClassType::OwnInstanceType() const {
  DCHECK(GlobalContext::IsInstanceTypesInitialized());
  return own_instance_type_;
}

base::Optional<std::pair<int, int>> ClassType::InstanceTypeRange() const {
  DCHECK(GlobalContext::IsInstanceTypesInitialized());
  return instance_type_range_;
}

namespace {
void ComputeSlotKindsHelper(std::vector<ObjectSlotKind>* slots,
                            size_t start_offset,
                            const std::vector<Field>& fields) {
  size_t offset = start_offset;
  for (const Field& field : fields) {
    size_t field_size = std::get<0>(field.GetFieldSizeInformation());
    size_t slot_index = offset / TargetArchitecture::TaggedSize();
    // Rounding-up division to find the number of slots occupied by all the
    // fields up to and including the current one.
    size_t used_slots =
        (offset + field_size + TargetArchitecture::TaggedSize() - 1) /
        TargetArchitecture::TaggedSize();
    while (used_slots > slots->size()) {
      slots->push_back(ObjectSlotKind::kNoPointer);
    }
    const Type* type = field.name_and_type.type;
    if (auto struct_type = type->StructSupertype()) {
      ComputeSlotKindsHelper(slots, offset, (*struct_type)->fields());
    } else {
      ObjectSlotKind kind;
      if (type->IsSubtypeOf(TypeOracle::GetObjectType())) {
623
        if (field.custom_weak_marking) {
624 625 626 627 628
          kind = ObjectSlotKind::kCustomWeakPointer;
        } else {
          kind = ObjectSlotKind::kStrongPointer;
        }
      } else if (type->IsSubtypeOf(TypeOracle::GetTaggedType())) {
629
        DCHECK(!field.custom_weak_marking);
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
        kind = ObjectSlotKind::kMaybeObjectPointer;
      } else {
        kind = ObjectSlotKind::kNoPointer;
      }
      DCHECK(slots->at(slot_index) == ObjectSlotKind::kNoPointer);
      slots->at(slot_index) = kind;
    }

    offset += field_size;
  }
}
}  // namespace

std::vector<ObjectSlotKind> ClassType::ComputeHeaderSlotKinds() const {
  std::vector<ObjectSlotKind> result;
  std::vector<Field> header_fields = ComputeHeaderFields();
  ComputeSlotKindsHelper(&result, 0, header_fields);
647 648
  DCHECK_EQ(std::ceil(static_cast<double>(header_size()) /
                      TargetArchitecture::TaggedSize()),
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
            result.size());
  return result;
}

base::Optional<ObjectSlotKind> ClassType::ComputeArraySlotKind() const {
  std::vector<ObjectSlotKind> kinds;
  ComputeSlotKindsHelper(&kinds, 0, ComputeArrayFields());
  if (kinds.empty()) return base::nullopt;
  std::sort(kinds.begin(), kinds.end());
  if (kinds.front() == kinds.back()) return {kinds.front()};
  if (kinds.front() == ObjectSlotKind::kStrongPointer &&
      kinds.back() == ObjectSlotKind::kMaybeObjectPointer) {
    return ObjectSlotKind::kMaybeObjectPointer;
  }
  Error("Array fields mix types with different GC visitation requirements.")
      .Throw();
}

bool ClassType::HasNoPointerSlots() const {
  for (ObjectSlotKind slot : ComputeHeaderSlotKinds()) {
    if (slot != ObjectSlotKind::kNoPointer) return false;
  }
  if (auto slot = ComputeArraySlotKind()) {
    if (*slot != ObjectSlotKind::kNoPointer) return false;
  }
  return true;
}

677 678 679 680 681 682 683 684 685 686
bool ClassType::HasIndexedFieldsIncludingInParents() const {
  for (const auto& field : fields_) {
    if (field.index.has_value()) return true;
  }
  if (const ClassType* parent = GetSuperClass()) {
    return parent->HasIndexedFieldsIncludingInParents();
  }
  return false;
}

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
const Field* ClassType::GetFieldPreceding(size_t field_index) const {
  if (field_index > 0) {
    return &fields_[field_index - 1];
  }
  if (const ClassType* parent = GetSuperClass()) {
    return parent->GetFieldPreceding(parent->fields_.size());
  }
  return nullptr;
}

const ClassType* ClassType::GetClassDeclaringField(const Field& f) const {
  for (const Field& field : fields_) {
    if (f.name_and_type.name == field.name_and_type.name) return this;
  }
  return GetSuperClass()->GetClassDeclaringField(f);
}

std::string ClassType::GetSliceMacroName(const Field& field) const {
  const ClassType* declarer = GetClassDeclaringField(field);
  return "FieldSlice" + declarer->name() +
         CamelifyString(field.name_and_type.name);
}

710
void ClassType::GenerateAccessors() {
711 712 713 714
  bool at_or_after_indexed_field = false;
  if (const ClassType* parent = GetSuperClass()) {
    at_or_after_indexed_field = parent->HasIndexedFieldsIncludingInParents();
  }
715
  // For each field, construct AST snippets that implement a CSA accessor
716
  // function. The implementation iterator will turn the snippets into code.
717 718
  for (size_t field_index = 0; field_index < fields_.size(); ++field_index) {
    Field& field = fields_[field_index];
719
    if (field.name_and_type.type == TypeOracle::GetVoidType()) {
720 721
      continue;
    }
722 723
    at_or_after_indexed_field =
        at_or_after_indexed_field || field.index.has_value();
724
    CurrentSourcePosition::Scope position_activator(field.pos);
725

726 727
    IdentifierExpression* parameter = MakeIdentifierExpression("o");
    IdentifierExpression* index = MakeIdentifierExpression("i");
728 729

    std::string camel_field_name = CamelifyString(field.name_and_type.name);
730 731

    if (at_or_after_indexed_field) {
732 733 734 735 736 737 738 739 740
      if (!field.index.has_value()) {
        // There's no fundamental reason we couldn't generate functions to get
        // references instead of slices, but it's not yet implemented.
        ReportError(
            "Torque doesn't yet support non-indexed fields after indexed "
            "fields");
      }

      GenerateSliceAccessor(field_index);
741
    }
742 743 744 745 746 747

    // For now, only generate indexed accessors for simple types
    if (field.index.has_value() && field.name_and_type.type->IsStructType()) {
      continue;
    }

748 749 750 751
    // An explicit index is only used for indexed fields not marked as optional.
    // Optional fields implicitly load or store item zero.
    bool use_index = field.index && !field.index->optional;

752 753
    // Load accessor
    std::string load_macro_name = "Load" + this->name() + camel_field_name;
754 755 756
    Signature load_signature;
    load_signature.parameter_names.push_back(MakeNode<Identifier>("o"));
    load_signature.parameter_types.types.push_back(this);
757
    if (use_index) {
758 759 760 761
      load_signature.parameter_names.push_back(MakeNode<Identifier>("i"));
      load_signature.parameter_types.types.push_back(
          TypeOracle::GetIntPtrType());
    }
762 763
    load_signature.parameter_types.var_args = false;
    load_signature.return_type = field.name_and_type.type;
764

765 766
    Expression* load_expression =
        MakeFieldAccessExpression(parameter, field.name_and_type.name);
767
    if (use_index) {
768 769 770 771
      load_expression =
          MakeNode<ElementAccessExpression>(load_expression, index);
    }
    Statement* load_body = MakeNode<ReturnStatement>(load_expression);
772
    Declarations::DeclareMacro(load_macro_name, true, base::nullopt,
773
                               load_signature, load_body, base::nullopt);
774 775

    // Store accessor
776
    if (!field.const_qualified) {
777
      IdentifierExpression* value = MakeIdentifierExpression("v");
778 779 780 781
      std::string store_macro_name = "Store" + this->name() + camel_field_name;
      Signature store_signature;
      store_signature.parameter_names.push_back(MakeNode<Identifier>("o"));
      store_signature.parameter_types.types.push_back(this);
782
      if (use_index) {
783 784 785 786 787 788 789 790 791
        store_signature.parameter_names.push_back(MakeNode<Identifier>("i"));
        store_signature.parameter_types.types.push_back(
            TypeOracle::GetIntPtrType());
      }
      store_signature.parameter_names.push_back(MakeNode<Identifier>("v"));
      store_signature.parameter_types.types.push_back(field.name_and_type.type);
      store_signature.parameter_types.var_args = false;
      // TODO(danno): Store macros probably should return their value argument
      store_signature.return_type = TypeOracle::GetVoidType();
792 793
      Expression* store_expression =
          MakeFieldAccessExpression(parameter, field.name_and_type.name);
794
      if (use_index) {
795 796 797 798 799 800 801 802
        store_expression =
            MakeNode<ElementAccessExpression>(store_expression, index);
      }
      Statement* store_body = MakeNode<ExpressionStatement>(
          MakeNode<AssignmentExpression>(store_expression, value));
      Declarations::DeclareMacro(store_macro_name, true, base::nullopt,
                                 store_signature, store_body, base::nullopt,
                                 false);
803
    }
804 805 806
  }
}

807 808 809 810 811 812 813 814
void ClassType::GenerateSliceAccessor(size_t field_index) {
  // Generate a Torque macro for getting a Slice to this field. This macro can
  // be called by the dot operator for this field. In Torque, this function for
  // class "ClassName" and field "field_name" and field type "FieldType" would
  // be written as one of the following:
  //
  // If the field has a known offset (in this example, 16):
  // FieldSliceClassNameFieldName(o: ClassName) {
815 816 817 818 819
  //   return torque_internal::unsafe::New{Const,Mutable}Slice<FieldType>(
  //     /*object:*/ o,
  //     /*offset:*/ 16,
  //     /*length:*/ torque_internal::%IndexedFieldLength<ClassName>(
  //                     o, "field_name")
820
  //   );
821 822
  // }
  //
823 824
  // If the field has an unknown offset, and the previous field is named p, is
  // not const, and is of type PType with size 4:
825
  // FieldSliceClassNameFieldName(o: ClassName) {
826
  //   const previous = %FieldSlice<ClassName, MutableSlice<PType>>(o, "p");
827 828 829 830 831
  //   return torque_internal::unsafe::New{Const,Mutable}Slice<FieldType>(
  //     /*object:*/ o,
  //     /*offset:*/ previous.offset + 4 * previous.length,
  //     /*length:*/ torque_internal::%IndexedFieldLength<ClassName>(
  //                     o, "field_name")
832
  //   );
833 834 835 836 837 838 839 840
  // }
  const Field& field = fields_[field_index];
  std::string macro_name = GetSliceMacroName(field);
  Signature signature;
  Identifier* parameter_identifier = MakeNode<Identifier>("o");
  signature.parameter_names.push_back(parameter_identifier);
  signature.parameter_types.types.push_back(this);
  signature.parameter_types.var_args = false;
841 842 843 844
  signature.return_type =
      field.const_qualified
          ? TypeOracle::GetConstSliceType(field.name_and_type.type)
          : TypeOracle::GetMutableSliceType(field.name_and_type.type);
845 846 847 848 849 850 851 852

  std::vector<Statement*> statements;
  Expression* offset_expression = nullptr;
  IdentifierExpression* parameter =
      MakeNode<IdentifierExpression>(parameter_identifier);

  if (field.offset.has_value()) {
    offset_expression =
853
        MakeNode<IntegerLiteralExpression>(IntegerLiteral(*field.offset));
854 855 856 857
  } else {
    const Field* previous = GetFieldPreceding(field_index);
    DCHECK_NOT_NULL(previous);

858 859 860 861 862 863
    const Type* previous_slice_type =
        previous->const_qualified
            ? TypeOracle::GetConstSliceType(previous->name_and_type.type)
            : TypeOracle::GetMutableSliceType(previous->name_and_type.type);

    // %FieldSlice<ClassName, MutableSlice<PType>>(o, "p")
864
    Expression* previous_expression = MakeCallExpression(
865 866 867 868
        MakeIdentifierExpression(
            {"torque_internal"}, "%FieldSlice",
            {MakeNode<PrecomputedTypeExpression>(this),
             MakeNode<PrecomputedTypeExpression>(previous_slice_type)}),
869 870
        {parameter, MakeNode<StringLiteralExpression>(
                        StringLiteralQuote(previous->name_and_type.name))});
871

872
    // const previous = %FieldSlice<ClassName, MutableSlice<PType>>(o, "p");
873 874 875 876 877 878 879 880 881
    Statement* define_previous =
        MakeConstDeclarationStatement("previous", previous_expression);
    statements.push_back(define_previous);

    // 4
    size_t previous_element_size;
    std::tie(previous_element_size, std::ignore) =
        *SizeOf(previous->name_and_type.type);
    Expression* previous_element_size_expression =
882 883
        MakeNode<IntegerLiteralExpression>(
            IntegerLiteral(previous_element_size));
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910

    // previous.length
    Expression* previous_length_expression = MakeFieldAccessExpression(
        MakeIdentifierExpression("previous"), "length");

    // previous.offset
    Expression* previous_offset_expression = MakeFieldAccessExpression(
        MakeIdentifierExpression("previous"), "offset");

    // 4 * previous.length
    // In contrast to the code used for allocation, we don't need overflow
    // checks here because we already know all the offsets fit into memory.
    offset_expression = MakeCallExpression(
        "*", {previous_element_size_expression, previous_length_expression});

    // previous.offset + 4 * previous.length
    offset_expression = MakeCallExpression(
        "+", {previous_offset_expression, offset_expression});
  }

  // torque_internal::%IndexedFieldLength<ClassName>(o, "field_name")
  Expression* length_expression = MakeCallExpression(
      MakeIdentifierExpression({"torque_internal"}, "%IndexedFieldLength",
                               {MakeNode<PrecomputedTypeExpression>(this)}),
      {parameter, MakeNode<StringLiteralExpression>(
                      StringLiteralQuote(field.name_and_type.name))});

911
  // torque_internal::unsafe::New{Const,Mutable}Slice<FieldType>(
912 913 914 915
  //   /*object:*/ o,
  //   /*offset:*/ <<offset_expression>>,
  //   /*length:*/ torque_internal::%IndexedFieldLength<ClassName>(
  //                   o, "field_name")
916 917 918 919 920 921 922
  // )
  IdentifierExpression* new_struct = MakeIdentifierExpression(
      {"torque_internal", "unsafe"},
      field.const_qualified ? "NewConstSlice" : "NewMutableSlice",
      {MakeNode<PrecomputedTypeExpression>(field.name_and_type.type)});
  Expression* slice_expression = MakeCallExpression(
      new_struct, {parameter, offset_expression, length_expression});
923 924 925 926 927 928 929

  statements.push_back(MakeNode<ReturnStatement>(slice_expression));
  Statement* block =
      MakeNode<BlockStatement>(/*deferred=*/false, std::move(statements));

  Macro* macro = Declarations::DeclareMacro(macro_name, true, base::nullopt,
                                            signature, block, base::nullopt);
930 931
  GlobalContext::EnsureInCCOutputList(TorqueMacro::cast(macro),
                                      macro->Position().source);
932 933
}

934
bool ClassType::HasStaticSize() const {
935 936
  if (IsSubtypeOf(TypeOracle::GetJSObjectType()) && !IsShape()) return false;
  return size().SingleValue().has_value();
937 938
}

939 940 941 942 943 944 945 946 947
SourceId ClassType::AttributedToFile() const {
  bool in_test_directory = StringStartsWith(
      SourceFileMap::PathFromV8Root(GetPosition().source).substr(), "test/");
  if (!in_test_directory && (IsExtern() || ShouldExport())) {
    return GetPosition().source;
  }
  return SourceFileMap::GetSourceId("src/objects/torque-defined-classes.tq");
}

948
void PrintSignature(std::ostream& os, const Signature& sig, bool with_names) {
949
  os << "(";
950
  for (size_t i = 0; i < sig.parameter_types.types.size(); ++i) {
951 952 953 954 955 956
    if (i == 0 && sig.implicit_count != 0) os << "implicit ";
    if (sig.implicit_count > 0 && sig.implicit_count == i) {
      os << ")(";
    } else {
      if (i > 0) os << ", ";
    }
957
    if (with_names && !sig.parameter_names.empty()) {
958 959 960
      if (i < sig.parameter_names.size()) {
        os << sig.parameter_names[i] << ": ";
      }
961 962
    }
    os << *sig.parameter_types.types[i];
963 964 965 966 967 968
  }
  if (sig.parameter_types.var_args) {
    if (sig.parameter_names.size()) os << ", ";
    os << "...";
  }
  os << ")";
969
  os << ": " << *sig.return_type;
970

971
  if (sig.labels.empty()) return;
972 973 974 975

  os << " labels ";
  for (size_t i = 0; i < sig.labels.size(); ++i) {
    if (i > 0) os << ", ";
976
    os << sig.labels[i].name;
977
    if (sig.labels[i].types.size() > 0) os << "(" << sig.labels[i].types << ")";
978
  }
979 980
}

981 982 983 984 985 986 987
std::ostream& operator<<(std::ostream& os, const NameAndType& name_and_type) {
  os << name_and_type.name;
  os << ": ";
  os << *name_and_type.type;
  return os;
}

988 989
std::ostream& operator<<(std::ostream& os, const Field& field) {
  os << field.name_and_type;
990 991
  if (field.custom_weak_marking) {
    os << " (custom weak)";
992 993 994 995
  }
  return os;
}

996 997
std::ostream& operator<<(std::ostream& os, const Signature& sig) {
  PrintSignature(os, sig, true);
998 999 1000 1001
  return os;
}

std::ostream& operator<<(std::ostream& os, const TypeVector& types) {
1002
  PrintCommaSeparatedList(os, types);
1003 1004 1005 1006
  return os;
}

std::ostream& operator<<(std::ostream& os, const ParameterTypes& p) {
1007
  PrintCommaSeparatedList(os, p.types);
1008 1009 1010 1011 1012 1013 1014
  if (p.var_args) {
    if (p.types.size() > 0) os << ", ";
    os << "...";
  }
  return os;
}

1015 1016
bool Signature::HasSameTypesAs(const Signature& other,
                               ParameterMode mode) const {
1017 1018
  auto compare_types = types();
  auto other_compare_types = other.types();
1019 1020 1021 1022
  if (mode == ParameterMode::kIgnoreImplicit) {
    compare_types = GetExplicitTypes();
    other_compare_types = other.GetExplicitTypes();
  }
1023
  if (!(compare_types == other_compare_types &&
1024 1025 1026 1027 1028 1029 1030 1031
        parameter_types.var_args == other.parameter_types.var_args &&
        return_type == other.return_type)) {
    return false;
  }
  if (labels.size() != other.labels.size()) {
    return false;
  }
  size_t i = 0;
1032
  for (const auto& l : labels) {
1033 1034 1035 1036 1037 1038 1039
    if (l.types != other.labels[i++].types) {
      return false;
    }
  }
  return true;
}

1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
namespace {
bool FirstTypeIsContext(const std::vector<const Type*> parameter_types) {
  return !parameter_types.empty() &&
         parameter_types[0] == TypeOracle::GetContextType();
}
}  // namespace

bool Signature::HasContextParameter() const {
  return FirstTypeIsContext(types());
}

bool BuiltinPointerType::HasContextParameter() const {
  return FirstTypeIsContext(parameter_types());
}

1055 1056
bool IsAssignableFrom(const Type* to, const Type* from) {
  if (to == from) return true;
1057
  if (from->IsSubtypeOf(to)) return true;
1058
  return TypeOracle::ImplicitlyConvertableFrom(to, from).has_value();
1059 1060
}

1061
bool operator<(const Type& a, const Type& b) { return a.id() < b.id(); }
1062

1063
VisitResult ProjectStructField(VisitResult structure,
1064 1065
                               const std::string& fieldname) {
  BottomOffset begin = structure.stack_range().begin();
1066 1067

  // Check constructor this super classes for fields.
1068
  const StructType* type = *structure.type()->StructSupertype();
1069 1070
  auto& fields = type->fields();
  for (auto& field : fields) {
1071 1072 1073
    BottomOffset end = begin + LoweredSlotCount(field.name_and_type.type);
    if (field.name_and_type.name == fieldname) {
      return VisitResult(field.name_and_type.type, StackRange{begin, end});
1074 1075 1076
    }
    begin = end;
  }
1077

1078 1079
  ReportError("struct '", type->name(), "' doesn't contain a field '",
              fieldname, "'");
1080
}
1081

1082 1083 1084 1085 1086
namespace {
void AppendLoweredTypes(const Type* type, std::vector<const Type*>* result) {
  DCHECK_NE(type, TypeOracle::GetNeverType());
  if (type->IsConstexpr()) return;
  if (type == TypeOracle::GetVoidType()) return;
1087 1088
  if (base::Optional<const StructType*> s = type->StructSupertype()) {
    for (const Field& field : (*s)->fields()) {
1089
      AppendLoweredTypes(field.name_and_type.type, result);
1090 1091
    }
  } else {
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
    result->push_back(type);
  }
}
}  // namespace

TypeVector LowerType(const Type* type) {
  TypeVector result;
  AppendLoweredTypes(type, &result);
  return result;
}

size_t LoweredSlotCount(const Type* type) { return LowerType(type).size(); }

TypeVector LowerParameterTypes(const TypeVector& parameters) {
  std::vector<const Type*> result;
  for (const Type* t : parameters) {
    AppendLoweredTypes(t, &result);
  }
  return result;
}

TypeVector LowerParameterTypes(const ParameterTypes& parameter_types,
                               size_t arg_count) {
  std::vector<const Type*> result = LowerParameterTypes(parameter_types.types);
  for (size_t i = parameter_types.types.size(); i < arg_count; ++i) {
    DCHECK(parameter_types.var_args);
    AppendLoweredTypes(TypeOracle::GetObjectType(), &result);
1119
  }
1120 1121 1122 1123 1124 1125 1126
  return result;
}

VisitResult VisitResult::NeverResult() {
  VisitResult result;
  result.type_ = TypeOracle::GetNeverType();
  return result;
1127 1128
}

1129 1130 1131 1132 1133 1134 1135
VisitResult VisitResult::TopTypeResult(std::string top_reason,
                                       const Type* from_type) {
  VisitResult result;
  result.type_ = TypeOracle::GetTopType(std::move(top_reason), from_type);
  return result;
}

1136
std::tuple<size_t, std::string> Field::GetFieldSizeInformation() const {
1137
  auto optional = SizeOf(this->name_and_type.type);
1138 1139 1140 1141
  if (optional.has_value()) {
    return *optional;
  }
  Error("fields of type ", *name_and_type.type, " are not (yet) supported")
1142 1143
      .Position(pos)
      .Throw();
1144 1145
}

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
size_t Type::AlignmentLog2() const {
  if (parent()) return parent()->AlignmentLog2();
  return TargetArchitecture::TaggedSize();
}

size_t AbstractType::AlignmentLog2() const {
  size_t alignment;
  if (this == TypeOracle::GetTaggedType()) {
    alignment = TargetArchitecture::TaggedSize();
  } else if (this == TypeOracle::GetRawPtrType()) {
    alignment = TargetArchitecture::RawPtrSize();
1157 1158
  } else if (this == TypeOracle::GetExternalPointerType()) {
    alignment = TargetArchitecture::ExternalPointerSize();
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
  } else if (this == TypeOracle::GetVoidType()) {
    alignment = 1;
  } else if (this == TypeOracle::GetInt8Type()) {
    alignment = kUInt8Size;
  } else if (this == TypeOracle::GetUint8Type()) {
    alignment = kUInt8Size;
  } else if (this == TypeOracle::GetInt16Type()) {
    alignment = kUInt16Size;
  } else if (this == TypeOracle::GetUint16Type()) {
    alignment = kUInt16Size;
  } else if (this == TypeOracle::GetInt32Type()) {
    alignment = kInt32Size;
  } else if (this == TypeOracle::GetUint32Type()) {
    alignment = kInt32Size;
  } else if (this == TypeOracle::GetFloat64Type()) {
    alignment = kDoubleSize;
  } else if (this == TypeOracle::GetIntPtrType()) {
    alignment = TargetArchitecture::RawPtrSize();
  } else if (this == TypeOracle::GetUIntPtrType()) {
    alignment = TargetArchitecture::RawPtrSize();
  } else {
    return Type::AlignmentLog2();
  }
  alignment = std::min(alignment, TargetArchitecture::TaggedSize());
  return base::bits::WhichPowerOfTwo(alignment);
}

size_t StructType::AlignmentLog2() const {
1187 1188 1189
  if (this == TypeOracle::GetFloat64OrHoleType()) {
    return TypeOracle::GetFloat64Type()->AlignmentLog2();
  }
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
  size_t alignment_log_2 = 0;
  for (const Field& field : fields()) {
    alignment_log_2 =
        std::max(alignment_log_2, field.name_and_type.type->AlignmentLog2());
  }
  return alignment_log_2;
}

void Field::ValidateAlignment(ResidueClass at_offset) const {
  const Type* type = name_and_type.type;
1200
  base::Optional<const StructType*> struct_type = type->StructSupertype();
1201
  if (struct_type && struct_type != TypeOracle::GetFloat64OrHoleType()) {
1202
    for (const Field& field : (*struct_type)->fields()) {
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
      field.ValidateAlignment(at_offset);
      size_t field_size = std::get<0>(field.GetFieldSizeInformation());
      at_offset += field_size;
    }
  } else {
    size_t alignment_log_2 = name_and_type.type->AlignmentLog2();
    if (at_offset.AlignmentLog2() < alignment_log_2) {
      Error("field ", name_and_type.name, " at offset ", at_offset, " is not ",
            size_t{1} << alignment_log_2, "-byte aligned.")
          .Position(pos);
    }
  }
}

1217
base::Optional<std::tuple<size_t, std::string>> SizeOf(const Type* type) {
1218
  std::string size_string;
1219 1220 1221
  size_t size;
  if (type->IsSubtypeOf(TypeOracle::GetTaggedType())) {
    size = TargetArchitecture::TaggedSize();
1222
    size_string = "kTaggedSize";
1223 1224
  } else if (type->IsSubtypeOf(TypeOracle::GetRawPtrType())) {
    size = TargetArchitecture::RawPtrSize();
1225
    size_string = "kSystemPointerSize";
1226 1227 1228
  } else if (type->IsSubtypeOf(TypeOracle::GetExternalPointerType())) {
    size = TargetArchitecture::ExternalPointerSize();
    size_string = "kExternalPointerSize";
1229 1230
  } else if (type->IsSubtypeOf(TypeOracle::GetVoidType())) {
    size = 0;
1231
    size_string = "0";
1232 1233
  } else if (type->IsSubtypeOf(TypeOracle::GetInt8Type())) {
    size = kUInt8Size;
1234
    size_string = "kUInt8Size";
1235 1236
  } else if (type->IsSubtypeOf(TypeOracle::GetUint8Type())) {
    size = kUInt8Size;
1237
    size_string = "kUInt8Size";
1238 1239
  } else if (type->IsSubtypeOf(TypeOracle::GetInt16Type())) {
    size = kUInt16Size;
1240
    size_string = "kUInt16Size";
1241 1242
  } else if (type->IsSubtypeOf(TypeOracle::GetUint16Type())) {
    size = kUInt16Size;
1243
    size_string = "kUInt16Size";
1244 1245
  } else if (type->IsSubtypeOf(TypeOracle::GetInt32Type())) {
    size = kInt32Size;
1246
    size_string = "kInt32Size";
1247 1248
  } else if (type->IsSubtypeOf(TypeOracle::GetUint32Type())) {
    size = kInt32Size;
1249
    size_string = "kInt32Size";
1250 1251
  } else if (type->IsSubtypeOf(TypeOracle::GetFloat64Type())) {
    size = kDoubleSize;
1252
    size_string = "kDoubleSize";
1253 1254
  } else if (type->IsSubtypeOf(TypeOracle::GetIntPtrType())) {
    size = TargetArchitecture::RawPtrSize();
1255
    size_string = "kIntptrSize";
1256 1257
  } else if (type->IsSubtypeOf(TypeOracle::GetUIntPtrType())) {
    size = TargetArchitecture::RawPtrSize();
1258
    size_string = "kIntptrSize";
1259
  } else if (auto struct_type = type->StructSupertype()) {
1260 1261 1262 1263
    if (type == TypeOracle::GetFloat64OrHoleType()) {
      size = kDoubleSize;
      size_string = "kDoubleSize";
    } else {
1264
      size = (*struct_type)->PackedSize();
1265 1266
      size_string = std::to_string(size);
    }
1267
  } else {
1268
    return {};
1269
  }
1270
  return std::make_tuple(size, size_string);
1271 1272
}

1273 1274
bool IsAnyUnsignedInteger(const Type* type) {
  return type == TypeOracle::GetUint32Type() ||
1275
         type == TypeOracle::GetUint31Type() ||
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
         type == TypeOracle::GetUint16Type() ||
         type == TypeOracle::GetUint8Type() ||
         type == TypeOracle::GetUIntPtrType();
}

bool IsAllowedAsBitField(const Type* type) {
  if (type->IsBitFieldStructType()) {
    // No nested bitfield structs for now. We could reconsider if there's a
    // compelling use case.
    return false;
  }
1287 1288 1289
  // Any integer-ish type, including bools and enums which inherit from integer
  // types, are allowed. Note, however, that we always zero-extend during
  // decoding regardless of signedness.
1290 1291 1292 1293 1294 1295 1296 1297 1298
  return IsPointerSizeIntegralType(type) || Is32BitIntegralType(type);
}

bool IsPointerSizeIntegralType(const Type* type) {
  return type->IsSubtypeOf(TypeOracle::GetUIntPtrType()) ||
         type->IsSubtypeOf(TypeOracle::GetIntPtrType());
}

bool Is32BitIntegralType(const Type* type) {
1299
  return type->IsSubtypeOf(TypeOracle::GetUint32Type()) ||
1300
         type->IsSubtypeOf(TypeOracle::GetInt32Type()) ||
1301 1302 1303
         type->IsSubtypeOf(TypeOracle::GetBoolType());
}

1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
base::Optional<NameAndType> ExtractSimpleFieldArraySize(
    const ClassType& class_type, Expression* array_size) {
  IdentifierExpression* identifier =
      IdentifierExpression::DynamicCast(array_size);
  if (!identifier || !identifier->generic_arguments.empty() ||
      !identifier->namespace_qualification.empty())
    return {};
  if (!class_type.HasField(identifier->name->value)) return {};
  return class_type.LookupField(identifier->name->value).name_and_type;
}

1315
std::string Type::GetRuntimeType() const {
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
  if (IsSubtypeOf(TypeOracle::GetSmiType())) return "Smi";
  if (IsSubtypeOf(TypeOracle::GetTaggedType())) {
    return GetGeneratedTNodeTypeName();
  }
  if (base::Optional<const StructType*> struct_type = StructSupertype()) {
    std::stringstream result;
    result << "std::tuple<";
    bool first = true;
    for (const Type* field_type : LowerType(*struct_type)) {
      if (!first) result << ", ";
      first = false;
      result << field_type->GetRuntimeType();
    }
    result << ">";
    return result.str();
  }
  return ConstexprVersion()->GetGeneratedTypeName();
1333 1334
}

1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
std::string Type::GetDebugType() const {
  if (IsSubtypeOf(TypeOracle::GetSmiType())) return "uintptr_t";
  if (IsSubtypeOf(TypeOracle::GetTaggedType())) {
    return "uintptr_t";
  }
  if (base::Optional<const StructType*> struct_type = StructSupertype()) {
    std::stringstream result;
    result << "std::tuple<";
    bool first = true;
    for (const Type* field_type : LowerType(*struct_type)) {
      if (!first) result << ", ";
      first = false;
      result << field_type->GetDebugType();
    }
    result << ">";
    return result.str();
  }
  return ConstexprVersion()->GetGeneratedTypeName();
}

1355 1356 1357
}  // namespace torque
}  // namespace internal
}  // namespace v8