/
vm.h
2380 lines (2165 loc) · 112 KB
/
vm.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (C) 2019-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#pragma once
#include <absl/container/flat_hash_map.h>
#include <absl/container/inlined_vector.h>
#include <absl/hash/hash.h>
#include <boost/optional/optional.hpp>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <memory>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
#include "mongo/base/compare_numbers.h"
#include "mongo/base/data_type_endian.h"
#include "mongo/base/string_data.h"
#include "mongo/base/string_data_comparator.h"
#include "mongo/config.h" // IWYU pragma: keep
#include "mongo/db/exec/sbe/makeobj_spec.h"
#include "mongo/db/exec/sbe/sort_spec.h"
#include "mongo/db/exec/sbe/values/column_op.h"
#include "mongo/db/exec/sbe/values/slot.h"
#include "mongo/db/exec/sbe/values/value.h"
#include "mongo/db/exec/sbe/vm/datetime.h"
#include "mongo/db/exec/sbe/vm/label.h"
#include "mongo/db/exec/sbe/vm/makeobj_cursors.h"
#include "mongo/db/pipeline/accumulator_multi.h"
#include "mongo/db/query/collation/collator_interface.h"
#include "mongo/db/query/datetime/date_time_support.h"
#include "mongo/platform/compiler.h"
#include "mongo/platform/decimal128.h"
#include "mongo/util/allocator.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/debug_util.h"
#if !defined(MONGO_CONFIG_DEBUG_BUILD)
#define MONGO_COMPILER_ALWAYS_INLINE_OPT MONGO_COMPILER_ALWAYS_INLINE
#else
#define MONGO_COMPILER_ALWAYS_INLINE_OPT
#endif
namespace mongo {
namespace sbe {
namespace vm {
template <typename Op>
std::pair<value::TypeTags, value::Value> genericCompare(
value::TypeTags lhsTag,
value::Value lhsValue,
value::TypeTags rhsTag,
value::Value rhsValue,
const StringDataComparator* comparator = nullptr,
Op op = {}) {
if (value::isNumber(lhsTag) && value::isNumber(rhsTag)) {
switch (getWidestNumericalType(lhsTag, rhsTag)) {
case value::TypeTags::NumberInt32: {
auto result = op(value::numericCast<int32_t>(lhsTag, lhsValue),
value::numericCast<int32_t>(rhsTag, rhsValue));
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(result)};
}
case value::TypeTags::NumberInt64: {
auto result = op(value::numericCast<int64_t>(lhsTag, lhsValue),
value::numericCast<int64_t>(rhsTag, rhsValue));
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(result)};
}
case value::TypeTags::NumberDouble: {
auto result = [&]() {
if (lhsTag == value::TypeTags::NumberInt64) {
auto rhs = value::bitcastTo<double>(rhsValue);
if (std::isnan(rhs)) {
return false;
}
return op(compareLongToDouble(value::bitcastTo<int64_t>(lhsValue), rhs), 0);
} else if (rhsTag == value::TypeTags::NumberInt64) {
auto lhs = value::bitcastTo<double>(lhsValue);
if (std::isnan(lhs)) {
return false;
}
return op(compareDoubleToLong(lhs, value::bitcastTo<int64_t>(rhsValue)), 0);
} else {
return op(value::numericCast<double>(lhsTag, lhsValue),
value::numericCast<double>(rhsTag, rhsValue));
}
}();
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(result)};
}
case value::TypeTags::NumberDecimal: {
auto result = [&]() {
if (lhsTag == value::TypeTags::NumberDouble) {
if (value::isNaN(lhsTag, lhsValue) || value::isNaN(rhsTag, rhsValue)) {
return false;
}
return op(compareDoubleToDecimal(value::bitcastTo<double>(lhsValue),
value::bitcastTo<Decimal128>(rhsValue)),
0);
} else if (rhsTag == value::TypeTags::NumberDouble) {
if (value::isNaN(lhsTag, lhsValue) || value::isNaN(rhsTag, rhsValue)) {
return false;
}
return op(compareDecimalToDouble(value::bitcastTo<Decimal128>(lhsValue),
value::bitcastTo<double>(rhsValue)),
0);
} else {
return op(value::numericCast<Decimal128>(lhsTag, lhsValue),
value::numericCast<Decimal128>(rhsTag, rhsValue));
}
}();
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(result)};
}
default:
MONGO_UNREACHABLE;
}
} else if (isStringOrSymbol(lhsTag) && isStringOrSymbol(rhsTag)) {
auto lhsStr = value::getStringOrSymbolView(lhsTag, lhsValue);
auto rhsStr = value::getStringOrSymbolView(rhsTag, rhsValue);
auto result =
op(comparator ? comparator->compare(lhsStr, rhsStr) : lhsStr.compare(rhsStr), 0);
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(result)};
} else if (lhsTag == value::TypeTags::Date && rhsTag == value::TypeTags::Date) {
auto result = op(value::bitcastTo<int64_t>(lhsValue), value::bitcastTo<int64_t>(rhsValue));
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(result)};
} else if (lhsTag == value::TypeTags::Timestamp && rhsTag == value::TypeTags::Timestamp) {
auto result =
op(value::bitcastTo<uint64_t>(lhsValue), value::bitcastTo<uint64_t>(rhsValue));
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(result)};
} else if (lhsTag == value::TypeTags::Boolean && rhsTag == value::TypeTags::Boolean) {
auto result = op(value::bitcastTo<bool>(lhsValue), value::bitcastTo<bool>(rhsValue));
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(result)};
} else if (lhsTag == value::TypeTags::Null && rhsTag == value::TypeTags::Null) {
// This is where Mongo differs from SQL.
auto result = op(0, 0);
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(result)};
} else if (lhsTag == value::TypeTags::MinKey && rhsTag == value::TypeTags::MinKey) {
auto result = op(0, 0);
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(result)};
} else if (lhsTag == value::TypeTags::MaxKey && rhsTag == value::TypeTags::MaxKey) {
auto result = op(0, 0);
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(result)};
} else if (lhsTag == value::TypeTags::bsonUndefined &&
rhsTag == value::TypeTags::bsonUndefined) {
auto result = op(0, 0);
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(result)};
} else if ((value::isArray(lhsTag) && value::isArray(rhsTag)) ||
(value::isObject(lhsTag) && value::isObject(rhsTag)) ||
(value::isBinData(lhsTag) && value::isBinData(rhsTag))) {
auto [tag, val] = value::compareValue(lhsTag, lhsValue, rhsTag, rhsValue, comparator);
if (tag == value::TypeTags::NumberInt32) {
auto result = op(value::bitcastTo<int32_t>(val), 0);
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(result)};
}
} else if (isObjectId(lhsTag) && isObjectId(rhsTag)) {
auto lhsObjId = lhsTag == value::TypeTags::ObjectId
? value::getObjectIdView(lhsValue)->data()
: value::bitcastTo<uint8_t*>(lhsValue);
auto rhsObjId = rhsTag == value::TypeTags::ObjectId
? value::getObjectIdView(rhsValue)->data()
: value::bitcastTo<uint8_t*>(rhsValue);
auto threeWayResult = memcmp(lhsObjId, rhsObjId, sizeof(value::ObjectIdType));
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(op(threeWayResult, 0))};
} else if (lhsTag == value::TypeTags::bsonRegex && rhsTag == value::TypeTags::bsonRegex) {
auto lhsRegex = value::getBsonRegexView(lhsValue);
auto rhsRegex = value::getBsonRegexView(rhsValue);
if (auto threeWayResult = lhsRegex.pattern.compare(rhsRegex.pattern); threeWayResult != 0) {
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(op(threeWayResult, 0))};
}
auto threeWayResult = lhsRegex.flags.compare(rhsRegex.flags);
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(op(threeWayResult, 0))};
} else if (lhsTag == value::TypeTags::bsonDBPointer &&
rhsTag == value::TypeTags::bsonDBPointer) {
auto lhsDBPtr = value::getBsonDBPointerView(lhsValue);
auto rhsDBPtr = value::getBsonDBPointerView(rhsValue);
if (lhsDBPtr.ns.size() != rhsDBPtr.ns.size()) {
return {value::TypeTags::Boolean,
value::bitcastFrom<bool>(op(lhsDBPtr.ns.size(), rhsDBPtr.ns.size()))};
}
if (auto threeWayResult = lhsDBPtr.ns.compare(rhsDBPtr.ns); threeWayResult != 0) {
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(op(threeWayResult, 0))};
}
auto threeWayResult = memcmp(lhsDBPtr.id, rhsDBPtr.id, sizeof(value::ObjectIdType));
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(op(threeWayResult, 0))};
} else if (lhsTag == value::TypeTags::bsonJavascript &&
rhsTag == value::TypeTags::bsonJavascript) {
auto lhsCode = value::getBsonJavascriptView(lhsValue);
auto rhsCode = value::getBsonJavascriptView(rhsValue);
return {value::TypeTags::Boolean,
value::bitcastFrom<bool>(op(lhsCode.compare(rhsCode), 0))};
} else if (lhsTag == value::TypeTags::bsonCodeWScope &&
rhsTag == value::TypeTags::bsonCodeWScope) {
auto lhsCws = value::getBsonCodeWScopeView(lhsValue);
auto rhsCws = value::getBsonCodeWScopeView(rhsValue);
if (auto threeWayResult = lhsCws.code.compare(rhsCws.code); threeWayResult != 0) {
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(op(threeWayResult, 0))};
}
// Special string comparison semantics do not apply to strings nested inside the
// CodeWScope scope object, so we do not pass through the string comparator.
auto [tag, val] = value::compareValue(value::TypeTags::bsonObject,
value::bitcastFrom<const char*>(lhsCws.scope),
value::TypeTags::bsonObject,
value::bitcastFrom<const char*>(rhsCws.scope));
if (tag == value::TypeTags::NumberInt32) {
auto result = op(value::bitcastTo<int32_t>(val), 0);
return {value::TypeTags::Boolean, value::bitcastFrom<bool>(result)};
}
}
return {value::TypeTags::Nothing, 0};
}
template <typename Op>
std::pair<value::TypeTags, value::Value> genericCompare(value::TypeTags lhsTag,
value::Value lhsValue,
value::TypeTags rhsTag,
value::Value rhsValue,
value::TypeTags collTag,
value::Value collValue,
Op op = {}) {
if (collTag != value::TypeTags::collator) {
return {value::TypeTags::Nothing, 0};
}
auto comparator = static_cast<StringDataComparator*>(value::getCollatorView(collValue));
return genericCompare(lhsTag, lhsValue, rhsTag, rhsValue, comparator, op);
}
namespace {
template <typename T>
T readFromMemory(const uint8_t* ptr) noexcept {
static_assert(!IsEndian<T>::value);
T val;
memcpy(&val, ptr, sizeof(T));
return val;
}
template <typename T>
size_t writeToMemory(uint8_t* ptr, const T val) noexcept {
static_assert(!IsEndian<T>::value);
memcpy(ptr, &val, sizeof(T));
return sizeof(T);
}
} // namespace
/**
* Enumeration of built-in VM instructions. These are implemented in vm.cpp ByteCode::runInternal.
*
* See also enum class Builtin for built-in functions, like 'addToArray', that are implemented as
* C++ rather than VM instructions.
*/
struct Instruction {
enum Tags {
pushConstVal,
pushAccessVal,
pushOwnedAccessorVal,
pushEnvAccessorVal,
pushMoveVal,
pushLocalVal,
pushMoveLocalVal,
pushLocalLambda,
pop,
swap,
add,
sub,
mul,
div,
idiv,
mod,
negate,
numConvert,
logicNot,
less,
lessEq,
greater,
greaterEq,
eq,
neq,
// 3 way comparison (spaceship) with bson woCompare semantics.
cmp3w,
// collation-aware comparison instructions
collLess,
collLessEq,
collGreater,
collGreaterEq,
collEq,
collNeq,
collCmp3w,
fillEmpty,
fillEmptyImm,
getField,
getFieldImm,
getElement,
collComparisonKey,
getFieldOrElement,
traverseP, // traverse projection paths
traversePImm,
traverseF, // traverse filter paths
traverseFImm,
// Iterates over values in column index cells. Skips values from nested arrays.
traverseCsiCellValues,
// Iterates the column index cell and returns values representing the types of cell's
// content, including arrays and nested objects. Skips contents of nested arrays.
traverseCsiCellTypes,
setField, // add or overwrite a field in a document
getArraySize, // number of elements
aggSum,
aggMin,
aggMax,
aggFirst,
aggLast,
aggCollMin,
aggCollMax,
exists,
isNull,
isObject,
isArray,
isInListData,
isString,
isNumber,
isBinData,
isDate,
isNaN,
isInfinity,
isRecordId,
isMinKey,
isMaxKey,
isTimestamp,
typeMatchImm,
function,
functionSmall,
jmp, // offset is calculated from the end of instruction
jmpTrue,
jmpFalse,
jmpNothing,
jmpNotNothing,
ret, // used only by simple local lambdas
allocStack,
fail,
dateTruncImm,
valueBlockApplyLambda, // Applies a lambda to each element in a block, returning a new
// block.
lastInstruction // this is just a marker used to calculate number of instructions
};
enum Constants : uint8_t {
Nothing,
Null,
False,
True,
Int32One,
};
constexpr static size_t kMaxInlineStringSize = 256;
/**
* An instruction parameter descriptor. Values (instruction arguments) live on the VM stack and
* the descriptor tells where to find it. The position on the stack is expressed as an offset
* from the top of stack.
* Optionally, an instruction can "consume" the value by popping the stack. All non-named
* temporaries are popped after the use. Naturally, only the top of stack (offset 0) can be
* popped. We do not support an arbitrary erasure from the middle of stack.
*/
struct Parameter {
int variable{0};
bool moveFrom{false};
boost::optional<FrameId> frameId;
// Get the size in bytes of an instruction parameter encoded in byte code.
size_t size() const noexcept {
return sizeof(bool) + (frameId ? sizeof(int) : 0);
}
MONGO_COMPILER_ALWAYS_INLINE_OPT
static FastTuple<bool, bool, int> decodeParam(const uint8_t*& pcPointer) noexcept {
auto flags = readFromMemory<uint8_t>(pcPointer);
bool pop = flags & 1u;
bool moveFrom = flags & 2u;
pcPointer += sizeof(pop);
int offset = 0;
if (!pop) {
offset = readFromMemory<int>(pcPointer);
pcPointer += sizeof(offset);
}
return {pop, moveFrom, offset};
}
};
static const char* toStringConstants(Constants k) {
switch (k) {
case Nothing:
return "Nothing";
case Null:
return "Null";
case True:
return "True";
case False:
return "False";
case Int32One:
return "1";
default:
return "unknown";
}
}
// Make sure that values in this arrays are always in-sync with the enum.
static int stackOffset[];
uint8_t tag;
const char* toString() const {
switch (tag) {
case pushConstVal:
return "pushConstVal";
case pushAccessVal:
return "pushAccessVal";
case pushOwnedAccessorVal:
return "pushOwnedAccessorVal";
case pushEnvAccessorVal:
return "pushEnvAccessorVal";
case pushMoveVal:
return "pushMoveVal";
case pushLocalVal:
return "pushLocalVal";
case pushMoveLocalVal:
return "pushMoveLocalVal";
case pushLocalLambda:
return "pushLocalLambda";
case pop:
return "pop";
case swap:
return "swap";
case add:
return "add";
case sub:
return "sub";
case mul:
return "mul";
case div:
return "div";
case idiv:
return "idiv";
case mod:
return "mod";
case negate:
return "negate";
case numConvert:
return "numConvert";
case logicNot:
return "logicNot";
case less:
return "less";
case lessEq:
return "lessEq";
case greater:
return "greater";
case greaterEq:
return "greaterEq";
case eq:
return "eq";
case neq:
return "neq";
case cmp3w:
return "cmp3w";
case collLess:
return "collLess";
case collLessEq:
return "collLessEq";
case collGreater:
return "collGreater";
case collGreaterEq:
return "collGreaterEq";
case collEq:
return "collEq";
case collNeq:
return "collNeq";
case collCmp3w:
return "collCmp3w";
case fillEmpty:
return "fillEmpty";
case fillEmptyImm:
return "fillEmptyImm";
case getField:
return "getField";
case getFieldImm:
return "getFieldImm";
case getElement:
return "getElement";
case collComparisonKey:
return "collComparisonKey";
case getFieldOrElement:
return "getFieldOrElement";
case traverseP:
return "traverseP";
case traversePImm:
return "traversePImm";
case traverseF:
return "traverseF";
case traverseFImm:
return "traverseFImm";
case traverseCsiCellValues:
return "traverseCsiCellValues";
case traverseCsiCellTypes:
return "traverseCsiCellTypes";
case setField:
return "setField";
case getArraySize:
return "getArraySize";
case aggSum:
return "aggSum";
case aggMin:
return "aggMin";
case aggMax:
return "aggMax";
case aggFirst:
return "aggFirst";
case aggLast:
return "aggLast";
case aggCollMin:
return "aggCollMin";
case aggCollMax:
return "aggCollMax";
case exists:
return "exists";
case isNull:
return "isNull";
case isObject:
return "isObject";
case isArray:
return "isArray";
case isInListData:
return "isInListData";
case isString:
return "isString";
case isNumber:
return "isNumber";
case isBinData:
return "isBinData";
case isDate:
return "isDate";
case isNaN:
return "isNaN";
case isInfinity:
return "isInfinity";
case isRecordId:
return "isRecordId";
case isMinKey:
return "isMinKey";
case isMaxKey:
return "isMaxKey";
case isTimestamp:
return "isTimestamp";
case typeMatchImm:
return "typeMatchImm";
case function:
return "function";
case functionSmall:
return "functionSmall";
case jmp:
return "jmp";
case jmpTrue:
return "jmpTrue";
case jmpFalse:
return "jmpFalse";
case jmpNothing:
return "jmpNothing";
case jmpNotNothing:
return "jmpNotNothing";
case ret:
return "ret";
case allocStack:
return "allocStack";
case fail:
return "fail";
case dateTruncImm:
return "dateTruncImm";
default:
return "unrecognized";
}
}
};
static_assert(sizeof(Instruction) == sizeof(uint8_t));
/**
* Enumeration of SBE VM built-in functions. These are dispatched by ByteCode::dispatchBuiltin() in
* vm.cpp. An enum value 'foo' refers to a C++ implementing function named builtinFoo().
*
* See also struct Instruction for "functions" like 'setField' that are implemented as single VM
* instructions.
*
* Builtins which can fit into one byte and have small arity are encoded using a special instruction
* tag, functionSmall.
*/
using SmallBuiltinType = uint8_t;
enum class Builtin : uint16_t {
split,
regexMatch,
replaceOne, // replace first occurrence of a specified substring with a diffferent substring
dateDiff,
dateParts,
dateToParts,
isoDateToParts,
dayOfYear,
dayOfMonth,
dayOfWeek,
datePartsWeekYear,
dateToString,
dateFromString,
dateFromStringNoThrow,
dropFields,
newArray, // create a new array from the top 'arity' values on the stack
keepFields,
newArrayFromRange,
newObj, // create a new object from 'arity' alternating field names and values on the stack
ksToString, // KeyString to string
newKs, // new KeyString
collNewKs, // new KeyString (with collation)
abs, // absolute value
ceil,
floor,
trunc,
exp,
ln,
log10,
sqrt,
pow,
addToArray, // agg function to append to an array
addToArrayCapped, // agg function to append to an array, fails when the array reaches specified
// size
mergeObjects, // agg function to merge BSON documents
addToSet, // agg function to append to a set
addToSetCapped, // agg function to append to a set, fails when the set reaches specified size
collAddToSet, // agg function to append to a set (with collation)
collAddToSetCapped, // agg function to append to a set (with collation), fails when the set
// reaches specified size
// Special double summation.
doubleDoubleSum,
// A variant of the standard sum aggregate function which maintains a DoubleDouble as the
// accumulator's underlying state.
aggDoubleDoubleSum,
// Converts a DoubleDouble sum into a single numeric scalar for use once the summation is
// complete.
doubleDoubleSumFinalize,
// Converts a partial sum into a format suitable for serialization over the wire to the merging
// node. The merging node expects the internal state of the DoubleDouble summation to be
// serialized in a particular format.
doubleDoublePartialSumFinalize,
// An agg function which can be used to sum a sequence of DoubleDouble inputs, producing the
// resulting total as a DoubleDouble.
aggMergeDoubleDoubleSums,
// Implements Welford's online algorithm for computing sample or population standard deviation
// in a single pass.
aggStdDev,
// Combines standard deviations that have been partially computed on a subset of the data
// using Welford's online algorithm.
aggMergeStdDevs,
stdDevPopFinalize,
stdDevSampFinalize,
bitTestZero, // test bitwise mask & value is zero
bitTestMask, // test bitwise mask & value is mask
bitTestPosition, // test BinData with a bit position list
bsonSize, // implements $bsonSize
strLenBytes,
toUpper,
toLower,
coerceToBool,
coerceToString,
concat,
concatArrays,
trim,
ltrim,
rtrim,
// Agg function to concatenate arrays, failing when the accumulator reaches a specified size.
aggConcatArraysCapped,
// Agg functions to compute the set union of two arrays (no size cap).
aggSetUnion,
aggCollSetUnion,
// Agg functions to compute the set union of two arrays (with a size cap).
aggSetUnionCapped,
aggCollSetUnionCapped,
acos,
acosh,
asin,
asinh,
atan,
atanh,
atan2,
cos,
cosh,
degreesToRadians,
radiansToDegrees,
sin,
sinh,
tan,
tanh,
round,
isMember,
indexOfBytes,
indexOfCP,
isDayOfWeek,
isTimeUnit,
isTimezone,
isValidToStringFormat,
validateFromStringFormat,
setUnion,
setIntersection,
setDifference,
setEquals,
setIsSubset,
collSetUnion,
collSetIntersection,
collSetDifference,
collSetEquals,
collSetIsSubset,
runJsPredicate,
regexCompile, // compile <pattern, options> into value::pcreRegex
regexFind,
regexFindAll,
shardFilter,
shardHash,
extractSubArray,
isArrayEmpty,
reverseArray,
sortArray,
dateAdd,
hasNullBytes,
getRegexPattern,
getRegexFlags,
hash,
ftsMatch,
generateSortKey,
generateCheapSortKey,
sortKeyComponentVectorGetElement,
sortKeyComponentVectorToArray,
makeBsonObj,
tsSecond,
tsIncrement,
typeMatch,
dateTrunc,
internalLeast, // helper functions for computation of sort keys
internalGreatest, // helper functions for computation of sort keys
year,
month,
hour,
minute,
second,
millisecond,
week,
isoWeekYear,
isoDayOfWeek,
isoWeek,
objectToArray,
setToArray,
arrayToObject,
aggFirstNNeedsMoreInput,
aggFirstN,
aggFirstNMerge,
aggFirstNFinalize,
aggLastN,
aggLastNMerge,
aggLastNFinalize,
aggTopN,
aggTopNMerge,
aggTopNFinalize,
aggBottomN,
aggBottomNMerge,
aggBottomNFinalize,
aggMaxN,
aggMaxNMerge,
aggMaxNFinalize,
aggMinN,
aggMinNMerge,
aggMinNFinalize,
aggRank,
aggRankColl,
aggDenseRank,
aggDenseRankColl,
aggRankFinalize,
aggExpMovingAvg,
aggExpMovingAvgFinalize,
aggRemovableSumAdd,
aggRemovableSumRemove,
aggRemovableSumFinalize,
aggIntegralInit,
aggIntegralAdd,
aggIntegralRemove,
aggIntegralFinalize,
aggDerivativeFinalize,
aggCovarianceAdd,
aggCovarianceRemove,
aggCovarianceSampFinalize,
aggCovariancePopFinalize,
aggRemovablePushAdd,
aggRemovablePushRemove,
aggRemovablePushFinalize,
aggRemovableStdDevAdd,
aggRemovableStdDevRemove,
aggRemovableStdDevSampFinalize,
aggRemovableStdDevPopFinalize,
aggRemovableAvgFinalize,
aggLinearFillCanAdd,
aggLinearFillAdd,
aggLinearFillFinalize,
aggRemovableFirstNInit,
aggRemovableFirstNAdd,
aggRemovableFirstNRemove,
aggRemovableFirstNFinalize,
aggRemovableLastNInit,
aggRemovableLastNAdd,
aggRemovableLastNRemove,
aggRemovableLastNFinalize,
aggRemovableAddToSetInit,
aggRemovableAddToSetCollInit,
aggRemovableAddToSetAdd,
aggRemovableAddToSetRemove,
aggRemovableAddToSetFinalize,
aggRemovableMinMaxNCollInit,
aggRemovableMinMaxNInit,
aggRemovableMinMaxNAdd,
aggRemovableMinMaxNRemove,
aggRemovableMinNFinalize,
aggRemovableMaxNFinalize,
aggRemovableTopNInit,
aggRemovableTopNAdd,
aggRemovableTopNRemove,
aggRemovableTopNFinalize,
aggRemovableBottomNInit,
aggRemovableBottomNAdd,
aggRemovableBottomNRemove,
aggRemovableBottomNFinalize,
// Additional one-byte builtins go here.
// Start of 2 byte builtins.
valueBlockExists = 256,
valueBlockFillEmpty,
valueBlockFillEmptyBlock,
valueBlockMin,
valueBlockMax,
valueBlockCount,
valueBlockDateTrunc,
valueBlockSum,
valueBlockGtScalar,
valueBlockGteScalar,
valueBlockEqScalar,
valueBlockNeqScalar,
valueBlockLtScalar,
valueBlockLteScalar,
valueBlockCmp3wScalar,
valueBlockCombine,
valueBlockLogicalAnd,
valueBlockLogicalOr,
valueBlockLogicalNot,
valueBlockNewFill,
valueBlockSize,
valueBlockNone,
cellFoldValues_F,
cellFoldValues_P,
cellBlockGetFlatValuesBlock,
};
std::string builtinToString(Builtin b);
/**
* This enum defines indices into an 'Array' that store state for $AccumulatorN expressions.
*
* The array contains five elements:
* - The element at index `kInternalArr` is the array that holds the values.
* - The element at index `kStartIdx` is the logical start index in the internal array. This is
* used for emulating queue behaviour.
* - The element at index `kMaxSize` is the maximum number entries the data structure holds.
* - The element at index `kMemUsage` holds the current memory usage
* - The element at index `kMemLimit` holds the max memory limit allowed
* - The element at index `kIsGroupAccum` specifices if the accumulator belongs to group-by stage
*/
enum class AggMultiElems {
kInternalArr,
kStartIdx,
kMaxSize,
kMemUsage,
kMemLimit,
kIsGroupAccum,
kSizeOfArray
};
/**
* Less than comparison based on a sort pattern.
*/
struct SortPatternLess {
SortPatternLess(const SortSpec* sortSpec) : _sortSpec(sortSpec) {}
bool operator()(const std::pair<value::TypeTags, value::Value>& lhs,
const std::pair<value::TypeTags, value::Value>& rhs) const {
auto [cmpTag, cmpVal] = _sortSpec->compare(lhs.first, lhs.second, rhs.first, rhs.second);
uassert(5807000, "Invalid comparison result", cmpTag == value::TypeTags::NumberInt32);
return value::bitcastTo<int32_t>(cmpVal) < 0;
}
private:
const SortSpec* _sortSpec;
};
/**
* Greater than comparison based on a sort pattern.
*/
struct SortPatternGreater {
SortPatternGreater(const SortSpec* sortSpec) : _sortSpec(sortSpec) {}
bool operator()(const std::pair<value::TypeTags, value::Value>& lhs,
const std::pair<value::TypeTags, value::Value>& rhs) const {
auto [cmpTag, cmpVal] = _sortSpec->compare(lhs.first, lhs.second, rhs.first, rhs.second);
uassert(5807001, "Invalid comparison result", cmpTag == value::TypeTags::NumberInt32);
return value::bitcastTo<int32_t>(cmpVal) > 0;
}
private:
const SortSpec* _sortSpec;
};
/**
* Comparison based on the key of a pair of elements.
*/
template <typename Comp>
struct PairKeyComp {
PairKeyComp(const Comp& comp) : _comp(comp) {}
bool operator()(const std::pair<value::TypeTags, value::Value>& lhs,
const std::pair<value::TypeTags, value::Value>& rhs) const {
auto [lPairTag, lPairVal] = lhs;
auto lPair = value::getArrayView(lPairVal);
auto lKey = lPair->getAt(0);
auto [rPairTag, rPairVal] = rhs;
auto rPair = value::getArrayView(rPairVal);
auto rKey = rPair->getAt(0);