-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathEncoder.cpp
1721 lines (1492 loc) · 67.1 KB
/
Encoder.cpp
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) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "Backend.h"
#include "Core/CRC.h"
#include "NativeEntryPointData.h"
#include "JitTransferData.h"
///----------------------------------------------------------------------------
///
/// Encoder::Encode
///
/// Main entrypoint of encoder. Encode each IR instruction into the
/// appropriate machine encoding.
///
///----------------------------------------------------------------------------
void
Encoder::Encode()
{
NoRecoverMemoryArenaAllocator localArena(_u("BE-Encoder"), m_func->m_alloc->GetPageAllocator(), Js::Throw::OutOfMemory);
m_tempAlloc = &localArena;
#if ENABLE_OOP_NATIVE_CODEGEN
class AutoLocalAlloc {
public:
AutoLocalAlloc(Func * func) : localXdataAddr(nullptr), localAddress(nullptr), segment(nullptr), func(func) { }
~AutoLocalAlloc()
{
if (localAddress)
{
this->func->GetOOPThreadContext()->GetCodePageAllocators()->FreeLocal(this->localAddress, this->segment);
}
if (localXdataAddr)
{
this->func->GetOOPThreadContext()->GetCodePageAllocators()->FreeLocal(this->localXdataAddr, this->segment);
}
}
Func * func;
char * localXdataAddr;
char * localAddress;
void * segment;
} localAlloc(m_func);
#endif
uint32 instrCount = m_func->GetInstrCount();
size_t totalJmpTableSizeInBytes = 0;
JmpTableList * jumpTableListForSwitchStatement = nullptr;
m_encoderMD.Init(this);
m_encodeBufferSize = UInt32Math::Mul(instrCount, MachMaxInstrSize);
m_encodeBufferSize += m_func->m_totalJumpTableSizeInBytesForSwitchStatements;
m_encodeBuffer = AnewArray(m_tempAlloc, BYTE, m_encodeBufferSize);
#if DBG_DUMP
m_instrNumber = 0;
m_offsetBuffer = AnewArray(m_tempAlloc, uint, instrCount);
#endif
m_pragmaInstrToRecordMap = Anew(m_tempAlloc, PragmaInstrList, m_tempAlloc);
if (DoTrackAllStatementBoundary())
{
// Create a new list, if we are tracking all statement boundaries.
m_pragmaInstrToRecordOffset = Anew(m_tempAlloc, PragmaInstrList, m_tempAlloc);
}
else
{
// Set the list to the same as the throw map list, so that processing of the list
// of pragma are done on those only.
m_pragmaInstrToRecordOffset = m_pragmaInstrToRecordMap;
}
#if defined(_M_IX86) || defined(_M_X64)
// for BR shortening
m_inlineeFrameRecords = Anew(m_tempAlloc, InlineeFrameRecords, m_tempAlloc);
#endif
m_pc = m_encodeBuffer;
m_inlineeFrameMap = Anew(m_tempAlloc, ArenaInlineeFrameMap, m_tempAlloc);
m_sortedLazyBailoutRecordList = Anew(m_tempAlloc, ArenaLazyBailoutRecordList, m_tempAlloc);
IR::PragmaInstr* pragmaInstr = nullptr;
uint32 pragmaOffsetInBuffer = 0;
#ifdef _M_X64
bool inProlog = false;
#endif
bool isCallInstr = false;
// CRC Check to ensure the integrity of the encoded bytes.
uint initialCRCSeed = 0;
errno_t err = rand_s(&initialCRCSeed);
if (err != 0)
{
Fatal();
}
uint bufferCRC = initialCRCSeed;
FOREACH_INSTR_IN_FUNC(instr, m_func)
{
Assert(Lowerer::ValidOpcodeAfterLower(instr, m_func));
if (GetCurrentOffset() + MachMaxInstrSize < m_encodeBufferSize)
{
ptrdiff_t count;
#if DBG_DUMP
AssertMsg(m_instrNumber < instrCount, "Bad instr count?");
__analysis_assume(m_instrNumber < instrCount);
m_offsetBuffer[m_instrNumber++] = GetCurrentOffset();
#endif
if (instr->IsPragmaInstr())
{
switch (instr->m_opcode)
{
#ifdef _M_X64
case Js::OpCode::PrologStart:
m_func->m_prologEncoder.Begin(m_pc - m_encodeBuffer);
inProlog = true;
continue;
case Js::OpCode::PrologEnd:
m_func->m_prologEncoder.End();
inProlog = false;
continue;
#endif
case Js::OpCode::StatementBoundary:
pragmaOffsetInBuffer = GetCurrentOffset();
pragmaInstr = instr->AsPragmaInstr();
pragmaInstr->m_offsetInBuffer = pragmaOffsetInBuffer;
// will record after BR shortening with adjusted offsets
if (DoTrackAllStatementBoundary())
{
m_pragmaInstrToRecordOffset->Add(pragmaInstr);
}
break;
default:
continue;
}
}
else if (instr->IsBranchInstr() && instr->AsBranchInstr()->IsMultiBranch())
{
Assert(instr->GetSrc1() && instr->GetSrc1()->IsRegOpnd());
IR::MultiBranchInstr * multiBranchInstr = instr->AsBranchInstr()->AsMultiBrInstr();
if (multiBranchInstr->m_isSwitchBr &&
(multiBranchInstr->m_kind == IR::MultiBranchInstr::IntJumpTable || multiBranchInstr->m_kind == IR::MultiBranchInstr::SingleCharStrJumpTable))
{
BranchJumpTableWrapper * branchJumpTableWrapper = multiBranchInstr->GetBranchJumpTable();
if (jumpTableListForSwitchStatement == nullptr)
{
jumpTableListForSwitchStatement = Anew(m_tempAlloc, JmpTableList, m_tempAlloc);
}
jumpTableListForSwitchStatement->Add(branchJumpTableWrapper);
totalJmpTableSizeInBytes += (branchJumpTableWrapper->tableSize * sizeof(void*));
}
else
{
//Reloc Records
EncoderMD * encoderMD = &(this->m_encoderMD);
multiBranchInstr->MapMultiBrTargetByAddress([=](void ** offset) -> void
{
#if defined(_M_ARM32_OR_ARM64)
encoderMD->AddLabelReloc((byte*)offset);
#else
encoderMD->AppendRelocEntry(RelocTypeLabelUse, (void*)(offset), *(IR::LabelInstr**)(offset));
*((size_t*)offset) = 0;
#endif
});
}
}
else
{
isCallInstr = LowererMD::IsCall(instr);
if (pragmaInstr && (instr->isInlineeEntryInstr || isCallInstr))
{
// will record throw map after BR shortening with adjusted offsets
m_pragmaInstrToRecordMap->Add(pragmaInstr);
pragmaInstr = nullptr; // Only once per pragma instr -- do we need to make this record?
}
if (instr->HasBailOutInfo())
{
Assert(this->m_func->hasBailout);
Assert(LowererMD::IsCall(instr));
instr->GetBailOutInfo()->FinalizeBailOutRecord(this->m_func);
}
if (instr->isInlineeEntryInstr)
{
m_encoderMD.EncodeInlineeCallInfo(instr, GetCurrentOffset());
}
if (instr->m_opcode == Js::OpCode::InlineeStart)
{
Assert(!instr->isInlineeEntryInstr);
if (pragmaInstr)
{
m_pragmaInstrToRecordMap->Add(pragmaInstr);
pragmaInstr = nullptr;
}
Func* inlinee = instr->m_func;
if (inlinee->frameInfo && inlinee->frameInfo->record)
{
inlinee->frameInfo->record->Finalize(inlinee, GetCurrentOffset());
#if defined(_M_IX86) || defined(_M_X64)
// Store all records to be adjusted for BR shortening
m_inlineeFrameRecords->Add(inlinee->frameInfo->record);
#endif
}
continue;
}
}
count = m_encoderMD.Encode(instr, m_pc, m_encodeBuffer);
#if defined(_M_IX86) || defined(_M_X64)
bufferCRC = CalculateCRC(bufferCRC, count, m_pc);
#endif
#if DBG_DUMP
if (PHASE_TRACE(Js::EncoderPhase, this->m_func))
{
instr->Dump((IRDumpFlags)(IRDumpFlags_SimpleForm | IRDumpFlags_SkipEndLine | IRDumpFlags_SkipByteCodeOffset));
Output::SkipToColumn(80);
for (BYTE * current = m_pc; current < m_pc + count; current++)
{
Output::Print(_u("%02X "), *current);
}
Output::Print(_u("\n"));
Output::Flush();
}
#endif
#ifdef _M_X64
if (inProlog)
m_func->m_prologEncoder.EncodeInstr(instr, count & 0xFF);
#endif
m_pc += count;
#if defined(_M_IX86) || defined(_M_X64)
// for BR shortening.
if (instr->isInlineeEntryInstr)
m_encoderMD.AppendRelocEntry(RelocType::RelocTypeInlineeEntryOffset, (void*)(m_pc - MachPtr));
#endif
if (isCallInstr)
{
isCallInstr = false;
this->RecordInlineeFrame(instr->m_func, GetCurrentOffset());
}
if (instr->HasLazyBailOut())
{
this->SaveToLazyBailOutRecordList(instr, this->GetCurrentOffset());
}
if (instr->m_opcode == Js::OpCode::LazyBailOutThunkLabel)
{
this->SaveLazyBailOutThunkOffset(this->GetCurrentOffset());
}
}
else
{
Fatal();
}
} NEXT_INSTR_IN_FUNC;
ptrdiff_t codeSize = m_pc - m_encodeBuffer + totalJmpTableSizeInBytes;
BOOL isSuccessBrShortAndLoopAlign = false;
#if defined(_M_IX86) || defined(_M_X64)
// Shorten branches. ON by default
if (!PHASE_OFF(Js::BrShortenPhase, m_func))
{
uint brShortenedbufferCRC = initialCRCSeed;
isSuccessBrShortAndLoopAlign = ShortenBranchesAndLabelAlign(&m_encodeBuffer, &codeSize, &brShortenedbufferCRC, bufferCRC, totalJmpTableSizeInBytes);
if (isSuccessBrShortAndLoopAlign)
{
bufferCRC = brShortenedbufferCRC;
}
}
#endif
#if DBG_DUMP | defined(VTUNE_PROFILING)
if (this->m_func->DoRecordNativeMap())
{
// Record PragmaInstr offsets and throw maps
for (int32 i = 0; i < m_pragmaInstrToRecordOffset->Count(); i++)
{
IR::PragmaInstr *inst = m_pragmaInstrToRecordOffset->Item(i);
inst->Record(inst->m_offsetInBuffer);
}
}
#endif
if (m_pragmaInstrToRecordMap->Count() > 0)
{
if (m_func->IsOOPJIT())
{
int allocSize = m_pragmaInstrToRecordMap->Count();
Js::ThrowMapEntry * throwMap = NativeCodeDataNewArrayNoFixup(m_func->GetNativeCodeDataAllocator(), Js::ThrowMapEntry, allocSize);
for (int i = 0; i < allocSize; i++)
{
IR::PragmaInstr *inst = m_pragmaInstrToRecordMap->Item(i);
throwMap[i].nativeBufferOffset = inst->m_offsetInBuffer;
throwMap[i].statementIndex = inst->m_statementIndex;
}
m_func->GetJITOutput()->RecordThrowMap(throwMap, m_pragmaInstrToRecordMap->Count());
}
else
{
auto entryPointInfo = m_func->GetInProcJITEntryPointInfo();
auto functionBody = entryPointInfo->GetFunctionBody();
Js::SmallSpanSequenceIter iter;
for (int32 i = 0; i < m_pragmaInstrToRecordMap->Count(); i++)
{
IR::PragmaInstr *inst = m_pragmaInstrToRecordMap->Item(i);
functionBody->RecordNativeThrowMap(iter, inst->m_offsetInBuffer, inst->m_statementIndex, entryPointInfo, Js::LoopHeader::NoLoop);
}
}
}
// Assembly Dump Phase
// This phase exists to assist tooling that expects "assemblable" output - that is,
// output that, with minimal manual handling, could theoretically be fed to another
// assembler to make a valid function for the target platform. We don't guarantee a
// dump from this will _actually_ be assemblable, but it is significantly closer to
// that than our normal, annotated output
#if DBG_DUMP
if (PHASE_DUMP(Js::AssemblyPhase, m_func))
{
FOREACH_INSTR_IN_FUNC(instr, m_func)
{
bool hasPrintedForOpnds = false;
Func* localScopeFuncForLambda = m_func;
auto printOpnd = [&hasPrintedForOpnds, localScopeFuncForLambda](IR::Opnd* opnd)
{
if (hasPrintedForOpnds)
{
Output::Print(_u(", "));
}
switch (opnd->m_kind)
{
case IR::OpndKindInvalid:
AssertMsg(false, "Should be unreachable");
break;
case IR::OpndKindIntConst:
Output::Print(_u("%lli"), (long long int)opnd->AsIntConstOpnd()->GetValue());
break;
case IR::OpndKindInt64Const:
case IR::OpndKindFloatConst:
case IR::OpndKindFloat32Const:
case IR::OpndKindSimd128Const:
AssertMsg(false, "Not Yet Implemented");
break;
case IR::OpndKindHelperCall:
Output::Print(_u("%s"), IR::GetMethodName(opnd->AsHelperCallOpnd()->m_fnHelper));
break;
case IR::OpndKindSym:
Output::Print(_u("SYM("));
opnd->Dump(IRDumpFlags_SimpleForm, localScopeFuncForLambda);
Output::Print(_u(")"));
break;
case IR::OpndKindReg:
Output::Print(_u("%S"), RegNames[opnd->AsRegOpnd()->GetReg()]);
break;
case IR::OpndKindAddr:
Output::Print(_u("0x%p"), opnd->AsAddrOpnd()->m_address);
break;
case IR::OpndKindIndir:
{
IR::IndirOpnd* indirOpnd = opnd->AsIndirOpnd();
IR::RegOpnd* baseOpnd = indirOpnd->GetBaseOpnd();
IR::RegOpnd* indexOpnd = indirOpnd->GetIndexOpnd();
Output::Print(_u("["));
bool hasPrintedComponent = false;
if (baseOpnd != nullptr)
{
Output::Print(_u("%S"), RegNames[baseOpnd->GetReg()]);
hasPrintedComponent = true;
}
if (indexOpnd != nullptr)
{
if (hasPrintedComponent)
{
Output::Print(_u(" + "));
}
Output::Print(_u("%S * %u"), RegNames[indexOpnd->GetReg()], indirOpnd->GetScale());
hasPrintedComponent = true;
}
if (hasPrintedComponent)
{
Output::Print(_u(" + "));
}
Output::Print(_u("(%i)]"), indirOpnd->GetOffset());
break;
}
case IR::OpndKindLabel:
opnd->Dump(IRDumpFlags_SimpleForm, localScopeFuncForLambda);
break;
case IR::OpndKindMemRef:
opnd->DumpOpndKindMemRef(true, localScopeFuncForLambda);
break;
case IR::OpndKindRegBV:
AssertMsg(false, "Should be unreachable");
break;
case IR::OpndKindList:
AssertMsg(false, "Should be unreachable");
break;
default:
AssertMsg(false, "Missing operand type");
}
hasPrintedForOpnds = true;
};
switch(instr->GetKind())
{
case IR::InstrKindInvalid:
Assert(false);
break;
case IR::InstrKindJitProfiling:
case IR::InstrKindProfiled:
case IR::InstrKindInstr:
{
Output::SkipToColumn(4);
Output::Print(_u("%s "), Js::OpCodeUtil::GetOpCodeName(instr->m_opcode));
Output::SkipToColumn(18);
IR::Opnd* dst = instr->GetDst();
IR::Opnd* src1 = instr->GetSrc1();
IR::Opnd* src2 = instr->GetSrc2();
if (dst != nullptr && (src1 == nullptr || !dst->IsRegOpnd() || !src1->IsRegOpnd() || dst->AsRegOpnd()->GetReg() != src1->AsRegOpnd()->GetReg())) // Print dst if it's there, and not the same reg as src1 (which is usually an instr that has a srcdest
{
printOpnd(dst);
}
if (src1 != nullptr)
{
printOpnd(src1);
}
if (src2 != nullptr)
{
printOpnd(src2);
}
break;
}
case IR::InstrKindBranch:
Output::SkipToColumn(4);
Output::Print(_u("%s "), Js::OpCodeUtil::GetOpCodeName(instr->m_opcode));
Output::SkipToColumn(18);
if (instr->AsBranchInstr()->IsMultiBranch())
{
Assert(instr->GetSrc1() != nullptr);
printOpnd(instr->GetSrc1());
}
else
{
Output::Print(_u("L%u"), instr->AsBranchInstr()->GetTarget()->m_id);
}
break;
case IR::InstrKindProfiledLabel:
case IR::InstrKindLabel:
Output::Print(_u("L%u:"), instr->AsLabelInstr()->m_id);
break;
case IR::InstrKindEntry:
case IR::InstrKindExit:
case IR::InstrKindPragma:
// No output
break;
case IR::InstrKindByteCodeUses:
AssertMsg(false, "Instruction kind shouldn't be present here");
break;
default:
Assert(false);
break;
}
Output::SetAlignAndPrefix(60, _u("; "));
instr->Dump();
Output::ResetAlignAndPrefix();
} NEXT_INSTR_IN_FUNC;
}
#endif
// End Assembly Dump Phase
BEGIN_CODEGEN_PHASE(m_func, Js::EmitterPhase);
// Copy to permanent buffer.
Assert(Math::FitsInDWord(codeSize));
ushort xdataSize;
ushort pdataCount;
#ifdef _M_X64
pdataCount = 1;
xdataSize = (ushort)m_func->m_prologEncoder.SizeOfUnwindInfo();
#elif defined(_M_ARM64)
pdataCount = 1;
xdataSize = XDATA_SIZE;
#elif defined(_M_ARM)
pdataCount = (ushort)m_func->m_unwindInfo.GetPDataCount(codeSize);
xdataSize = (UnwindInfoManager::MaxXdataBytes + 3) * pdataCount;
#else
xdataSize = 0;
pdataCount = 0;
#endif
OUTPUT_VERBOSE_TRACE(Js::EmitterPhase, _u("PDATA count:%u\n"), pdataCount);
OUTPUT_VERBOSE_TRACE(Js::EmitterPhase, _u("Size of XDATA:%u\n"), xdataSize);
OUTPUT_VERBOSE_TRACE(Js::EmitterPhase, _u("Size of code:%u\n"), codeSize);
TryCopyAndAddRelocRecordsForSwitchJumpTableEntries(m_encodeBuffer, codeSize, jumpTableListForSwitchStatement, totalJmpTableSizeInBytes);
CustomHeap::Allocation * allocation = nullptr;
bool inPrereservedRegion = false;
char * localAddress = nullptr;
#if ENABLE_OOP_NATIVE_CODEGEN
if (JITManager::GetJITManager()->IsJITServer())
{
EmitBufferAllocation<SectionAllocWrapper, PreReservedSectionAllocWrapper> * alloc = m_func->GetJITOutput()->RecordOOPNativeCodeSize(m_func, (DWORD)codeSize, pdataCount, xdataSize);
allocation = alloc->allocation;
inPrereservedRegion = alloc->inPrereservedRegion;
localAlloc.segment = (alloc->bytesCommitted > CustomHeap::Page::MaxAllocationSize) ? allocation->largeObjectAllocation.segment : allocation->page->segment;
localAddress = m_func->GetOOPThreadContext()->GetCodePageAllocators()->AllocLocal(allocation->address, alloc->bytesCommitted, localAlloc.segment);
localAlloc.localAddress = localAddress;
if (localAddress == nullptr)
{
Js::Throw::OutOfMemory();
}
}
else
#endif
{
EmitBufferAllocation<VirtualAllocWrapper, PreReservedVirtualAllocWrapper> * alloc = m_func->GetJITOutput()->RecordInProcNativeCodeSize(m_func, (DWORD)codeSize, pdataCount, xdataSize);
allocation = alloc->allocation;
inPrereservedRegion = alloc->inPrereservedRegion;
localAddress = allocation->address;
}
if (!inPrereservedRegion)
{
m_func->GetThreadContextInfo()->ResetIsAllJITCodeInPreReservedRegion();
}
// Relocs
m_encoderMD.ApplyRelocs((size_t)allocation->address, codeSize, &bufferCRC, isSuccessBrShortAndLoopAlign);
m_func->GetJITOutput()->RecordNativeCode(m_encodeBuffer, (BYTE *)localAddress);
#if defined(_M_IX86) || defined(_M_X64)
if (!JITManager::GetJITManager()->IsJITServer())
{
ValidateCRCOnFinalBuffer((BYTE *)allocation->address, codeSize, totalJmpTableSizeInBytes, m_encodeBuffer, initialCRCSeed, bufferCRC, isSuccessBrShortAndLoopAlign);
}
#endif
#ifdef TARGET_64
#ifdef _M_X64
PrologEncoder &unwindInfo = m_func->m_prologEncoder;
unwindInfo.FinalizeUnwindInfo((BYTE*)m_func->GetJITOutput()->GetCodeAddress(), (DWORD)codeSize);
#else
UnwindInfoManager &unwindInfo = m_func->m_unwindInfo;
unwindInfo.FinalizeUnwindInfo((BYTE*)localAddress, (DWORD)codeSize);
#endif
char * localXdataAddr = nullptr;
#if ENABLE_OOP_NATIVE_CODEGEN
if (JITManager::GetJITManager()->IsJITServer())
{
localXdataAddr = m_func->GetOOPThreadContext()->GetCodePageAllocators()->AllocLocal((char*)allocation->xdata.address, XDATA_SIZE, localAlloc.segment);
localAlloc.localXdataAddr = localXdataAddr;
if (localXdataAddr == nullptr)
{
Js::Throw::OutOfMemory();
}
}
else
#endif
{
localXdataAddr = (char*)allocation->xdata.address;
}
m_func->GetJITOutput()->RecordUnwindInfo(
unwindInfo.GetUnwindInfo(),
unwindInfo.SizeOfUnwindInfo(),
allocation->xdata.address,
(BYTE*)localXdataAddr);
#elif _M_ARM
m_func->m_unwindInfo.EmitUnwindInfo(m_func->GetJITOutput(), allocation);
if (m_func->IsOOPJIT())
{
size_t allocSize = XDataAllocator::GetAllocSize(allocation->xdata.pdataCount, allocation->xdata.xdataSize);
BYTE * xprocXdata = NativeCodeDataNewArrayNoFixup(m_func->GetNativeCodeDataAllocator(), BYTE, allocSize);
memcpy_s(xprocXdata, allocSize, allocation->xdata.address, allocSize);
m_func->GetJITOutput()->RecordXData(xprocXdata);
}
else
{
XDataAllocator::Register(&allocation->xdata, m_func->GetJITOutput()->GetCodeAddress(), (DWORD)m_func->GetJITOutput()->GetCodeSize());
m_func->GetInProcJITEntryPointInfo()->GetNativeEntryPointData()->SetXDataInfo(&allocation->xdata);
}
m_func->GetJITOutput()->SetCodeAddress(m_func->GetJITOutput()->GetCodeAddress() | 0x1); // Set thumb mode
#endif
const bool isSimpleJit = m_func->IsSimpleJit();
if (this->m_inlineeFrameMap->Count() > 0 &&
!(this->m_inlineeFrameMap->Count() == 1 && this->m_inlineeFrameMap->Item(0).record == nullptr))
{
if (!m_func->IsOOPJIT()) // in-proc JIT
{
m_func->GetInProcJITEntryPointInfo()->GetInProcNativeEntryPointData()->RecordInlineeFrameMap(m_inlineeFrameMap);
}
else // OOP JIT
{
NativeOffsetInlineeFrameRecordOffset* pairs = NativeCodeDataNewArrayZNoFixup(m_func->GetNativeCodeDataAllocator(), NativeOffsetInlineeFrameRecordOffset, this->m_inlineeFrameMap->Count());
this->m_inlineeFrameMap->Map([&pairs](int i, NativeOffsetInlineeFramePair& p)
{
pairs[i].offset = p.offset;
if (p.record)
{
pairs[i].recordOffset = NativeCodeData::GetDataChunk(p.record)->offset;
}
else
{
pairs[i].recordOffset = NativeOffsetInlineeFrameRecordOffset::InvalidRecordOffset;
}
});
m_func->GetJITOutput()->RecordInlineeFrameOffsetsInfo(NativeCodeData::GetDataChunk(pairs)->offset, this->m_inlineeFrameMap->Count());
}
}
this->SaveLazyBailOutJitTransferData();
if (this->m_func->pinnedTypeRefs != nullptr)
{
Assert(!isSimpleJit);
int pinnedTypeRefCount = this->m_func->pinnedTypeRefs->Count();
PinnedTypeRefsIDL* pinnedTypeRefs = nullptr;
if (this->m_func->IsOOPJIT())
{
pinnedTypeRefs = (PinnedTypeRefsIDL*)midl_user_allocate(offsetof(PinnedTypeRefsIDL, typeRefs) + sizeof(void*)*pinnedTypeRefCount);
if (!pinnedTypeRefs)
{
Js::Throw::OutOfMemory();
}
__analysis_assume(pinnedTypeRefs);
pinnedTypeRefs->count = pinnedTypeRefCount;
pinnedTypeRefs->isOOPJIT = true;
}
else
{
pinnedTypeRefs = HeapNewStructPlus(offsetof(PinnedTypeRefsIDL, typeRefs) + sizeof(void*)*pinnedTypeRefCount - sizeof(PinnedTypeRefsIDL), PinnedTypeRefsIDL);
pinnedTypeRefs->count = pinnedTypeRefCount;
pinnedTypeRefs->isOOPJIT = false;
}
int index = 0;
this->m_func->pinnedTypeRefs->Map([&pinnedTypeRefs, &index](void* typeRef) -> void
{
pinnedTypeRefs->typeRefs[index++] = ((JITType*)typeRef)->GetAddr();
});
if (PHASE_TRACE(Js::TracePinnedTypesPhase, this->m_func))
{
char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
Output::Print(_u("PinnedTypes: function %s(%s) pinned %d types.\n"),
this->m_func->GetJITFunctionBody()->GetDisplayName(), this->m_func->GetDebugNumberSet(debugStringBuffer), pinnedTypeRefCount);
Output::Flush();
}
this->m_func->GetJITOutput()->GetOutputData()->pinnedTypeRefs = pinnedTypeRefs;
}
// Save all equivalent type guards in a fixed size array on the JIT transfer data
if (this->m_func->equivalentTypeGuards != nullptr)
{
AssertMsg(!PHASE_OFF(Js::EquivObjTypeSpecPhase, this->m_func), "Why do we have equivalent type guards if we don't do equivalent object type spec?");
int equivalentTypeGuardsCount = this->m_func->equivalentTypeGuards->Count();
if (this->m_func->IsOOPJIT())
{
auto& equivalentTypeGuardOffsets = this->m_func->GetJITOutput()->GetOutputData()->equivalentTypeGuardOffsets;
size_t allocSize = offsetof(EquivalentTypeGuardOffsets, guards) + equivalentTypeGuardsCount * sizeof(EquivalentTypeGuardIDL);
equivalentTypeGuardOffsets = (EquivalentTypeGuardOffsets*)midl_user_allocate(allocSize);
if (equivalentTypeGuardOffsets == nullptr)
{
Js::Throw::OutOfMemory();
}
equivalentTypeGuardOffsets->count = equivalentTypeGuardsCount;
int i = 0;
this->m_func->equivalentTypeGuards->Map([&equivalentTypeGuardOffsets, &i](Js::JitEquivalentTypeGuard* srcGuard) -> void
{
equivalentTypeGuardOffsets->guards[i].offset = NativeCodeData::GetDataTotalOffset(srcGuard);
auto cache = srcGuard->GetCache();
equivalentTypeGuardOffsets->guards[i].cache.guardOffset = NativeCodeData::GetDataTotalOffset(cache->guard);
equivalentTypeGuardOffsets->guards[i].cache.hasFixedValue = cache->hasFixedValue;
equivalentTypeGuardOffsets->guards[i].cache.isLoadedFromProto = cache->isLoadedFromProto;
equivalentTypeGuardOffsets->guards[i].cache.nextEvictionVictim = cache->nextEvictionVictim;
equivalentTypeGuardOffsets->guards[i].cache.record.propertyCount = cache->record.propertyCount;
equivalentTypeGuardOffsets->guards[i].cache.record.propertyOffset = NativeCodeData::GetDataTotalOffset(cache->record.properties);
for (int j = 0; j < EQUIVALENT_TYPE_CACHE_SIZE; j++)
{
equivalentTypeGuardOffsets->guards[i].cache.types[j] = (intptr_t)PointerValue(cache->types[j]);
}
i++;
});
Assert(equivalentTypeGuardsCount == i);
}
else
{
Js::JitEquivalentTypeGuard** guards = HeapNewArrayZ(Js::JitEquivalentTypeGuard*, equivalentTypeGuardsCount);
Js::JitEquivalentTypeGuard** dstGuard = guards;
this->m_func->equivalentTypeGuards->Map([&dstGuard](Js::JitEquivalentTypeGuard* srcGuard) -> void
{
*dstGuard++ = srcGuard;
});
m_func->GetInProcJITEntryPointInfo()->GetJitTransferData()->SetEquivalentTypeGuards(guards, equivalentTypeGuardsCount);
}
}
// Save all property guards on the JIT transfer data in a map keyed by property ID. We will use this map when installing the entry
// point to register each guard for invalidation.
if (this->m_func->propertyGuardsByPropertyId != nullptr)
{
Assert(!isSimpleJit);
AssertMsg(!(PHASE_OFF(Js::ObjTypeSpecPhase, this->m_func) && PHASE_OFF(Js::FixedMethodsPhase, this->m_func)),
"Why do we have type guards if we don't do object type spec or fixed methods?");
#if DBG
int totalGuardCount = (this->m_func->singleTypeGuards != nullptr ? this->m_func->singleTypeGuards->Count() : 0)
+ (this->m_func->equivalentTypeGuards != nullptr ? this->m_func->equivalentTypeGuards->Count() : 0);
Assert(totalGuardCount > 0);
Assert(totalGuardCount == this->m_func->indexedPropertyGuardCount);
#endif
if (!this->m_func->IsOOPJIT())
{
int propertyCount = this->m_func->propertyGuardsByPropertyId->Count();
Assert(propertyCount > 0);
int guardSlotCount = 0;
this->m_func->propertyGuardsByPropertyId->Map([&guardSlotCount](Js::PropertyId propertyId, Func::IndexedPropertyGuardSet* set) -> void
{
guardSlotCount += set->Count();
});
size_t typeGuardTransferSize = // Reserve enough room for:
propertyCount * sizeof(Js::TypeGuardTransferEntry) + // each propertyId,
propertyCount * sizeof(Js::JitIndexedPropertyGuard*) + // terminating nullptr guard for each propertyId,
guardSlotCount * sizeof(Js::JitIndexedPropertyGuard*); // a pointer for each guard we counted above.
// The extra room for sizeof(Js::TypePropertyGuardEntry) allocated by HeapNewPlus will be used for the terminating invalid propertyId.
// Review (jedmiad): Skip zeroing? This is heap allocated so there shouldn't be any false recycler references.
Js::TypeGuardTransferEntry* typeGuardTransferRecord = HeapNewPlusZ(typeGuardTransferSize, Js::TypeGuardTransferEntry);
Func* func = this->m_func;
Js::TypeGuardTransferEntry* dstEntry = typeGuardTransferRecord;
this->m_func->propertyGuardsByPropertyId->Map([func, &dstEntry](Js::PropertyId propertyId, Func::IndexedPropertyGuardSet* srcSet) -> void
{
dstEntry->propertyId = propertyId;
int guardIndex = 0;
srcSet->Map([dstEntry, &guardIndex](Js::JitIndexedPropertyGuard* guard) -> void
{
dstEntry->guards[guardIndex++] = guard;
});
dstEntry->guards[guardIndex++] = nullptr;
dstEntry = reinterpret_cast<Js::TypeGuardTransferEntry*>(&dstEntry->guards[guardIndex]);
});
dstEntry->propertyId = Js::Constants::NoProperty;
dstEntry++;
Assert(reinterpret_cast<char*>(dstEntry) <= reinterpret_cast<char*>(typeGuardTransferRecord) + typeGuardTransferSize + sizeof(Js::TypeGuardTransferEntry));
m_func->GetInProcJITEntryPointInfo()->GetJitTransferData()->RecordTypeGuards(this->m_func->indexedPropertyGuardCount, typeGuardTransferRecord, typeGuardTransferSize);
}
else
{
Func* func = this->m_func;
this->m_func->GetJITOutput()->GetOutputData()->propertyGuardCount = this->m_func->indexedPropertyGuardCount;
auto entry = &this->m_func->GetJITOutput()->GetOutputData()->typeGuardEntries;
this->m_func->propertyGuardsByPropertyId->Map([func, &entry](Js::PropertyId propertyId, Func::IndexedPropertyGuardSet* srcSet) -> void
{
auto count = srcSet->Count();
(*entry) = (TypeGuardTransferEntryIDL*)midl_user_allocate(offsetof(TypeGuardTransferEntryIDL, guardOffsets) + count*sizeof(int));
if (!*entry)
{
Js::Throw::OutOfMemory();
}
__analysis_assume(*entry);
(*entry)->propId = propertyId;
(*entry)->guardsCount = count;
(*entry)->next = nullptr;
auto& guardOffsets = (*entry)->guardOffsets;
int guardIndex = 0;
srcSet->Map([&guardOffsets, &guardIndex](Js::JitIndexedPropertyGuard* guard) -> void
{
guardOffsets[guardIndex++] = NativeCodeData::GetDataTotalOffset(guard);
});
Assert(guardIndex == count);
entry = &(*entry)->next;
});
}
}
// Save all constructor caches on the JIT transfer data in a map keyed by property ID. We will use this map when installing the entry
// point to register each cache for invalidation.
if (this->m_func->ctorCachesByPropertyId != nullptr)
{
Assert(!isSimpleJit);
AssertMsg(!(PHASE_OFF(Js::ObjTypeSpecPhase, this->m_func) && PHASE_OFF(Js::FixedMethodsPhase, this->m_func)),
"Why do we have constructor cache guards if we don't do object type spec or fixed methods?");
int propertyCount = this->m_func->ctorCachesByPropertyId->Count();
Assert(propertyCount > 0);
int cacheSlotCount = 0;
this->m_func->ctorCachesByPropertyId->Map([&cacheSlotCount](Js::PropertyId propertyId, Func::CtorCacheSet* cacheSet) -> void
{
cacheSlotCount += cacheSet->Count();
});
if (m_func->IsOOPJIT())
{
Func* func = this->m_func;
m_func->GetJITOutput()->GetOutputData()->ctorCachesCount = propertyCount;
m_func->GetJITOutput()->GetOutputData()->ctorCacheEntries = (CtorCacheTransferEntryIDL**)midl_user_allocate(propertyCount * sizeof(CtorCacheTransferEntryIDL*));
CtorCacheTransferEntryIDL** entries = m_func->GetJITOutput()->GetOutputData()->ctorCacheEntries;
if (!entries)
{
Js::Throw::OutOfMemory();
}
__analysis_assume(entries);
uint propIndex = 0;
m_func->ctorCachesByPropertyId->Map([func, entries, &propIndex](Js::PropertyId propertyId, Func::CtorCacheSet* srcCacheSet) -> void
{
entries[propIndex] = (CtorCacheTransferEntryIDL*)midl_user_allocate(srcCacheSet->Count() * sizeof(intptr_t) + sizeof(CtorCacheTransferEntryIDL));
if (!entries[propIndex])
{
Js::Throw::OutOfMemory();
}
__analysis_assume(entries[propIndex]);
entries[propIndex]->propId = propertyId;
int cacheIndex = 0;
srcCacheSet->Map([entries, propIndex, &cacheIndex](intptr_t cache) -> void
{
entries[propIndex]->caches[cacheIndex++] = cache;
});
entries[propIndex]->cacheCount = cacheIndex;
propIndex++;
});
}
else
{
Assert(m_func->GetInProcJITEntryPointInfo()->GetNativeEntryPointData()->GetConstructorCacheCount() > 0);
size_t ctorCachesTransferSize = // Reserve enough room for:
propertyCount * sizeof(Js::CtorCacheGuardTransferEntry) + // each propertyId,
propertyCount * sizeof(Js::ConstructorCache*) + // terminating null cache for each propertyId,
cacheSlotCount * sizeof(Js::JitIndexedPropertyGuard*); // a pointer for each cache we counted above.
// The extra room for sizeof(Js::CtorCacheGuardTransferEntry) allocated by HeapNewPlus will be used for the terminating invalid propertyId.
// Review (jedmiad): Skip zeroing? This is heap allocated so there shouldn't be any false recycler references.
Js::CtorCacheGuardTransferEntry* ctorCachesTransferRecord = HeapNewPlusZ(ctorCachesTransferSize, Js::CtorCacheGuardTransferEntry);
Func* func = this->m_func;
Js::CtorCacheGuardTransferEntry* dstEntry = ctorCachesTransferRecord;
this->m_func->ctorCachesByPropertyId->Map([func, &dstEntry](Js::PropertyId propertyId, Func::CtorCacheSet* srcCacheSet) -> void
{
dstEntry->propertyId = propertyId;
int cacheIndex = 0;
srcCacheSet->Map([dstEntry, &cacheIndex](intptr_t cache) -> void
{
dstEntry->caches[cacheIndex++] = cache;
});
dstEntry->caches[cacheIndex++] = 0;
dstEntry = reinterpret_cast<Js::CtorCacheGuardTransferEntry*>(&dstEntry->caches[cacheIndex]);
});
dstEntry->propertyId = Js::Constants::NoProperty;
dstEntry++;
Assert(reinterpret_cast<char*>(dstEntry) <= reinterpret_cast<char*>(ctorCachesTransferRecord) + ctorCachesTransferSize + sizeof(Js::CtorCacheGuardTransferEntry));
m_func->GetInProcJITEntryPointInfo()->GetJitTransferData()->RecordCtorCacheGuards(ctorCachesTransferRecord, ctorCachesTransferSize);
}
}
m_func->GetJITOutput()->FinalizeNativeCode();
END_CODEGEN_PHASE(m_func, Js::EmitterPhase);
#if DBG_DUMP
m_func->m_codeSize = codeSize;
if (PHASE_DUMP(Js::EncoderPhase, m_func) || PHASE_DUMP(Js::BackEndPhase, m_func))
{
bool dumpIRAddressesValue = Js::Configuration::Global.flags.DumpIRAddresses;
Js::Configuration::Global.flags.DumpIRAddresses = true;
this->m_func->DumpHeader();
m_instrNumber = 0;
FOREACH_INSTR_IN_FUNC(instr, m_func)
{
__analysis_assume(m_instrNumber < instrCount);
instr->DumpGlobOptInstrString();
#ifdef TARGET_64
Output::Print(_u("%12IX "), m_offsetBuffer[m_instrNumber++] + (BYTE *)m_func->GetJITOutput()->GetCodeAddress());
#else
Output::Print(_u("%8IX "), m_offsetBuffer[m_instrNumber++] + (BYTE *)m_func->GetJITOutput()->GetCodeAddress());
#endif
instr->Dump();
} NEXT_INSTR_IN_FUNC;
Output::Flush();
Js::Configuration::Global.flags.DumpIRAddresses = dumpIRAddressesValue;
}
if (PHASE_DUMP(Js::EncoderPhase, m_func) && Js::Configuration::Global.flags.Verbose && !m_func->IsOOPJIT())
{
this->DumpInlineeFrameMap(m_func->GetJITOutput()->GetCodeAddress());
Output::Flush();
}
#endif
}
bool Encoder::DoTrackAllStatementBoundary() const
{
#if DBG_DUMP | defined(VTUNE_PROFILING)
return this->m_func->DoRecordNativeMap();
#else
return false;
#endif
}
void Encoder::TryCopyAndAddRelocRecordsForSwitchJumpTableEntries(BYTE *codeStart, size_t codeSize, JmpTableList * jumpTableListForSwitchStatement, size_t totalJmpTableSizeInBytes)
{
if (jumpTableListForSwitchStatement == nullptr)
{
return;
}
BYTE * jmpTableStartAddress = codeStart + codeSize - totalJmpTableSizeInBytes;
EncoderMD * encoderMD = &m_encoderMD;
jumpTableListForSwitchStatement->Map([&](uint index, BranchJumpTableWrapper * branchJumpTableWrapper) -> void
{
Assert(branchJumpTableWrapper != nullptr);
void ** srcJmpTable = branchJumpTableWrapper->jmpTable;
size_t jmpTableSizeInBytes = branchJumpTableWrapper->tableSize * sizeof(void*);
AssertMsg(branchJumpTableWrapper->labelInstr != nullptr, "Label not yet created?");
Assert(branchJumpTableWrapper->labelInstr->GetPC() == nullptr);
branchJumpTableWrapper->labelInstr->SetPC(jmpTableStartAddress);
memcpy(jmpTableStartAddress, srcJmpTable, jmpTableSizeInBytes);
for (int i = 0; i < branchJumpTableWrapper->tableSize; i++)
{
void * addressOfJmpTableEntry = jmpTableStartAddress + (i * sizeof(void*));
Assert((ptrdiff_t) addressOfJmpTableEntry - (ptrdiff_t) jmpTableStartAddress < (ptrdiff_t) jmpTableSizeInBytes);
#if defined(_M_ARM32_OR_ARM64)
encoderMD->AddLabelReloc((byte*) addressOfJmpTableEntry);
#else
encoderMD->AppendRelocEntry(RelocTypeLabelUse, addressOfJmpTableEntry, *(IR::LabelInstr**)addressOfJmpTableEntry);
*((size_t*)addressOfJmpTableEntry) = 0;
#endif
}
jmpTableStartAddress += (jmpTableSizeInBytes);
});
Assert(jmpTableStartAddress == codeStart + codeSize);
}