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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
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
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
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
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
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
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
#![allow(clippy::too_many_arguments)]

use crate::dr;
use crate::spirv;

use super::Error;
use std::result;

type BuildResult<T> = result::Result<T, Error>;

/// The data representation builder.
///
/// Constructs a [`Module`](struct.Module.html) by aggregating results from
/// method calls for various instructions.
///
/// This builder is designed to be low level; its build methods' signatures
/// basically reflects the layout of the corresponding SPIR-V instructions
/// faithfully.
///
/// If a SPIR-V instruction generates a result id and the result id can be
/// forward referenced, the build method will take an optional `result_id`
/// parameter. Filling it with `Some(val)` will instruct the builder to use
/// the given `val` as the result id. For other cases, an unused result id
/// will be automatically assigned from the builder.
///
/// So for instructions forward referencing an id, to avoid id collision,
/// you can either
///
/// * first append the target instruction generating that id and then append the
///   forward referencing instruction; or
/// * use the `id()` method to get an unused id from the builder, use it in the
///   forward referencing instruction, and then later fill the optional
///   `result_id` parameter of the target instruction with the same id.
///
/// Instructions belonging to the module (e.g., `OpDecorate`) can be appended
/// at any time, no matter that a block is currently under construction
/// or not. Intructions that can appear both in the module and block
/// (e.g., `OpVariable`) will be inserted to the current block under
/// construction first, if any.
///
/// # Errors
///
/// Methods in the builder implement little sanity check; only appending
/// instructions that violates the module structure is guarded. So methods
/// possibly returning errors are basically those related to function and
/// block construction (e.g., `OpFunction` and `OpLabel`).
///
/// Errors returned are enumerants related to function structure from the
/// [`Error`](enum.Error.html) enum.
///
/// # Examples
///
/// ```
/// use rspirv::binary::Disassemble;
///
/// fn main() {
///     let mut b = rspirv::dr::Builder::new();
///     b.set_version(1, 0);
///     b.memory_model(spirv::AddressingModel::Logical, spirv::MemoryModel::Simple);
///     let void = b.type_void();
///     let voidf = b.type_function(void, vec![void]);
///     b.begin_function(void,
///                      None,
///                      (spirv::FunctionControl::DONT_INLINE |
///                       spirv::FunctionControl::CONST),
///                      voidf)
///      .unwrap();
///     b.begin_block(None).unwrap();
///     b.ret().unwrap();
///     b.end_function().unwrap();
///
///     assert_eq!(b.module().disassemble(),
///                "; SPIR-V\n\
///                 ; Version: 1.0\n\
///                 ; Generator: rspirv\n\
///                 ; Bound: 5\n\
///                 OpMemoryModel Logical Simple\n\
///                 %1 = OpTypeVoid\n\
///                 %2 = OpTypeFunction %1 %1\n\
///                 %3 = OpFunction  %1  DontInline|Const %2\n\
///                 %4 = OpLabel\n\
///                 OpReturn\n\
///                 OpFunctionEnd");
/// }
/// ```
#[derive(Default)]
pub struct Builder {
    module: dr::Module,
    next_id: u32,
    selected_function: Option<usize>,
    selected_block: Option<usize>,
}

pub enum InsertPoint {
    Begin,
    End,
    FromBegin(usize),
    FromEnd(usize),
}

impl Builder {
    /// Creates a new empty builder.
    pub fn new() -> Builder {
        Builder {
            module: dr::Module::new(),
            next_id: 1,
            selected_function: None,
            selected_block: None,
        }
    }

    /// Create a new builder from an existing module
    pub fn new_from_module(module: dr::Module) -> Builder {
        let next_id = module
            .header
            .as_ref()
            .map(|h| h.bound)
            .expect("Expecting ModuleHeader with valid bound");

        Builder {
            module,
            next_id,
            selected_function: None,
            selected_block: None,
        }
    }

    pub fn insert_into_block(
        &mut self,
        insert_point: InsertPoint,
        inst: dr::Instruction,
    ) -> BuildResult<()> {
        let (selected_function, selected_block) =
            match (self.selected_function, self.selected_block) {
                (Some(f), Some(b)) => (f, b),
                _ => return Err(Error::DetachedInstruction(Some(inst))),
            };

        let block = &mut self.module.functions[selected_function].blocks[selected_block];

        match insert_point {
            InsertPoint::End => block.instructions.push(inst),
            InsertPoint::Begin => block.instructions.insert(0, inst),
            InsertPoint::FromEnd(offset) => {
                let end = block.instructions.len();
                block.instructions.insert(end - offset, inst)
            }
            InsertPoint::FromBegin(offset) => block.instructions.insert(offset, inst),
        }

        Ok(())
    }

    pub fn insert_types_global_values(&mut self, insert_point: InsertPoint, inst: dr::Instruction) {
        match insert_point {
            InsertPoint::End => self.module.types_global_values.push(inst),
            InsertPoint::Begin => self.module.types_global_values.insert(0, inst),
            InsertPoint::FromEnd(offset) => {
                let end = self.module.types_global_values.len();
                self.module.types_global_values.insert(end - offset, inst)
            }
            InsertPoint::FromBegin(offset) => self.module.types_global_values.insert(offset, inst),
        }
    }

    pub fn pop_instruction(&mut self) -> BuildResult<dr::Instruction> {
        let (selected_function, selected_block) =
            match (self.selected_function, self.selected_block) {
                (Some(f), Some(b)) => (f, b),
                _ => return Err(Error::DetachedInstruction(None)),
            };

        let block = &mut self.module.functions[selected_function].blocks[selected_block];

        block.instructions.pop().ok_or(Error::EmptyInstructionList)
    }

    /// Sets the SPIR-V version to the given major.minor version.
    ///
    /// If this method is not called, the generated SPIR-V will be set as the newest version
    /// supported.
    pub fn set_version(&mut self, major: u8, minor: u8) {
        if self.module.header.is_none() {
            // The bound will be fixed up when module() is called.
            self.module.header = Some(dr::ModuleHeader::new(0));
        }
        self.module
            .header
            .as_mut()
            .unwrap()
            .set_version(major, minor);
    }

    /// Get the SPIR-V version as a (major, minor) tuple
    pub fn version(&self) -> Option<(u8, u8)> {
        self.module.header.as_ref().map(|h| h.version())
    }

    /// Returns the `Module` under construction.
    pub fn module(self) -> dr::Module {
        let mut module = self.module;

        match &mut module.header {
            Some(header) => header.bound = self.next_id,
            None => module.header = Some(dr::ModuleHeader::new(self.next_id)),
        }

        module
    }

    /// Returns the `Module` under construction as a reference. Note that header.bound will be inaccurate.
    pub fn module_ref(&self) -> &dr::Module {
        &self.module
    }

    /// Returns the `Module` under construction as a mutable reference. Note that header.bound will be inaccurate.
    pub fn module_mut(&mut self) -> &mut dr::Module {
        &mut self.module
    }

    pub fn selected_function(&self) -> Option<usize> {
        self.selected_function
    }

    pub fn selected_block(&self) -> Option<usize> {
        self.selected_block
    }

    /// Returns the next unused id.
    pub fn id(&mut self) -> spirv::Word {
        let id = self.next_id;
        self.next_id += 1;
        id
    }

    /// Insert a OpType instruction, deduplicate it if needed and either return the existing ID
    /// or a new unused ID if we can't find find the instruction already. Useful to uphold
    /// the SPIR-V rule that non-aggregate types can't be duplicates.
    pub fn dedup_insert_type(&mut self, inst: &dr::Instruction) -> Option<spirv::Word> {
        for ty in &self.module.types_global_values {
            if ty.is_type_identical(&inst) {
                if let Some(id) = ty.result_id {
                    return Some(id);
                }
            }
        }

        None
    }

    /// Find all blocks that end in OpReturn
    pub fn find_return_block_indices(&self) -> Vec<usize> {
        let mut result = vec![];

        if let Some(sel_fn) = self.selected_function {
            let func = &self.module.functions[sel_fn];

            for (idx, blk) in func.blocks.iter().enumerate() {
                // OpReturn must be the last instruction in a block
                let last_instr = blk.instructions.last().unwrap();

                match last_instr.class.opcode {
                    spirv::Op::Return | spirv::Op::ReturnValue => {
                        result.push(idx);
                    }
                    _ => {}
                }
            }
        }

        result
    }

    /// Select a function to insert instructions into by name
    pub fn select_function_by_name(&mut self, name: &str) -> BuildResult<()> {
        for dbg in &self.module.debug_names {
            if dbg.class.opcode == spirv::Op::Name {
                if let dr::Operand::IdRef(target_id) = dbg.operands[0] {
                    if let dr::Operand::LiteralString(found_name) = &dbg.operands[1] {
                        if found_name == name {
                            for (idx, func) in self.module.functions.iter().enumerate() {
                                if func.def.as_ref().unwrap().result_id.unwrap() == target_id {
                                    return self.select_function(Some(idx));
                                }
                            }
                        }
                    }
                }
            }
        }

        Err(Error::FunctionNotFound)
    }

    /// Select a function to insert instructions into by index (indexed into self.module.functions), or unselect if None
    pub fn select_function(&mut self, idx: Option<usize>) -> BuildResult<()> {
        match idx {
            Some(idx) => {
                if idx < self.module.functions.len() {
                    self.selected_function = Some(idx);
                    Ok(())
                } else {
                    Err(Error::FunctionNotFound)
                }
            }
            None => {
                // make sure to unselect block too
                self.selected_block = None;
                self.selected_function = None;
                Ok(())
            }
        }
    }

    /// Select a basic block (by index) to insert instructions into, indexed off of self.modules.functions[self.selected_function].blocks[idx], or unselect if None
    pub fn select_block(&mut self, idx: Option<usize>) -> BuildResult<()> {
        match idx {
            Some(idx) => {
                let selected_function = match self.selected_function {
                    Some(f) => f,
                    None => return Err(Error::DetachedBlock),
                };
                if idx < self.module.functions[selected_function].blocks.len() {
                    self.selected_block = Some(idx);
                    Ok(())
                } else {
                    Err(Error::BlockNotFound)
                }
            }
            None => {
                self.selected_block = None;
                Ok(())
            }
        }
    }

    /// Begins building of a new function.
    ///
    /// If `function_id` is `Some(val)`, then `val` will be used as the result
    /// id of the function under construction; otherwise, an unused result id
    /// will be automatically assigned.
    pub fn begin_function(
        &mut self,
        return_type: spirv::Word,
        function_id: Option<spirv::Word>,
        control: spirv::FunctionControl,
        function_type: spirv::Word,
    ) -> BuildResult<spirv::Word> {
        if self.selected_function.is_some() {
            return Err(Error::NestedFunction);
        }

        let id = match function_id {
            Some(v) => v,
            None => self.id(),
        };

        let mut f = dr::Function::new();
        f.def = Some(dr::Instruction::new(
            spirv::Op::Function,
            Some(return_type),
            Some(id),
            vec![
                dr::Operand::FunctionControl(control),
                dr::Operand::IdRef(function_type),
            ],
        ));
        self.module.functions.push(f);
        self.selected_function = Some(self.module.functions.len() - 1);
        Ok(id)
    }

    /// Ends building of the current function.
    pub fn end_function(&mut self) -> BuildResult<()> {
        let selected_function = match self.selected_function {
            Some(f) => f,
            None => return Err(Error::MismatchedFunctionEnd),
        };

        self.module.functions[selected_function].end = Some(dr::Instruction::new(
            spirv::Op::FunctionEnd,
            None,
            None,
            vec![],
        ));
        self.selected_function = None;
        Ok(())
    }

    /// Declares a formal parameter for the current function.
    pub fn function_parameter(&mut self, result_type: spirv::Word) -> BuildResult<spirv::Word> {
        let selected_function = match self.selected_function {
            Some(f) => f,
            None => return Err(Error::DetachedFunctionParameter),
        };
        let id = self.id();
        let inst = dr::Instruction::new(
            spirv::Op::FunctionParameter,
            Some(result_type),
            Some(id),
            vec![],
        );
        self.module.functions[selected_function]
            .parameters
            .push(inst);
        Ok(id)
    }

    /// Begins building of a new block.
    ///
    /// If `label_id` is `Some(val)`, then `val` will be used as the result
    /// id for the `OpLabel` instruction begining this block; otherwise,
    /// a unused result id will be automatically assigned.
    pub fn begin_block(&mut self, label_id: Option<spirv::Word>) -> BuildResult<spirv::Word> {
        let selected_function = match self.selected_function {
            Some(f) => f,
            None => return Err(Error::DetachedBlock),
        };
        if self.selected_block.is_some() {
            return Err(Error::NestedBlock);
        }

        let id = match label_id {
            Some(v) => v,
            None => self.id(),
        };

        let mut bb = dr::Block::new();
        bb.label = Some(dr::Instruction::new(
            spirv::Op::Label,
            None,
            Some(id),
            vec![],
        ));

        let blocks = &mut self.module.functions[selected_function].blocks;
        blocks.push(bb);
        self.selected_block = Some(blocks.len() - 1);
        Ok(id)
    }

    /// Begins building of a new block.
    ///
    /// Counter to `begin_block` that always generates a new OpLabel at the beginning of a block - in some cases
    /// this is undesirable (such as when constructing a branch).
    pub fn begin_block_no_label(
        &mut self,
        label_id: Option<spirv::Word>,
    ) -> BuildResult<spirv::Word> {
        let selected_function = match self.selected_function {
            Some(f) => f,
            None => return Err(Error::DetachedBlock),
        };
        if self.selected_block.is_some() {
            return Err(Error::NestedBlock);
        }

        let id = match label_id {
            Some(v) => v,
            None => self.id(),
        };

        let bb = dr::Block::new();
        let blocks = &mut self.module.functions[selected_function].blocks;
        blocks.push(bb);
        self.selected_block = Some(blocks.len() - 1);
        Ok(id)
    }

    fn end_block(&mut self, inst: dr::Instruction) -> BuildResult<()> {
        self.insert_end_block(InsertPoint::End, inst)
    }

    fn insert_end_block(
        &mut self,
        insert_point: InsertPoint,
        inst: dr::Instruction,
    ) -> BuildResult<()> {
        if self.selected_block.is_some() {
            self.insert_into_block(insert_point, inst)?;
            self.selected_block = None;
            return Ok(());
        }

        Err(Error::MismatchedTerminator)
    }

    /// Appends an OpCapability instruction.
    pub fn capability(&mut self, capability: spirv::Capability) {
        let inst = dr::Instruction::new(
            spirv::Op::Capability,
            None,
            None,
            vec![dr::Operand::Capability(capability)],
        );
        self.module.capabilities.push(inst);
    }

    /// Appends an OpExtension instruction.
    pub fn extension(&mut self, extension: impl Into<String>) {
        let inst = dr::Instruction::new(
            spirv::Op::Extension,
            None,
            None,
            vec![dr::Operand::LiteralString(extension.into())],
        );
        self.module.extensions.push(inst);
    }

    /// Appends an OpExtInstImport instruction and returns the result id.
    pub fn ext_inst_import(&mut self, extended_inst_set: impl Into<String>) -> spirv::Word {
        let id = self.id();
        let inst = dr::Instruction::new(
            spirv::Op::ExtInstImport,
            None,
            Some(id),
            vec![dr::Operand::LiteralString(extended_inst_set.into())],
        );
        self.module.ext_inst_imports.push(inst);
        id
    }

    /// Appends an OpMemoryModel instruction.
    pub fn memory_model(
        &mut self,
        addressing_model: spirv::AddressingModel,
        memory_model: spirv::MemoryModel,
    ) {
        let inst = dr::Instruction::new(
            spirv::Op::MemoryModel,
            None,
            None,
            vec![
                dr::Operand::AddressingModel(addressing_model),
                dr::Operand::MemoryModel(memory_model),
            ],
        );
        self.module.memory_model = Some(inst);
    }

    /// Appends an OpEntryPoint instruction.
    pub fn entry_point(
        &mut self,
        execution_model: spirv::ExecutionModel,
        entry_point: spirv::Word,
        name: impl Into<String>,
        interface: impl AsRef<[spirv::Word]>,
    ) {
        let mut operands = vec![
            dr::Operand::ExecutionModel(execution_model),
            dr::Operand::IdRef(entry_point),
            dr::Operand::LiteralString(name.into()),
        ];
        for v in interface.as_ref() {
            operands.push(dr::Operand::IdRef(*v));
        }

        let inst = dr::Instruction::new(spirv::Op::EntryPoint, None, None, operands);
        self.module.entry_points.push(inst);
    }

    /// Appends an OpExecutionMode instruction.
    pub fn execution_mode(
        &mut self,
        entry_point: spirv::Word,
        execution_mode: spirv::ExecutionMode,
        params: impl AsRef<[u32]>,
    ) {
        let mut operands = vec![
            dr::Operand::IdRef(entry_point),
            dr::Operand::ExecutionMode(execution_mode),
        ];
        for v in params.as_ref() {
            operands.push(dr::Operand::LiteralInt32(*v));
        }

        let inst = dr::Instruction::new(spirv::Op::ExecutionMode, None, None, operands);
        self.module.execution_modes.push(inst);
    }

    /// Appends an OpExecutionModeId instruction.
    pub fn execution_mode_id(
        &mut self,
        entry_point: spirv::Word,
        execution_mode: spirv::ExecutionMode,
        params: impl AsRef<[u32]>,
    ) {
        let mut operands = vec![
            dr::Operand::IdRef(entry_point),
            dr::Operand::ExecutionMode(execution_mode),
        ];
        for v in params.as_ref() {
            operands.push(dr::Operand::LiteralInt32(*v));
        }

        let inst = dr::Instruction::new(spirv::Op::ExecutionModeId, None, None, operands);
        self.module.execution_modes.push(inst);
    }

    pub fn ext_inst(
        &mut self,
        result_type: spirv::Word,
        result_id: Option<spirv::Word>,
        extension_set: spirv::Word,
        instruction: spirv::Word,
        operands: impl IntoIterator<Item = dr::Operand>,
    ) -> BuildResult<spirv::Word> {
        let mut ops = vec![
            dr::Operand::IdRef(extension_set),
            dr::Operand::LiteralExtInstInteger(instruction),
        ];
        ops.extend(operands);
        let _id = result_id.unwrap_or_else(|| self.id());
        let inst = dr::Instruction::new(spirv::Op::ExtInst, Some(result_type), Some(_id), ops);
        self.insert_into_block(InsertPoint::End, inst)?;
        Ok(_id)
    }

    /// Appends an `OpLine` instruction.
    ///
    /// If a block is currently selected, the `OpLine` is inserted into that block. If no block is
    /// currently selected, the `OpLine` is inserted into `types_global_values`.
    pub fn line(&mut self, file: spirv::Word, line: u32, column: u32) {
        let inst = dr::Instruction::new(
            spirv::Op::Line,
            None,
            None,
            vec![
                dr::Operand::IdRef(file),
                dr::Operand::LiteralInt32(line),
                dr::Operand::LiteralInt32(column),
            ],
        );
        if self.selected_block.is_some() {
            self.insert_into_block(InsertPoint::End, inst)
                .expect("Internal error: insert_into_block failed when selected_block was Some");
        } else {
            // types_global_values is the only valid section (other than functions) that
            // OpLine/OpNoLine can be placed in, so put it there.
            self.module.types_global_values.push(inst);
        }
    }

    /// Appends an `OpNoLine` instruction.
    ///
    /// If a block is currently selected, the `OpNoLine` is inserted into that block. If no block
    /// is currently selected, the `OpNoLine` is inserted into `types_global_values`.
    pub fn no_line(&mut self) {
        let inst = dr::Instruction::new(spirv::Op::NoLine, None, None, vec![]);
        if self.selected_block.is_some() {
            self.insert_into_block(InsertPoint::End, inst)
                .expect("Internal error: insert_into_block failed when selected_block was Some");
        } else {
            // types_global_values is the only valid section (other than functions) that
            // OpLine/OpNoLine can be placed in, so put it there.
            self.module.types_global_values.push(inst);
        }
    }
}

include!("autogen_type.rs");
include!("autogen_constant.rs");
include!("autogen_annotation.rs");
include!("autogen_terminator.rs");
include!("autogen_debug.rs");

impl Builder {
    /// Appends an OpDecorationGroup instruction and returns the result id.
    pub fn decoration_group(&mut self) -> spirv::Word {
        let id = self.id();
        self.module.annotations.push(dr::Instruction::new(
            spirv::Op::DecorationGroup,
            None,
            Some(id),
            vec![],
        ));
        id
    }

    pub fn string(&mut self, s: impl Into<String>) -> spirv::Word {
        let id = self.id();
        self.module.debug_string_source.push(dr::Instruction::new(
            spirv::Op::String,
            None,
            Some(id),
            vec![dr::Operand::LiteralString(s.into())],
        ));
        id
    }
}

impl Builder {
    /// Appends an OpTypeForwardPointer instruction.
    pub fn type_forward_pointer(
        &mut self,
        pointer_type: spirv::Word,
        storage_class: spirv::StorageClass,
    ) {
        self.module.types_global_values.push(dr::Instruction::new(
            spirv::Op::TypeForwardPointer,
            None,
            None,
            vec![
                dr::Operand::IdRef(pointer_type),
                dr::Operand::StorageClass(storage_class),
            ],
        ));
    }

    /// Appends an OpTypePointer instruction and returns the result id, or return the existing id if the instruction was already present.
    pub fn type_pointer(
        &mut self,
        result_id: Option<spirv::Word>,
        storage_class: spirv::StorageClass,
        pointee_type: spirv::Word,
    ) -> spirv::Word {
        let mut inst = dr::Instruction::new(
            spirv::Op::TypePointer,
            None,
            result_id,
            vec![
                dr::Operand::StorageClass(storage_class),
                dr::Operand::IdRef(pointee_type),
            ],
        );
        if let Some(result_id) = result_id {
            // An explicit ID was provided, emit it no matter what.
            self.module.types_global_values.push(inst);
            result_id
        } else if let Some(id) = self.dedup_insert_type(&inst) {
            // No ID was provided, and the type has already been declared.
            id
        } else {
            // No ID was provided, it didn't already exist, so generate a new ID and emit it.
            let new_id = self.id();
            inst.result_id = Some(new_id);
            self.module.types_global_values.push(inst);
            new_id
        }
    }

    /// Appends an OpTypeOpaque instruction and returns the result id.
    pub fn type_opaque(&mut self, type_name: impl Into<String>) -> spirv::Word {
        let id = self.id();
        self.module.types_global_values.push(dr::Instruction::new(
            spirv::Op::TypeOpaque,
            None,
            Some(id),
            vec![dr::Operand::LiteralString(type_name.into())],
        ));
        id
    }

    /// Appends an OpConstant instruction with the given 32-bit float `value`.
    /// or the module if no block is under construction.
    pub fn constant_f32(&mut self, result_type: spirv::Word, value: f32) -> spirv::Word {
        let id = self.id();
        let inst = dr::Instruction::new(
            spirv::Op::Constant,
            Some(result_type),
            Some(id),
            vec![dr::Operand::LiteralFloat32(value)],
        );
        self.module.types_global_values.push(inst);
        id
    }

    /// Appends an OpConstant instruction with the given 64-bit float `value`.
    pub fn constant_f64(&mut self, result_type: spirv::Word, value: f64) -> spirv::Word {
        let id = self.id();
        let inst = dr::Instruction::new(
            spirv::Op::Constant,
            Some(result_type),
            Some(id),
            vec![dr::Operand::LiteralFloat64(value)],
        );
        self.module.types_global_values.push(inst);
        id
    }

    /// Appends an OpConstant instruction with the given 32-bit integer `value`.
    /// or the module if no block is under construction.
    pub fn constant_u32(&mut self, result_type: spirv::Word, value: u32) -> spirv::Word {
        let id = self.id();
        let inst = dr::Instruction::new(
            spirv::Op::Constant,
            Some(result_type),
            Some(id),
            vec![dr::Operand::LiteralInt32(value)],
        );
        self.module.types_global_values.push(inst);
        id
    }

    /// Appends an OpConstant instruction with the given 64-bit integer `value`.
    pub fn constant_u64(&mut self, result_type: spirv::Word, value: u64) -> spirv::Word {
        let id = self.id();
        let inst = dr::Instruction::new(
            spirv::Op::Constant,
            Some(result_type),
            Some(id),
            vec![dr::Operand::LiteralInt64(value)],
        );
        self.module.types_global_values.push(inst);
        id
    }

    /// Appends an OpSpecConstant instruction with the given 32-bit float `value`.
    /// or the module if no block is under construction.
    pub fn spec_constant_f32(&mut self, result_type: spirv::Word, value: f32) -> spirv::Word {
        let id = self.id();
        let inst = dr::Instruction::new(
            spirv::Op::SpecConstant,
            Some(result_type),
            Some(id),
            vec![dr::Operand::LiteralFloat32(value)],
        );
        self.module.types_global_values.push(inst);
        id
    }

    /// Appends an OpSpecConstant instruction with the given 64-bit float `value`.
    pub fn spec_constant_f64(&mut self, result_type: spirv::Word, value: f64) -> spirv::Word {
        let id = self.id();
        let inst = dr::Instruction::new(
            spirv::Op::SpecConstant,
            Some(result_type),
            Some(id),
            vec![dr::Operand::LiteralFloat64(value)],
        );
        self.module.types_global_values.push(inst);
        id
    }

    /// Appends an OpSpecConstant instruction with the given 32-bit integer `value`.
    /// or the module if no block is under construction.
    pub fn spec_constant_u32(&mut self, result_type: spirv::Word, value: u32) -> spirv::Word {
        let id = self.id();
        let inst = dr::Instruction::new(
            spirv::Op::SpecConstant,
            Some(result_type),
            Some(id),
            vec![dr::Operand::LiteralInt32(value)],
        );
        self.module.types_global_values.push(inst);
        id
    }

    /// Appends an OpSpecConstant instruction with the given 32-bit integer `value`.
    pub fn spec_constant_u64(&mut self, result_type: spirv::Word, value: u64) -> spirv::Word {
        let id = self.id();
        let inst = dr::Instruction::new(
            spirv::Op::SpecConstant,
            Some(result_type),
            Some(id),
            vec![dr::Operand::LiteralInt64(value)],
        );
        self.module.types_global_values.push(inst);
        id
    }

    /// Appends an OpVariable instruction to either the current block
    /// or the module if no block is under construction.
    pub fn variable(
        &mut self,
        result_type: spirv::Word,
        result_id: Option<spirv::Word>,
        storage_class: spirv::StorageClass,
        initializer: Option<spirv::Word>,
    ) -> spirv::Word {
        let id = match result_id {
            Some(v) => v,
            None => self.id(),
        };
        let mut operands = vec![dr::Operand::StorageClass(storage_class)];
        if let Some(val) = initializer {
            operands.push(dr::Operand::IdRef(val));
        }
        let inst = dr::Instruction::new(spirv::Op::Variable, Some(result_type), Some(id), operands);

        match (self.selected_function, self.selected_block) {
            (Some(selected_function), Some(selected_block)) => {
                self.module.functions[selected_function].blocks[selected_block]
                    .instructions
                    .push(inst)
            }
            _ => self.module.types_global_values.push(inst),
        }
        id
    }

    /// Appends an OpUndef instruction to either the current block
    /// or the module if no block is under construction.
    pub fn undef(
        &mut self,
        result_type: spirv::Word,
        result_id: Option<spirv::Word>,
    ) -> spirv::Word {
        let id = match result_id {
            Some(v) => v,
            None => self.id(),
        };
        let inst = dr::Instruction::new(spirv::Op::Undef, Some(result_type), Some(id), vec![]);

        match (self.selected_function, self.selected_block) {
            (Some(selected_function), Some(selected_block)) => {
                self.module.functions[selected_function].blocks[selected_block]
                    .instructions
                    .push(inst)
            }
            _ => self.module.types_global_values.push(inst),
        }
        id
    }
}

include!("autogen_norm_insts.rs");

#[cfg(test)]
mod tests {
    use crate::dr;
    use crate::spirv;

    use super::Builder;
    use std::f32;

    use crate::binary::Disassemble;

    fn has_only_one_global_inst(module: &dr::Module) -> bool {
        if !module.functions.is_empty() {
            return false;
        }
        (module.capabilities.len()
            + module.extensions.len()
            + module.ext_inst_imports.len()
            + module.entry_points.len()
            + module.types_global_values.len()
            + module.execution_modes.len()
            + module.debug_string_source.len()
            + module.debug_names.len()
            + module.debug_module_processed.len()
            + module.annotations.len())
            + (if module.memory_model.is_some() { 1 } else { 0 })
            == 1
    }

    #[test]
    fn test_spirv_version() {
        let mut b = Builder::new();
        b.set_version(1, 2);
        let m = b.module();
        let header = &m.header;
        assert!(header.is_some());
        assert_eq!((1, 2), header.as_ref().unwrap().version());
    }

    #[test]
    fn test_memory_model() {
        let mut b = Builder::new();
        b.memory_model(spirv::AddressingModel::Logical, spirv::MemoryModel::Simple);
        let m = b.module();
        assert!(m.memory_model.is_some());
        let inst = m.memory_model.as_ref().unwrap();
        assert!(has_only_one_global_inst(&m));
        assert_eq!("MemoryModel", inst.class.opname);
        assert_eq!(2, inst.operands.len());
        assert_eq!(
            dr::Operand::from(spirv::AddressingModel::Logical),
            inst.operands[0]
        );
        assert_eq!(
            dr::Operand::from(spirv::MemoryModel::Simple),
            inst.operands[1]
        );
    }

    #[test]
    fn test_decoration_no_additional_params() {
        let mut b = Builder::new();
        b.member_decorate(1, 0, spirv::Decoration::RelaxedPrecision, vec![]);
        let m = b.module();
        assert!(has_only_one_global_inst(&m));
        let inst = m.annotations.last().unwrap();
        assert_eq!("MemberDecorate", inst.class.opname);
        assert_eq!(3, inst.operands.len());
        assert_eq!(dr::Operand::IdRef(1), inst.operands[0]);
        assert_eq!(dr::Operand::from(0u32), inst.operands[1]);
        assert_eq!(
            dr::Operand::from(spirv::Decoration::RelaxedPrecision),
            inst.operands[2]
        );
    }

    #[test]
    fn test_decoration_with_additional_params() {
        let mut b = Builder::new();
        b.decorate(
            1,
            spirv::Decoration::LinkageAttributes,
            vec![
                dr::Operand::from("name"),
                dr::Operand::from(spirv::LinkageType::Export),
            ],
        );
        let m = b.module();
        assert!(has_only_one_global_inst(&m));
        let inst = m.annotations.last().unwrap();
        assert_eq!("Decorate", inst.class.opname);
        assert_eq!(4, inst.operands.len());
        assert_eq!(dr::Operand::IdRef(1), inst.operands[0]);
        assert_eq!(
            dr::Operand::from(spirv::Decoration::LinkageAttributes),
            inst.operands[1]
        );
        assert_eq!(dr::Operand::from("name"), inst.operands[2]);
        assert_eq!(
            dr::Operand::from(spirv::LinkageType::Export),
            inst.operands[3]
        );
    }

    #[test]
    fn test_constant_f32() {
        let mut b = Builder::new();
        let float = b.type_float(32);
        // Normal numbers
        b.constant_f32(float, 3.14);
        b.constant_f32(float, 2e-10);
        // Zero
        b.constant_f32(float, 0.);
        // Inf
        b.constant_f32(float, f32::NEG_INFINITY);
        // Subnormal numbers
        b.constant_f32(float, -1.0e-40_f32);
        // Nan
        b.constant_f32(float, f32::NAN);
        let m = b.module();
        assert_eq!(7, m.types_global_values.len());

        let inst = &m.types_global_values[1];
        assert_eq!(spirv::Op::Constant, inst.class.opcode);
        assert_eq!(Some(1), inst.result_type);
        assert_eq!(Some(2), inst.result_id);
        assert_eq!(dr::Operand::from(3.14f32), inst.operands[0]);

        let inst = &m.types_global_values[2];
        assert_eq!(spirv::Op::Constant, inst.class.opcode);
        assert_eq!(Some(1), inst.result_type);
        assert_eq!(Some(3), inst.result_id);
        assert_eq!(dr::Operand::from(2e-10_f32), inst.operands[0]);

        let inst = &m.types_global_values[3];
        assert_eq!(spirv::Op::Constant, inst.class.opcode);
        assert_eq!(Some(1), inst.result_type);
        assert_eq!(Some(4), inst.result_id);
        assert_eq!(dr::Operand::from(0.0f32), inst.operands[0]);

        let inst = &m.types_global_values[4];
        assert_eq!(spirv::Op::Constant, inst.class.opcode);
        assert_eq!(Some(1), inst.result_type);
        assert_eq!(Some(5), inst.result_id);
        assert_eq!(dr::Operand::from(f32::NEG_INFINITY), inst.operands[0]);

        let inst = &m.types_global_values[5];
        assert_eq!(spirv::Op::Constant, inst.class.opcode);
        assert_eq!(Some(1), inst.result_type);
        assert_eq!(Some(6), inst.result_id);
        assert_eq!(dr::Operand::from(-1.0e-40_f32), inst.operands[0]);

        let inst = &m.types_global_values[6];
        assert_eq!(spirv::Op::Constant, inst.class.opcode);
        assert_eq!(Some(1), inst.result_type);
        assert_eq!(Some(7), inst.result_id);
        // NaN != NaN
        match inst.operands[0] {
            dr::Operand::LiteralFloat32(f) => assert!(f.is_nan()),
            _ => assert!(false),
        }
    }

    #[test]
    fn test_spec_constant_f32() {
        let mut b = Builder::new();
        let float = b.type_float(32);
        // Normal numbers
        b.spec_constant_f32(float, 10.);
        // Zero
        b.spec_constant_f32(float, -0.);
        // Inf
        b.spec_constant_f32(float, f32::INFINITY);
        // Subnormal numbers
        b.spec_constant_f32(float, 1.0e-40_f32);
        // Nan
        b.spec_constant_f32(float, f32::NAN);
        let m = b.module();
        assert_eq!(6, m.types_global_values.len());

        let inst = &m.types_global_values[1];
        assert_eq!(spirv::Op::SpecConstant, inst.class.opcode);
        assert_eq!(Some(1), inst.result_type);
        assert_eq!(Some(2), inst.result_id);
        assert_eq!(dr::Operand::from(10.0f32), inst.operands[0]);

        let inst = &m.types_global_values[2];
        assert_eq!(spirv::Op::SpecConstant, inst.class.opcode);
        assert_eq!(Some(1), inst.result_type);
        assert_eq!(Some(3), inst.result_id);
        assert_eq!(dr::Operand::from(-0.0f32), inst.operands[0]);

        let inst = &m.types_global_values[3];
        assert_eq!(spirv::Op::SpecConstant, inst.class.opcode);
        assert_eq!(Some(1), inst.result_type);
        assert_eq!(Some(4), inst.result_id);
        assert_eq!(dr::Operand::from(f32::INFINITY), inst.operands[0]);

        let inst = &m.types_global_values[4];
        assert_eq!(spirv::Op::SpecConstant, inst.class.opcode);
        assert_eq!(Some(1), inst.result_type);
        assert_eq!(Some(5), inst.result_id);
        assert_eq!(dr::Operand::from(1.0e-40_f32), inst.operands[0]);

        let inst = &m.types_global_values[5];
        assert_eq!(spirv::Op::SpecConstant, inst.class.opcode);
        assert_eq!(Some(1), inst.result_type);
        assert_eq!(Some(6), inst.result_id);
        // NaN != NaN
        match inst.operands[0] {
            dr::Operand::LiteralFloat32(f) => assert!(f.is_nan()),
            _ => assert!(false),
        }
    }

    #[test]
    fn test_forward_ref_pointer_type() {
        let mut b = Builder::new();
        let float = b.type_float(32); // 1
                                      // Let builder generate
        let p1 = b.type_pointer(None, spirv::StorageClass::Input, float); // 2
                                                                          // We supply
        let pointee = b.id(); // 3
        b.type_forward_pointer(pointee, spirv::StorageClass::Output);
        let p2 = b.type_pointer(Some(pointee), spirv::StorageClass::Output, float);
        let m = b.module();
        assert_eq!(1, float);
        assert_eq!(2, p1);
        assert_eq!(pointee, p2); // Return the same id
        assert_eq!(4, m.types_global_values.len());

        let inst = &m.types_global_values[0];
        assert_eq!(spirv::Op::TypeFloat, inst.class.opcode);
        assert_eq!(None, inst.result_type);
        assert_eq!(Some(1), inst.result_id);
        assert_eq!(vec![dr::Operand::LiteralInt32(32)], inst.operands);

        let inst = &m.types_global_values[1];
        assert_eq!(spirv::Op::TypePointer, inst.class.opcode);
        assert_eq!(None, inst.result_type);
        assert_eq!(Some(2), inst.result_id);
        assert_eq!(
            vec![
                dr::Operand::from(spirv::StorageClass::Input),
                dr::Operand::IdRef(1),
            ],
            inst.operands
        );

        let inst = &m.types_global_values[2];
        assert_eq!(spirv::Op::TypeForwardPointer, inst.class.opcode);
        assert_eq!(None, inst.result_type);
        assert_eq!(None, inst.result_id);
        assert_eq!(
            vec![
                dr::Operand::IdRef(3),
                dr::Operand::from(spirv::StorageClass::Output),
            ],
            inst.operands
        );

        let inst = &m.types_global_values[3];
        assert_eq!(spirv::Op::TypePointer, inst.class.opcode);
        assert_eq!(None, inst.result_type);
        assert_eq!(Some(3), inst.result_id);
        assert_eq!(
            vec![
                dr::Operand::from(spirv::StorageClass::Output),
                dr::Operand::IdRef(1),
            ],
            inst.operands
        );
    }

    #[test]
    fn test_forward_ref_phi() {
        let mut b = Builder::new();

        let float = b.type_float(32);
        assert_eq!(1, float);
        let f32ff32 = b.type_function(float, vec![float]);
        assert_eq!(2, f32ff32);
        let c0 = b.constant_f32(float, 0.0f32);
        assert_eq!(3, c0);

        let fid = b
            .begin_function(float, None, spirv::FunctionControl::NONE, f32ff32)
            .unwrap();
        assert_eq!(4, fid);

        let epid = b.begin_block(None).unwrap(); // Entry block id
        assert_eq!(5, epid);
        let target1 = b.id();
        assert_eq!(6, target1);
        assert!(b.branch(target1).is_ok());

        let pbid = b.begin_block(Some(target1)).unwrap(); // Phi block id
        assert_eq!(target1, pbid);
        let target2 = b.id();
        assert_eq!(7, target2);
        let fr_add = b.id();
        assert_eq!(8, fr_add);
        // OpPhi can forward reference ids for both labels and results
        let phi = b
            .phi(
                float,
                None,
                // From above, from this, from below
                vec![(c0, epid), (fr_add, pbid), (c0, target2)],
            )
            .unwrap();
        assert_eq!(9, phi);
        let res_add = b.f_add(float, Some(fr_add), c0, c0).unwrap();
        assert_eq!(res_add, fr_add);
        assert!(b.branch(target2).is_ok());

        let exid = b.begin_block(Some(target2)).unwrap(); // Exit block id
        assert_eq!(exid, target2);
        assert!(b.ret_value(c0).is_ok());

        assert!(b.end_function().is_ok());

        let m = b.module();
        assert_eq!(1, m.functions.len());
        assert_eq!(
            m.functions.first().unwrap().disassemble(),
            "%4 = OpFunction  %1  None %2\n\
                    %5 = OpLabel\n\
                    OpBranch %6\n\
                    %6 = OpLabel\n\
                    %9 = OpPhi  %1  %3 %5 %8 %6 %3 %7\n\
                    %8 = OpFAdd  %1  %3 %3\n\
                    OpBranch %7\n\
                    %7 = OpLabel\n\
                    OpReturnValue %3\n\
                    OpFunctionEnd"
        );
    }

    #[test]
    fn test_build_variables() {
        let mut b = Builder::new();

        let void = b.type_void();
        assert_eq!(1, void);
        let float = b.type_float(32);
        assert_eq!(2, float);
        let ifp = b.type_pointer(None, spirv::StorageClass::Input, float);
        assert_eq!(3, ifp);
        let ffp = b.type_pointer(None, spirv::StorageClass::Function, float);
        assert_eq!(4, ffp);
        let voidfvoid = b.type_function(void, vec![void]);
        assert_eq!(5, voidfvoid);

        // Global variable
        let v1 = b.variable(ifp, None, spirv::StorageClass::Input, None);
        assert_eq!(6, v1);

        let f = b
            .begin_function(void, None, spirv::FunctionControl::NONE, voidfvoid)
            .unwrap();
        assert_eq!(7, f);
        let bb = b.begin_block(None).unwrap();
        assert_eq!(8, bb);
        // Local variable
        let v2 = b.variable(ffp, None, spirv::StorageClass::Function, None);
        assert_eq!(9, v2);
        assert!(b.ret().is_ok());
        assert!(b.end_function().is_ok());

        // Global variable again
        let v3 = b.variable(ifp, None, spirv::StorageClass::Input, None);
        assert_eq!(10, v3);

        assert_eq!(
            b.module().disassemble(),
            "; SPIR-V\n; Version: 1.5\n; Generator: rspirv\n; Bound: 11\n\
                    %1 = OpTypeVoid\n\
                    %2 = OpTypeFloat 32\n\
                    %3 = OpTypePointer Input %2\n\
                    %4 = OpTypePointer Function %2\n\
                    %5 = OpTypeFunction %1 %1\n\
                    %6 = OpVariable  %3  Input\n\
                    %10 = OpVariable  %3  Input\n\
                    %7 = OpFunction  %1  None %5\n\
                    %8 = OpLabel\n\
                    %9 = OpVariable  %4  Function\n\
                    OpReturn\n\
                    OpFunctionEnd"
        );
    }

    #[test]
    fn test_build_undefs() {
        let mut b = Builder::new();

        let void = b.type_void();
        assert_eq!(1, void);
        let float = b.type_float(32);
        assert_eq!(2, float);
        let voidfvoid = b.type_function(void, vec![void]);
        assert_eq!(3, voidfvoid);

        // Global undef
        let v1 = b.undef(float, None);
        assert_eq!(4, v1);

        let f = b
            .begin_function(void, None, spirv::FunctionControl::NONE, voidfvoid)
            .unwrap();
        assert_eq!(5, f);
        let bb = b.begin_block(None).unwrap();
        assert_eq!(6, bb);
        // Local undef
        let v2 = b.undef(float, None);
        assert_eq!(7, v2);
        assert!(b.ret().is_ok());
        assert!(b.end_function().is_ok());

        // Global undef again
        let v3 = b.undef(float, None);
        assert_eq!(8, v3);

        assert_eq!(
            b.module().disassemble(),
            "; SPIR-V\n; Version: 1.5\n; Generator: rspirv\n; Bound: 9\n\
                    %1 = OpTypeVoid\n\
                    %2 = OpTypeFloat 32\n\
                    %3 = OpTypeFunction %1 %1\n\
                    %4 = OpUndef  %2\n\
                    %8 = OpUndef  %2\n\
                    %5 = OpFunction  %1  None %3\n\
                    %6 = OpLabel\n\
                    %7 = OpUndef  %2\n\
                    OpReturn\n\
                    OpFunctionEnd"
        );
    }
}