-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
jit.rs
2245 lines (1962 loc) · 82.4 KB
/
jit.rs
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
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::iter::FromIterator;
use std::mem;
use std::ptr::NonNull;
use analysis::AnalysisType;
use codegen;
use control_flow;
use control_flow::WasmStructure;
use cpu::cpu;
use cpu::global_pointers;
use cpu::memory;
use cpu_context::CpuContext;
use jit_instructions;
use opstats;
use page::Page;
use profiler;
use profiler::stat;
use state_flags::CachedStateFlags;
use util::SafeToU16;
use wasmgen::wasm_builder::{Label, WasmBuilder, WasmLocal};
#[derive(Copy, Clone, Eq, Hash, PartialEq)]
#[repr(transparent)]
pub struct WasmTableIndex(u16);
impl WasmTableIndex {
pub fn to_u16(self) -> u16 { self.0 }
}
mod unsafe_jit {
use jit::{CachedStateFlags, WasmTableIndex};
extern "C" {
pub fn codegen_finalize(
wasm_table_index: WasmTableIndex,
phys_addr: u32,
state_flags: CachedStateFlags,
ptr: u32,
len: u32,
);
pub fn jit_clear_func(wasm_table_index: WasmTableIndex);
}
}
fn codegen_finalize(
wasm_table_index: WasmTableIndex,
phys_addr: u32,
state_flags: CachedStateFlags,
ptr: u32,
len: u32,
) {
unsafe { unsafe_jit::codegen_finalize(wasm_table_index, phys_addr, state_flags, ptr, len) }
}
pub fn jit_clear_func(wasm_table_index: WasmTableIndex) {
unsafe { unsafe_jit::jit_clear_func(wasm_table_index) }
}
// less branches will generate if-else, more will generate brtable
pub const BRTABLE_CUTOFF: usize = 10;
pub const WASM_TABLE_SIZE: u32 = 900;
pub const HASH_PRIME: u32 = 6151;
pub const CHECK_JIT_STATE_INVARIANTS: bool = false;
pub const JIT_USE_LOOP_SAFETY: bool = true;
pub const JIT_THRESHOLD: u32 = 200 * 1000;
pub const MAX_EXTRA_BASIC_BLOCKS: usize = 250;
const MAX_INSTRUCTION_LENGTH: u32 = 16;
#[allow(non_upper_case_globals)]
static mut jit_state: NonNull<JitState> =
unsafe { NonNull::new_unchecked(mem::align_of::<JitState>() as *mut _) };
pub fn get_jit_state() -> &'static mut JitState { unsafe { jit_state.as_mut() } }
#[no_mangle]
pub fn rust_init() {
let x = Box::new(JitState::create_and_initialise());
unsafe {
jit_state = NonNull::new(Box::into_raw(x)).unwrap()
}
use std::panic;
panic::set_hook(Box::new(|panic_info| {
console_log!("{}", panic_info.to_string());
}));
}
pub struct Entry {
#[cfg(any(debug_assertions, feature = "profiler"))]
pub len: u32,
#[cfg(debug_assertions)]
pub opcode: u32,
pub initial_state: u16,
pub wasm_table_index: WasmTableIndex,
pub state_flags: CachedStateFlags,
}
enum PageState {
Compiling { entries: Vec<(u32, Entry)> },
CompilingWritten,
}
pub struct JitState {
wasm_builder: WasmBuilder,
// as an alternative to HashSet, we could use a bitmap of 4096 bits here
// (faster, but uses much more memory)
// or a compressed bitmap (likely faster)
// or HashSet<u32> rather than nested
entry_points: HashMap<Page, HashSet<u16>>,
hot_pages: [u32; HASH_PRIME as usize],
wasm_table_index_free_list: Vec<WasmTableIndex>,
used_wasm_table_indices: HashMap<WasmTableIndex, HashSet<Page>>,
// All pages from used_wasm_table_indices
// Used to improve the performance of jit_dirty_page and jit_page_has_code
all_pages: HashSet<Page>,
cache: HashMap<u32, Entry>,
compiling: Option<(WasmTableIndex, PageState)>,
}
pub fn check_jit_state_invariants(ctx: &mut JitState) {
if !CHECK_JIT_STATE_INVARIANTS {
return;
}
let mut all_pages = HashSet::new();
for pages in ctx.used_wasm_table_indices.values() {
all_pages.extend(pages);
}
dbg_assert!(ctx.all_pages == all_pages);
}
impl JitState {
pub fn create_and_initialise() -> JitState {
// don't assign 0 (XXX: Check)
let wasm_table_indices = (1..=(WASM_TABLE_SIZE - 1) as u16).map(|x| WasmTableIndex(x));
JitState {
wasm_builder: WasmBuilder::new(),
entry_points: HashMap::new(),
hot_pages: [0; HASH_PRIME as usize],
wasm_table_index_free_list: Vec::from_iter(wasm_table_indices),
used_wasm_table_indices: HashMap::new(),
all_pages: HashSet::new(),
cache: HashMap::new(),
compiling: None,
}
}
}
#[derive(PartialEq, Eq)]
pub enum BasicBlockType {
Normal {
next_block_addr: Option<u32>,
jump_offset: i32,
jump_offset_is_32: bool,
},
ConditionalJump {
next_block_addr: Option<u32>,
next_block_branch_taken_addr: Option<u32>,
condition: u8,
jump_offset: i32,
jump_offset_is_32: bool,
},
// Set eip to an absolute value (ret, jmp r/m, call r/m)
AbsoluteEip,
Exit,
}
pub struct BasicBlock {
pub addr: u32,
pub virt_addr: i32,
pub last_instruction_addr: u32,
pub end_addr: u32,
pub is_entry_block: bool,
pub ty: BasicBlockType,
pub has_sti: bool,
pub number_of_instructions: u32,
}
#[derive(Copy, Clone, PartialEq)]
pub struct CachedCode {
pub wasm_table_index: WasmTableIndex,
pub initial_state: u16,
}
impl CachedCode {
pub const NONE: CachedCode = CachedCode {
wasm_table_index: WasmTableIndex(0),
initial_state: 0,
};
}
#[derive(PartialEq)]
pub enum InstructionOperand {
WasmLocal(WasmLocal),
Immediate(i32),
Other,
}
pub enum Instruction {
Cmp {
dest: InstructionOperand,
source: InstructionOperand,
opsize: i32,
},
Sub {
opsize: i32,
},
// Any instruction that sets last_result
Arithmetic {
opsize: i32,
},
Other,
}
pub struct JitContext<'a> {
pub cpu: &'a mut CpuContext,
pub builder: &'a mut WasmBuilder,
pub register_locals: &'a mut Vec<WasmLocal>,
pub start_of_current_instruction: u32,
pub exit_with_fault_label: Label,
pub exit_label: Label,
pub current_instruction: Instruction,
pub previous_instruction: Instruction,
pub instruction_counter: WasmLocal,
}
impl<'a> JitContext<'a> {
pub fn reg(&self, i: u32) -> WasmLocal { self.register_locals[i as usize].unsafe_clone() }
}
pub const JIT_INSTR_BLOCK_BOUNDARY_FLAG: u32 = 1 << 0;
fn jit_hot_hash_page(page: Page) -> u32 { page.to_u32() % HASH_PRIME }
pub fn is_near_end_of_page(address: u32) -> bool {
address & 0xFFF >= 0x1000 - MAX_INSTRUCTION_LENGTH
}
pub fn jit_find_cache_entry(phys_address: u32, state_flags: CachedStateFlags) -> CachedCode {
if is_near_end_of_page(phys_address) {
profiler::stat_increment(stat::RUN_INTERPRETED_NEAR_END_OF_PAGE);
}
let ctx = get_jit_state();
match ctx.cache.get(&phys_address) {
Some(entry) => {
if entry.state_flags == state_flags {
return CachedCode {
wasm_table_index: entry.wasm_table_index,
initial_state: entry.initial_state,
};
}
else {
profiler::stat_increment(stat::RUN_INTERPRETED_DIFFERENT_STATE);
}
},
None => {},
}
return CachedCode::NONE;
}
#[no_mangle]
pub fn jit_find_cache_entry_in_page(
phys_address: u32,
wasm_table_index: WasmTableIndex,
state_flags: u32,
) -> i32 {
profiler::stat_increment(stat::INDIRECT_JUMP);
let state_flags = CachedStateFlags::of_u32(state_flags);
let ctx = get_jit_state();
match ctx.cache.get(&phys_address) {
Some(entry) => {
if entry.state_flags == state_flags && entry.wasm_table_index == wasm_table_index {
return entry.initial_state as i32;
}
},
None => {},
}
profiler::stat_increment(stat::INDIRECT_JUMP_NO_ENTRY);
return -1;
}
pub fn record_entry_point(phys_address: u32) {
let ctx = get_jit_state();
if is_near_end_of_page(phys_address) {
return;
}
let page = Page::page_of(phys_address);
let offset_in_page = phys_address as u16 & 0xFFF;
let mut is_new = false;
ctx.entry_points
.entry(page)
.or_insert_with(|| {
is_new = true;
HashSet::new()
})
.insert(offset_in_page);
if is_new {
cpu::tlb_set_has_code(page, true);
}
}
// Maximum number of pages per wasm module. Necessary for the following reasons:
// - There is an upper limit on the size of a single function in wasm (currently ~7MB in all browsers)
// See https://github.com/WebAssembly/design/issues/1138
// - v8 poorly handles large br_table elements and OOMs on modules much smaller than the above limit
// See https://bugs.chromium.org/p/v8/issues/detail?id=9697 and https://bugs.chromium.org/p/v8/issues/detail?id=9141
// Will hopefully be fixed in the near future by generating direct control flow
const MAX_PAGES: usize = 3;
fn jit_find_basic_blocks(
ctx: &mut JitState,
entry_points: HashSet<i32>,
cpu: CpuContext,
) -> Vec<BasicBlock> {
fn follow_jump(
virt_target: i32,
ctx: &mut JitState,
pages: &mut HashSet<Page>,
page_blacklist: &mut HashSet<Page>,
max_pages: usize,
marked_as_entry: &mut HashSet<i32>,
to_visit_stack: &mut Vec<i32>,
) -> Option<u32> {
if is_near_end_of_page(virt_target as u32) {
return None;
}
let phys_target = match cpu::translate_address_read_no_side_effects(virt_target) {
Err(()) => {
dbg_log!("Not analysing {:x} (page not mapped)", virt_target);
return None;
},
Ok(t) => t,
};
let phys_page = Page::page_of(phys_target);
if !pages.contains(&phys_page) && pages.len() == max_pages
|| page_blacklist.contains(&phys_page)
{
return None;
}
if !pages.contains(&phys_page) {
// page seen for the first time, handle entry points
if let Some(entry_points) = ctx.entry_points.get(&phys_page) {
if entry_points.iter().all(|&entry_point| {
ctx.cache
.contains_key(&(phys_page.to_address() | u32::from(entry_point)))
}) {
profiler::stat_increment(stat::COMPILE_PAGE_SKIPPED_NO_NEW_ENTRY_POINTS);
page_blacklist.insert(phys_page);
return None;
}
let address_hash = jit_hot_hash_page(phys_page) as usize;
ctx.hot_pages[address_hash] = 0;
for &addr_low in entry_points {
let addr = virt_target & !0xFFF | addr_low as i32;
to_visit_stack.push(addr);
marked_as_entry.insert(addr);
}
}
else {
// no entry points: ignore this page?
}
pages.insert(phys_page);
dbg_assert!(pages.len() <= max_pages);
}
to_visit_stack.push(virt_target);
Some(phys_target)
}
let mut to_visit_stack: Vec<i32> = Vec::new();
let mut marked_as_entry: HashSet<i32> = HashSet::new();
let mut basic_blocks: BTreeMap<u32, BasicBlock> = BTreeMap::new();
let mut pages: HashSet<Page> = HashSet::new();
let mut page_blacklist = HashSet::new();
// 16-bit doesn't not work correctly, most likely due to instruction pointer wrap-around
let max_pages = if cpu.state_flags.is_32() { MAX_PAGES } else { 1 };
for virt_addr in entry_points {
let ok = follow_jump(
virt_addr,
ctx,
&mut pages,
&mut page_blacklist,
max_pages,
&mut marked_as_entry,
&mut to_visit_stack,
);
dbg_assert!(ok.is_some());
dbg_assert!(marked_as_entry.contains(&virt_addr));
}
while let Some(to_visit) = to_visit_stack.pop() {
let phys_addr = match cpu::translate_address_read_no_side_effects(to_visit) {
Err(()) => {
dbg_log!("Not analysing {:x} (page not mapped)", to_visit);
continue;
},
Ok(phys_addr) => phys_addr,
};
if basic_blocks.contains_key(&phys_addr) {
continue;
}
if is_near_end_of_page(phys_addr) {
// Empty basic block, don't insert
profiler::stat_increment(stat::COMPILE_CUT_OFF_AT_END_OF_PAGE);
continue;
}
let mut current_address = phys_addr;
let mut current_block = BasicBlock {
addr: current_address,
virt_addr: to_visit,
last_instruction_addr: 0,
end_addr: 0,
ty: BasicBlockType::Exit,
is_entry_block: false,
has_sti: false,
number_of_instructions: 0,
};
loop {
let addr_before_instruction = current_address;
let mut cpu = &mut CpuContext {
eip: current_address,
..cpu
};
let analysis = ::analysis::analyze_step(&mut cpu);
current_block.number_of_instructions += 1;
let has_next_instruction = !analysis.no_next_instruction;
current_address = cpu.eip;
dbg_assert!(Page::page_of(current_address) == Page::page_of(addr_before_instruction));
let current_virt_addr = to_visit & !0xFFF | current_address as i32 & 0xFFF;
match analysis.ty {
AnalysisType::Normal | AnalysisType::STI => {
dbg_assert!(has_next_instruction);
dbg_assert!(!analysis.absolute_jump);
if current_block.has_sti {
// Convert next instruction after STI (i.e., the current instruction) into block boundary
marked_as_entry.insert(current_virt_addr);
to_visit_stack.push(current_virt_addr);
current_block.last_instruction_addr = addr_before_instruction;
current_block.end_addr = current_address;
break;
}
if analysis.ty == AnalysisType::STI {
current_block.has_sti = true;
dbg_assert!(
!is_near_end_of_page(current_address),
"TODO: Handle STI instruction near end of page"
);
}
else {
// Only split non-STI blocks (one instruction needs to run after STI before
// handle_irqs may be called)
if basic_blocks.contains_key(¤t_address) {
current_block.last_instruction_addr = addr_before_instruction;
current_block.end_addr = current_address;
dbg_assert!(!is_near_end_of_page(current_address));
current_block.ty = BasicBlockType::Normal {
next_block_addr: Some(current_address),
jump_offset: 0,
jump_offset_is_32: true,
};
break;
}
}
},
AnalysisType::Jump {
offset,
is_32,
condition: Some(condition),
} => {
dbg_assert!(!analysis.absolute_jump);
// conditional jump: continue at next and continue at jump target
let jump_target = if is_32 {
current_virt_addr + offset
}
else {
cpu.cs_offset as i32
+ (current_virt_addr - cpu.cs_offset as i32 + offset & 0xFFFF)
};
dbg_assert!(has_next_instruction);
to_visit_stack.push(current_virt_addr);
let next_block_addr = if is_near_end_of_page(current_address) {
None
}
else {
Some(current_address)
};
current_block.ty = BasicBlockType::ConditionalJump {
next_block_addr,
next_block_branch_taken_addr: follow_jump(
jump_target,
ctx,
&mut pages,
&mut page_blacklist,
max_pages,
&mut marked_as_entry,
&mut to_visit_stack,
),
condition,
jump_offset: offset,
jump_offset_is_32: is_32,
};
current_block.last_instruction_addr = addr_before_instruction;
current_block.end_addr = current_address;
break;
},
AnalysisType::Jump {
offset,
is_32,
condition: None,
} => {
dbg_assert!(!analysis.absolute_jump);
// non-conditional jump: continue at jump target
let jump_target = if is_32 {
current_virt_addr + offset
}
else {
cpu.cs_offset as i32
+ (current_virt_addr - cpu.cs_offset as i32 + offset & 0xFFFF)
};
if has_next_instruction {
// Execution will eventually come back to the next instruction (CALL)
marked_as_entry.insert(current_virt_addr);
to_visit_stack.push(current_virt_addr);
}
current_block.ty = BasicBlockType::Normal {
next_block_addr: follow_jump(
jump_target,
ctx,
&mut pages,
&mut page_blacklist,
max_pages,
&mut marked_as_entry,
&mut to_visit_stack,
),
jump_offset: offset,
jump_offset_is_32: is_32,
};
current_block.last_instruction_addr = addr_before_instruction;
current_block.end_addr = current_address;
break;
},
AnalysisType::BlockBoundary => {
// a block boundary but not a jump, get out
if has_next_instruction {
// block boundary, but execution will eventually come back
// to the next instruction. Create a new basic block
// starting at the next instruction and register it as an
// entry point
marked_as_entry.insert(current_virt_addr);
to_visit_stack.push(current_virt_addr);
}
if analysis.absolute_jump {
current_block.ty = BasicBlockType::AbsoluteEip;
}
current_block.last_instruction_addr = addr_before_instruction;
current_block.end_addr = current_address;
break;
},
}
if is_near_end_of_page(current_address) {
current_block.last_instruction_addr = addr_before_instruction;
current_block.end_addr = current_address;
profiler::stat_increment(stat::COMPILE_CUT_OFF_AT_END_OF_PAGE);
break;
}
}
let previous_block = basic_blocks
.range(..current_block.addr)
.next_back()
.filter(|(_, previous_block)| (!previous_block.has_sti))
.map(|(_, previous_block)| previous_block.clone());
if let Some(previous_block) = previous_block {
if current_block.addr < previous_block.end_addr {
// If this block overlaps with the previous block, re-analyze the previous block
to_visit_stack.push(previous_block.virt_addr);
let addr = previous_block.addr;
let old_block = basic_blocks.remove(&addr);
dbg_assert!(old_block.is_some());
// Note that this does not ensure the invariant that two consecutive blocks don't
// overlay. For that, we also need to check the following block.
}
}
dbg_assert!(current_block.addr < current_block.end_addr);
dbg_assert!(current_block.addr <= current_block.last_instruction_addr);
dbg_assert!(current_block.last_instruction_addr < current_block.end_addr);
basic_blocks.insert(current_block.addr, current_block);
}
dbg_assert!(pages.len() <= max_pages);
for block in basic_blocks.values_mut() {
if marked_as_entry.contains(&block.virt_addr) {
block.is_entry_block = true;
}
}
let basic_blocks: Vec<BasicBlock> = basic_blocks.into_iter().map(|(_, block)| block).collect();
for i in 0..basic_blocks.len() - 1 {
let next_block_addr = basic_blocks[i + 1].addr;
let next_block_end_addr = basic_blocks[i + 1].end_addr;
let next_block_is_entry = basic_blocks[i + 1].is_entry_block;
let block = &basic_blocks[i];
dbg_assert!(block.addr < next_block_addr);
if next_block_addr < block.end_addr {
dbg_log!(
"Overlapping first=[from={:x} to={:x} is_entry={}] second=[from={:x} to={:x} is_entry={}]",
block.addr,
block.end_addr,
block.is_entry_block as u8,
next_block_addr,
next_block_end_addr,
next_block_is_entry as u8
);
}
}
basic_blocks
}
#[no_mangle]
#[cfg(debug_assertions)]
pub fn jit_force_generate_unsafe(virt_addr: i32) {
let ctx = get_jit_state();
let phys_addr = cpu::translate_address_read(virt_addr).unwrap();
record_entry_point(phys_addr);
let cs_offset = cpu::get_seg_cs() as u32;
let state_flags = cpu::pack_current_state_flags();
jit_analyze_and_generate(ctx, virt_addr, phys_addr, cs_offset, state_flags);
}
#[inline(never)]
fn jit_analyze_and_generate(
ctx: &mut JitState,
virt_entry_point: i32,
phys_entry_point: u32,
cs_offset: u32,
state_flags: CachedStateFlags,
) {
let page = Page::page_of(phys_entry_point);
if ctx.compiling.is_some() {
return;
}
let entry_points = ctx.entry_points.get(&page);
let entry_points = match entry_points {
None => return,
Some(entry_points) => entry_points,
};
if entry_points.iter().all(|&entry_point| {
ctx.cache
.contains_key(&(page.to_address() | u32::from(entry_point)))
}) {
profiler::stat_increment(stat::COMPILE_SKIPPED_NO_NEW_ENTRY_POINTS);
return;
}
profiler::stat_increment(stat::COMPILE);
let cpu = CpuContext {
eip: 0,
prefixes: 0,
cs_offset,
state_flags,
};
dbg_assert!(
cpu::translate_address_read_no_side_effects(virt_entry_point).unwrap() == phys_entry_point
);
let virt_page = Page::page_of(virt_entry_point as u32);
let entry_points: HashSet<i32> = entry_points
.iter()
.map(|e| virt_page.to_address() as i32 | *e as i32)
.collect();
let basic_blocks = jit_find_basic_blocks(ctx, entry_points, cpu.clone());
let mut pages = HashSet::new();
for b in basic_blocks.iter() {
// Remove this assertion once page-crossing jit is enabled
dbg_assert!(Page::page_of(b.addr) == Page::page_of(b.end_addr));
pages.insert(Page::page_of(b.addr));
}
let print = false;
for b in basic_blocks.iter() {
if !print {
break;
}
let last_instruction_opcode = memory::read32s(b.last_instruction_addr);
let op = opstats::decode(last_instruction_opcode as u32);
dbg_log!(
"BB: 0x{:x} {}{:02x} {} {}",
b.addr,
if op.is_0f { "0f" } else { "" },
op.opcode,
if b.is_entry_block { "entry" } else { "noentry" },
match &b.ty {
BasicBlockType::ConditionalJump {
next_block_addr: Some(next_block_addr),
next_block_branch_taken_addr: Some(next_block_branch_taken_addr),
..
} => format!(
"0x{:x} 0x{:x}",
next_block_addr, next_block_branch_taken_addr
),
BasicBlockType::ConditionalJump {
next_block_addr: None,
next_block_branch_taken_addr: Some(next_block_branch_taken_addr),
..
} => format!("0x{:x}", next_block_branch_taken_addr),
BasicBlockType::ConditionalJump {
next_block_addr: Some(next_block_addr),
next_block_branch_taken_addr: None,
..
} => format!("0x{:x}", next_block_addr),
BasicBlockType::ConditionalJump {
next_block_addr: None,
next_block_branch_taken_addr: None,
..
} => format!(""),
BasicBlockType::Normal {
next_block_addr: Some(next_block_addr),
..
} => format!("0x{:x}", next_block_addr),
BasicBlockType::Normal {
next_block_addr: None,
..
} => format!(""),
BasicBlockType::Exit => format!(""),
BasicBlockType::AbsoluteEip => format!(""),
}
);
}
let graph = control_flow::make_graph(&basic_blocks);
let mut structure = control_flow::loopify(&graph);
if print {
dbg_log!("before blockify:");
for group in &structure {
dbg_log!("=> Group");
group.print(0);
}
}
control_flow::blockify(&mut structure, &graph);
if cfg!(debug_assertions) {
control_flow::assert_invariants(&structure);
}
if print {
dbg_log!("after blockify:");
for group in &structure {
dbg_log!("=> Group");
group.print(0);
}
}
if ctx.wasm_table_index_free_list.is_empty() {
dbg_log!("wasm_table_index_free_list empty, clearing cache");
// When no free slots are available, delete all cached modules. We could increase the
// size of the table, but this way the initial size acts as an upper bound for the
// number of wasm modules that we generate, which we want anyway to avoid getting our
// tab killed by browsers due to memory constraints.
jit_clear_cache(ctx);
profiler::stat_increment(stat::INVALIDATE_ALL_MODULES_NO_FREE_WASM_INDICES);
dbg_log!(
"after jit_clear_cache: {} free",
ctx.wasm_table_index_free_list.len(),
);
// This assertion can fail if all entries are pending (not possible unless
// WASM_TABLE_SIZE is set very low)
dbg_assert!(!ctx.wasm_table_index_free_list.is_empty());
}
// allocate an index in the wasm table
let wasm_table_index = ctx
.wasm_table_index_free_list
.pop()
.expect("allocate wasm table index");
dbg_assert!(wasm_table_index != WasmTableIndex(0));
dbg_assert!(!pages.is_empty());
dbg_assert!(pages.len() <= MAX_PAGES);
ctx.used_wasm_table_indices
.insert(wasm_table_index, pages.clone());
ctx.all_pages.extend(pages.clone());
let basic_block_by_addr: HashMap<u32, BasicBlock> =
basic_blocks.into_iter().map(|b| (b.addr, b)).collect();
let entries = jit_generate_module(
structure,
&basic_block_by_addr,
cpu.clone(),
&mut ctx.wasm_builder,
wasm_table_index,
state_flags,
);
dbg_assert!(!entries.is_empty());
profiler::stat_increment_by(
stat::COMPILE_WASM_TOTAL_BYTES,
ctx.wasm_builder.get_output_len() as u64,
);
profiler::stat_increment_by(stat::COMPILE_PAGE, pages.len() as u64);
cpu::tlb_set_has_code_multiple(&pages, true);
dbg_assert!(ctx.compiling.is_none());
ctx.compiling = Some((wasm_table_index, PageState::Compiling { entries }));
let phys_addr = page.to_address();
// will call codegen_finalize_finished asynchronously when finished
codegen_finalize(
wasm_table_index,
phys_addr,
state_flags,
ctx.wasm_builder.get_output_ptr() as u32,
ctx.wasm_builder.get_output_len(),
);
profiler::stat_increment(stat::COMPILE_SUCCESS);
check_jit_state_invariants(ctx);
}
#[no_mangle]
pub fn codegen_finalize_finished(
wasm_table_index: WasmTableIndex,
phys_addr: u32,
state_flags: CachedStateFlags,
) {
let ctx = get_jit_state();
dbg_assert!(wasm_table_index != WasmTableIndex(0));
dbg_log!(
"Finished compiling for page at {:x}",
Page::page_of(phys_addr).to_address()
);
let entries = match mem::replace(&mut ctx.compiling, None) {
None => {
dbg_assert!(false);
return;
},
Some((in_progress_wasm_table_index, PageState::CompilingWritten)) => {
dbg_assert!(wasm_table_index == in_progress_wasm_table_index);
profiler::stat_increment(stat::INVALIDATE_MODULE_WRITTEN_WHILE_COMPILED);
free_wasm_table_index(ctx, wasm_table_index);
return;
},
Some((in_progress_wasm_table_index, PageState::Compiling { entries })) => {
dbg_assert!(wasm_table_index == in_progress_wasm_table_index);
entries
},
};
let mut check_for_unused_wasm_table_index = HashSet::new();
dbg_assert!(!entries.is_empty());
for (addr, entry) in entries {
let maybe_old_entry = ctx.cache.insert(addr, entry);
if let Some(old_entry) = maybe_old_entry {
check_for_unused_wasm_table_index.insert(old_entry.wasm_table_index);
profiler::stat_increment(stat::JIT_CACHE_OVERRIDE);
if old_entry.state_flags != state_flags {
profiler::stat_increment(stat::JIT_CACHE_OVERRIDE_DIFFERENT_STATE_FLAGS)
}
}
}
for index in check_for_unused_wasm_table_index {
let pages = ctx.used_wasm_table_indices.get(&index).unwrap();
let mut is_used = false;
'outer: for p in pages {
for addr in p.address_range() {
if let Some(entry) = ctx.cache.get(&addr) {
if entry.wasm_table_index == index {
is_used = true;
break 'outer;
}
}
}
}
if !is_used {
profiler::stat_increment(stat::INVALIDATE_MODULE_UNUSED_AFTER_OVERWRITE);
free_wasm_table_index(ctx, index);
}
if !is_used {
for (_, entry) in &ctx.cache {
dbg_assert!(entry.wasm_table_index != index);
}
}
else {
let mut ok = false;
for (_, entry) in &ctx.cache {
if entry.wasm_table_index == index {
ok = true;
break;
}
}
dbg_assert!(ok);
}
}
check_jit_state_invariants(ctx);
}
fn jit_generate_module(
structure: Vec<WasmStructure>,
basic_blocks: &HashMap<u32, BasicBlock>,
mut cpu: CpuContext,
builder: &mut WasmBuilder,
wasm_table_index: WasmTableIndex,
state_flags: CachedStateFlags,
) -> Vec<(u32, Entry)> {
builder.reset();
let mut register_locals = (0..8)
.map(|i| {
builder.load_fixed_i32(global_pointers::get_reg32_offset(i));
builder.set_new_local()