types.cc 34.3 KB
Newer Older
1 2 3
// Copyright 2014 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.
4

5
#include <iomanip>
6

7
#include "src/compiler/types.h"
8

9
#include "src/handles-inl.h"
10
#include "src/objects-inl.h"
11
#include "src/ostreams.h"
12 13 14

namespace v8 {
namespace internal {
15
namespace compiler {
16

17 18
// NOTE: If code is marked as being a "shortcut", this means that removing
// the code won't affect the semantics of the surrounding function definition.
19

20 21 22 23
// static
bool Type::IsInteger(i::Object* x) {
  return x->IsNumber() && Type::IsInteger(x->Number());
}
24

25 26
// -----------------------------------------------------------------------------
// Range-related helper functions.
27

28
bool RangeType::Limits::IsEmpty() { return this->min > this->max; }
29

30
RangeType::Limits RangeType::Limits::Intersect(Limits lhs, Limits rhs) {
31 32
  DisallowHeapAllocation no_allocation;
  Limits result(lhs);
33 34
  if (lhs.min < rhs.min) result.min = rhs.min;
  if (lhs.max > rhs.max) result.max = rhs.max;
35
  return result;
36 37
}

38
RangeType::Limits RangeType::Limits::Union(Limits lhs, Limits rhs) {
39
  DisallowHeapAllocation no_allocation;
40 41
  if (lhs.IsEmpty()) return rhs;
  if (rhs.IsEmpty()) return lhs;
42
  Limits result(lhs);
43 44
  if (lhs.min > rhs.min) result.min = rhs.min;
  if (lhs.max < rhs.max) result.max = rhs.max;
45
  return result;
46 47
}

48
bool Type::Overlap(const RangeType* lhs, const RangeType* rhs) {
49
  DisallowHeapAllocation no_allocation;
50 51 52
  return !RangeType::Limits::Intersect(RangeType::Limits(lhs),
                                       RangeType::Limits(rhs))
              .IsEmpty();
53 54
}

55
bool Type::Contains(const RangeType* lhs, const RangeType* rhs) {
56
  DisallowHeapAllocation no_allocation;
57
  return lhs->Min() <= rhs->Min() && rhs->Max() <= lhs->Max();
58 59
}

60
bool Type::Contains(const RangeType* range, i::Object* val) {
61
  DisallowHeapAllocation no_allocation;
62 63
  return IsInteger(val) && range->Min() <= val->Number() &&
         val->Number() <= range->Max();
64 65
}

66 67 68
// -----------------------------------------------------------------------------
// Min and Max computation.

69
double Type::Min() const {
70
  DCHECK(this->Is(Number()));
71
  DCHECK(!this->Is(NaN()));
72 73
  if (this->IsBitset()) return BitsetType::Min(this->AsBitset());
  if (this->IsUnion()) {
74
    double min = +V8_INFINITY;
75
    for (int i = 1, n = AsUnion()->Length(); i < n; ++i) {
76
      min = std::min(min, AsUnion()->Get(i).Min());
77
    }
78
    Type bitset = AsUnion()->Get(0);
79
    if (!bitset.Is(NaN())) min = std::min(min, bitset.Min());
80 81
    return min;
  }
82
  if (this->IsRange()) return this->AsRange()->Min();
83 84
  DCHECK(this->IsOtherNumberConstant());
  return this->AsOtherNumberConstant()->Value();
85 86
}

87
double Type::Max() const {
88
  DCHECK(this->Is(Number()));
89
  DCHECK(!this->Is(NaN()));
90 91
  if (this->IsBitset()) return BitsetType::Max(this->AsBitset());
  if (this->IsUnion()) {
92
    double max = -V8_INFINITY;
93
    for (int i = 1, n = this->AsUnion()->Length(); i < n; ++i) {
94
      max = std::max(max, this->AsUnion()->Get(i).Max());
95
    }
96
    Type bitset = this->AsUnion()->Get(0);
97
    if (!bitset.Is(NaN())) max = std::max(max, bitset.Max());
98 99
    return max;
  }
100
  if (this->IsRange()) return this->AsRange()->Max();
101 102
  DCHECK(this->IsOtherNumberConstant());
  return this->AsOtherNumberConstant()->Value();
103 104
}

105 106 107 108
// -----------------------------------------------------------------------------
// Glb and lub computation.

// The largest bitset subsumed by this type.
109
Type::bitset Type::BitsetGlb() const {
110
  DisallowHeapAllocation no_allocation;
111
  // Fast case.
112 113 114 115
  if (IsBitset()) {
    return AsBitset();
  } else if (IsUnion()) {
    SLOW_DCHECK(AsUnion()->Wellformed());
116 117
    return AsUnion()->Get(0).BitsetGlb() |
           AsUnion()->Get(1).BitsetGlb();  // Shortcut.
118 119
  } else if (IsRange()) {
    bitset glb = BitsetType::Glb(AsRange()->Min(), AsRange()->Max());
120
    return glb;
121
  } else {
122
    return BitsetType::kNone;
123
  }
124 125
}

126
// The smallest bitset subsuming this type, possibly not a proper one.
127
Type::bitset Type::BitsetLub() const {
128
  DisallowHeapAllocation no_allocation;
129 130
  if (IsBitset()) return AsBitset();
  if (IsUnion()) {
131 132
    // Take the representation from the first element, which is always
    // a bitset.
133
    int bitset = AsUnion()->Get(0).BitsetLub();
134
    for (int i = 0, n = AsUnion()->Length(); i < n; ++i) {
135
      // Other elements only contribute their semantic part.
136
      bitset |= AsUnion()->Get(i).BitsetLub();
137 138
    }
    return bitset;
139
  }
140 141 142 143 144 145
  if (IsHeapConstant()) return AsHeapConstant()->Lub();
  if (IsOtherNumberConstant()) {
    return AsOtherNumberConstant()->Lub();
  }
  if (IsRange()) return AsRange()->Lub();
  if (IsTuple()) return BitsetType::kOtherInternal;
146
  UNREACHABLE();
147 148
}

149
Type::bitset BitsetType::Lub(i::Map* map) {
150
  DisallowHeapAllocation no_allocation;
151 152
  switch (map->instance_type()) {
    case CONS_STRING_TYPE:
153
    case CONS_ONE_BYTE_STRING_TYPE:
154 155
    case THIN_STRING_TYPE:
    case THIN_ONE_BYTE_STRING_TYPE:
156
    case SLICED_STRING_TYPE:
157
    case SLICED_ONE_BYTE_STRING_TYPE:
158
    case EXTERNAL_STRING_TYPE:
159
    case EXTERNAL_ONE_BYTE_STRING_TYPE:
160 161
    case EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
    case SHORT_EXTERNAL_STRING_TYPE:
162
    case SHORT_EXTERNAL_ONE_BYTE_STRING_TYPE:
163
    case SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE:
164 165
    case STRING_TYPE:
    case ONE_BYTE_STRING_TYPE:
166
      return kString;
167
    case EXTERNAL_INTERNALIZED_STRING_TYPE:
168
    case EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE:
169 170
    case EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE:
    case SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE:
171
    case SHORT_EXTERNAL_ONE_BYTE_INTERNALIZED_STRING_TYPE:
172
    case SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE:
173 174
    case INTERNALIZED_STRING_TYPE:
    case ONE_BYTE_INTERNALIZED_STRING_TYPE:
175
      return kInternalizedString;
176 177
    case SYMBOL_TYPE:
      return kSymbol;
178 179
    case BIGINT_TYPE:
      return kBigInt;
180 181 182 183 184
    case ODDBALL_TYPE: {
      Heap* heap = map->GetHeap();
      if (map == heap->undefined_map()) return kUndefined;
      if (map == heap->null_map()) return kNull;
      if (map == heap->boolean_map()) return kBoolean;
185 186
      if (map == heap->the_hole_map()) return kHole;
      DCHECK(map == heap->uninitialized_map() ||
187
             map == heap->termination_exception_map() ||
188
             map == heap->arguments_marker_map() ||
189 190
             map == heap->optimized_out_map() ||
             map == heap->stale_register_map());
191
      return kOtherInternal;
192
    }
193
    case HEAP_NUMBER_TYPE:
194
      return kNumber;
195
    case JS_OBJECT_TYPE:
196 197
    case JS_ARGUMENTS_TYPE:
    case JS_ERROR_TYPE:
198 199
    case JS_GLOBAL_OBJECT_TYPE:
    case JS_GLOBAL_PROXY_TYPE:
200
    case JS_API_OBJECT_TYPE:
201
    case JS_SPECIAL_API_OBJECT_TYPE:
202 203 204 205 206 207 208 209 210 211 212
      if (map->is_undetectable()) {
        // Currently we assume that every undetectable receiver is also
        // callable, which is what we need to support document.all.  We
        // could add another Type bit to support other use cases in the
        // future if necessary.
        DCHECK(map->is_callable());
        return kOtherUndetectable;
      }
      if (map->is_callable()) {
        return kOtherCallable;
      }
213
      return kOtherObject;
214 215
    case JS_ARRAY_TYPE:
      return kArray;
216
    case JS_VALUE_TYPE:
217
    case JS_MESSAGE_OBJECT_TYPE:
218 219 220
    case JS_DATE_TYPE:
    case JS_CONTEXT_EXTENSION_OBJECT_TYPE:
    case JS_GENERATOR_OBJECT_TYPE:
221
    case JS_ASYNC_GENERATOR_OBJECT_TYPE:
222
    case JS_MODULE_NAMESPACE_TYPE:
223
    case JS_ARRAY_BUFFER_TYPE:
224
    case JS_ARRAY_ITERATOR_TYPE:
225
    case JS_REGEXP_TYPE:  // TODO(rossberg): there should be a RegExp type.
226
    case JS_REGEXP_STRING_ITERATOR_TYPE:
227 228 229 230
    case JS_TYPED_ARRAY_TYPE:
    case JS_DATA_VIEW_TYPE:
    case JS_SET_TYPE:
    case JS_MAP_TYPE:
231 232 233 234 235
    case JS_SET_KEY_VALUE_ITERATOR_TYPE:
    case JS_SET_VALUE_ITERATOR_TYPE:
    case JS_MAP_KEY_ITERATOR_TYPE:
    case JS_MAP_KEY_VALUE_ITERATOR_TYPE:
    case JS_MAP_VALUE_ITERATOR_TYPE:
236
    case JS_STRING_ITERATOR_TYPE:
237
    case JS_ASYNC_FROM_SYNC_ITERATOR_TYPE:
238 239
    case JS_WEAK_MAP_TYPE:
    case JS_WEAK_SET_TYPE:
240
    case JS_PROMISE_TYPE:
241
    case WASM_MODULE_TYPE:
242
    case WASM_GLOBAL_TYPE:
243 244 245
    case WASM_INSTANCE_TYPE:
    case WASM_MEMORY_TYPE:
    case WASM_TABLE_TYPE:
246
      DCHECK(!map->is_callable());
247
      DCHECK(!map->is_undetectable());
248
      return kOtherObject;
249 250 251
    case JS_BOUND_FUNCTION_TYPE:
      DCHECK(!map->is_undetectable());
      return kBoundFunction;
252
    case JS_FUNCTION_TYPE:
253
      DCHECK(!map->is_undetectable());
254
      return kFunction;
255
    case JS_PROXY_TYPE:
256
      DCHECK(!map->is_undetectable());
257 258
      if (map->is_callable()) return kCallableProxy;
      return kOtherProxy;
259
    case MAP_TYPE:
260
    case ALLOCATION_SITE_TYPE:
261
    case ACCESSOR_INFO_TYPE:
262
    case SHARED_FUNCTION_INFO_TYPE:
263
    case FUNCTION_TEMPLATE_INFO_TYPE:
264 265
    case ACCESSOR_PAIR_TYPE:
    case FIXED_ARRAY_TYPE:
266
    case HASH_TABLE_TYPE:
267
    case WEAK_FIXED_ARRAY_TYPE:
268
    case WEAK_ARRAY_LIST_TYPE:
269
    case FIXED_DOUBLE_ARRAY_TYPE:
270
    case FEEDBACK_METADATA_TYPE:
271
    case BYTE_ARRAY_TYPE:
272
    case BYTECODE_ARRAY_TYPE:
273
    case BOILERPLATE_DESCRIPTION_TYPE:
274
    case DESCRIPTOR_ARRAY_TYPE:
275
    case TRANSITION_ARRAY_TYPE:
276
    case FEEDBACK_CELL_TYPE:
277
    case FEEDBACK_VECTOR_TYPE:
278
    case PROPERTY_ARRAY_TYPE:
279
    case FOREIGN_TYPE:
280
    case SCOPE_INFO_TYPE:
281 282 283 284 285 286 287 288 289
    case BLOCK_CONTEXT_TYPE:
    case CATCH_CONTEXT_TYPE:
    case DEBUG_EVALUATE_CONTEXT_TYPE:
    case EVAL_CONTEXT_TYPE:
    case FUNCTION_CONTEXT_TYPE:
    case MODULE_CONTEXT_TYPE:
    case NATIVE_CONTEXT_TYPE:
    case SCRIPT_CONTEXT_TYPE:
    case WITH_CONTEXT_TYPE:
290
    case SCRIPT_TYPE:
291
    case CODE_TYPE:
292
    case PROPERTY_CELL_TYPE:
293
    case MODULE_TYPE:
294
    case MODULE_INFO_ENTRY_TYPE:
295
    case CELL_TYPE:
296
      return kOtherInternal;
297 298

    // Remaining instance types are unsupported for now. If any of them do
299
    // require bit set types, they should get kOtherInternal.
300 301 302 303 304 305 306 307 308
    case MUTABLE_HEAP_NUMBER_TYPE:
    case FREE_SPACE_TYPE:
#define FIXED_TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \
  case FIXED_##TYPE##_ARRAY_TYPE:

      TYPED_ARRAYS(FIXED_TYPED_ARRAY_CASE)
#undef FIXED_TYPED_ARRAY_CASE
    case FILLER_TYPE:
    case ACCESS_CHECK_INFO_TYPE:
309
    case CALL_HANDLER_INFO_TYPE:
310 311 312 313
    case INTERCEPTOR_INFO_TYPE:
    case OBJECT_TEMPLATE_INFO_TYPE:
    case ALLOCATION_MEMENTO_TYPE:
    case ALIASED_ARGUMENTS_ENTRY_TYPE:
314 315
    case PROMISE_CAPABILITY_TYPE:
    case PROMISE_REACTION_TYPE:
316
    case DEBUG_INFO_TYPE:
317
    case STACK_FRAME_INFO_TYPE:
318
    case WEAK_CELL_TYPE:
319
    case SMALL_ORDERED_HASH_MAP_TYPE:
320
    case SMALL_ORDERED_HASH_SET_TYPE:
321
    case PROTOTYPE_INFO_TYPE:
322
    case INTERPRETER_DATA_TYPE:
323
    case TUPLE2_TYPE:
324
    case TUPLE3_TYPE:
325
    case WASM_COMPILED_MODULE_TYPE:
326
    case WASM_DEBUG_INFO_TYPE:
327
    case WASM_SHARED_MODULE_DATA_TYPE:
328 329
    case LOAD_HANDLER_TYPE:
    case STORE_HANDLER_TYPE:
330
    case ASYNC_GENERATOR_REQUEST_TYPE:
331
    case CODE_DATA_CONTAINER_TYPE:
332 333 334 335 336
    case CALLBACK_TASK_TYPE:
    case CALLABLE_TASK_TYPE:
    case PROMISE_FULFILL_REACTION_JOB_TASK_TYPE:
    case PROMISE_REJECT_REACTION_JOB_TASK_TYPE:
    case PROMISE_RESOLVE_THENABLE_JOB_TASK_TYPE:
337
      UNREACHABLE();
338
  }
339
  UNREACHABLE();
340 341
}

342
Type::bitset BitsetType::Lub(i::Object* value) {
343 344
  DisallowHeapAllocation no_allocation;
  if (value->IsNumber()) {
345
    return Lub(value->Number());
346
  }
347
  return Lub(i::HeapObject::cast(value)->map());
348 349
}

350
Type::bitset BitsetType::Lub(double value) {
351
  DisallowHeapAllocation no_allocation;
352 353
  if (i::IsMinusZero(value)) return kMinusZero;
  if (std::isnan(value)) return kNaN;
354
  if (IsUint32Double(value) || IsInt32Double(value)) return Lub(value, value);
355
  return kOtherNumber;
356
}
357

358
// Minimum values of plain numeric bitsets.
359 360 361 362 363 364 365 366 367 368 369 370
const BitsetType::Boundary BitsetType::BoundariesArray[] = {
    {kOtherNumber, kPlainNumber, -V8_INFINITY},
    {kOtherSigned32, kNegative32, kMinInt},
    {kNegative31, kNegative31, -0x40000000},
    {kUnsigned30, kUnsigned30, 0},
    {kOtherUnsigned31, kUnsigned31, 0x40000000},
    {kOtherUnsigned32, kUnsigned32, 0x80000000},
    {kOtherNumber, kPlainNumber, static_cast<double>(kMaxUInt32) + 1}};

const BitsetType::Boundary* BitsetType::Boundaries() { return BoundariesArray; }

size_t BitsetType::BoundariesSize() {
371 372 373 374
  // Windows doesn't like arraysize here.
  // return arraysize(BoundariesArray);
  return 7;
}
375

376
Type::bitset BitsetType::ExpandInternals(Type::bitset bits) {
377
  DCHECK_IMPLIES(bits & kOtherString, (bits & kString) == kString);
378
  DisallowHeapAllocation no_allocation;
379
  if (!(bits & kPlainNumber)) return bits;  // Shortcut.
380 381 382
  const Boundary* boundaries = Boundaries();
  for (size_t i = 0; i < BoundariesSize(); ++i) {
    DCHECK(BitsetType::Is(boundaries[i].internal, boundaries[i].external));
383
    if (bits & boundaries[i].internal) bits |= boundaries[i].external;
384 385 386 387
  }
  return bits;
}

388
Type::bitset BitsetType::Lub(double min, double max) {
389 390
  DisallowHeapAllocation no_allocation;
  int lub = kNone;
391
  const Boundary* mins = Boundaries();
392

393
  for (size_t i = 1; i < BoundariesSize(); ++i) {
394
    if (min < mins[i].min) {
395
      lub |= mins[i - 1].internal;
396 397 398
      if (max < mins[i].min) return lub;
    }
  }
399
  return lub | mins[BoundariesSize() - 1].internal;
400 401
}

402
Type::bitset BitsetType::NumberBits(bitset bits) { return bits & kPlainNumber; }
403

404
Type::bitset BitsetType::Glb(double min, double max) {
405 406 407 408 409 410 411 412 413 414
  DisallowHeapAllocation no_allocation;
  int glb = kNone;
  const Boundary* mins = Boundaries();

  // If the range does not touch 0, the bound is empty.
  if (max < -1 || min > 0) return glb;

  for (size_t i = 1; i + 1 < BoundariesSize(); ++i) {
    if (min <= mins[i].min) {
      if (max + 1 < mins[i + 1].min) break;
415
      glb |= mins[i].external;
416 417 418
    }
  }
  // OtherNumber also contains float numbers, so it can never be
419
  // in the greatest lower bound.
420
  return glb & ~(kOtherNumber);
421 422
}

423
double BitsetType::Min(bitset bits) {
424
  DisallowHeapAllocation no_allocation;
425
  DCHECK(Is(bits, kNumber));
426
  DCHECK(!Is(bits, kNaN));
427
  const Boundary* mins = Boundaries();
428
  bool mz = bits & kMinusZero;
429
  for (size_t i = 0; i < BoundariesSize(); ++i) {
430
    if (Is(mins[i].internal, bits)) {
431 432
      return mz ? std::min(0.0, mins[i].min) : mins[i].min;
    }
433
  }
434 435
  DCHECK(mz);
  return 0;
436 437
}

438
double BitsetType::Max(bitset bits) {
439
  DisallowHeapAllocation no_allocation;
440
  DCHECK(Is(bits, kNumber));
441
  DCHECK(!Is(bits, kNaN));
442
  const Boundary* mins = Boundaries();
443 444
  bool mz = bits & kMinusZero;
  if (BitsetType::Is(mins[BoundariesSize() - 1].internal, bits)) {
445
    return +V8_INFINITY;
446
  }
447
  for (size_t i = BoundariesSize() - 1; i-- > 0;) {
448
    if (Is(mins[i].internal, bits)) {
449
      return mz ? std::max(0.0, mins[i + 1].min - 1) : mins[i + 1].min - 1;
450
    }
451
  }
452 453
  DCHECK(mz);
  return 0;
454 455
}

456 457 458 459 460 461 462 463 464 465 466 467 468 469
// static
bool OtherNumberConstantType::IsOtherNumberConstant(double value) {
  // Not an integer, not NaN, and not -0.
  return !std::isnan(value) && !Type::IsInteger(value) &&
         !i::IsMinusZero(value);
}

// static
bool OtherNumberConstantType::IsOtherNumberConstant(Object* value) {
  return value->IsHeapNumber() &&
         IsOtherNumberConstant(HeapNumber::cast(value)->value());
}

HeapConstantType::HeapConstantType(BitsetType::bitset bitset,
470
                                   i::Handle<i::HeapObject> object)
471
    : TypeBase(kHeapConstant), bitset_(bitset), object_(object) {
472
  DCHECK(!object->IsHeapNumber());
473
  DCHECK_IMPLIES(object->IsString(), object->IsInternalizedString());
474 475
}

476 477 478
// -----------------------------------------------------------------------------
// Predicates.

479
bool Type::SimplyEquals(Type that) const {
480
  DisallowHeapAllocation no_allocation;
481
  if (this->IsHeapConstant()) {
482
    return that.IsHeapConstant() &&
483
           this->AsHeapConstant()->Value().address() ==
484
               that.AsHeapConstant()->Value().address();
485 486
  }
  if (this->IsOtherNumberConstant()) {
487
    return that.IsOtherNumberConstant() &&
488
           this->AsOtherNumberConstant()->Value() ==
489
               that.AsOtherNumberConstant()->Value();
490 491
  }
  if (this->IsRange()) {
492
    if (that.IsHeapConstant() || that.IsOtherNumberConstant()) return false;
493
  }
494
  if (this->IsTuple()) {
495
    if (!that.IsTuple()) return false;
496
    const TupleType* this_tuple = this->AsTuple();
497
    const TupleType* that_tuple = that.AsTuple();
498 499 500 501
    if (this_tuple->Arity() != that_tuple->Arity()) {
      return false;
    }
    for (int i = 0, n = this_tuple->Arity(); i < n; ++i) {
502
      if (!this_tuple->Element(i).Equals(that_tuple->Element(i))) return false;
503 504 505
    }
    return true;
  }
506 507 508 509
  UNREACHABLE();
}

// Check if [this] <= [that].
510
bool Type::SlowIs(Type that) const {
511
  DisallowHeapAllocation no_allocation;
512

513
  // Fast bitset cases
514 515
  if (that.IsBitset()) {
    return BitsetType::Is(this->BitsetLub(), that.AsBitset());
516
  }
517

518
  if (this->IsBitset()) {
519
    return BitsetType::Is(this->AsBitset(), that.BitsetGlb());
520 521 522
  }

  // (T1 \/ ... \/ Tn) <= T  if  (T1 <= T) /\ ... /\ (Tn <= T)
523
  if (this->IsUnion()) {
524
    for (int i = 0, n = this->AsUnion()->Length(); i < n; ++i) {
525
      if (!this->AsUnion()->Get(i).Is(that)) return false;
526 527 528 529
    }
    return true;
  }

530
  // T <= (T1 \/ ... \/ Tn)  if  (T <= T1) \/ ... \/ (T <= Tn)
531 532 533
  if (that.IsUnion()) {
    for (int i = 0, n = that.AsUnion()->Length(); i < n; ++i) {
      if (this->Is(that.AsUnion()->Get(i))) return true;
534 535 536
      if (i > 1 && this->IsRange()) return false;  // Shortcut.
    }
    return false;
537
  }
538

539 540
  if (that.IsRange()) {
    return (this->IsRange() && Contains(that.AsRange(), this->AsRange()));
541 542
  }
  if (this->IsRange()) return false;
543

544
  return this->SimplyEquals(that);
545 546
}

547
// Check if [this] and [that] overlap.
548
bool Type::Maybe(Type that) const {
549 550
  DisallowHeapAllocation no_allocation;

551
  if (BitsetType::IsNone(this->BitsetLub() & that.BitsetLub())) return false;
552

553
  // (T1 \/ ... \/ Tn) overlaps T  if  (T1 overlaps T) \/ ... \/ (Tn overlaps T)
554
  if (this->IsUnion()) {
555
    for (int i = 0, n = this->AsUnion()->Length(); i < n; ++i) {
556
      if (this->AsUnion()->Get(i).Maybe(that)) return true;
557 558 559 560
    }
    return false;
  }

561
  // T overlaps (T1 \/ ... \/ Tn)  if  (T overlaps T1) \/ ... \/ (T overlaps Tn)
562 563 564
  if (that.IsUnion()) {
    for (int i = 0, n = that.AsUnion()->Length(); i < n; ++i) {
      if (this->Maybe(that.AsUnion()->Get(i))) return true;
565 566 567 568
    }
    return false;
  }

569
  if (this->IsBitset() && that.IsBitset()) return true;
570 571

  if (this->IsRange()) {
572 573
    if (that.IsRange()) {
      return Overlap(this->AsRange(), that.AsRange());
574
    }
575 576
    if (that.IsBitset()) {
      bitset number_bits = BitsetType::NumberBits(that.AsBitset());
577 578 579 580 581 582
      if (number_bits == BitsetType::kNone) {
        return false;
      }
      double min = std::max(BitsetType::Min(number_bits), this->Min());
      double max = std::min(BitsetType::Max(number_bits), this->Max());
      return min <= max;
583
    }
584
  }
585 586
  if (that.IsRange()) {
    return that.Maybe(*this);  // This case is handled above.
587 588
  }

589
  if (this->IsBitset() || that.IsBitset()) return true;
590

591
  return this->SimplyEquals(that);
592 593
}

594
// Return the range in [this], or [nullptr].
595
Type Type::GetRange() const {
596
  DisallowHeapAllocation no_allocation;
597
  if (this->IsRange()) return *this;
598
  if (this->IsUnion() && this->AsUnion()->Get(1).IsRange()) {
599
    return this->AsUnion()->Get(1);
600
  }
601
  return nullptr;
602 603
}

604
bool UnionType::Wellformed() const {
605 606 607
  DisallowHeapAllocation no_allocation;
  // This checks the invariants of the union representation:
  // 1. There are at least two elements.
608 609
  // 2. The first element is a bitset, no other element is a bitset.
  // 3. At most one element is a range, and it must be the second one.
610
  // 4. No element is itself a union.
611
  // 5. No element (except the bitset) is a subtype of any other.
612 613
  // 6. If there is a range, then the bitset type does not contain
  //    plain number bits.
614
  DCHECK_LE(2, this->Length());      // (1)
615
  DCHECK(this->Get(0).IsBitset());   // (2a)
616

617
  for (int i = 0; i < this->Length(); ++i) {
618 619 620
    if (i != 0) DCHECK(!this->Get(i).IsBitset());  // (2b)
    if (i != 1) DCHECK(!this->Get(i).IsRange());   // (3)
    DCHECK(!this->Get(i).IsUnion());               // (4)
621
    for (int j = 0; j < this->Length(); ++j) {
622
      if (i != j && i != 0) DCHECK(!this->Get(i).Is(this->Get(j)));  // (5)
623 624
    }
  }
625 626
  DCHECK(!this->Get(1).IsRange() ||
         (BitsetType::NumberBits(this->Get(0).AsBitset()) ==
627
          BitsetType::kNone));  // (6)
628 629 630 631 632 633
  return true;
}

// -----------------------------------------------------------------------------
// Union and intersection

634
Type Type::Intersect(Type type1, Type type2, Zone* zone) {
635
  // Fast case: bit sets.
636 637
  if (type1.IsBitset() && type2.IsBitset()) {
    return NewBitset(type1.AsBitset() & type2.AsBitset());
638
  }
639 640

  // Fast case: top or bottom types.
641 642
  if (type1.IsNone() || type2.IsAny()) return type1;  // Shortcut.
  if (type2.IsNone() || type1.IsAny()) return type2;  // Shortcut.
643 644

  // Semi-fast case.
645 646
  if (type1.Is(type2)) return type1;
  if (type2.Is(type1)) return type2;
647 648

  // Slow case: create union.
649 650

  // Semantic subtyping check - this is needed for consistency with the
651
  // semi-fast case above.
652
  if (type1.Is(type2)) {
653
    type2 = Any();
654
  } else if (type2.Is(type1)) {
655
    type1 = Any();
656 657
  }

658 659 660
  bitset bits = type1.BitsetGlb() & type2.BitsetGlb();
  int size1 = type1.IsUnion() ? type1.AsUnion()->Length() : 1;
  int size2 = type2.IsUnion() ? type2.AsUnion()->Length() : 1;
661 662 663
  int size;
  if (base::bits::SignedAddOverflow32(size1, size2, &size)) return Any();
  if (base::bits::SignedAddOverflow32(size, 2, &size)) return Any();
664
  UnionType* result = UnionType::New(size, zone);
665 666 667
  size = 0;

  // Deal with bitsets.
668
  result->Set(size++, NewBitset(bits));
669

670 671
  RangeType::Limits lims = RangeType::Limits::Empty();
  size = IntersectAux(type1, type2, result, size, &lims, zone);
672 673 674

  // If the range is not empty, then insert it into the union and
  // remove the number bits from the bitset.
675
  if (!lims.IsEmpty()) {
676
    size = UpdateRange(Type::Range(lims, zone), result, size, zone);
677 678 679 680

    // Remove the number bits.
    bitset number_bits = BitsetType::NumberBits(bits);
    bits &= ~number_bits;
681
    result->Set(0, NewBitset(bits));
682
  }
683
  return NormalizeUnion(result, size, zone);
684 685
}

686
int Type::UpdateRange(Type range, UnionType* result, int size, Zone* zone) {
687 688 689 690 691 692
  if (size == 1) {
    result->Set(size++, range);
  } else {
    // Make space for the range.
    result->Set(size++, result->Get(1));
    result->Set(1, range);
693 694 695
  }

  // Remove any components that just got subsumed.
696
  for (int i = 2; i < size;) {
697
    if (result->Get(i).Is(range)) {
698 699 700
      result->Set(i, result->Get(--size));
    } else {
      ++i;
701
    }
702
  }
703
  return size;
704 705
}

706
RangeType::Limits Type::ToLimits(bitset bits, Zone* zone) {
707 708
  bitset number_bits = BitsetType::NumberBits(bits);

709
  if (number_bits == BitsetType::kNone) {
710
    return RangeType::Limits::Empty();
711 712
  }

713 714
  return RangeType::Limits(BitsetType::Min(number_bits),
                           BitsetType::Max(number_bits));
715 716
}

717
RangeType::Limits Type::IntersectRangeAndBitset(Type range, Type bitset,
718
                                                Zone* zone) {
719 720
  RangeType::Limits range_lims(range.AsRange());
  RangeType::Limits bitset_lims = ToLimits(bitset.AsBitset(), zone);
721
  return RangeType::Limits::Intersect(range_lims, bitset_lims);
722 723
}

724
int Type::IntersectAux(Type lhs, Type rhs, UnionType* result, int size,
725
                       RangeType::Limits* lims, Zone* zone) {
726 727 728
  if (lhs.IsUnion()) {
    for (int i = 0, n = lhs.AsUnion()->Length(); i < n; ++i) {
      size = IntersectAux(lhs.AsUnion()->Get(i), rhs, result, size, lims, zone);
729 730 731
    }
    return size;
  }
732 733 734
  if (rhs.IsUnion()) {
    for (int i = 0, n = rhs.AsUnion()->Length(); i < n; ++i) {
      size = IntersectAux(lhs, rhs.AsUnion()->Get(i), result, size, lims, zone);
735 736
    }
    return size;
737 738
  }

739
  if (BitsetType::IsNone(lhs.BitsetLub() & rhs.BitsetLub())) return size;
740

741 742
  if (lhs.IsRange()) {
    if (rhs.IsBitset()) {
743
      RangeType::Limits lim = IntersectRangeAndBitset(lhs, rhs, zone);
744

745
      if (!lim.IsEmpty()) {
746
        *lims = RangeType::Limits::Union(lim, *lims);
747 748 749
      }
      return size;
    }
750
    if (rhs.IsRange()) {
751
      RangeType::Limits lim = RangeType::Limits::Intersect(
752
          RangeType::Limits(lhs.AsRange()), RangeType::Limits(rhs.AsRange()));
753
      if (!lim.IsEmpty()) {
754
        *lims = RangeType::Limits::Union(lim, *lims);
755 756
      }
    }
757
    return size;
758
  }
759
  if (rhs.IsRange()) {
760
    // This case is handled symmetrically above.
761
    return IntersectAux(rhs, lhs, result, size, lims, zone);
762
  }
763 764
  if (lhs.IsBitset() || rhs.IsBitset()) {
    return AddToUnion(lhs.IsBitset() ? rhs : lhs, result, size, zone);
765
  }
766
  if (lhs.SimplyEquals(rhs)) {
767
    return AddToUnion(lhs, result, size, zone);
768 769
  }
  return size;
770 771
}

772 773
// Make sure that we produce a well-formed range and bitset:
// If the range is non-empty, the number bits in the bitset should be
774
// clear. Moreover, if we have a canonical range (such as Signed32),
775
// we want to produce a bitset rather than a range.
776
Type Type::NormalizeRangeAndBitset(Type range, bitset* bits, Zone* zone) {
777 778 779 780 781 782 783
  // Fast path: If the bitset does not mention numbers, we can just keep the
  // range.
  bitset number_bits = BitsetType::NumberBits(*bits);
  if (number_bits == 0) {
    return range;
  }

784 785
  // If the range is semantically contained within the bitset, return None and
  // leave the bitset untouched.
786
  bitset range_lub = range.BitsetLub();
787
  if (BitsetType::Is(range_lub, *bits)) {
788
    return None();
789 790 791 792 793 794
  }

  // Slow path: reconcile the bitset range and the range.
  double bitset_min = BitsetType::Min(number_bits);
  double bitset_max = BitsetType::Max(number_bits);

795 796
  double range_min = range.Min();
  double range_max = range.Max();
797 798

  // Remove the number bits from the bitset, they would just confuse us now.
799 800
  // NOTE: bits contains OtherNumber iff bits contains PlainNumber, in which
  // case we already returned after the subtype check above.
801 802
  *bits &= ~number_bits;

803
  if (range_min <= bitset_min && range_max >= bitset_max) {
804 805 806 807 808
    // Bitset is contained within the range, just return the range.
    return range;
  }

  if (bitset_min < range_min) {
809
    range_min = bitset_min;
810 811
  }
  if (bitset_max > range_max) {
812
    range_max = bitset_max;
813
  }
814
  return Type::Range(range_min, range_max, zone);
815 816
}

817
Type Type::NewConstant(double value, Zone* zone) {
818 819 820 821 822 823 824 825 826 827 828 829
  if (IsInteger(value)) {
    return Range(value, value, zone);
  } else if (i::IsMinusZero(value)) {
    return Type::MinusZero();
  } else if (std::isnan(value)) {
    return Type::NaN();
  }

  DCHECK(OtherNumberConstantType::IsOtherNumberConstant(value));
  return OtherNumberConstant(value, zone);
}

830
Type Type::NewConstant(i::Handle<i::Object> value, Zone* zone) {
831 832 833 834 835
  if (IsInteger(*value)) {
    double v = value->Number();
    return Range(v, v, zone);
  } else if (value->IsHeapNumber()) {
    return NewConstant(value->Number(), zone);
836
  } else if (value->IsString() && !value->IsInternalizedString()) {
837
    return Type::String();
838
  }
839
  return HeapConstant(i::Handle<i::HeapObject>::cast(value), zone);
840 841
}

842
Type Type::Union(Type type1, Type type2, Zone* zone) {
843
  // Fast case: bit sets.
844 845
  if (type1.IsBitset() && type2.IsBitset()) {
    return NewBitset(type1.AsBitset() | type2.AsBitset());
846 847
  }

848
  // Fast case: top or bottom types.
849 850
  if (type1.IsAny() || type2.IsNone()) return type1;
  if (type2.IsAny() || type1.IsNone()) return type2;
851

852
  // Semi-fast case.
853 854
  if (type1.Is(type2)) return type2;
  if (type2.Is(type1)) return type1;
855 856

  // Slow case: create union.
857 858
  int size1 = type1.IsUnion() ? type1.AsUnion()->Length() : 1;
  int size2 = type2.IsUnion() ? type2.AsUnion()->Length() : 1;
859 860 861
  int size;
  if (base::bits::SignedAddOverflow32(size1, size2, &size)) return Any();
  if (base::bits::SignedAddOverflow32(size, 2, &size)) return Any();
862
  UnionType* result = UnionType::New(size, zone);
863 864
  size = 0;

865
  // Compute the new bitset.
866
  bitset new_bitset = type1.BitsetGlb() | type2.BitsetGlb();
867 868

  // Deal with ranges.
869
  Type range = None();
870 871
  Type range1 = type1.GetRange();
  Type range2 = type2.GetRange();
872
  if (range1 != nullptr && range2 != nullptr) {
873
    RangeType::Limits lims =
874 875
        RangeType::Limits::Union(RangeType::Limits(range1.AsRange()),
                                 RangeType::Limits(range2.AsRange()));
876
    Type union_range = Type::Range(lims, zone);
877
    range = NormalizeRangeAndBitset(union_range, &new_bitset, zone);
878
  } else if (range1 != nullptr) {
879
    range = NormalizeRangeAndBitset(range1, &new_bitset, zone);
880
  } else if (range2 != nullptr) {
881
    range = NormalizeRangeAndBitset(range2, &new_bitset, zone);
882
  }
883
  Type bits = NewBitset(new_bitset);
884
  result->Set(size++, bits);
885
  if (!range.IsNone()) result->Set(size++, range);
886

887 888
  size = AddToUnion(type1, result, size, zone);
  size = AddToUnion(type2, result, size, zone);
889
  return NormalizeUnion(result, size, zone);
890 891 892 893
}

// Add [type] to [result] unless [type] is bitset, range, or already subsumed.
// Return new size of [result].
894
int Type::AddToUnion(Type type, UnionType* result, int size, Zone* zone) {
895 896 897 898
  if (type.IsBitset() || type.IsRange()) return size;
  if (type.IsUnion()) {
    for (int i = 0, n = type.AsUnion()->Length(); i < n; ++i) {
      size = AddToUnion(type.AsUnion()->Get(i), result, size, zone);
899 900
    }
    return size;
901
  }
902
  for (int i = 0; i < size; ++i) {
903
    if (type.Is(result->Get(i))) return size;
904
  }
905 906 907
  result->Set(size++, type);
  return size;
}
908

909
Type Type::NormalizeUnion(UnionType* unioned, int size, Zone* zone) {
910
  DCHECK_LE(1, size);
911
  DCHECK(unioned->Get(0).IsBitset());
912 913 914
  // If the union has just one element, return it.
  if (size == 1) {
    return unioned->Get(0);
915
  }
916
  bitset bits = unioned->Get(0).AsBitset();
917
  // If the union only consists of a range, we can get rid of the union.
918
  if (size == 2 && bits == BitsetType::kNone) {
919 920 921
    if (unioned->Get(1).IsRange()) {
      return Type::Range(unioned->Get(1).AsRange()->Min(),
                         unioned->Get(1).AsRange()->Max(), zone);
922
    }
923
  }
924 925
  unioned->Shrink(size);
  SLOW_DCHECK(unioned->Wellformed());
926
  return Type(unioned);
927 928
}

929
int Type::NumConstants() const {
930
  DisallowHeapAllocation no_allocation;
931
  if (this->IsHeapConstant() || this->IsOtherNumberConstant()) {
932 933 934
    return 1;
  } else if (this->IsUnion()) {
    int result = 0;
935
    for (int i = 0, n = this->AsUnion()->Length(); i < n; ++i) {
936
      if (this->AsUnion()->Get(i).IsHeapConstant()) ++result;
937 938 939 940 941 942 943 944 945
    }
    return result;
  } else {
    return 0;
  }
}

// -----------------------------------------------------------------------------
// Printing.
946

947
const char* BitsetType::Name(bitset bits) {
948
  switch (bits) {
949 950
#define RETURN_NAMED_TYPE(type, value) \
  case k##type:                        \
951
    return #type;
952 953 954
    PROPER_BITSET_TYPE_LIST(RETURN_NAMED_TYPE)
    INTERNAL_BITSET_TYPE_LIST(RETURN_NAMED_TYPE)
#undef RETURN_NAMED_TYPE
955

956
    default:
957
      return nullptr;
958 959 960
  }
}

961 962
void BitsetType::Print(std::ostream& os,  // NOLINT
                       bitset bits) {
963
  DisallowHeapAllocation no_allocation;
964
  const char* name = Name(bits);
965
  if (name != nullptr) {
966 967 968 969
    os << name;
    return;
  }

970
  // clang-format off
971
  static const bitset named_bitsets[] = {
972
#define BITSET_CONSTANT(type, value) k##type,
973
    INTERNAL_BITSET_TYPE_LIST(BITSET_CONSTANT)
974
    PROPER_BITSET_TYPE_LIST(BITSET_CONSTANT)
975 976
#undef BITSET_CONSTANT
  };
977
  // clang-format on
978 979 980

  bool is_first = true;
  os << "(";
981 982 983
  for (int i(arraysize(named_bitsets) - 1); bits != 0 && i >= 0; --i) {
    bitset subset = named_bitsets[i];
    if ((bits & subset) == subset) {
984 985 986
      if (!is_first) os << " | ";
      is_first = false;
      os << Name(subset);
987
      bits -= subset;
988 989
    }
  }
990
  DCHECK_EQ(0, bits);
991
  os << ")";
992 993
}

994
void Type::PrintTo(std::ostream& os) const {
995
  DisallowHeapAllocation no_allocation;
996 997
  if (this->IsBitset()) {
    BitsetType::Print(os, this->AsBitset());
998 999 1000 1001 1002
  } else if (this->IsHeapConstant()) {
    os << "HeapConstant(" << Brief(*this->AsHeapConstant()->Value()) << ")";
  } else if (this->IsOtherNumberConstant()) {
    os << "OtherNumberConstant(" << this->AsOtherNumberConstant()->Value()
       << ")";
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
  } else if (this->IsRange()) {
    std::ostream::fmtflags saved_flags = os.setf(std::ios::fixed);
    std::streamsize saved_precision = os.precision(0);
    os << "Range(" << this->AsRange()->Min() << ", " << this->AsRange()->Max()
       << ")";
    os.flags(saved_flags);
    os.precision(saved_precision);
  } else if (this->IsUnion()) {
    os << "(";
    for (int i = 0, n = this->AsUnion()->Length(); i < n; ++i) {
1013
      Type type_i = this->AsUnion()->Get(i);
1014
      if (i > 0) os << " | " << type_i;
1015
    }
1016 1017 1018 1019
    os << ")";
  } else if (this->IsTuple()) {
    os << "<";
    for (int i = 0, n = this->AsTuple()->Arity(); i < n; ++i) {
1020
      Type type_i = this->AsTuple()->Element(i);
1021
      if (i > 0) os << ", " << type_i;
1022 1023 1024 1025
    }
    os << ">";
  } else {
    UNREACHABLE();
1026 1027 1028
  }
}

1029
#ifdef DEBUG
1030
void Type::Print() const {
1031 1032
  OFStream os(stdout);
  PrintTo(os);
1033
  os << std::endl;
1034
}
1035
void BitsetType::Print(bitset bits) {
1036 1037
  OFStream os(stdout);
  Print(os, bits);
1038
  os << std::endl;
1039
}
1040 1041
#endif

1042 1043 1044 1045 1046 1047 1048 1049
BitsetType::bitset BitsetType::SignedSmall() {
  return i::SmiValuesAre31Bits() ? kSigned31 : kSigned32;
}

BitsetType::bitset BitsetType::UnsignedSmall() {
  return i::SmiValuesAre31Bits() ? kUnsigned30 : kUnsigned31;
}

1050
// static
1051
Type Type::Tuple(Type first, Type second, Type third, Zone* zone) {
1052 1053 1054 1055 1056 1057 1058 1059
  TupleType* tuple = TupleType::New(3, zone);
  tuple->InitElement(0, first);
  tuple->InitElement(1, second);
  tuple->InitElement(2, third);
  return FromTypeBase(tuple);
}

// static
1060
Type Type::OtherNumberConstant(double value, Zone* zone) {
1061 1062 1063 1064
  return FromTypeBase(OtherNumberConstantType::New(value, zone));
}

// static
1065
Type Type::HeapConstant(i::Handle<i::HeapObject> value, Zone* zone) {
1066 1067 1068 1069
  return FromTypeBase(HeapConstantType::New(value, zone));
}

// static
1070
Type Type::Range(double min, double max, Zone* zone) {
1071 1072 1073 1074
  return FromTypeBase(RangeType::New(min, max, zone));
}

// static
1075
Type Type::Range(RangeType::Limits lims, Zone* zone) {
1076 1077 1078 1079
  return FromTypeBase(RangeType::New(lims, zone));
}

// static
1080
Type Type::Union(int length, Zone* zone) {
1081 1082 1083
  return FromTypeBase(UnionType::New(length, zone));
}

1084
const HeapConstantType* Type::AsHeapConstant() const {
1085
  DCHECK(IsKind(TypeBase::kHeapConstant));
1086
  return static_cast<const HeapConstantType*>(ToTypeBase());
1087 1088
}

1089
const OtherNumberConstantType* Type::AsOtherNumberConstant() const {
1090
  DCHECK(IsKind(TypeBase::kOtherNumberConstant));
1091
  return static_cast<const OtherNumberConstantType*>(ToTypeBase());
1092 1093
}

1094
const RangeType* Type::AsRange() const {
1095
  DCHECK(IsKind(TypeBase::kRange));
1096
  return static_cast<const RangeType*>(ToTypeBase());
1097 1098
}

1099
const TupleType* Type::AsTuple() const {
1100
  DCHECK(IsKind(TypeBase::kTuple));
1101
  return static_cast<const TupleType*>(ToTypeBase());
1102 1103
}

1104
const UnionType* Type::AsUnion() const {
1105
  DCHECK(IsKind(TypeBase::kUnion));
1106 1107 1108 1109 1110 1111
  return static_cast<const UnionType*>(ToTypeBase());
}

std::ostream& operator<<(std::ostream& os, Type type) {
  type.PrintTo(os);
  return os;
1112 1113
}

1114
}  // namespace compiler
1115 1116
}  // namespace internal
}  // namespace v8