WARNING! Access to this system is limited to authorised users only.
Unauthorised users may be subject to prosecution.
Unauthorised access to this system is a criminal offence under Australian law (Federal Crimes Act 1914 Part VIA)
It is a criminal offence to:
(1) Obtain access to data without authority. -Penalty 2 years imprisonment.
(2) Damage, delete, alter or insert data without authority. -Penalty 10 years imprisonment.
User activity is monitored and recorded. Anyone using this system expressly consents to such monitoring and recording.

To protect your data, the CISO officer has suggested users to enable 2FA as soon as possible.
Currently 2.7% of users enabled 2FA.

mod.rs 90.8 KB
Newer Older
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1
// Copyright 2017 The Australian National University
2
//
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
3
4
5
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
6
//
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
9
10
11
12
13
14
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15
16
17
18
19
20
21
22
23
24
// TODO: CHECK THAT THE TYPE OF EVERY MEMORY LOCATION HAS THE CORRECT SIZE
// (the size should be size of the area in memory that it is referring to, and will indicate
// how much data any load/store instructions that uses it will operate on
// (so it should be [1], 8, 16, 32, 64, or 128 bits in size (when using emit_mem, it can have other sizes before this))


#![allow(non_upper_case_globals)]
// TODO: Move architecture independent codes in here, inst_sel and asm_backend to somewhere else...
pub mod inst_sel;

25
26
use utils::bit_utils::bits_ones;

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
mod codegen;
pub use compiler::backend::aarch64::codegen::CodeGenerator;

mod asm_backend;
pub use compiler::backend::aarch64::asm_backend::ASMCodeGen;
pub use compiler::backend::aarch64::asm_backend::emit_code;
pub use compiler::backend::aarch64::asm_backend::emit_context;
pub use compiler::backend::aarch64::asm_backend::emit_context_with_reloc;
use utils::Address;

#[cfg(feature = "aot")]
pub use compiler::backend::aarch64::asm_backend::spill_rewrite;

use ast::ptr::P;
use ast::ir::*;
use ast::types::*;
use ast::op;
use compiler::backend::RegGroup;
use vm::VM;

47
use utils::ByteSize;
48
use utils::math::align_up;
49
50
51
52
use utils::LinkedHashMap;
use std::collections::HashMap;

// Number of nromal callee saved registers (excluding FP and LR, and SP)
53
pub const CALLEE_SAVED_COUNT: usize = 18;
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

macro_rules! REGISTER {
    ($id:expr, $name: expr, $ty: ident) => {
        {
            P(Value {
                hdr: MuEntityHeader::named($id, $name.to_string()),
                ty: $ty.clone(),
                v: Value_::SSAVar($id)
            })
        }
    };
}

macro_rules! GPR_ALIAS {
    ($alias: ident: ($id64: expr, $r64: ident) -> $r32: ident) => {
        lazy_static!{
            pub static ref $r64 : P<Value> = REGISTER!($id64,    stringify!($r64), UINT64_TYPE);
            pub static ref $r32 : P<Value> = REGISTER!($id64 +1, stringify!($r32), UINT32_TYPE);
            pub static ref $alias : [P<Value>; 2] = [$r64.clone(), $r32.clone()];
        }
    };
}

// Used to create a generic alias name
macro_rules! ALIAS {
    ($src: ident -> $dest: ident) => {
        //pub use $src as $dest;
        lazy_static!{
            pub static ref $dest : P<Value> = $src.clone();
        }
    };
}


macro_rules! FPR_ALIAS {
    ($alias: ident: ($id64: expr, $r64: ident) -> $r32: ident) => {
        lazy_static!{
            pub static ref $r64 : P<Value> = REGISTER!($id64,    stringify!($r64), DOUBLE_TYPE);
            pub static ref $r32 : P<Value> = REGISTER!($id64 +1, stringify!($r32), FLOAT_TYPE);
            pub static ref $alias : [P<Value>; 2] = [$r64.clone(), $r32.clone()];
        }
    };
}

GPR_ALIAS!(X0_ALIAS: (0, X0)  -> W0);
GPR_ALIAS!(X1_ALIAS: (2, X1)  -> W1);
GPR_ALIAS!(X2_ALIAS: (4, X2)  -> W2);
GPR_ALIAS!(X3_ALIAS: (6, X3)  -> W3);
GPR_ALIAS!(X4_ALIAS: (8, X4)  -> W4);
GPR_ALIAS!(X5_ALIAS: (10, X5)  -> W5);
GPR_ALIAS!(X6_ALIAS: (12, X6)  -> W6);
GPR_ALIAS!(X7_ALIAS: (14, X7)  -> W7);
GPR_ALIAS!(X8_ALIAS: (16, X8)  -> W8);
GPR_ALIAS!(X9_ALIAS: (18, X9)  -> W9);
GPR_ALIAS!(X10_ALIAS: (20, X10)  -> W10);
GPR_ALIAS!(X11_ALIAS: (22, X11)  -> W11);
GPR_ALIAS!(X12_ALIAS: (24, X12)  -> W12);
GPR_ALIAS!(X13_ALIAS: (26, X13)  -> W13);
GPR_ALIAS!(X14_ALIAS: (28, X14)  -> W14);
GPR_ALIAS!(X15_ALIAS: (30, X15)  -> W15);
GPR_ALIAS!(X16_ALIAS: (32, X16)  -> W16);
GPR_ALIAS!(X17_ALIAS: (34, X17)  -> W17);
GPR_ALIAS!(X18_ALIAS: (36, X18)  -> W18);
GPR_ALIAS!(X19_ALIAS: (38, X19)  -> W19);
GPR_ALIAS!(X20_ALIAS: (40, X20)  -> W20);
GPR_ALIAS!(X21_ALIAS: (42, X21)  -> W21);
GPR_ALIAS!(X22_ALIAS: (44, X22)  -> W22);
GPR_ALIAS!(X23_ALIAS: (46, X23)  -> W23);
GPR_ALIAS!(X24_ALIAS: (48, X24)  -> W24);
GPR_ALIAS!(X25_ALIAS: (50, X25)  -> W25);
GPR_ALIAS!(X26_ALIAS: (52, X26)  -> W26);
GPR_ALIAS!(X27_ALIAS: (54, X27)  -> W27);
GPR_ALIAS!(X28_ALIAS: (56, X28)  -> W28);
GPR_ALIAS!(X29_ALIAS: (58, X29)  -> W29);
GPR_ALIAS!(X30_ALIAS: (60, X30)  -> W30);
GPR_ALIAS!(SP_ALIAS: (62, SP)  -> WSP); // Special register (only some instructions can reference it)
GPR_ALIAS!(XZR_ALIAS: (64, XZR)  -> WZR); // Pseudo register, not to be used by register allocator

// Aliases
ALIAS!(X8 -> XR); // Indirect result location register (points to a location in memory to write return values to)
ALIAS!(X16 -> IP0); // Intra proecdure call register 0 (may be modified by the linker when executing BL/BLR instructions)
135
ALIAS!(X17 -> IP1); // Intra proecdure call register 1 (may be modified by the linker when executing BL/BLR instructions)
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
ALIAS!(X18 -> PR); // Platform Register (NEVER TOUCH THIS REGISTER (Unless you can prove Linux dosn't use it))
ALIAS!(X29 -> FP); // Frame Pointer (can be used as a normal register when not calling or returning)
ALIAS!(X30 -> LR); // Link Register (not supposed to be used for any other purpose)


lazy_static! {
    pub static ref GPR_ALIAS_TABLE : LinkedHashMap<MuID, Vec<P<Value>>> = {
        let mut ret = LinkedHashMap::new();

        ret.insert(X0.id(), X0_ALIAS.to_vec());
        ret.insert(X1.id(), X1_ALIAS.to_vec());
        ret.insert(X2.id(), X2_ALIAS.to_vec());
        ret.insert(X3.id(), X3_ALIAS.to_vec());
        ret.insert(X4.id(), X4_ALIAS.to_vec());
        ret.insert(X5.id(), X5_ALIAS.to_vec());
        ret.insert(X6.id(), X6_ALIAS.to_vec());
        ret.insert(X7.id(), X7_ALIAS.to_vec());
        ret.insert(X8.id(), X8_ALIAS.to_vec());
        ret.insert(X9.id(), X9_ALIAS.to_vec());
        ret.insert(X10.id(), X10_ALIAS.to_vec());
        ret.insert(X11.id(), X11_ALIAS.to_vec());
        ret.insert(X12.id(), X12_ALIAS.to_vec());
        ret.insert(X13.id(), X13_ALIAS.to_vec());
        ret.insert(X14.id(), X14_ALIAS.to_vec());
        ret.insert(X15.id(), X15_ALIAS.to_vec());
        ret.insert(X16.id(), X16_ALIAS.to_vec());
        ret.insert(X17.id(), X17_ALIAS.to_vec());
        ret.insert(X18.id(), X18_ALIAS.to_vec());
        ret.insert(X19.id(), X19_ALIAS.to_vec());
        ret.insert(X20.id(), X20_ALIAS.to_vec());
        ret.insert(X21.id(), X21_ALIAS.to_vec());
        ret.insert(X22.id(), X22_ALIAS.to_vec());
        ret.insert(X23.id(), X23_ALIAS.to_vec());
        ret.insert(X24.id(), X24_ALIAS.to_vec());
        ret.insert(X25.id(), X25_ALIAS.to_vec());
        ret.insert(X26.id(), X26_ALIAS.to_vec());
        ret.insert(X27.id(), X27_ALIAS.to_vec());
        ret.insert(X28.id(), X28_ALIAS.to_vec());
        ret.insert(X29.id(), X29_ALIAS.to_vec());
        ret.insert(X30.id(), X30_ALIAS.to_vec());
        ret.insert(SP.id(), SP_ALIAS.to_vec());
        ret.insert(XZR.id(), XZR_ALIAS.to_vec());
        ret
    };

    // e.g. given eax, return rax
    pub static ref GPR_ALIAS_LOOKUP : HashMap<MuID, P<Value>> = {
        let mut ret = HashMap::new();

        for vec in GPR_ALIAS_TABLE.values() {
            let colorable = vec[0].clone();

            for gpr in vec {
                ret.insert(gpr.id(), colorable.clone());
            }
        }

        ret
    };
}

// Is val a hard coded machine register (not a pseudo register)
pub fn is_machine_reg(val: &P<Value>) -> bool {
    match val.v {
        Value_::SSAVar(ref id) => {
            if *id < FPR_ID_START {
                match GPR_ALIAS_LOOKUP.get(&id) {
                    Some(_) => true,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
204
                    None => false,
205
206
207
208
                }
            } else {
                match FPR_ALIAS_LOOKUP.get(&id) {
                    Some(_) => true,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
209
                    None => false,
210
211
212
                }
            }
        }
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
213
        _ => false,
214
215
216
217
218
219
220
221
222
223
    }

}


// Returns a P<Value> to the register id
pub fn get_register_from_id(id: MuID) -> P<Value> {
    if id < FPR_ID_START {
        match GPR_ALIAS_LOOKUP.get(&id) {
            Some(val) => val.clone(),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
224
            None => panic!("cannot find GPR {}", id),
225
226
227
228
        }
    } else {
        match FPR_ALIAS_LOOKUP.get(&id) {
            Some(val) => val.clone(),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
229
            None => panic!("cannot find FPR {}", id),
230
231
232
233
234
235
236
237
        }
    }
}

pub fn get_alias_for_length(id: MuID, length: usize) -> P<Value> {
    if id < FPR_ID_START {
        let vec = match GPR_ALIAS_TABLE.get(&id) {
            Some(vec) => vec,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
238
            None => panic!("didnt find {} as GPR", id),
239
240
241
242
243
244
245
246
247
248
        };

        if length > 32 {
            vec[0].clone()
        } else {
            vec[1].clone()
        }
    } else {
        let vec = match FPR_ALIAS_TABLE.get(&id) {
            Some(vec) => vec,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
249
            None => panic!("didnt find {} as FPR", id),
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
        };

        if length > 32 {
            vec[0].clone()
        } else {
            vec[1].clone()
        }
    }
}

pub fn is_aliased(id1: MuID, id2: MuID) -> bool {
    return get_color_for_precolored(id1) == get_color_for_precolored(id2);
}

pub fn get_color_for_precolored(id: MuID) -> MuID {
    debug_assert!(id < MACHINE_ID_END);

    if id < FPR_ID_START {
        match GPR_ALIAS_LOOKUP.get(&id) {
            Some(val) => val.id(),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
270
            None => panic!("cannot find GPR {}", id),
271
272
273
274
        }
    } else {
        match FPR_ALIAS_LOOKUP.get(&id) {
            Some(val) => val.id(),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
275
            None => panic!("cannot find FPR {}", id),
276
277
278
279
280
281
282
        }
    }
}

#[inline(always)]
pub fn check_op_len(ty: &P<MuType>) -> usize {
    match ty.get_int_length() {
283
284
        Some(n) if n <= 32 => 32,
        Some(n) if n <= 64 => 64,
285
286
287
288
289
        Some(n) => panic!("unimplemented int size: {}", n),
        None => {
            match ty.v {
                MuType_::Float => 32,
                MuType_::Double => 64,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
290
                _ => panic!("unimplemented primitive type: {}", ty),
291
292
293
294
295
296
            }
        }
    }
}

#[inline(always)]
297
pub fn get_bit_size(ty: &P<MuType>, vm: &VM) -> usize {
298
299
300
301
302
303
    match ty.get_int_length() {
        Some(val) => val,
        None => {
            match ty.v {
                MuType_::Float => 32,
                MuType_::Double => 64,
304
305
                MuType_::Vector(ref t, n) => get_bit_size(t, vm) * n,
                MuType_::Array(ref t, n) => get_bit_size(t, vm) * n,
306
                MuType_::Void => 0,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
307
                _ => vm.get_backend_type_size(ty.id()) * 8,
308
309
310
311
312
313
            }
        }
    }
}

#[inline(always)]
314
pub fn get_type_alignment(ty: &P<MuType>, vm: &VM) -> usize {
315
316
317
318
    vm.get_backend_type_info(ty.id()).alignment
}

#[inline(always)]
319
pub fn primitive_byte_size(ty: &P<MuType>) -> usize {
320
    match ty.get_int_length() {
321
        Some(val) => (align_up(val, 8) / 8).next_power_of_two(),
322
323
324
325
326
        None => {
            match ty.v {
                MuType_::Float => 4,
                MuType_::Double => 8,
                MuType_::Void => 0,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
327
                _ => panic!("Not a primitive type"),
328
329
330
331
332
            }
        }
    }
}

333
#[allow(dead_code)]
334
lazy_static! {
335
336
    // Note: these are the same as the ARGUMENT_GPRS
    pub static ref RETURN_GPRS : [P<Value>; 8] = [
337
338
339
340
341
342
343
344
345
346
        X0.clone(),
        X1.clone(),
        X2.clone(),
        X3.clone(),
        X4.clone(),
        X5.clone(),
        X6.clone(),
        X7.clone()
    ];

347
    pub static ref ARGUMENT_GPRS : [P<Value>; 8] = [
348
349
350
351
352
353
354
355
356
357
        X0.clone(),
        X1.clone(),
        X2.clone(),
        X3.clone(),
        X4.clone(),
        X5.clone(),
        X6.clone(),
        X7.clone()
    ];

358
    pub static ref CALLEE_SAVED_GPRS : [P<Value>; 10] = [
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
        X19.clone(),
        X20.clone(),
        X21.clone(),
        X22.clone(),
        X23.clone(),
        X24.clone(),
        X25.clone(),
        X26.clone(),
        X27.clone(),
        X28.clone(),

        // Note: These two are technically CALLEE saved but need to be dealt with specially
        //X29.clone(), // Frame Pointer
        //X30.clone() // Link Register
    ];

375
    pub static ref CALLER_SAVED_GPRS : [P<Value>; 18] = [
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
        X0.clone(),
        X1.clone(),
        X2.clone(),
        X3.clone(),
        X4.clone(),
        X5.clone(),
        X6.clone(),
        X7.clone(),
        X8.clone(),
        X9.clone(),
        X10.clone(),
        X11.clone(),
        X12.clone(),
        X13.clone(),
        X14.clone(),
        X15.clone(),
        X16.clone(),
        X17.clone(),
        //X18.clone(), // Platform Register
    ];

397
    /*#[allow(dead_code)]
398
    static ref ALL_GPRS : [P<Value>; 30] = [
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
        X0.clone(),
        X1.clone(),
        X2.clone(),
        X3.clone(),
        X4.clone(),
        X5.clone(),
        X6.clone(),
        X7.clone(),
        X8.clone(),
        X9.clone(),
        X10.clone(),
        X11.clone(),
        X12.clone(),
        X13.clone(),
        X14.clone(),
        X15.clone(),
        X16.clone(),
        X17.clone(),
        //X18.clone(), // Platform Register
        X19.clone(),
        X20.clone(),
        X21.clone(),
        X22.clone(),
        X23.clone(),
        X24.clone(),
        X25.clone(),
        X26.clone(),
        X27.clone(),
        X28.clone(),
        X29.clone(), // Frame Pointer
        X30.clone() // Link Register
430
    ];*/
431
432
}

433
pub const FPR_ID_START: usize = 100;
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

FPR_ALIAS!(D0_ALIAS: (FPR_ID_START + 0, D0)  -> S0);
FPR_ALIAS!(D1_ALIAS: (FPR_ID_START + 2, D1)  -> S1);
FPR_ALIAS!(D2_ALIAS: (FPR_ID_START + 4, D2)  -> S2);
FPR_ALIAS!(D3_ALIAS: (FPR_ID_START + 6, D3)  -> S3);
FPR_ALIAS!(D4_ALIAS: (FPR_ID_START + 8, D4)  -> S4);
FPR_ALIAS!(D5_ALIAS: (FPR_ID_START + 10, D5)  -> S5);
FPR_ALIAS!(D6_ALIAS: (FPR_ID_START + 12, D6)  -> S6);
FPR_ALIAS!(D7_ALIAS: (FPR_ID_START + 14, D7)  -> S7);
FPR_ALIAS!(D8_ALIAS: (FPR_ID_START + 16, D8)  -> S8);
FPR_ALIAS!(D9_ALIAS: (FPR_ID_START + 18, D9)  -> S9);
FPR_ALIAS!(D10_ALIAS: (FPR_ID_START + 20, D10)  -> S10);
FPR_ALIAS!(D11_ALIAS: (FPR_ID_START + 22, D11)  -> S11);
FPR_ALIAS!(D12_ALIAS: (FPR_ID_START + 24, D12)  -> S12);
FPR_ALIAS!(D13_ALIAS: (FPR_ID_START + 26, D13)  -> S13);
FPR_ALIAS!(D14_ALIAS: (FPR_ID_START + 28, D14)  -> S14);
FPR_ALIAS!(D15_ALIAS: (FPR_ID_START + 30, D15)  -> S15);
FPR_ALIAS!(D16_ALIAS: (FPR_ID_START + 32, D16)  -> S16);
FPR_ALIAS!(D17_ALIAS: (FPR_ID_START + 34, D17)  -> S17);
FPR_ALIAS!(D18_ALIAS: (FPR_ID_START + 36, D18)  -> S18);
FPR_ALIAS!(D19_ALIAS: (FPR_ID_START + 38, D19)  -> S19);
FPR_ALIAS!(D20_ALIAS: (FPR_ID_START + 40, D20)  -> S20);
FPR_ALIAS!(D21_ALIAS: (FPR_ID_START + 42, D21)  -> S21);
FPR_ALIAS!(D22_ALIAS: (FPR_ID_START + 44, D22)  -> S22);
FPR_ALIAS!(D23_ALIAS: (FPR_ID_START + 46, D23)  -> S23);
FPR_ALIAS!(D24_ALIAS: (FPR_ID_START + 48, D24)  -> S24);
FPR_ALIAS!(D25_ALIAS: (FPR_ID_START + 50, D25)  -> S25);
FPR_ALIAS!(D26_ALIAS: (FPR_ID_START + 52, D26)  -> S26);
FPR_ALIAS!(D27_ALIAS: (FPR_ID_START + 54, D27)  -> S27);
FPR_ALIAS!(D28_ALIAS: (FPR_ID_START + 56, D28)  -> S28);
FPR_ALIAS!(D29_ALIAS: (FPR_ID_START + 58, D29)  -> S29);
FPR_ALIAS!(D30_ALIAS: (FPR_ID_START + 60, D30)  -> S30);
FPR_ALIAS!(D31_ALIAS: (FPR_ID_START + 62, D31)  -> S31);

lazy_static! {
    pub static ref FPR_ALIAS_TABLE : LinkedHashMap<MuID, Vec<P<Value>>> = {
        let mut ret = LinkedHashMap::new();

        ret.insert(D0.id(), D0_ALIAS.to_vec());
        ret.insert(D1.id(), D1_ALIAS.to_vec());
        ret.insert(D2.id(), D2_ALIAS.to_vec());
        ret.insert(D3.id(), D3_ALIAS.to_vec());
        ret.insert(D4.id(), D4_ALIAS.to_vec());
        ret.insert(D5.id(), D5_ALIAS.to_vec());
        ret.insert(D6.id(), D6_ALIAS.to_vec());
        ret.insert(D7.id(), D7_ALIAS.to_vec());
        ret.insert(D8.id(), D8_ALIAS.to_vec());
        ret.insert(D9.id(), D9_ALIAS.to_vec());
        ret.insert(D10.id(), D10_ALIAS.to_vec());
        ret.insert(D11.id(), D11_ALIAS.to_vec());
        ret.insert(D12.id(), D12_ALIAS.to_vec());
        ret.insert(D13.id(), D13_ALIAS.to_vec());
        ret.insert(D14.id(), D14_ALIAS.to_vec());
        ret.insert(D15.id(), D15_ALIAS.to_vec());
        ret.insert(D16.id(), D16_ALIAS.to_vec());
        ret.insert(D17.id(), D17_ALIAS.to_vec());
        ret.insert(D18.id(), D18_ALIAS.to_vec());
        ret.insert(D19.id(), D19_ALIAS.to_vec());
        ret.insert(D20.id(), D20_ALIAS.to_vec());
        ret.insert(D21.id(), D21_ALIAS.to_vec());
        ret.insert(D22.id(), D22_ALIAS.to_vec());
        ret.insert(D23.id(), D23_ALIAS.to_vec());
        ret.insert(D24.id(), D24_ALIAS.to_vec());
        ret.insert(D25.id(), D25_ALIAS.to_vec());
        ret.insert(D26.id(), D26_ALIAS.to_vec());
        ret.insert(D27.id(), D27_ALIAS.to_vec());
        ret.insert(D28.id(), D28_ALIAS.to_vec());
        ret.insert(D29.id(), D29_ALIAS.to_vec());
        ret.insert(D30.id(), D30_ALIAS.to_vec());
        ret.insert(D31.id(), D31_ALIAS.to_vec());

        ret
    };


    pub static ref FPR_ALIAS_LOOKUP : HashMap<MuID, P<Value>> = {
        let mut ret = HashMap::new();

        for vec in FPR_ALIAS_TABLE.values() {
            let colorable = vec[0].clone();

            for fpr in vec {
                ret.insert(fpr.id(), colorable.clone());
            }
        }

        ret
    };
}

lazy_static!{
525
526
    // Same as ARGUMENT_FPRS
    pub static ref RETURN_FPRS : [P<Value>; 8] = [
527
528
529
530
531
532
533
534
535
536
        D0.clone(),
        D1.clone(),
        D2.clone(),
        D3.clone(),
        D4.clone(),
        D5.clone(),
        D6.clone(),
        D7.clone()
    ];

537
    pub static ref ARGUMENT_FPRS : [P<Value>; 8] = [
538
539
540
541
542
543
544
545
546
547
        D0.clone(),
        D1.clone(),
        D2.clone(),
        D3.clone(),
        D4.clone(),
        D5.clone(),
        D6.clone(),
        D7.clone(),
    ];

548
    pub static ref CALLEE_SAVED_FPRS : [P<Value>; 8] = [
549
550
551
552
553
554
555
556
557
558
        D8.clone(),
        D9.clone(),
        D10.clone(),
        D11.clone(),
        D12.clone(),
        D13.clone(),
        D14.clone(),
        D15.clone()
    ];

559
    pub static ref CALLER_SAVED_FPRS : [P<Value>; 24] = [
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
        D0.clone(),
        D1.clone(),
        D2.clone(),
        D3.clone(),
        D4.clone(),
        D5.clone(),
        D6.clone(),
        D7.clone(),

        D16.clone(),
        D17.clone(),
        D18.clone(),
        D19.clone(),
        D20.clone(),
        D21.clone(),
        D22.clone(),
        D23.clone(),
        D24.clone(),
        D25.clone(),
        D26.clone(),
        D27.clone(),
        D28.clone(),
        D29.clone(),
        D30.clone(),
        D31.clone()
    ];

587
    /*#[allow(dead_code)]
588
    static ref ALL_FPRS : [P<Value>; 32] = [
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
        D0.clone(),
        D1.clone(),
        D2.clone(),
        D3.clone(),
        D4.clone(),
        D5.clone(),
        D6.clone(),
        D7.clone(),

        D8.clone(),
        D9.clone(),
        D10.clone(),
        D11.clone(),
        D12.clone(),
        D13.clone(),
        D14.clone(),
        D15.clone(),

        D16.clone(),
        D17.clone(),
        D18.clone(),
        D19.clone(),
        D20.clone(),
        D21.clone(),
        D22.clone(),
        D23.clone(),
        D24.clone(),
        D25.clone(),
        D26.clone(),
        D27.clone(),
        D28.clone(),
        D29.clone(),
        D30.clone(),
        D31.clone()
623
    ];*/
624
625
626
}

lazy_static! {
627
    pub static ref ALL_MACHINE_REGS : LinkedHashMap<MuID, P<Value>> = {
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
        let mut map = LinkedHashMap::new();

        for vec in GPR_ALIAS_TABLE.values() {
            for reg in vec {
                map.insert(reg.id(), reg.clone());
            }
        }

        for vec in FPR_ALIAS_TABLE.values() {
            for reg in vec {
                map.insert(reg.id(), reg.clone());
            }
        }

        map
    };

645
    pub static ref CALLEE_SAVED_REGS : [P<Value>; 18] = [
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
        X19.clone(),
        X20.clone(),
        X21.clone(),
        X22.clone(),
        X23.clone(),
        X24.clone(),
        X25.clone(),
        X26.clone(),
        X27.clone(),
        X28.clone(),

        // Note: These two are technically CALLEE saved but need to be dealt with specially
        //X29.clone(), // Frame Pointer
        //X30.clone() // Link Register

        D8.clone(),
        D9.clone(),
        D10.clone(),
        D11.clone(),
        D12.clone(),
        D13.clone(),
        D14.clone(),
        D15.clone()
    ];

671
    pub static ref ALL_USABLE_GPRS : Vec<P<Value>> = vec![
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
        X0.clone(),
        X1.clone(),
        X2.clone(),
        X3.clone(),
        X4.clone(),
        X5.clone(),
        X6.clone(),
        X7.clone(),
        X8.clone(),
        X9.clone(),
        X10.clone(),
        X11.clone(),
        X12.clone(),
        X13.clone(),
        X14.clone(),
        X15.clone(),
        X16.clone(),
        X17.clone(),
        // X18.clone(), // Platform Register

        X19.clone(),
        X20.clone(),
        X21.clone(),
        X22.clone(),
        X23.clone(),
        X24.clone(),
        X25.clone(),
        X26.clone(),
        X27.clone(),
        X28.clone(),
        //X29.clone(), // Frame Pointer
        //X30.clone(), // Link Register
704
    ];
705

706
    pub static ref ALL_USABLE_FPRS : Vec<P<Value>> = vec![
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
        D0.clone(),
        D1.clone(),
        D2.clone(),
        D3.clone(),
        D4.clone(),
        D5.clone(),
        D6.clone(),
        D7.clone(),

        D16.clone(),
        D17.clone(),
        D18.clone(),
        D19.clone(),
        D20.clone(),
        D21.clone(),
        D22.clone(),
        D23.clone(),
        D24.clone(),
        D25.clone(),
        D26.clone(),
        D27.clone(),
        D28.clone(),
        D29.clone(),
        D30.clone(),
731
732
733
734
735
736
737
738
739
740
        D31.clone(),

        D8.clone(),
        D9.clone(),
        D10.clone(),
        D11.clone(),
        D12.clone(),
        D13.clone(),
        D14.clone(),
        D15.clone(),
741
    ];
742
743
744
745
746
747
748
749

    // put caller saved regs first (they imposes no overhead if there is no call instruction)
    pub static ref ALL_USABLE_MACHINE_REGS : Vec<P<Value>> = {
        let mut ret = vec![];
        ret.extend_from_slice(&ALL_USABLE_GPRS);
        ret.extend_from_slice(&ALL_USABLE_FPRS);
        ret
    };
750
751
}

752
pub fn init_machine_regs_for_func(func_context: &mut FunctionContext) {
753
    for reg in ALL_MACHINE_REGS.values() {
754
755
756
757
758
759
760
        let reg_id = reg.extract_ssa_id().unwrap();
        let entry = SSAVarEntry::new(reg.clone());

        func_context.values.insert(reg_id, entry);
    }
}

761
pub fn number_of_usable_regs_in_group(group: RegGroup) -> usize {
762
    match group {
qinsoon's avatar
qinsoon committed
763
764
        RegGroup::GPR => ALL_USABLE_GPRS.len(),
        RegGroup::FPR => ALL_USABLE_FPRS.len(),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
765
        RegGroup::GPREX => unimplemented!(),
766
767
768
769
    }
}

pub fn number_of_all_regs() -> usize {
770
    ALL_MACHINE_REGS.len()
771
772
773
}

pub fn all_regs() -> &'static LinkedHashMap<MuID, P<Value>> {
774
    &ALL_MACHINE_REGS
775
776
777
}

pub fn all_usable_regs() -> &'static Vec<P<Value>> {
778
    &ALL_USABLE_MACHINE_REGS
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
}

pub fn pick_group_for_reg(reg_id: MuID) -> RegGroup {
    let reg = all_regs().get(&reg_id).unwrap();
    if is_int_reg(&reg) {
        RegGroup::GPR
    } else if is_fp_reg(&reg) {
        RegGroup::FPR
    } else {
        panic!("expect a machine reg to be either a GPR or a FPR: {}", reg)
    }
}

// Gets the previouse frame pointer with respect to the current
#[inline(always)]
pub fn get_previous_frame_pointer(frame_pointer: Address) -> Address {
    unsafe { frame_pointer.load::<Address>() }
}

// Gets the return address for the current frame pointer
#[inline(always)]
pub fn get_return_address(frame_pointer: Address) -> Address {
801
    unsafe { (frame_pointer + 8 as ByteSize).load::<Address>() }
802
803
804
805
}

// Gets the stack pointer before the current frame was created
#[inline(always)]
806
pub fn get_previous_stack_pointer(frame_pointer: Address, stack_arg_size: usize) -> Address {
807
    frame_pointer + 16 as ByteSize + stack_arg_size
808
809
810
811
812
813
814
815
816
817
}

#[inline(always)]
pub fn set_previous_frame_pointer(frame_pointer: Address, value: Address) {
    unsafe { frame_pointer.store::<Address>(value) }
}

// Gets the return address for the current frame pointer
#[inline(always)]
pub fn set_return_address(frame_pointer: Address, value: Address) {
818
    unsafe { (frame_pointer + 8 as ByteSize).store::<Address>(value) }
819
820
821
822
823
824
}

// Reg should be a 64-bit callee saved GPR or FPR
pub fn get_callee_saved_offset(reg: MuID) -> isize {
    debug_assert!(is_callee_saved(reg));
    let id = if reg < FPR_ID_START {
825
        (reg - CALLEE_SAVED_GPRS[0].id()) / 2
826
    } else {
827
        (reg - CALLEE_SAVED_FPRS[0].id()) / 2 + CALLEE_SAVED_GPRS.len()
828
    };
829
    (id as isize + 1) * (-8)
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
}

// Returns the callee saved register with the id...
/*pub fn get_callee_saved_register(offset: isize) -> P<Value> {
    debug_assert!(offset <= -8 && (-offset) % 8 == 0);
    let id = ((offset/-8) - 1) as usize;
    if id < CALLEE_SAVED_GPRs.len() {
        CALLEE_SAVED_GPRs[id].clone()
    } else if id - CALLEE_SAVED_GPRs.len() < CALLEE_SAVED_FPRs.len() {
        CALLEE_SAVED_FPRs[id - CALLEE_SAVED_GPRs.len()].clone()
    } else {
        panic!("There is no callee saved register with id {}", offset)
    }
}*/

pub fn is_callee_saved(reg_id: MuID) -> bool {

847
    for reg in CALLEE_SAVED_GPRS.iter() {
848
849
850
851
852
        if reg_id == reg.extract_ssa_id().unwrap() {
            return true;
        }
    }

853
    for reg in CALLEE_SAVED_FPRS.iter() {
854
855
856
857
858
859
860
861
862
863
864
865
866
867
        if reg_id == reg.extract_ssa_id().unwrap() {
            return true;
        }
    }
    false
}

// TODO: Check that these numbers are reasonable (THEY ARE ONLY AN ESTIMATE)
use ast::inst::*;
pub fn estimate_insts_for_ir(inst: &Instruction) -> usize {
    use ast::inst::Instruction_::*;

    match inst.v {
        // simple
868
        BinOp(_, _, _) => 1,
869
        BinOpWithStatus(_, _, _, _) => 2,
870
871
        CmpOp(_, _, _) => 1,
        ConvOp { .. } => 1,
872
873

        // control flow
874
875
876
877
878
879
        Branch1(_) => 1,
        Branch2 { .. } => 1,
        Select { .. } => 2,
        Watchpoint { .. } => 1,
        WPBranch { .. } => 2,
        Switch { .. } => 3,
880
881

        // call
882
883
        ExprCall { .. } | ExprCCall { .. } | Call { .. } | CCall { .. } => 5,
        Return(_) => 1,
884
885
886
        TailCall(_) => 1,

        // memory access
887
888
889
890
891
892
        Load { .. } | Store { .. } => 1,
        CmpXchg { .. } => 1,
        AtomicRMW { .. } => 1,
        AllocA(_) => 1,
        AllocAHybrid(_, _) => 1,
        Fence(_) => 1,
893
894

        // memory addressing
895
896
897
898
899
        GetIRef(_) |
        GetFieldIRef { .. } |
        GetElementIRef { .. } |
        ShiftIRef { .. } |
        GetVarPartIRef { .. } => 0,
900
901
902
903

        // runtime
        New(_) | NewHybrid(_, _) => 10,
        NewStack(_) | NewThread(_, _) | NewThreadExn(_, _) | NewFrameCursor(_) => 10,
904
905
906
        ThreadExit => 10,
        Throw(_) => 10,
        SwapStack { .. } => 10,
907
908
909
910
911
912
913
        CommonInst_GetThreadLocal | CommonInst_SetThreadLocal(_) => 10,
        CommonInst_Pin(_) | CommonInst_Unpin(_) => 10,

        // others
        Move(_) => 0,
        PrintHex(_) => 10,
        SetRetval(_) => 10,
914
        ExnInstruction { ref inner, .. } => estimate_insts_for_ir(&inner),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
915
        _ => unimplemented!(),
916
917
918
919
920
921
    }
}


// Splits an integer immediate into four 16-bit segments (returns the least significant first)
pub fn split_aarch64_imm_u64(val: u64) -> (u16, u16, u16, u16) {
922
923
924
925
    (
        val as u16,
        (val >> 16) as u16,
        (val >> 32) as u16,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
926
        (val >> 48) as u16,
927
    )
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
}

// Trys to reduce the given floating point to an immediate u64 that can be used with MOVI
pub fn f64_to_aarch64_u64(val: f64) -> Option<u64> {
    use std::mem;
    // WARNING: this assumes a little endian representation
    let bytes: [u8; 8] = unsafe { mem::transmute(val) };

    // Check that each byte is all 1 or all 0
    for i in 0..7 {
        if bytes[i] != 0b11111111 || bytes[i] != 0 {
            return None;
        }
    }

943
    Some(unsafe { mem::transmute::<f64, u64>(val) })
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
}

// Check that the given floating point fits in 8 bits
pub fn is_valid_f32_imm(val: f32) -> bool {
    use std::mem;

    // returns true if val has the format:
    //       aBbbbbbc defgh000 00000000 00000000 (where B = !b)
    //index: FEDCBA98 76543210 FEDCBA98 76543210
    //                       1                 0

    let uval = unsafe { mem::transmute::<f32, u32>(val) };

    let b = get_bit(uval as u64, 0x19);

    get_bit(uval as u64, 0x1E) == !b &&
960
        ((uval & (0b11111 << 0x19)) == if b { 0b11111 << 0x19 } else { 0 }) &&
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
        ((uval & !(0b1111111111111 << 0x13)) == 0)
}

// Reduces the given floating point constant to 8-bits (if it won't loose precision, otherwise returns 0)
pub fn is_valid_f64_imm(val: f64) -> bool {
    use std::mem;

    // returns true if val has the format:
    //       aBbbbbbb bbcdefgh 00000000 00000000 00000000 00000000 00000000 00000000 (where B = !b)
    //index: FEDCBA98 76543210 FEDCBA98 76543210 FEDCBA98 76543210 FEDCBA98 76543210
    //                       3                 2                 1                 0

    let uval = unsafe { mem::transmute::<f64, u64>(val) };

    let b = (uval & (1 << 0x36)) != 0;

    ((uval & (1 << 0x3E)) != 0) == !b &&
978
        ((uval & (0b11111111 << 0x36)) == if b { 0b11111111 << 0x36 } else { 0 }) &&
979
980
981
982
983
984
985
        ((uval & !(0b1111111111111111 << 0x30)) == 0)

}

// Returns the 'ith bit of x
#[inline(always)]
pub fn get_bit(x: u64, i: usize) -> bool {
986
    (x & ((1 as u64) << i)) != 0
987
988
989
}

// Returns true if val = A << S, from some 0 <= A < 4096, and S = 0 or S = 12
990
pub fn is_valid_arithmetic_imm(val: u64) -> bool {
991
992
993
994
995
996
997
    val < 4096 || ((val & 0b111111111111) == 0 && val < (4096 << 12))
}

// aarch64 instructions only operate on 32 and 64-bit registers
// so a valid n bit logical immediate (where n < 32) can't be dirrectly used
// this function will replicate the bit pattern so that it can be used
// (the resulting value will be valid iff 'val' is valid, and the lower 'n' bits will equal val)
998
pub fn replicate_logical_imm(val: u64, n: usize) -> u64 {
999
1000
1001
1002
    let op_size = if n <= 32 { 32 } else { 64 };
    let mut val = val;
    for i in 1..op_size / n {
        val |= val << i * n;
1003
    }
1004
    val
1005
1006
1007
1008
1009
1010
1011
}


// 'val' is a valid logical immediate if the binary value of ROR(val, r) matches the regular expresion
//      (0{k-x}1{x}){m/k}
//      for some r, k that divides N, 2 <= k <= n, and x with 0 < x < k
//      (note: 0 =< r < k);
1012
pub fn is_valid_logical_imm(val: u64, n: usize) -> bool {
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
    // val should be an 'n' bit number
    debug_assert!(0 < n && n <= 64 && (n == 64 || (val < (1 << n))));
    debug_assert!(n.is_power_of_two());

    // all 0's and all 1's are invalid
    if val == 0 || val == bits_ones(n) {
        return false;
    }

    // find the rightmost '1' with '0' to the right
    let mut r = 0;
    while r < n {
        let current_bit = get_bit(val, r);
        let next_bit = get_bit(val, (r + n - 1) % n);
        if current_bit && !next_bit {
            break;
        }

        r += 1;
    }

    // rotate 'val' so that the MSB is a 0, and the LSB is a 1
    // (since there is a '0' to the right of val[start_index])
    let mut val = val.rotate_right(r as u32);

    // lower n bits ored with the upper n bits
    if n < 64 {
        val = (val & bits_ones(n)) | ((val & (bits_ones(n) << (64 - n))) >> (64 - n))
    }

    let mut x = 0; // number of '1's in a row
    while x < n {
        // found a '0' at position x, there must be x 1's to the right
        if !get_bit(val, x) {
            break;
        }
        x += 1;
    }

    let mut k = x + 1; // where the next '1' is
    while k < n {
        // found a '1'
        if get_bit(val, k) {
            break;
        }
        k += 1;
    }
    // Note: the above may not have found a 1, in which case k == n

    // note: k >= 2, since if k = 1, val = 1....1 (which we've already checked for)
    // check that k divides N
    if n % k != 0 {
        return false;
    }

    // Now we need to check that the pattern (0{k-x}1{x}) is repetead N/K times in val

    let k_mask = bits_ones(k);
    let val_0 = val & k_mask; // the first 'k' bits of val

    // for each N/k expected repitions of val_0 (except the first one_
1074
1075
    for i in 1..(n / k) {
        if val_0 != ((val >> (k * i)) & k_mask) {
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
            return false; // val_0 dosen't repeat
        }
    }

    return true;
}

// Returns the value of 'val' truncated to 'size', and then zero extended
pub fn get_unsigned_value(val: u64, size: usize) -> u64 {
    (val & bits_ones(size)) as u64 // clears all but the lowest 'size' bits of val
}

// Returns the value of 'val' truncated to 'size', and then sign extended
pub fn get_signed_value(val: u64, size: usize) -> i64 {
    if size == 64 {
        val as i64
    } else {
        let negative = (val & (1 << (size - 1))) != 0;

        if negative {
1096
            (val | (bits_ones(64 - size) << size)) as i64 // set the highest '64 - size' bits of val
1097
1098
1099
1100
1101
1102
        } else {
            (val & bits_ones(size)) as i64 // clears all but the lowest 'size' bits of val
        }
    }
}

1103
1104
1105
1106
1107
1108
// Returns the value of 'val' truncated to 'size', treated as a negative number
// (i.e. the highest 64-size bits are set to 1)
pub fn get_negative_value(val: u64, size: usize) -> i64 {
    if size == 64 {
        val as i64
    } else {
1109
        (val | (bits_ones(64 - size) << size)) as i64 // set the highest '64 - size' bits of val
1110
1111
1112
    }
}

1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
fn invert_condition_code(cond: &str) -> &'static str {
    match cond {
        "EQ" => "NE",
        "NE" => "EQ",

        "CC" => "CS",
        "CS" => "CV",

        "HS" => "LO",
        "LO" => "HS",

        "MI" => "PL",
        "PL" => "MI",

        "VS" => "VN",
        "VN" => "VS",

        "HI" => "LS",
        "LS" => "HI",

        "GE" => "LT",
        "LT" => "GE",

        "GT" => "LE",
        "LE" => "GT",

        "AL" | "NV" => panic!("AL and NV don't have inverses"),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1140
        _ => panic!("Unrecognised condition code"),
1141
1142
1143
1144
1145
1146
1147
    }
}

// Returns the aarch64 condition codes corresponding to the given comparison op
// (the comparisoon is true when the logical or of these conditions is true)
fn get_condition_codes(op: op::CmpOp) -> Vec<&'static str> {
    match op {
1148
1149
        op::CmpOp::EQ | op::CmpOp::FOEQ => vec!["EQ"],
        op::CmpOp::NE | op::CmpOp::FUNE => vec!["NE"],
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
        op::CmpOp::SGT | op::CmpOp::FOGT => vec!["GT"],
        op::CmpOp::SGE | op::CmpOp::FOGE => vec!["GE"],
        op::CmpOp::SLT | op::CmpOp::FULT => vec!["LT"],
        op::CmpOp::SLE | op::CmpOp::FULE => vec!["LE"],
        op::CmpOp::UGT | op::CmpOp::FUGT => vec!["HI"],
        op::CmpOp::UGE | op::CmpOp::FUGE => vec!["HS"],
        op::CmpOp::ULE | op::CmpOp::FOLE => vec!["LS"],
        op::CmpOp::ULT | op::CmpOp::FOLT => vec!["LO"],
        op::CmpOp::FUNO => vec!["VS"],
        op::CmpOp::FORD => vec!["VC"],
        op::CmpOp::FUEQ => vec!["EQ", "VS"],
        op::CmpOp::FONE => vec!["MI", "GT"],

        // These need to be handeled specially
        op::CmpOp::FFALSE => vec![],
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1165
        op::CmpOp::FTRUE => vec![],
1166
1167
1168
1169
1170
1171
1172
    }
}

// if t is a homogenouse floating point aggregate
// (i.e. an array or struct where each element is the same floating-point type, and there are at most 4 elements)
// returns the number of elements, otherwise returns 0

1173
fn hfa_length(t: &P<MuType>) -> usize {
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
    match t.v {
        MuType_::Struct(ref name) => {
            let read_lock = STRUCT_TAG_MAP.read().unwrap();
            let struc = read_lock.get(name).unwrap();
            let tys = struc.get_tys();
            if tys.len() < 1 || tys.len() > 4 {
                return 0;
            }

            let ref base = tys[0];
            match base.v {
                MuType_::Float | MuType_::Double => {
                    for i in 1..tys.len() - 1 {
                        if tys[i].v != base.v {
                            return 0;
                        }
                    }
                    return tys.len(); // All elements are the same type
                }
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1193
                _ => return 0,
1194
1195
1196
            }


1197
        } // TODO: how do I extra the list of member-types from this??
1198
1199
1200
        MuType_::Array(ref base, n) if n <= 4 => {
            match base.v {
                MuType_::Float | MuType_::Double => n,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1201
                _ => 0,
1202
1203
            }
        }
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1204
        _ => 0,
1205
1206
1207
1208
1209
1210

    }
}

// val is an unsigned multiple of n and val/n fits in 12 bits
#[inline(always)]
1211
pub fn is_valid_immediate_offset(val: i64, n: usize) -> bool {
1212
1213
1214
1215
1216
1217
    use std;
    let n_align = std::cmp::max(n, 8);
    if n <= 8 {
        (val >= -(1 << 8) && val < (1 << 8)) || // Valid 9 bit signed unscaled offset
            // Valid unsigned 12-bit scalled offset
            (val >= 0 && (val as u64) % (n_align as u64) == 0 && ((val as u64) / (n_align as u64) < (1 << 12)))
1218
1219
    } else {
        // Will be using a load/store-pair
1220
        // Is val a signed 7 bit multiple of n_align
1221
        (val as u64) % (n_align as u64) == 0 && ((val as u64) / (n_align as u64) < (1 << 7))
1222
1223
1224
1225
    }
}

#[inline(always)]
1226
pub fn is_valid_immediate_scale(val: u64, n: usize) -> bool {
1227
1228
1229
1230
1231
    // if n > 8, then a load pair will be used, and they don't support scales
    n <= 8 && (val == (n as u64) || val == 1)
}

#[inline(always)]
1232
1233
1234
pub fn is_valid_immediate_extension(val: u64) -> bool {
    val <= 4
}
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261

#[inline(always)]
// Log2, assumes value is a power of two
// TODO: Implement this more efficiently?
pub fn log2(val: u64) -> u64 {
    debug_assert!(val.is_power_of_two());
    debug_assert!(val != 0);
    let mut ret = 0;
    for i in 0..63 {
        if val & (1 << i) != 0 {
            ret = i;
        }
    }
    // WARNING: This will only work for val < 2^31
    //let ret = (val as f64).log2() as u64;
    debug_assert!(val == 1 << ret);
    ret
}

// Gets a primitive integer type with the given alignment
pub fn get_alignment_type(align: usize) -> P<MuType> {
    match align {
        1 => UINT8_TYPE.clone(),
        2 => UINT16_TYPE.clone(),
        4 => UINT32_TYPE.clone(),
        8 => UINT64_TYPE.clone(),
        16 => UINT128_TYPE.clone(),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1262
        _ => panic!("aarch64 dosn't have types with alignment {}", align),
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
    }
}

#[inline(always)]
pub fn is_zero_register(val: &P<Value>) -> bool {
    is_zero_register_id(val.extract_ssa_id().unwrap())
}

#[inline(always)]
pub fn is_zero_register_id(id: MuID) -> bool {
    id == XZR.extract_ssa_id().unwrap() || id == WZR.extract_ssa_id().unwrap()
}

1276
pub fn match_node_f32imm(op: &TreeNode) -> bool {
1277
    match op.v {
1278
1279
1280
        TreeNode_::Value(ref pv) => {
            match pv.v {
                Value_::Constant(Constant::Float(_)) => true,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1281
                _ => false,
1282
1283
            }
        }
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1284
        _ => false,
1285
1286
1287
    }
}

1288
pub fn match_node_f64imm(op: &TreeNode) -> bool {
1289
    match op.v {
1290
1291
1292
        TreeNode_::Value(ref pv) => {
            match pv.v {
                Value_::Constant(Constant::Double(_)) => true,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1293
                _ => false,
1294
1295
            }
        }
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1296
        _ => false,
1297
1298
1299
1300
1301
1302
    }
}

pub fn match_value_f64imm(op: &P<Value>) -> bool {
    match op.v {
        Value_::Constant(Constant::Double(_)) => true,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1303
        _ => false,
1304
1305
1306
1307
1308
1309
    }
}

pub fn match_value_f32imm(op: &P<Value>) -> bool {
    match op.v {
        Value_::Constant(Constant::Float(_)) => true,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1310
        _ => false,
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
    }
}

// The type of the node (for a value node)
pub fn node_type(op: &TreeNode) -> P<MuType> {
    match op.v {
        TreeNode_::Instruction(ref inst) => {
            if inst.value.is_some() {
                let ref value = inst.value.as_ref().unwrap();
                if value.len() != 1 {
                    panic!("the node {} does not have one result value", op);
                }

                value[0].ty.clone()
            } else {
                panic!("expected result from the node {}", op);
            }
        }
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1329
        TreeNode_::Value(ref pv) => pv.ty.clone(),
1330
1331
1332
1333
1334
1335
    }
}

pub fn match_value_imm(op: &P<Value>) -> bool {
    match op.v {
        Value_::Constant(_) => true,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1336
        _ => false,
1337
1338
1339
1340
1341
1342
    }
}

pub fn match_value_int_imm(op: &P<Value>) -> bool {
    match op.v {
        Value_::Constant(Constant::Int(_)) => true,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1343
        _ => false,
1344
1345
    }
}
1346
1347
1348
pub fn match_value_ref_imm(op: &P<Value>) -> bool {
    match op.v {
        Value_::Constant(Constant::NullRef) => true,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1349
        _ => false,
1350
1351
    }
}
1352
1353
1354
pub fn match_node_value(op: &TreeNode) -> bool {
    match op.v {
        TreeNode_::Value(_) => true,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1355
        _ => false,
1356
1357
1358
1359
1360
1361
    }
}

pub fn get_node_value(op: &TreeNode) -> P<Value> {
    match op.v {
        TreeNode_::Value(ref pv) => pv.clone(),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1362
        _ => panic!("Expected node with value"),
1363
1364
1365
1366
1367
1368
    }
}

pub fn match_node_int_imm(op: &TreeNode) -> bool {
    match op.v {
        TreeNode_::Value(ref pv) => match_value_int_imm(pv),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1369
        _ => false,
1370
1371
1372
    }
}

1373
1374
1375
1376
// The only valid ref immediate is a null ref
pub fn match_node_ref_imm(op: &TreeNode) -> bool {
    match op.v {
        TreeNode_::Value(ref pv) => match_value_ref_imm(pv),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1377
        _ => false,
1378
1379
1380
    }
}

1381
1382
1383
pub fn match_node_imm(op: &TreeNode) -> bool {
    match op.v {
        TreeNode_::Value(ref pv) => match_value_imm(pv),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1384
        _ => false,
1385
1386
1387
1388
1389
1390
    }
}

pub fn node_imm_to_u64(op: &TreeNode) -> u64 {
    match op.v {
        TreeNode_::Value(ref pv) => value_imm_to_u64(pv),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1391
        _ => panic!("expected imm"),
1392
1393
1394
1395
1396
    }
}
pub fn node_imm_to_i64(op: &TreeNode, signed: bool) -> u64 {
    match op.v {
        TreeNode_::Value(ref pv) => value_imm_to_i64(pv, signed),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1397
        _ => panic!("expected imm"),
1398
1399
1400
1401
1402
    }
}
pub fn node_imm_to_s64(op: &TreeNode) -> i64 {
    match op.v {
        TreeNode_::Value(ref pv) => value_imm_to_s64(pv),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1403
        _ => panic!("expected imm"),
1404
1405
1406
1407
1408
1409
    }
}

pub fn node_imm_to_f64(op: &TreeNode) -> f64 {
    match op.v {
        TreeNode_::Value(ref pv) => value_imm_to_f64(pv),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1410
        _ => panic!("expected imm"),
1411
1412
1413
1414
1415
1416
    }
}

pub fn node_imm_to_f32(op: &TreeNode) -> f32 {
    match op.v {
        TreeNode_::Value(ref pv) => value_imm_to_f32(pv),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1417
        _ => panic!("expected imm"),
1418
1419
1420
1421
1422
    }
}

pub fn node_imm_to_value(op: &TreeNode) -> P<Value> {
    match op.v {
1423
        TreeNode_::Value(ref pv) => pv.clone(),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1424
        _ => panic!("expected imm"),
1425
1426
1427
1428
1429
    }
}

pub fn value_imm_to_f32(op: &P<Value>) -> f32 {
    match op.v {
1430
        Value_::Constant(Constant::Float(val)) => val as f32,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1431
        _ => panic!("expected imm float"),
1432
1433
1434
1435
1436
    }
}

pub fn value_imm_to_f64(op: &P<Value>) -> f64 {
    match op.v {
1437
        Value_::Constant(Constant::Double(val)) => val as f64,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1438
        _ => panic!("expected imm double"),
1439
1440
1441
1442
1443
    }
}

pub fn value_imm_to_u64(op: &P<Value>) -> u64 {
    match op.v {
1444
1445
1446
        Value_::Constant(Constant::Int(val)) => {
            get_unsigned_value(val as u64, op.ty.get_int_length().unwrap())
        }
1447
        Value_::Constant(Constant::NullRef) => 0,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1448
        _ => panic!("expected imm int"),
1449
1450
1451
1452
1453
    }
}

pub fn value_imm_to_i64(op: &P<Value>, signed: bool) -> u64 {
    match op.v {
1454
        Value_::Constant(Constant::Int(val)) => {
1455
1456
1457
1458
            if signed {
                get_signed_value(val as u64, op.ty.get_int_length().unwrap()) as u64
            } else {
                get_unsigned_value(val as u64, op.ty.get_int_length().unwrap())
1459
1460
            }
        }
1461
        Value_::Constant(Constant::NullRef) => 0,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1462
        _ => panic!("expected imm int"),
1463
1464
1465
1466
1467
    }
}

pub fn value_imm_to_s64(op: &P<Value>) -> i64 {
    match op.v {
1468
1469
1470
        Value_::Constant(Constant::Int(val)) => {
            get_signed_value(val as u64, op.ty.get_int_length().unwrap())
        }
1471
        Value_::Constant(Constant::NullRef) => 0,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1472
        _ => panic!("expected imm int"),
1473
1474
1475
1476
1477
1478
1479
    }
}

pub fn make_value_int_const(val: u64, vm: &VM) -> P<Value> {
    P(Value {
        hdr: MuEntityHeader::unnamed(vm.next_id()),
        ty: UINT64_TYPE.clone(),
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1480
        v: Value_::Constant(Constant::Int(val)),
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
    })
}

// Replaces the zero register with a temporary whose value is zero (or returns the orignal register)
/* TODO use this function for the following arguments:

We can probabbly allow the zero register to be the second argument to an _ext function (as the assembler will simply use the shifted-register encoding, which allows it)
add[,s1] // tirival
add_ext[d, s1]  // trivial
add_imm[d, s1] // trivial

adds[,s1 // not trivial (sets flags)
adds_ext[,s1]   // not trivial (sets flags)
adds_imm[, s2] // not trivial (sets flags)

sub_ext[d, s1]  // trivial
sub_imm[d, s1] // trivial

subs_ext[,s1]   // not trivial (sets flags)
subs_imm[, s2] // not trivial (sets flags)

and_imm[d] // trivial
eor_imm[d] // trivial
orr_imm[d] // trivial

cmn_ext[s1] // not trivial (sets flags)
cmn_imm[s1] // not trivial (sets flags)

cmp_ext[s1] // not trivial (sets flags)
cmp_imm[s1] // not trivial (sets flags)

(they are all (or did I miss some??) places that the SP can be used, which takes up the encoding of the ZR
I believe the Zero register can be used in all other places that an integer register is expected
(BUT AM NOT CERTAIN)
*/

/*
Just insert this immediatly before each emit_XX where XX is one the above instructions,
and arg is the name of the argument that can't be the zero register (do so for each such argument)
let arg = replace_zero_register(backend, &arg, f_context, vm);
*/

1523
1524
1525
1526
pub fn replace_zero_register(
    backend: &mut CodeGenerator,
    val: &P<Value>,
    f_context: &mut FunctionContext,
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1527
    vm: &VM,
1528
) -> P<Value> {
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
    if is_zero_register(&val) {
        let temp = make_temporary(f_context, val.ty.clone(), vm);