-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tool.cpp
1716 lines (1583 loc) · 61 KB
/
Tool.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 "Tool.h"
string Tool::logFileTime = "";
string Tool::findGrammar(string type, string generateType, int expIndex)
{
Json::Reader reader;
Json::Value root;
string grammarJsonName = string(getenv("VGENERATOR_WORK_DIR")) + "/Data/Grammar.json";
if(generateType == "VTR")
grammarJsonName = string(getenv("VGENERATOR_WORK_DIR")) + "/Data/Grammar_VTR.json";
ifstream in(grammarJsonName, ios::binary);
if(!in.is_open()){
Tool::error("Error: Failed to open file " + grammarJsonName);
exit(1);
}
if(reader.parse(in, root)){
string index = to_string(expIndex);
string recentGrammar = root[type][index].asString();
if (recentGrammar != "")
return recentGrammar;
}
return "";
}
vector<string> Tool::extractGrammar(string grammar)
{
vector<string> resultStruct;
string temp_grammar = grammar;
int length = grammar.size();
int stateOr = 0;
int stateMultiple = 0;
string temp = "";
for(int i = 0; i <= length; i++){
if (i == length){
resultStruct.push_back(temp);
}
else if (temp_grammar[i] >= 'A' && temp_grammar[i] <= 'Z'){ //Detect Expression:
string tempExpr = "";
tempExpr += temp_grammar[i];
for(i = i + 1; isWord(temp_grammar[i]); i++)
tempExpr += temp_grammar[i];
temp += tempExpr;
i--;
}
else if (temp_grammar[i] == '+' || temp_grammar[i] == '*'){ //Connection
resultStruct.push_back(temp);
temp = "";
if (temp_grammar[i] == '*')
temp += '*';
}
else if (temp_grammar[i] == '|' || temp_grammar[i] == '-'){ //Inter calculation
temp += temp_grammar[i];
}
else if(temp_grammar[i] == '\''){ // String or char
string tempExpr = "";
tempExpr += temp_grammar[i];
for(i = i + 1; temp_grammar[i] != '\''; i++)
tempExpr += temp_grammar[i];
tempExpr += '\'';
temp += tempExpr;
}
else{
Tool::error("Error: extractGrammar find unknown syntax.");
}
}
return resultStruct;
}
int Tool::isWord(char c){
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
return 1;
return 0;
}
void Tool::error(string info){
ofstream testbench;
testbench.open("Vgenerator.log", ios::app);
if(testbench.is_open()){
testbench << info;
testbench.close();
}
else{
testbench.close();
}
cout << info << endl;
exit(1);
}
int Tool::getNumIndex(string grammarType, string generateType){
int index = 1;
while(true){
if(findGrammar(grammarType, generateType, index) != ""){
index++;
}
else
break;
}
return index - 1;
}
void Tool::logMessage(string message){
string targetLogTime = getLogFileTime();
string text = message + "\n";
std::ofstream testbench;
testbench.open("Vgenerator_" + targetLogTime+ ".log", ios::app);
if(testbench.is_open()){
testbench << text;
testbench.close();
}
else{
testbench.close();
}
cout << message << endl;
}
vector<Statement*> Tool::getTypeStateFromV(vector<Statement*> initialV, string grammarType, string actionType){
vector<Statement*> resultV;
for (auto it = initialV.begin(); it < initialV.end(); it++){
vector<Statement*> tempV = (*it)->getTargetSubStatement(grammarType, actionType);
resultV.insert(resultV.end(), tempV.begin(), tempV.end());
}
return resultV;
}
int Tool::isContianInV(vector<Statement*> initialV, string value, string grammarType){
for (auto it = initialV.begin(); it < initialV.end(); it++){
if((*it)->isContain(grammarType, value))
return 1;
}
return 0;
}
void Tool::setCodeinItem(Statement* item, string value){
item->setRealCode(value);
item->setIsterminal(1);
item->setExpIndex(0);
item->resetSubStatement();
}
int Tool::getRandomfromClosed(int start, int end){
return (rand() % (end - start + 1)) + start;
}
string Tool::intToBinary(int num){
string result = "";
if(num == 0)
return "0";
while(num != 1){
result = to_string(num % 2) + result;
num = num / 2;
}
result = "1" + result;
return result;
}
vector<Statement*> Tool::findSfromMultiS(Statement* multiS, string grammarType, string value){
vector<Statement*> result;
vector<Statement>* mDV = multiS->getSubStatement();
for(int i = 0 ; i < mDV->size(); i++){
vector<Statement*> recentResult = (*mDV)[i].getTargetSubStatement(grammarType, "ALL_LAYER");
for(auto subIt = recentResult.begin(); subIt < recentResult.end(); subIt++){
if((*subIt)->getRealCode() == value){
result.push_back(&(*mDV)[i]);
}
}
}
return result;
}
/*
Fire write. If get 0, the file was written successfully.
The filename should contain the path to the target location.
*/
bool Tool::fileWrite(string filename, string text, bool ifPrint){
std::ofstream testbench;
testbench.open(filename);
if(testbench.is_open()){
testbench << text;
testbench.close();
if(ifPrint)
Tool::logMessage(filename + " write successfully");
return 0;
}
else{
testbench.close();
Tool::logMessage(filename + " write failed");
return 1;
}
}
/*
getXMLTree: Get the tree data of XML file
filename: The path of target file.
*/
TiXmlElement* Tool::getXMLTree(string filename, string type){
// file<> fdoc(filename.c_str());
// xml_document<> doc;
// char* data = fdoc.data();
// doc.parse<0>(data);
TiXmlDocument* doc = new TiXmlDocument(filename);
TiXmlElement* result;
if(!doc->LoadFile()){
error("Error: getXMLTree cannot load " + type);
exit(1);
}
if(type == "")
result = doc->FirstChildElement();
else
result = doc->FirstChildElement(type.c_str());
return result;
}
vector<string> Tool::split(string s, char c, string clean){
vector<string> result;
int nextIndex = 0;
if(clean == "clean"){
bool isPreSpace = false;
string temp = "";
for(int i = 0; i < s.size(); i++){
if(s[i] == ' ' || s[i] == '\t'){
if(isPreSpace)
continue;
else{
isPreSpace = true;
temp += " ";
}
}
else{
isPreSpace = false;
temp += s[i];
}
}
s = temp;
}
while(true){
nextIndex = s.find(c);
if(nextIndex == string::npos)
nextIndex = s.size();
string recentELem = s.substr(0, nextIndex);
result.push_back(recentELem);
if(nextIndex == s.size())
break;
else if(nextIndex + 1 == s.size()){
result.push_back("");
break;
}
s = s.substr(nextIndex + 1, s.size() - nextIndex - 1);
}
return result;
}
int Tool::getNumFromClose(string s)
{
int leftIndex = s.find("[");
int rightIndex = s.find("]");
if(leftIndex == string::npos || rightIndex == string::npos)
error("Error: getNumFromClose cannot find []");
int result = atoi(s.substr(leftIndex + 1, rightIndex - leftIndex - 1).c_str());
return result;
}
TiXmlElement *Tool::getFirstElementByName(TiXmlElement *root, string name)
{
queue<TiXmlElement*> operateNode;
operateNode.push(root);
while(operateNode.size() != 0){
TiXmlElement* recentNode = operateNode.front();
operateNode.pop();
if(recentNode->Value() == name)
return recentNode;
else{
for(TiXmlElement* it = recentNode->FirstChildElement();
it != nullptr;
it = it->NextSiblingElement()){
operateNode.push(it);
}
}
}
return nullptr;
}
vector<vector<string>> Tool::twoDSplit(string s, char smallC, char largeC)
{
string cleanStr = "";
for(int i = 0; i < s.size(); i++)
if(s[i] != '\t')
cleanStr += s[i];
vector<string> temp = Tool::split(cleanStr, largeC);
vector<vector<string>> matrix;
for(auto rowString = temp.begin(); rowString < temp.end(); rowString++){
matrix.push_back(Tool::split(*rowString, smallC));
}
return matrix;
}
pair<int, int> Tool::getBracketPair(string s)
{
int commaIndex = s.find(",");
int firstNum = atoi(s.substr(1, commaIndex - 1).c_str());
int secondNum = atoi(s.substr(commaIndex + 1, s.size() - commaIndex - 2).c_str());
return pair<int, int>(firstNum, secondNum);
}
void Tool::verilogCom(string filepath1, string filepath2, string targetDirectory, string newFileName)
{
int lastSlash1 = filepath1.rfind('/');
string filename1 = filepath1;
if(lastSlash1 != string::npos)
filename1 = filepath1.substr(lastSlash1 + 1, filepath1.size() - lastSlash1 - 1);
int lastSlash2 = filepath2.rfind('/');
string filename2 = filepath2;
if(lastSlash2 != string::npos)
filename2 = filepath2.substr(lastSlash2 + 1, filepath2.size() - lastSlash2 - 1);
//read files
ifstream file1(filepath1);
if(!file1.is_open()){
Tool::error("Error opening file: " + filepath1);
return;
}
stringstream ss1;
ss1 << file1.rdbuf();
string content1 = ss1.str();
file1.close();
ifstream file2(filepath2);
if(!file2.is_open()){
Tool::error("Error opening file: " + filepath2);
return;
}
stringstream ss2;
ss2 << file2.rdbuf();
string content2 = ss2.str();
file2.close();
//deal with same module name
vector<string> moduleNames1 = getAllModuleNames(content1);
vector<string> moduleNames2 = getAllModuleNames(content2);
stringstream module1 = getModule(filepath1, moduleNames1[0]);
stringstream module2 = getModule(filepath2, moduleNames2[0]);
vector<string> commonModuleNames;
unordered_set<string> set(moduleNames1.begin(), moduleNames1.end());
for(const auto& str : moduleNames2){
if(set.count(str) > 0){
commonModuleNames.push_back(str);
}
}
for(const auto& name : commonModuleNames){
if(name.compare(moduleNames1[0]) == 0 || name.compare(moduleNames2[0]) == 0){
string result1;
string result2;
stringstream m1 = getModule(filepath1, name);
stringstream m2 = getModule(filepath2, name);
for(char c : m1.str()){
if(c != '\t' && c != '\n'){
result1 += c;
}
}
for(char c : m2.str()){
if(c != '\t' && c != '\n'){
result2 += c;
}
}
if(result1.compare(result2) != 0){
error("Error: Same main module with inconsist function.");
}
}
string moduleStart = "module " + name + "(";
string moduleEnd = "endmodule";
size_t startPos = content2.find(moduleStart);
size_t endPos = content2.find(moduleEnd, startPos + moduleStart.length());
content2 = content2.substr(0, startPos) + content2.substr(endPos + moduleEnd.length());
}
//deal with same variable name
string combinedContent = content1 + "\n" + content2;
// string combinedFilename = "_" + filename1.substr(0, filename1.find_last_of('.')) + "_and_" + filename2.substr(0, filename2.find_last_of('.')) + "_";
string def1;
string def2;
getline(module1, def1);
getline(module2, def2);
vector<string> variables1 = getVariables(def1);
vector<string> variables2 = getVariables(def2);
vector<string> originalV2 = variables2;
vector<string> commonVariables;
unordered_set<string> set1(variables1.begin(), variables1.end());
for(const auto& str : variables2){
if(set1.count(str) > 0){
commonVariables.push_back(str);
}
}
vector<string> modifiedVariables = commonVariables;
for(auto& v : modifiedVariables){
int suffix = 1;
while(find(variables1.begin(), variables1.end(), v) != variables1.end() ||
find(variables2.begin(), variables2.end(), v) != variables2.end() ||
hasDuplicate(modifiedVariables) || isSystemKeyword(v)){
if(isdigit(v[v.length()-1])){
size_t pos = v.find_last_not_of("0123456789");
if(pos != string::npos) {
size_t numericSuffixStart = pos + 1;
size_t numericSuffixLength = v.size() - numericSuffixStart;
string numericSuffix = v.substr(numericSuffixStart, numericSuffixLength);
suffix = stoi(numericSuffix) + 1;
v = v.substr(0, pos+1);
string completeSuffix = to_string(suffix);
if(numericSuffix[0] == '0' && numericSuffixLength != 1){
size_t count = numericSuffix.find_first_not_of('0');
count = (count == std::string::npos) ? numericSuffix.length() : count;
string leadingZeros(count, '0');
completeSuffix = leadingZeros + completeSuffix;
}
v += completeSuffix;
}
}
else{
v += to_string(suffix);
}
}
}
string line;
stringstream newModule2;
module2.seekg(0, ios::beg);
while(getline(module2, line)){
for(size_t i = 0; i < commonVariables.size(); i++){
size_t pos = line.find(commonVariables[i]);
while(pos != string::npos){
char prevChar = (pos > 0) ? line[pos - 1] : ' ';
char nextChar = (pos + commonVariables[i].length() < line.length()) ? line[pos + commonVariables[i].length()] : ' ';
if((isspace(prevChar) || prevChar == '(') && (nextChar == ',' || nextChar == ')' || nextChar == ';')){
line.replace(pos, commonVariables[i].length(), modifiedVariables[i]);
}
pos = line.find(commonVariables[i], pos + modifiedVariables[i].length());
}
}
newModule2 << line << '\n';
}
for(const auto& commonVar : commonVariables){
auto it = std::remove(variables2.begin(), variables2.end(), commonVar);
variables2.erase(it, variables2.end());
}
vector<string> newVariables;
newVariables.insert(newVariables.end(), variables1.begin(), variables1.end());
newVariables.insert(newVariables.end(), modifiedVariables.begin(), modifiedVariables.end());
newVariables.insert(newVariables.end(), variables2.begin(), variables2.end());
//establish the new main module
string newModule = "module " + newFileName + "(";
for(const auto& var : newVariables){
newModule += var + ", ";
}
newModule = newModule.substr(0, newModule.length()-2) + ");" + "\n";
module1.seekg(0, ios::beg);
getline(module1, line);
vector<string> v1 = variables1;
string previousLine = "";
while(getline(module1, line) && (variables1.size() != 0 || line.find("reg ") != string::npos)){
if((line.find("wire ") == string::npos && line.find("reg ") == string::npos) || line.find("input ") != string::npos || line.find("output ") != string::npos)
newModule += line + "\n";
for(auto it = variables1.begin(); it != variables1.end();){
if (line.find(" " + *it + ";") != string::npos || line.find(" " + *it + ",") != string::npos) {
it = variables1.erase(it);
} else {
++it;
}
}
previousLine = line;
}
getline(newModule2, line);
vector<string> newVariables2 = getVariables(line);
vector<string> v2 = newVariables2;
while(getline(newModule2, line) && (newVariables2.size() != 0 || line.find("reg ") != string::npos)){
if((line.find("wire ") == string::npos && line.find("reg ") == string::npos) || line.find("input ") != string::npos || line.find("output ") != string::npos)
newModule += line + "\n";
for(auto it = newVariables2.begin(); it != newVariables2.end();){
if (line.find(" " + *it + ";") != string::npos || line.find(" " + *it + ",") != string::npos) {
it = newVariables2.erase(it);
} else {
++it;
}
}
previousLine = line;
}
newModule += "\t" + filename1.substr(0, filename1.find_last_of('.')) + " ";
string character = filename1.substr(0, 1);
character[0] = toupper(character[0]);
int postNum = 1;
string callName1 = character + to_string(postNum);
while(find(newVariables.begin(), newVariables.end(), callName1) != newVariables.end()){
postNum++;
callName1 = character + to_string(postNum);
}
newModule += callName1 + "(";
for(const auto& var : v1){
newModule += "." + var + "(" + var + ")" + ", ";
}
newModule = newModule.substr(0, newModule.length()-2) + ");" + "\n";
newModule += "\t" +filename2.substr(0, filename2.find_last_of('.')) + " ";
string character2 = filename2.substr(0, 1);
character2[0] = toupper(character2[0]);
postNum = 1;
string callName2 = character2 + to_string(postNum);
while(find(newVariables.begin(), newVariables.end(), callName2) != newVariables.end() || callName2 == callName1){
postNum++;
callName2 = character + to_string(postNum);
}
newModule += callName2 + "(";
for(size_t i = 0; i < v2.size(); i++){
newModule += "." + originalV2[i] + "(" + v2[i] + ")" + ", ";
}
newModule = newModule.substr(0, newModule.length()-2) + ");" + "\n";
newModule += "endmodule";
//write into file
if(targetDirectory != "")
targetDirectory += "/";
ofstream outputFile(targetDirectory + newFileName + ".v");
if(!outputFile.is_open()){
Tool::error("Error creating output file: " + targetDirectory + newFileName);
return;
}
else{
logMessage("Create file " + targetDirectory + newFileName + ".v" + " successfully.\n");
}
outputFile << newModule;
outputFile << "\n";
outputFile << "\n";
outputFile << combinedContent;
outputFile.close();
// //write graph file
// string graphPath = targetDirectory + "graph/";
// string file1GraphPath = graphPath + filename1.substr(0, filename1.find_last_of('.')) + ".graph";
// string file2GraphPath = graphPath + filename2.substr(0, filename2.find_last_of('.')) + ".graph";
// if(!isFileExists(file1GraphPath) || !isFileExists(file2GraphPath)){
// Tool::error("Error: VerilogCom cannot found the graph of submodule.");
// }
// string formula1 = getFormulafromGraph(file1GraphPath);
// string formula2 = getFormulafromGraph(file2GraphPath);
// string newFormula = "( " + formula1 + " and " + formula2 + " )";
// string graphContent = generateGraph(newFileName + ".v", filename1, filename2, newFormula);
// fileWrite(graphPath + newFileName + ".graph", graphContent);
return;
}
stringstream Tool::getModule(string filepath, string moduleName)
{
string content = readFile(filepath);
return getStrModule(content, moduleName);
}
stringstream Tool::getStrModule(string content, string moduleName){
istringstream iss(content);
string line;
bool insideModule = false;
stringstream module;
while(getline(iss, line)) {
if (line.find("module " + moduleName + "(") != string::npos || line.find("module " + moduleName + " (") != string::npos) insideModule = true;
if (insideModule) {
module << line << "\n";
if (line.find("endmodule") != string::npos) {
insideModule = false;
break;
}
}
}
return module;
}
string Tool::getLogFileTime()
{
if(logFileTime == "" || logFileTime.empty()){
logFileTime = getRecentTime();
}
return logFileTime;
}
vector<string> Tool::getAllModuleNames(string verilog)
{
vector<string> moduleNames;
regex moduleRegex(R"(module\s+(\w+)\s*\()");
auto words_begin = sregex_iterator(verilog.begin(), verilog.end(), moduleRegex);
auto words_end = sregex_iterator();
for (sregex_iterator i = words_begin; i != words_end; ++i) {
smatch match = *i;
string moduleName = match.str(1);
moduleNames.push_back(moduleName);
}
return moduleNames;
}
vector<string> Tool::getVariables(string def)
{
vector<string> variables;
size_t startPos = def.find('(');
size_t endPos = def.find(')');
if(startPos != string::npos && endPos != string::npos && startPos < endPos){
string variableString = def.substr(startPos + 1, endPos - startPos - 1);
istringstream iss(variableString);
string variable;
while (std::getline(iss, variable, ',')) {
variable.erase(std::remove_if(variable.begin(), variable.end(), ::isspace), variable.end());
variables.push_back(variable);
}
}
return variables;
}
bool Tool::hasDuplicate(const vector<string>& vec)
{
unordered_set<string> uniqueStrings;
for(const auto& str : vec){
if (!uniqueStrings.insert(str).second) {
return true;
}
}
return false;
}
bool Tool::isDirectoryExists(string path){
struct stat fileStat;
return (stat(path.c_str(), &fileStat) == 0) && S_ISDIR(fileStat.st_mode);
}
bool Tool::isFileExists(string path){
ifstream fin(path);
bool isCannotOpen = !fin;
fin.close();
return !isCannotOpen;
}
bool Tool::createDirectory(string path){
if(mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0)
return true;
else
return false;
}
bool Tool::isDirectoryEmpty(const char* path){
DIR* dir = opendir(path);
if (dir == nullptr)
{
return false; // error opening directory
}
bool isEmpty = true;
struct dirent* entry;
while ((entry = readdir(dir)) != nullptr)
{
if (entry->d_type != DT_DIR || (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0))
{
isEmpty = false;
break;
}
}
closedir(dir);
return isEmpty;
}
void Tool::verilogSeiresCom(string filepath1, string filepath2, string targetDirectory, string newFileName, string strategy){
int lastSlash1 = filepath1.rfind('/');
string filename1 = filepath1;
if(lastSlash1 != string::npos)
filename1 = filepath1.substr(lastSlash1 + 1, filepath1.size() - lastSlash1 - 1);
int lastSlash2 = filepath2.rfind('/');
string filename2 = filepath2;
if(lastSlash2 != string::npos)
filename2 = filepath2.substr(lastSlash2 + 1, filepath2.size() - lastSlash2 - 1);
//read files
ifstream file1(filepath1);
if(!file1.is_open()){
Tool::error("Error opening file: " + filepath1);
return;
}
stringstream ss1;
ss1 << file1.rdbuf();
string content1 = ss1.str();
file1.close();
ifstream file2(filepath2);
if(!file2.is_open()){
Tool::error("Error opening file: " + filepath2);
return;
}
stringstream ss2;
ss2 << file2.rdbuf();
string content2 = ss2.str();
file2.close();
//deal with the duplicate module name
vector<string> moduleNames1 = getAllModuleNames(content1);
vector<string> moduleNames2 = getAllModuleNames(content2);
stringstream module1 = getModule(filepath1, moduleNames1[0]);
stringstream module2 = getModule(filepath2, moduleNames2[0]);
vector<string> commonModuleNames;
unordered_set<string> set(moduleNames1.begin(), moduleNames1.end());
for(const auto& str : moduleNames2){
if(set.count(str) > 0){
commonModuleNames.push_back(str);
}
}
for(const auto& name : commonModuleNames){
if(name.compare(moduleNames1[0]) == 0 || name.compare(moduleNames2[0]) == 0){
string result1;
string result2;
stringstream m1 = getModule(filepath1, name);
stringstream m2 = getModule(filepath2, name);
for(char c : m1.str()){
if(c != '\t' && c != '\n'){
result1 += c;
}
}
for(char c : m2.str()){
if(c != '\t' && c != '\n'){
result2 += c;
}
}
if(result1.compare(result2) != 0){
error("Error: Same main module with inconsist function.");
}
}
string moduleStart = "module " + name + "(";
string moduleEnd = "endmodule";
size_t startPos = content2.find(moduleStart);
size_t endPos = content2.find(moduleEnd, startPos + moduleStart.length());
content2 = content2.substr(0, startPos) + content2.substr(endPos + moduleEnd.length());
}
//Extract output of first module and input of second module.
string combinedContent = content1 + "\n" + content2;
// string combinedFilename = "_" + filename1.substr(0, filename1.find_last_of('.')) + "_next_" + filename2.substr(0, filename2.find_last_of('.')) + "_";
//Find output in first module.
string def;
vector<Attribute*> first_outputs, first_inputs, second_inputs, second_outputs;
bool firstModuleTimes = false;
extractInoutfromTextV(module1, first_outputs, first_inputs);
extractInoutfromTextV(module2, second_outputs, second_inputs);
//Turn second_outputs's type from reg to wire
for(auto it = second_outputs.begin(); it < second_outputs.end(); it++){
Attribute* attr = *it;
attr->setDataType("wire");
}
vector<Attribute> init_first_outputs, init_first_inputs, init_second_inputs, init_second_outputs;
init_first_inputs = deepCopyAttr(first_inputs);
init_first_outputs = deepCopyAttr(first_outputs);
init_second_inputs = deepCopyAttr(second_inputs);
init_second_outputs = deepCopyAttr(second_outputs);
//Generate new module
//whole inout generation.
string newModule = "module " + newFileName + "(";
vector<Attribute*> tempAV;
tempAV.insert(tempAV.end(), first_inputs.begin(), first_inputs.end());
tempAV.insert(tempAV.end(), first_outputs.begin(), first_outputs.end());
tempAV.insert(tempAV.end(), second_inputs.begin(), second_inputs.end());
tempAV.insert(tempAV.end(), second_outputs.begin(), second_outputs.end());
//eliminate repeated var
string commonVar = "";
for(auto it = tempAV.begin(); it < tempAV.end(); it++){
Attribute* attr = *it;
string varName = attr->getName();
if(varName == "if01")
int a = 0;
int suffix = 1;
vector<string> variables = Tool::split(commonVar, ';');
while(find(variables.begin(), variables.end(), varName) != variables.end() || isSystemKeyword(varName)){
if(isdigit(varName[varName.length()-1])){
size_t pos = varName.find_last_not_of("0123456789");
if(pos != string::npos) {
size_t numericSuffixStart = pos + 1;
size_t numericSuffixLength = varName.size() - numericSuffixStart;
string numericSuffix = varName.substr(numericSuffixStart, numericSuffixLength);
suffix = stoi(numericSuffix) + 1;
varName = varName.substr(0, pos+1);
string completeSuffix = to_string(suffix);
if(numericSuffix[0] == '0' && numericSuffixLength != 1){
size_t count = numericSuffix.find_first_not_of('0');
count = (count == std::string::npos) ? numericSuffix.length() : count;
string leadingZeros(count, '0');
completeSuffix = leadingZeros + completeSuffix;
}
varName += completeSuffix;
}
}
else{
varName += to_string(suffix);
}
}
attr->setName(varName);
commonVar += varName + ";";
}
//first input and second output interface write
vector<Attribute*> interfaceVar;
interfaceVar.insert(interfaceVar.end(), first_inputs.begin(), first_inputs.end());
interfaceVar.insert(interfaceVar.end(), second_outputs.begin(), second_outputs.end());
bool firstInterfacePin = true;
string interfaceVarStr = "";
for(auto it = interfaceVar.begin(); it < interfaceVar.end(); it++){
Attribute* attr = *it;
if(firstInterfacePin){
firstInterfacePin = false;
interfaceVarStr += attr->getName();
}
else{
interfaceVarStr += ", " + attr->getName();
}
}
newModule += interfaceVarStr;
newModule += ");\n";
newModule += genDecalaration(second_outputs, "inout");
newModule += genDecalaration(first_inputs, "inout");
newModule += genDecalaration(first_outputs, "none");
// newModule += genDecalaration(second_inputs, "none");
//Call first module
int signNum = 1;
string firstModuleName = filename1.substr(0, filename1.find_last_of('.'));
string callFirstModule = "\t" + firstModuleName;
string callInstance = " M" + to_string(signNum++);
while(commonVar.find(callInstance.substr(1, callInstance.size() - 1)) != string::npos)
callInstance = " M" + to_string(signNum++);
string callParams = "(";
bool firstAttr = true;
for(int i = 0; i < first_inputs.size(); i++){
string recentParam = ", ";
string acceptPin = init_first_inputs[i].getName();
string passParam = first_inputs[i]->getName();
if(firstAttr){
recentParam = "";
firstAttr = false;
}
recentParam += "." + acceptPin + "(" + passParam + ")";
callParams += recentParam;
}
for(int i = 0; i < first_outputs.size(); i++){
string recentParam = ", ";
string acceptPin = init_first_outputs[i].getName();
string passParam = first_outputs[i]->getName();
recentParam += "." + acceptPin + "(" + passParam + ")";
callParams += recentParam;
}
callParams += ");\n";
//Note: The result of first call will be added after temp var defination.
//Random connection between first_outputs and second_inputs.
vector<pair<int, int>> first_output_left;
vector<vector<vector<pair<int, int>>*>> second_input_choose;
vector<pair<int, int>> second_input_all;
//initial
string occupyFlag = "";
vector<string> secondOccupyFlagV;
int lenFirstOut = 0;
for(int i = 0; i < init_first_outputs.size(); i++){
Attribute recentAttr = init_first_outputs[i];
int start = recentAttr.getStart();
int end = recentAttr.getEnd();
for(int j = start; j <= end; j++){
//Pair first: passAttr; Pair second: concrect bit on passAttr
first_output_left.push_back(pair<int, int>(i, j));
lenFirstOut++;
occupyFlag += "0";
}
}
//Execute different Strategy
if(strategy == "simple"){ //simple connect
//random choose, second inputs full occupy.
for(int i = 0; i < init_second_inputs.size(); i++){
Attribute recentAttr = init_second_inputs[i];
int start = recentAttr.getStart();
int end = recentAttr.getEnd();
vector<vector<pair<int, int>>*> recentInputAttr;
for(int j = start; j <= end; j++){
vector<pair<int, int>>* recentInputBit = new vector<pair<int, int>>();
int randIndex = getRandomfromClosed(0, lenFirstOut - 1);
occupyFlag[randIndex] = '1';
pair<int, int> recentPass = first_output_left[randIndex];
recentInputBit->push_back(recentPass);
second_input_all.push_back(pair<int, int>(i, j));
recentInputAttr.push_back(recentInputBit);
}
second_input_choose.push_back(recentInputAttr);
}
//check if some pin is hang. If so, choose hang pin in first output and connect it to the random one in second input.
if(occupyFlag.find("0") != string::npos){
for(int i = 0; i < occupyFlag.size(); i++){
char recentC = occupyFlag[i];
if(recentC == '0'){
int randSecondInIndex = getRandomfromClosed(0, second_input_all.size() - 1);
pair<int, int> recentPass = first_output_left[i];
pair<int, int> recentInputPair = second_input_all[randSecondInIndex];
int recentAcceptVar = recentInputPair.first;
int recentAcceptVarBit = recentInputPair.second;
vector<pair<int, int>>* recentInputBit = second_input_choose[recentAcceptVar][recentAcceptVarBit];
recentInputBit->push_back(recentPass);
occupyFlag[i] = '1';
}
}
}
}
else if(strategy == "full"){ //full connect
//random choose, second inputs full occupy.
for(int i = 0; i < init_second_inputs.size(); i++){
Attribute recentAttr = init_second_inputs[i];
int start = recentAttr.getStart();
int end = recentAttr.getEnd();
vector<vector<pair<int, int>>*> recentInputAttr;
string recentAttrOccupy = "";
for(int j = start; j <= end; j++){
vector<pair<int, int>>* recentInputBit = new vector<pair<int, int>>();
// int randIndex = getRandomfromClosed(0, lenFirstOut - 1);
// occupyFlag[randIndex] = '1';
// pair<int, int> recentPass = first_output_left[randIndex];
// recentInputBit->push_back(recentPass);
second_input_all.push_back(pair<int, int>(i, j));
recentInputAttr.push_back(recentInputBit);
recentAttrOccupy += "0";
}
secondOccupyFlagV.push_back(recentAttrOccupy);
second_input_choose.push_back(recentInputAttr);
}
//check if some pin is hang. If so, random choose first and random choose second
//keep checking until all the pins are not hang.
while(occupyFlag.find("0") != string::npos || !oneCheckonV(secondOccupyFlagV)){
int randFirstOutIndex = getRandomfromClosed(0, lenFirstOut - 1);
int randSecondInIndex = getRandomfromClosed(0, second_input_all.size() - 1);
occupyFlag[randFirstOutIndex] = '1';
pair<int, int> recentPass = first_output_left[randFirstOutIndex];
pair<int, int> recentInputPair = second_input_all[randSecondInIndex];
secondOccupyFlagV[recentInputPair.first][recentInputPair.second] = '1';
int recentAcceptVar = recentInputPair.first;
int recentAcceptVarBit = recentInputPair.second;
vector<pair<int, int>>* recentInputBit = second_input_choose[recentAcceptVar][recentAcceptVarBit];
recentInputBit->push_back(recentPass);
}
}
else{ //invalid command: error
error("Error: Tool verilogSeriesCom cannot recognize command " + strategy + ".");
return;
}
//Connect
pair<int, int> lastPair;
string callSecond = "\t" + filename2.substr(0, filename2.find_last_of('.'));
string callSecondInstance = " M" + to_string(signNum++);
while(commonVar.find(callSecondInstance.substr(1, callSecondInstance.size() - 1)) != string::npos)
callSecondInstance = " M" + to_string(signNum++);
string callSecondParams = "(";
firstAttr = true;
vector<string> tempVarDeclare;
for(int i = 0; i < second_input_choose.size(); i++){
string paramItemStr = firstAttr ? "." : ", .";
firstAttr = false;
string calculateStr = "";
string tempVarDeclaration = "";
vector<vector<pair<int, int>>*> recentAcceptAttrPass = second_input_choose[i];
//temp declaration
Attribute recentAcceptAttr = init_second_inputs[i];
string assignorReg = "\t" + recentAcceptAttr.getDataType() + " ";
int endRecentAccept = recentAcceptAttr.getEnd();
int startRecentAccept = recentAcceptAttr.getStart();
string initalScope = endRecentAccept == startRecentAccept ?
"" : "[" + to_string(endRecentAccept) + ":" + to_string(startRecentAccept) + "] ";
string tempVar = "var" + to_string(signNum++);
tempVarDeclaration = assignorReg + initalScope + tempVar + ";\n";
//Assign resual of operation
string recentDataType = recentAcceptAttr.getDataType();
string assignDeclare = recentDataType == "reg" ? "\t" : "\tassign ";
for(int bitIndex = 0; bitIndex < recentAcceptAttrPass.size(); bitIndex++){
vector<pair<int, int>> recenInputBit = *recentAcceptAttrPass[bitIndex];
string targetPinUse = "";
bool innerFirstAttr = true;
string operators = "+-*&|";
string assignBit = initalScope == "" ? "" : "[" + to_string(bitIndex) + "]";
for(auto it = recenInputBit.begin(); it < recenInputBit.end(); it++){
pair<int, int> recentKV = *it;
Attribute* useFirstOutAttr = first_outputs[recentKV.first];
int bit = recentKV.second;
int operateRandIndex = getRandomfromClosed(0, operators.size() - 1);
char chooseOperator = operators[operateRandIndex];
string tempOperator = "";
tempOperator.push_back(chooseOperator);
string plus = innerFirstAttr ? "" : " " + tempOperator + " ";
string useBit = useFirstOutAttr->getStart() == useFirstOutAttr->getEnd() ? "" : "[" + to_string(bit) +"]";
string recentUseItem = useFirstOutAttr->getName() + useBit;