-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
1431 lines (1185 loc) · 41.1 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdio>
#include <cerrno>
#include <string.h>
#include <list>
#include<tuple>
#include <vector>
#include <array>
#include <stack>
#include <climits>
#include <unordered_map>
using namespace std;
enum State {
s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14,
s15, s16, s17, s18, s19, s20, s21, s22, s23, s24, s25, s26, s27,
s28, s29, s30, s31, s32, s33, s34, s35, s36, s37, sComma, sErr
};
enum Category {
EMPTY, MEMOP, LOADI, ARITHOP, OUTPUT, NOP, INTO, COMMA, CONST, REG, COMMENT
};
static const char *CategoryStr[] = {"EMPTY", "MEMOP", "LOADI", "ARITHOP", "OUTPUT", "NOP", "INTO", "COMMA", "CONST",
"REG"};
enum Operation {
load, store, loadI, add, sub, mult, lshift, rshift, output, nop, err
};
static const char *OperationStr[] = {"load", "store", "loadI", "add", "sub", "mult", "lshift", "rshift", "output",
"nop"};
// 0 - NU, 1 - PR, 2 - VR, 3 - SR
enum RegType {
NU, PR, VR, SR
};
//static const char *RegTypeStr[] = {"nu", "pr", "vr", "sr"}; //TODO: this is part of InstructionIR->showReg()
enum RegNum {
R1, R2, R3, Rnone
};
struct InctructionIR {
Operation opcode;
int line_num;
// R1, R2 => R3
// 0 - NU, 1 - PR, 2 - VR, 3 - SR
int registers[3][4];
int constant;
InctructionIR() {
opcode = err;
for (int i = 0; i < 12; ++i) {
registers[i / 4][i % 4] = INT_MAX;
}
constant = -1;
}
InctructionIR(Operation s, int r1, int r2, int r3, int c, RegType rType = SR) {
opcode = s;
registers[R1][rType] = r1;
registers[R2][rType] = r2;
registers[R3][rType] = r3;
constant = c;
}
void showReg(RegType RT) const {
//todo: fix this back
string rt = "r";//RegTypeStr[RT];
string s1 = (opcode == loadI || opcode == output) ? to_string(constant) : "";
cout << OperationStr[opcode] << " "
<< ((registers[R1][RT] != INT_MAX) ? rt + to_string(registers[R1][RT]) : s1)
<< ((registers[R2][RT] != INT_MAX) ? ", " + rt + to_string(registers[R2][RT]) : "")
<< ((registers[R3][RT] != INT_MAX) ? " => " + rt + to_string(registers[R3][RT]) : "") << endl;
}
void showAllRegs() const {
int tmpReg;
cout << "opcode " << "\t Const " << "\tR1 (SR,VR,PR,LU) " << " R2 " << "\t R3 " << endl;
cout << OperationStr[opcode] << "\t" << constant << "\t";
for (int i = 0; i < 3; ++i) {
for (int j = 3; j >= 0; --j) {
tmpReg = registers[i][j];
cout << ((j == 3) ? " | " : " ") << ((tmpReg != INT_MAX) ? to_string(tmpReg) : "-") << " ";
}
}
cout << endl;
}
};
struct InstructionBlock {
list <InctructionIR> instructions;
// showIR - print IR in human readable form
void showInstructions() const {
if (instructions.empty()) {
cerr << "ERROR: Not valid instructions, run terminates." << endl;
return;
}
for (const InctructionIR &inst : instructions) {
switch (inst.opcode) {
case load:
cout << "load\t [ sr" << inst.registers[R1][SR] << " ], [ ], [ sr" << inst.registers[R3][SR] << " ]"
<< endl;
break;
case store:
cout << "store\t [ sr" << inst.registers[R1][SR] << " ], [ ], [ sr" << inst.registers[R3][SR]
<< " ]"
<< endl;
break;
case loadI:
cout << "loadI\t [ val " << inst.constant << " ], [ ], [ sr" << inst.registers[R3][SR] << " ]"
<< endl;
break;
case output:
cout << OperationStr[inst.opcode] << "\t [ val " << inst.constant << " ], [ ], [ ]" << endl;
break;
case nop:
cout << "nop\t [ ], [ ], [ ]" << endl;
break;
default: //
cout << OperationStr[inst.opcode] << "\t [ sr" << inst.registers[R1][SR] << " ], [ sr"
<< inst.registers[R2][SR] << " ], [ sr" << inst.registers[R3][SR] << " ]" << endl;
break;
}
}
}
void showIR(RegType rt = SR) const {
if (instructions.empty()) {
cerr << "ERROR: Not valid instructions, run terminates." << endl;
return;
}
for (const InctructionIR &inst : this->instructions) {
inst.showReg(rt);
}
}
void showAllRegs() const {
if (instructions.empty()) {
cerr << "ERROR: Not valid instructions, run terminates." << endl;
return;
}
for (const InctructionIR &inst : this->instructions) {
inst.showAllRegs();
}
}
};
enum InputMode {
s, p, r, k, x, h
};
// Parsing funcitons
tuple<InputMode, int, char *> manageInput(int argc, char *argv[]);
int strToInt(const string &str);
void takeErrWord(int line_num, const string &line, int &char_pos, string &err_word);
InstructionBlock scan(char *filename, bool check_semantics, bool display_tokens);
vector <pair<Category, string>> processLine(const string &line, int line_num, bool display_tokens);
pair <State, Category> nextState(State state, char new_char, string &lexeme);
InctructionIR parse(const vector <pair<Category, string>> &words, int line_num);
InctructionIR setupInstruction(InctructionIR &inst, const vector <pair<Category, string>> &words, int line_num);
InctructionIR
checkSemantics(const vector <pair<Category, string>> &words, const vector <Category> &grammar, int line_num);
//***********************************************************************************************************
//TODO: maybe put vector for srToVr and lastUse
struct TableSrVr {
int *srToVr;
int *lastUse;
int n;
TableSrVr(int size) : n(size) {
try {
srToVr = new int[size];
lastUse = new int[size];
} catch (bad_alloc &ba) {
cerr << "ERROR ALLOCATING MEMORY: bad_alloc caugth: " << ba.what() << endl;
exit(1);
}
for (int i = 0; i < size; ++i) {
srToVr[i] = INT_MAX;
lastUse[i] = INT_MAX;
}
}
~TableSrVr() {
delete[] srToVr;
delete[] lastUse;
}
void show() {
cout << endl << "srToVr: ";
for (int i = 0; i < n; ++i)
cout << srToVr[i] << ", ";
cout << endl << "LU: ";
for (int i = 0; i < n; ++i)
cout << lastUse[i] << ", ";
cout << endl;
}
};
//Registar Renaming
int registerRenaming(const InstructionBlock &block);
int regNormalize(InstructionBlock &block) {
int cnt = 0;
unordered_map<int, int> regMap;
// cout<<"Reg Normalize: "<<endl;
for (auto &ir: block.instructions) {
for (int i = 0; i < 3; ++i) {
if (ir.registers[i][SR] == INT_MAX)
continue;
if (regMap.find(ir.registers[i][SR]) != regMap.end()) {
ir.registers[i][SR] = regMap[ir.registers[i][SR]];
} else {
// cout<<cnt<<" SR = "<< ir.registers[i][SR] <<" => SR_norm = "<<cnt<<endl;
regMap[ir.registers[i][SR]] = cnt;
ir.registers[i][SR] = cnt++;
}
}
}
return regMap.size();
}
void opDef(int regs[][4], TableSrVr &table, int &vrName, RegNum Ri = R3) {
//OP defines
if (table.srToVr[regs[Ri][SR]] == INT_MAX) { //unused srToVr
table.srToVr[regs[Ri][SR]] = vrName++;
}
regs[R3][VR] = table.srToVr[regs[Ri][SR]];
regs[R3][NU] = table.lastUse[regs[Ri][SR]];
table.srToVr[regs[Ri][SR]] = INT_MAX;
table.lastUse[regs[Ri][SR]] = INT_MAX;
}
void opUse(int regs[][4], TableSrVr &table, int &vrName, RegNum Ri, const int &index) {
//OP uses
// cout << "opUse"<<endl;
// cout << regs[Ri][SR]<<endl;//<<" "<<table.srToVr[regs[Ri][SR]]<<endl;
if (table.srToVr[regs[Ri][SR]] == INT_MAX) { //last Use
table.srToVr[regs[Ri][SR]] = vrName++;
}
regs[Ri][VR] = table.srToVr[regs[Ri][SR]];
regs[Ri][NU] = table.lastUse[regs[Ri][SR]];
table.lastUse[regs[Ri][SR]] = index;
}
void setVR(list<InctructionIR>::iterator ins, TableSrVr &table, int &vrName, const int &index) {
// cout << "SET VR"<<endl;
switch (ins->opcode) {
case load:
opDef(ins->registers, table, vrName, R3);
opUse(ins->registers, table, vrName, R1, index);
break;
case loadI:
opDef(ins->registers, table, vrName, R3);
break;
case store:
opUse(ins->registers, table, vrName, R1, index);
opUse(ins->registers, table, vrName, R3, index);
break;
case output:
break;
default: //ARITH
opDef(ins->registers, table, vrName, R3);
opUse(ins->registers, table, vrName, R1, index);
opUse(ins->registers, table, vrName, R2, index);
break;
}
// cout << endl << index << " " << OperationStr[ins->opcode] << ": vrName = " << vrName;
// table.show();
}
int registerRenaming(InstructionBlock &block) {
int vrName = 0;
int index = block.instructions.size() - 1; //just to come to 0
int maxReg = regNormalize(block);
TableSrVr table(maxReg);
// int maxLive = 0;//TODO: maybe this info will be useful
// cout << "Num Reg = " << maxReg << endl;
// block.showIR(SR);
//Go from end of list to begin
for (auto it = prev(block.instructions.end()); it != prev(block.instructions.begin()); --it) {
if (it->opcode == nop) {
it = block.instructions.erase(it);
continue;
}
setVR(it, table, vrName, index);
index--;
}
return vrName;
}
//---------------------------------------------------------------------
// for each physical register p, VR TO PR [PR TO VR[p]] = p
// for each virtual register v, if VR TO PR [v] is defined, PR TO VR[VR TO PR [v]] = v
// if you have same value on reg try to allocate same reg for same virtual reg (avoid reg to reg copy)
pair <list<RegNum>, RegNum> opUseDef(Operation op) {
// cout<<"OP: "<<OperationStr[op]<<endl;
switch (op) {
case load:
return make_pair(list < RegNum > {R1}, R3);
case loadI:
return make_pair(list < RegNum > {}, R3);
case store:
return make_pair(list < RegNum > {R1, R3}, Rnone);
case output:
return make_pair(list < RegNum > {}, Rnone);
default: //ARITH
return make_pair(list < RegNum > {R1, R2}, R3);
}
}
struct TableVrPr {
vector<int> vrToPr;
vector <pair<bool, int>> vrRemat; //if bool = 0, int = location in memory
//if bool = 1, int = const for loadI,
int memLoc;
vector<int> prToVr; //prNum-1 places for regular operations and 1 for spill
vector<int> prNU; // TODO: heap_max
// vector<bool> prMarked;
stack<int> prFree;
int markedReg[2];
TableVrPr(int vrNum, int prNum, int mem) : vrToPr(vrNum, INT_MAX), vrRemat(vrNum, make_pair(false, INT_MAX)),
memLoc(mem), prToVr(prNum-1, INT_MAX), prNU(prNum-1, INT_MAX){
for (int i = prNum-2; i >= 0 ; --i) {
prFree.push(i);
}
markedReg[0] = INT_MAX;
markedReg[1] = INT_MAX;
}
// prMarked(prNum-1, INT_MAX) {}
void printFreePR(){
list<int> tmp;
cout<< "Free PR:"<<endl;
while(!prFree.empty()){
tmp.push_front(prFree.top());
cout<<prFree.top()<<" | ";
prFree.pop();
}
cout<<endl;
for(auto &x: tmp)
prFree.push(x);
}
void print(){
cout<<"----------------------------------------------"<<endl;
cout<<"Table:"<<endl<<"vrToPr | vrRemat: "<<endl;
for (int i = 0; i < int(vrToPr.size()); ++i) {
cout <<i<<". "<< vrToPr[i] << " [ " << vrRemat[i].first << " , " << vrRemat[i].second <<" ]"<<endl;
}
cout<<endl;
cout<<"prToVr | NU: "<<endl;
for(int i = 0; i < int(prToVr.size()); ++i){
cout<<i<<". "<< prToVr[i]<< " | "<<prNU[i]<<endl;
}
cout<<endl;
printFreePR();
cout<<"----------------------------------------------"<<endl;
cout<<endl;
}
void clearMark() {
markedReg[0] = INT_MAX;
markedReg[1] = INT_MAX;
}
};
int posMax(TableVrPr &table) {
int pos=-1, m = 0;
for (int i = 0; i < int(table.prNU.size()); ++i) {
// cout<<"i = "<<i<<" table.prNU[i] = "<<table.prNU[i]<<" VR = "<<table.prToVr[i];
// cout<<" LoadI = "<<table.vrRemat[table.prToVr[i]].first<< endl;
if (i == table.markedReg[0] || i == table.markedReg[1])
continue;
if (table.prNU[i] > m) {
m = table.prNU[i];
pos = i;
}else if (table.prNU[i] >= m-1 && table.vrRemat[table.prToVr[i]].first == true){//loadI VR
pos = i;
}
// if(table.vrRemat[table.prToVr[i]].first == true) //loadI VR
// return i;
}
if(pos == -1)
cerr<<"Free PR not found"<<endl<<endl;
return pos;
}
int spill(list<InctructionIR> &block, list<InctructionIR>::iterator ins, TableVrPr &table) {
// cout<<"SPILL-------------------------"<<endl;
// cout<<"Ins: ";
// ins->showReg(VR);
// cout<<"Marked: "<<table.markedReg[0]<<" | "<< table.markedReg[1]<<endl;
int prSpill = posMax(table);
// cout<<"prSpill: "<<prSpill<<endl;
int &vrSpill = table.prToVr[prSpill];
int prMem = table.prToVr.size();
if (table.vrRemat[vrSpill].first == false && table.prNU[prSpill] != INT_MAX) {
//Spill LRU Physical REG
block.insert(ins, InctructionIR(loadI, INT_MAX, INT_MAX, prMem, table.memLoc, PR));
block.insert(ins, InctructionIR(store, prSpill, INT_MAX, prMem, -1, PR));
table.vrRemat[vrSpill].second = table.memLoc;
table.memLoc += 4;
}
table.vrToPr[vrSpill] = INT_MAX;
// cout <<"SPILL::MARKED = "<< table.markedReg[0]<<", "<<table.markedReg[1]<<"| newPR-> "<< prSpill<<endl;
return prSpill;
}
void restore(list<InctructionIR> &block, list<InctructionIR>::iterator ins, RegNum reg, TableVrPr &table, int vr) {
int prMem = table.prToVr.size();
if(table.vrRemat[vr].first == true){ //Rematerialize
block.insert(ins, InctructionIR(loadI, INT_MAX, INT_MAX, table.vrToPr[vr], table.vrRemat[vr].second, PR));
}else{ // Have to ReLoad from Mem
block.insert(ins, InctructionIR(loadI, INT_MAX, INT_MAX, prMem, table.vrRemat[vr].second, PR));
block.insert(ins, InctructionIR(load, prMem, INT_MAX, table.vrToPr[vr], INT_MAX, PR));
}
}
int getPr(list<InctructionIR> &block, list<InctructionIR>::iterator ins, RegNum reg, TableVrPr &table) {
int &vr = ins->registers[reg][VR];
int &nu = ins->registers[reg][NU];
int pr;
// cout<<"GetPR: VR = "<<vr << " NU = "<<nu<<endl;
if (table.prFree.empty()) {
// cout<<"No Free PRs"<<endl;
pr = spill(block, ins, table);
} else {
pr = table.prFree.top();
table.prFree.pop();
}
table.vrToPr[vr] = pr;
table.prToVr[pr] = vr;
table.prNU[pr] = nu;
return pr;
}
//bool if instruction need to be deleted
bool setPr(list<InctructionIR> &block, list<InctructionIR>::iterator ins, TableVrPr &table) {
pair <list<RegNum>, RegNum> regUseDef = opUseDef(ins->opcode); // first - uses, second - def
RegNum &r3 = regUseDef.second;
int pr;
int vr;
// table.clearMark();
// If no R3 next use just update NU for PR if any
if (ins->registers[r3][NU] == INT_MAX){
for (auto &r1_2: regUseDef.first) {
vr = ins->registers[r1_2][VR];
pr = table.vrToPr[vr];
if (pr != INT_MAX){
table.prNU[pr] = ins->registers[r1_2][NU];
}
}
return true;
}
for (auto &r1_2: regUseDef.first) {
// cout << regUseDef.first.empty()<<" SetPR: R1_2 = "<< r1_2 <<endl;
vr = ins->registers[r1_2][VR];
// cout << "VR: "<< vr <<endl;
pr = table.vrToPr[vr];
// cout << "PR: "<< pr <<endl;
if (pr == INT_MAX) {
pr = getPr(block, ins, r1_2, table);
restore(block, ins, r1_2, table, vr);
// table.print();
}else if (ins->registers[r3][NU] == INT_MAX){
// If no R3 next use just update NU for PR if any
table.prNU[pr] = ins->registers[r1_2][NU];
continue;
}
ins->registers[r1_2][PR] = pr;
table.markedReg[r1_2] = pr;
table.prNU[pr] = ins->registers[r1_2][NU];
}
// If last use clean PR
for (auto &r1_2: regUseDef.first) {
pr = ins->registers[r1_2][PR];
if (ins->registers[r1_2][NU] == INT_MAX && pr != INT_MAX) {
table.vrToPr[table.prToVr[pr]] = INT_MAX;
table.prToVr[pr] = INT_MAX;
table.prNU[pr] = INT_MAX;
table.prFree.push(pr);
}
}
table.clearMark();
// cout << "SetPR: R3 = "<< regUseDef.second<<endl;
if (ins->registers[r3][NU] == INT_MAX) // if no next use true->delete inst
return true;
else if ( r3 != Rnone) {
// cout << "dVR: "<< vr <<endl;
if (ins->opcode == loadI){
vr = ins->registers[r3][VR];
table.vrRemat[vr] = make_pair(true, ins->constant);
return true;
}else{
pr = getPr(block, ins, r3, table);
// table.print();
ins->registers[r3][PR] = pr;
// cout << "dPR: "<< pr <<endl;
}
// table.prMarked[pr] = true;
}
return false;
}
int bottomUpAllocator(InstructionBlock &block, int vrNum, int prNum) {
TableVrPr table(vrNum, prNum, 40000);
bool delInst;
// cout << "table init: VRnum = "<< vrNum<< "| PRnum = "<< prNum<<endl;
for (auto it = block.instructions.begin(); it != block.instructions.end(); ) {
// cout<<"----------------------------------------------"<<endl;
// it->showReg(VR);
delInst = setPr(block.instructions, it, table);
if(delInst == true)
it = block.instructions.erase(it);
else
++it;
}
return 0;
}
//***********************************************************************************************************
// HELPER FUNCTIONS
// manageInput - parse command line
tuple<InputMode, int, char *> manageInput(int argc, char *argv[]) {
tuple<InputMode, int, char *> input(make_tuple(s, 0, argv[argc - 1]));
// cout << "INPUT MODE"<<endl;
if( argc == 1)
get<0>(input) = h;
else if (argc == 2) {
get<0>(input) = p;
return input;
}else if(argc == 3){
int regNum = strToInt(argv[1]);
if ( regNum != INT_MAX){
if (3 <= regNum && regNum <= 64){
get<0>(input) = k;
get<1>(input) = regNum;
}else{
cerr << "Number of registers must be in interval [3, 64]" << endl;
exit(1);
}
}else if (strcmp(argv[1], "-x") == 0) {
get<0>(input) = x;
}
return input;
}
for (int i = 1; i < argc - 1; ++i) {
if (strcmp(argv[i], "-h") == 0) {
get<0>(input) = h;
} else if (strcmp(argv[i], "-x") == 0 && get<0>(input) < h) {
get<0>(input) = x;
} else if (strcmp(argv[i], "-r") == 0 && get<0>(input) < r) {
get<0>(input) = r;
} else if (strcmp(argv[i], "-p") == 0 && get<0>(input) < p) {
get<0>(input) = p;
} else if (strcmp(argv[i], "-s") == 0 && get<0>(input) < s) {
get<0>(input) = s;
}
}
return input;
}
// strToInt - converts string(const | r+const) to int
int strToInt(const string &str) {
int n = 0;
int i = 0;
if (str[0] == 'r') {
i = 1;
}
for (; i < int(str.length()); ++i) {
if(str[i] < '0' || str[i] > '9')
return INT_MAX;
n = 10 * n + (str[i] - '0');
}
return n;
}
// strToOperation - converts string to enum Operation
Operation strToOperation(const string &op) {
if (op == "load")
return load;
else if (op == "store")
return store;
else if (op == "loadI")
return loadI;
else if (op == "add")
return add;
else if (op == "sub")
return sub;
else if (op == "mult")
return mult;
else if (op == "lshift")
return lshift;
else if (op == "rshift")
return rshift;
else if (op == "output")
return output;
else
return nop;
}
// If error happen it gets whole word as error word
void takeErrWord(int line_num, const string &line, int &char_pos, string &err_word) {
while (line[char_pos] != ' ' && line[char_pos] != '\t' && line[char_pos] != '\n') {
err_word.push_back(line[++char_pos]);
}
if (line[char_pos] == ' ' || line[char_pos] == '\t' || line[char_pos] == '\n')
err_word.pop_back();
cerr << "ERROR: " << line_num << ": Lexical: \"" << err_word <<
"\" is not a valid word." << endl;
return;
}
// MAIN FUNCTIONS Implementations
// Scan - creates tokens from input file, check lexical errors, and check_semantics(make IR)
InstructionBlock scan(char *filename, bool check_semantics = false, bool display_tokens = false) {
ifstream input_stream(filename, ifstream::in);
if (!input_stream) cerr << "Cannot open input file: \"" << filename << "\"" << endl;
string line;
int line_num = 0;
int inst_count = 0;
vector <pair<Category, string>> result;
InctructionIR inst;
InstructionBlock block;
int error_count = 0;
while (getline(input_stream, line)) {
// cout << "LINE: " << line << endl;
line.push_back('\n');
result = processLine(line, ++line_num, display_tokens);
if (result.empty())
continue;
inst_count++;
// Parse Part
if (check_semantics) {
inst = parse(result, line_num);
if (inst.opcode != err) {
if (error_count == 0)
block.instructions.push_back(inst);
} else {
error_count++;
}
}
}
if (display_tokens) {
cout << line_num << ": < ENDFILE , \"\" >" << endl;
}
if (check_semantics) {
if (error_count == 0) {
// cout << endl << "Parse succeeded, finding " << inst_count - error_count << " ILOC operations." << endl;
} else {
cerr << endl << "Parser found " << error_count << " Syntax errors in " << line_num << " lines of input."
<< endl;
}
}
if (inst_count == 0) {
cout << "WARNING: ILOC file contained no operations." << endl;
}
return (error_count == 0) ? block : InstructionBlock();
}
// processLine - creates vector of tokens(Category, string)
vector <pair<Category, string>> processLine(const string &line, int line_num, bool display_tokens) {
string lexeme, err_str;
pair <State, Category> s;
vector <pair<Category, string>> tokens;
ostringstream stream;
// cout << "PROCSS LINE: " << line;
//Initialize first state
s.first = s0;
// line.push_back('\n');
for (int char_pos = 0; char_pos < int(line.length()); ++char_pos) {
// cout << s <<"->";
s = nextState(s.first, line[char_pos], lexeme);
// cout << s << endl;
if (s.first != sErr) {
if (s.second != EMPTY) {
// Category {EMPTY, MEMOP, LOADI, ARITHOP, OUTPUT, NOP, INTO, COMMA, CONST, REG, COMMENT};
if (s.second == COMMENT) {
break;
} else { //ALL OPERATIONS, REG, CONST
stream << line_num << ": < " << CategoryStr[s.second] << "\t, \"" << lexeme << "\" >" << endl;
tokens.push_back(make_pair(s.second, lexeme));
if (s.second == REG && s.first == sComma) {
stream << line_num << ": < COMMA\t, \",\" >" << endl;
tokens.push_back(make_pair(COMMA, ","));
s.first = s0;
}
}
}
} else { // Error States
if (s.second != EMPTY) { //Accept lexeme[0:n-1] and make err message
err_str = lexeme;
lexeme.pop_back(); // word you accept
stream << line_num << ": < " << CategoryStr[s.second] << "\t, \"" << lexeme << "\" >" << endl;
tokens.push_back(make_pair(s.second, lexeme));
takeErrWord(line_num, line, char_pos, err_str);
tokens.push_back(make_pair(EMPTY, err_str));
s.first = s0;
} else { // make err message
takeErrWord(line_num, line, char_pos, lexeme);
tokens.push_back(make_pair(EMPTY, lexeme));
s.first = s0;
}
}
}
if (display_tokens) {
cout << stream.str();
}
return tokens;
}
// nextState - DFA of trasitions
pair <State, Category> nextState(State state, char new_char, string &lexeme) {
Category cat = EMPTY;
switch (state) {
case s0:
lexeme.clear();
lexeme.push_back(new_char);
if (new_char == 's') {
state = s1;
} else if (new_char == 'l') {
state = s8;
} else if (new_char == 'r') {
state = s13;
} else if (new_char == 'm') {
state = s19;
} else if (new_char == 'a') {
state = s22;
} else if (new_char == 'n') {
state = s25;
} else if (new_char == 'o') {
state = s28;
} else if (new_char == '=') {
state = s34;
} else if (new_char == ',') {
cat = COMMA;
state = s0;
} else if (new_char == ' ' || new_char == '\t' || new_char == '\n') {
state = s0;
} else if (new_char >= '0' && new_char <= '9') {
state = s35;
} else if (new_char == '/') {
state = s37;
} else {
state = sErr;
}
break;
case s1:
lexeme.push_back(new_char);
if (new_char == 't') {
state = s2;
} else if (new_char == 'u') {
state = s6;
} else {
state = sErr;
}
break;
case s2:
lexeme.push_back(new_char);
if (new_char == 'o') {
state = s3;
} else {
state = sErr;
}
break;
case s3:
lexeme.push_back(new_char);
if (new_char == 'r') {
state = s4;
} else {
state = sErr;
}
break;
case s4:
lexeme.push_back(new_char);
if (new_char == 'e') {
state = s5;
} else {
state = sErr;
}
break;
case s5: //store
if (new_char == ' ' || new_char == '\t' || new_char == '\n') {
cat = MEMOP;
state = s0;
} else {
state = sErr;
cat = MEMOP;
lexeme.push_back(new_char);
}
break;
case s6:
lexeme.push_back(new_char);
if (new_char == 'b') {
state = s7;
} else {
state = sErr;
}
break;
case s7: //sub
if (new_char == ' ' || new_char == '\t' || new_char == '\n') {
cat = ARITHOP;
state = s0;
} else {
state = sErr;
cat = ARITHOP;
lexeme.push_back(new_char);
}
break;
case s8:
lexeme.push_back(new_char);
if (new_char == 'o') {
state = s9;
} else if (new_char == 's') {
state = s14;
} else {
state = sErr;
}
break;
case s9:
lexeme.push_back(new_char);
if (new_char == 'a') {
state = s10;
} else {
state = sErr;
}
break;
case s10:
lexeme.push_back(new_char);
if (new_char == 'd') {
state = s11;
} else {
state = sErr;
}
break;
case s11: //load
if (new_char == 'I') {
state = s12;
lexeme.push_back(new_char);
} else if (new_char == ' ' || new_char == '\t' || new_char == '\n') {
cat = MEMOP;
state = s0;
} else {
state = sErr;
cat = MEMOP;
lexeme.push_back(new_char);
}
break;
case s12:
if (new_char == ' ' || new_char == '\t' || new_char == '\n') {
cat = LOADI;
state = s0;
} else {
state = sErr;
cat = LOADI;
lexeme.push_back(new_char);
}
break;