/
AstToRamTranslator.cpp
1226 lines (1043 loc) · 51.5 KB
/
AstToRamTranslator.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
/*
* Souffle - A Datalog Compiler
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved
* Licensed under the Universal Permissive License v 1.0 as shown at:
* - https://opensource.org/licenses/UPL
* - <souffle root>/licenses/SOUFFLE-UPL.txt
*/
/************************************************************************
*
* @file AstToRamTranslator.cpp
*
* Translator from AST to RAM structures.
*
***********************************************************************/
#include "ast2ram/AstToRamTranslator.h"
#include "Global.h"
#include "LogStatement.h"
#include "ast/Aggregator.h"
#include "ast/Argument.h"
#include "ast/Atom.h"
#include "ast/BinaryConstraint.h"
#include "ast/Clause.h"
#include "ast/Constant.h"
#include "ast/Constraint.h"
#include "ast/Counter.h"
#include "ast/Directive.h"
#include "ast/Functor.h"
#include "ast/IntrinsicFunctor.h"
#include "ast/Literal.h"
#include "ast/Negation.h"
#include "ast/NilConstant.h"
#include "ast/Node.h"
#include "ast/NumericConstant.h"
#include "ast/QualifiedName.h"
#include "ast/RecordInit.h"
#include "ast/Relation.h"
#include "ast/StringConstant.h"
#include "ast/SubroutineArgument.h"
#include "ast/TranslationUnit.h"
#include "ast/UnnamedVariable.h"
#include "ast/UserDefinedFunctor.h"
#include "ast/Variable.h"
#include "ast/analysis/AuxArity.h"
#include "ast/analysis/Functor.h"
#include "ast/analysis/IOType.h"
#include "ast/analysis/PolymorphicObjects.h"
#include "ast/analysis/RecursiveClauses.h"
#include "ast/analysis/RelationSchedule.h"
#include "ast/analysis/SCCGraph.h"
#include "ast/analysis/TopologicallySortedSCCGraph.h"
#include "ast/analysis/TypeEnvironment.h"
#include "ast/utility/NodeMapper.h"
#include "ast/utility/SipsMetric.h"
#include "ast/utility/Utils.h"
#include "ast/utility/Visitor.h"
#include "ast2ram/ClauseTranslator.h"
#include "ast2ram/Location.h"
#include "ast2ram/ProvenanceClauseTranslator.h"
#include "ast2ram/ValueIndex.h"
#include "parser/SrcLocation.h"
#include "ram/AutoIncrement.h"
#include "ram/Call.h"
#include "ram/Clear.h"
#include "ram/Condition.h"
#include "ram/Conjunction.h"
#include "ram/Constraint.h"
#include "ram/DebugInfo.h"
#include "ram/EmptinessCheck.h"
#include "ram/ExistenceCheck.h"
#include "ram/Exit.h"
#include "ram/Expression.h"
#include "ram/Extend.h"
#include "ram/Filter.h"
#include "ram/FloatConstant.h"
#include "ram/IO.h"
#include "ram/IntrinsicOperator.h"
#include "ram/LogRelationTimer.h"
#include "ram/LogSize.h"
#include "ram/LogTimer.h"
#include "ram/Loop.h"
#include "ram/Negation.h"
#include "ram/PackRecord.h"
#include "ram/Parallel.h"
#include "ram/Program.h"
#include "ram/Project.h"
#include "ram/ProvenanceExistenceCheck.h"
#include "ram/Query.h"
#include "ram/Relation.h"
#include "ram/RelationSize.h"
#include "ram/Scan.h"
#include "ram/Sequence.h"
#include "ram/SignedConstant.h"
#include "ram/Statement.h"
#include "ram/SubroutineArgument.h"
#include "ram/SubroutineReturn.h"
#include "ram/Swap.h"
#include "ram/TranslationUnit.h"
#include "ram/TupleElement.h"
#include "ram/UndefValue.h"
#include "ram/UnsignedConstant.h"
#include "ram/UserDefinedOperator.h"
#include "ram/utility/Utils.h"
#include "reports/DebugReport.h"
#include "reports/ErrorReport.h"
#include "souffle/BinaryConstraintOps.h"
#include "souffle/SymbolTable.h"
#include "souffle/TypeAttribute.h"
#include "souffle/utility/FunctionalUtil.h"
#include "souffle/utility/MiscUtil.h"
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstddef>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <vector>
namespace souffle::ast2ram {
AstToRamTranslator::AstToRamTranslator() = default;
AstToRamTranslator::~AstToRamTranslator() = default;
/** append statement to a list of statements */
inline void appendStmt(VecOwn<ram::Statement>& stmtList, Own<ram::Statement> stmt) {
if (stmt) {
stmtList.push_back(std::move(stmt));
}
}
Own<ram::TupleElement> AstToRamTranslator::makeRamTupleElement(const Location& loc) {
return mk<ram::TupleElement>(loc.identifier, loc.element);
}
size_t AstToRamTranslator::getEvaluationArity(const ast::Atom* atom) const {
if (atom->getQualifiedName().toString().find("@delta_") == 0) {
const ast::QualifiedName& originalRel =
ast::QualifiedName(atom->getQualifiedName().toString().substr(7));
return auxArityAnalysis->getArity(getRelation(*program, originalRel));
} else if (atom->getQualifiedName().toString().find("@new_") == 0) {
const ast::QualifiedName& originalRel =
ast::QualifiedName(atom->getQualifiedName().toString().substr(5));
return auxArityAnalysis->getArity(getRelation(*program, originalRel));
} else if (atom->getQualifiedName().toString().find("@info_") == 0) {
return 0;
} else {
return auxArityAnalysis->getArity(atom);
}
}
std::vector<std::map<std::string, std::string>> AstToRamTranslator::getInputDirectives(
const ast::Relation* rel) {
std::vector<std::map<std::string, std::string>> inputDirectives;
for (const auto* load : program->getDirectives()) {
if (load->getQualifiedName() != rel->getQualifiedName() ||
load->getType() != ast::DirectiveType::input) {
continue;
}
std::map<std::string, std::string> directives;
for (const auto& currentPair : load->getParameters()) {
directives.insert(std::make_pair(currentPair.first, unescape(currentPair.second)));
}
inputDirectives.push_back(directives);
}
if (inputDirectives.empty()) {
inputDirectives.emplace_back();
}
return inputDirectives;
}
std::vector<std::map<std::string, std::string>> AstToRamTranslator::getOutputDirectives(
const ast::Relation* rel) {
std::vector<std::map<std::string, std::string>> outputDirectives;
for (const auto* store : program->getDirectives()) {
if (store->getQualifiedName() != rel->getQualifiedName() ||
(store->getType() != ast::DirectiveType::printsize &&
store->getType() != ast::DirectiveType::output)) {
continue;
}
std::map<std::string, std::string> directives;
for (const auto& currentPair : store->getParameters()) {
directives.insert(std::make_pair(currentPair.first, unescape(currentPair.second)));
}
outputDirectives.push_back(directives);
}
if (outputDirectives.empty()) {
outputDirectives.emplace_back();
}
return outputDirectives;
}
std::string AstToRamTranslator::translateRelation(const ast::Atom* atom) {
return getRelationName(atom->getQualifiedName());
}
std::string AstToRamTranslator::translateRelation(
const ast::Relation* rel, const std::string relationNamePrefix) {
return relationNamePrefix + getRelationName(rel->getQualifiedName());
}
std::string AstToRamTranslator::translateDeltaRelation(const ast::Relation* rel) {
return translateRelation(rel, "@delta_");
}
std::string AstToRamTranslator::translateNewRelation(const ast::Relation* rel) {
return translateRelation(rel, "@new_");
}
Own<ram::Expression> AstToRamTranslator::translateValue(const ast::Argument* arg, const ValueIndex& index) {
if (arg == nullptr) {
return nullptr;
}
class ValueTranslator : public ast::Visitor<Own<ram::Expression>> {
AstToRamTranslator& translator;
const ValueIndex& index;
const ast::analysis::PolymorphicObjectsAnalysis* polyAnalysis;
public:
ValueTranslator(AstToRamTranslator& translator, const ValueIndex& index,
const ast::analysis::PolymorphicObjectsAnalysis* polyAnalysis)
: translator(translator), index(index), polyAnalysis(polyAnalysis) {}
Own<ram::Expression> visitVariable(const ast::Variable& var) override {
if (!index.isDefined(var)) fatal("variable `%s` is not grounded", var);
return makeRamTupleElement(index.getDefinitionPoint(var));
}
Own<ram::Expression> visitUnnamedVariable(const ast::UnnamedVariable&) override {
return mk<ram::UndefValue>();
}
Own<ram::Expression> visitNumericConstant(const ast::NumericConstant& c) override {
assert(!polyAnalysis->hasInvalidType(&c) && "constant should have valid type");
switch (polyAnalysis->getOverloadedType(&c)) {
case ast::NumericConstant::Type::Int:
return mk<ram::SignedConstant>(RamSignedFromString(c.getConstant(), nullptr, 0));
case ast::NumericConstant::Type::Uint:
return mk<ram::UnsignedConstant>(RamUnsignedFromString(c.getConstant(), nullptr, 0));
case ast::NumericConstant::Type::Float:
return mk<ram::FloatConstant>(RamFloatFromString(c.getConstant()));
}
fatal("unexpected numeric constant type");
}
Own<ram::Expression> visitStringConstant(const ast::StringConstant& c) override {
return mk<ram::SignedConstant>(translator.getSymbolTable().lookup(c.getConstant()));
}
Own<ram::Expression> visitNilConstant(const ast::NilConstant&) override {
return mk<ram::SignedConstant>(0);
}
Own<ram::Expression> visitIntrinsicFunctor(const ast::IntrinsicFunctor& inf) override {
VecOwn<ram::Expression> values;
for (const auto& cur : inf.getArguments()) {
values.push_back(translator.translateValue(cur, index));
}
if (ast::analysis::FunctorAnalysis::isMultiResult(inf)) {
return translator.makeRamTupleElement(index.getGeneratorLoc(inf));
} else {
return mk<ram::IntrinsicOperator>(inf.getFunctionOp().value(), std::move(values));
}
}
Own<ram::Expression> visitUserDefinedFunctor(const ast::UserDefinedFunctor& udf) override {
VecOwn<ram::Expression> values;
for (const auto& cur : udf.getArguments()) {
values.push_back(translator.translateValue(cur, index));
}
auto returnType = translator.functorAnalysis->getReturnType(&udf);
auto argTypes = translator.functorAnalysis->getArgTypes(udf);
return mk<ram::UserDefinedOperator>(udf.getName(), argTypes, returnType,
translator.functorAnalysis->isStateful(&udf), std::move(values));
}
Own<ram::Expression> visitCounter(const ast::Counter&) override {
return mk<ram::AutoIncrement>();
}
Own<ram::Expression> visitRecordInit(const ast::RecordInit& init) override {
VecOwn<ram::Expression> values;
for (const auto& cur : init.getArguments()) {
values.push_back(translator.translateValue(cur, index));
}
return mk<ram::PackRecord>(std::move(values));
}
Own<ram::Expression> visitAggregator(const ast::Aggregator& agg) override {
// here we look up the location the aggregation result gets bound
return translator.makeRamTupleElement(index.getGeneratorLoc(agg));
}
Own<ram::Expression> visitSubroutineArgument(const ast::SubroutineArgument& subArg) override {
return mk<ram::SubroutineArgument>(subArg.getNumber());
}
};
return ValueTranslator(*this, index, polyAnalysis)(*arg);
}
SymbolTable& AstToRamTranslator::getSymbolTable() {
static SymbolTable symbolTable;
return symbolTable;
}
Own<ram::Condition> AstToRamTranslator::translateConstraint(
const ast::Literal* lit, const ValueIndex& index) {
class ConstraintTranslator : public ast::Visitor<Own<ram::Condition>> {
AstToRamTranslator& translator;
const ValueIndex& index;
public:
ConstraintTranslator(AstToRamTranslator& translator, const ValueIndex& index)
: translator(translator), index(index) {}
/** for atoms */
Own<ram::Condition> visitAtom(const ast::Atom&) override {
return nullptr; // covered already within the scan/lookup generation step
}
/** for binary relations */
Own<ram::Condition> visitBinaryConstraint(const ast::BinaryConstraint& binRel) override {
auto valLHS = translator.translateValue(binRel.getLHS(), index);
auto valRHS = translator.translateValue(binRel.getRHS(), index);
return mk<ram::Constraint>(binRel.getOperator(), std::move(valLHS), std::move(valRHS));
}
/** for provenance negation */
Own<ram::Condition> visitProvenanceNegation(const ast::ProvenanceNegation& neg) override {
const auto* atom = neg.getAtom();
size_t auxiliaryArity = translator.getEvaluationArity(atom);
assert(auxiliaryArity <= atom->getArity() && "auxiliary arity out of bounds");
size_t arity = atom->getArity() - auxiliaryArity;
VecOwn<ram::Expression> values;
auto args = atom->getArguments();
for (size_t i = 0; i < arity; i++) {
values.push_back(translator.translateValue(args[i], index));
}
// we don't care about the provenance columns when doing the existence check
if (Global::config().has("provenance")) {
// undefined value for rule number
values.push_back(mk<ram::UndefValue>());
// add the height annotation for provenanceNotExists
for (size_t height = 1; height < auxiliaryArity; height++) {
values.push_back(translator.translateValue(args[arity + height], index));
}
}
return mk<ram::Negation>(
mk<ram::ProvenanceExistenceCheck>(translator.translateRelation(atom), std::move(values)));
}
/** for negations */
Own<ram::Condition> visitNegation(const ast::Negation& neg) override {
const auto* atom = neg.getAtom();
size_t auxiliaryArity = translator.getEvaluationArity(atom);
assert(auxiliaryArity <= atom->getArity() && "auxiliary arity out of bounds");
size_t arity = atom->getArity() - auxiliaryArity;
if (arity == 0) {
// for a nullary, negation is a simple emptiness check
return mk<ram::EmptinessCheck>(translator.translateRelation(atom));
}
// else, we construct the atom and create a negation
VecOwn<ram::Expression> values;
auto args = atom->getArguments();
for (size_t i = 0; i < arity; i++) {
values.push_back(translator.translateValue(args[i], index));
}
for (size_t i = 0; i < auxiliaryArity; i++) {
values.push_back(mk<ram::UndefValue>());
}
return mk<ram::Negation>(
mk<ram::ExistenceCheck>(translator.translateRelation(atom), std::move(values)));
}
};
return ConstraintTranslator(*this, index)(*lit);
}
RamDomain AstToRamTranslator::getConstantRamRepresentation(const ast::Constant& constant) {
if (auto strConstant = dynamic_cast<const ast::StringConstant*>(&constant)) {
return getSymbolTable().lookup(strConstant->getConstant());
} else if (isA<ast::NilConstant>(&constant)) {
return 0;
} else if (auto* numConstant = dynamic_cast<const ast::NumericConstant*>(&constant)) {
assert(!polyAnalysis->hasInvalidType(numConstant) && "constant should have valid type");
switch (polyAnalysis->getOverloadedType(numConstant)) {
case ast::NumericConstant::Type::Int:
return RamSignedFromString(numConstant->getConstant(), nullptr, 0);
case ast::NumericConstant::Type::Uint:
return RamUnsignedFromString(numConstant->getConstant(), nullptr, 0);
case ast::NumericConstant::Type::Float: return RamFloatFromString(numConstant->getConstant());
}
}
fatal("unaccounted-for constant");
}
Own<ram::Expression> AstToRamTranslator::translateConstant(ast::Constant const& c) {
auto const rawConstant = getConstantRamRepresentation(c);
if (auto* const c_num = dynamic_cast<const ast::NumericConstant*>(&c)) {
switch (polyAnalysis->getOverloadedType(c_num)) {
case ast::NumericConstant::Type::Int: return mk<ram::SignedConstant>(rawConstant);
case ast::NumericConstant::Type::Uint: return mk<ram::UnsignedConstant>(rawConstant);
case ast::NumericConstant::Type::Float: return mk<ram::FloatConstant>(rawConstant);
}
}
return mk<ram::SignedConstant>(rawConstant);
}
/** generate RAM code for a non-recursive relation */
Own<ram::Statement> AstToRamTranslator::translateNonRecursiveRelation(
const ast::Relation& rel, const ast::analysis::RecursiveClausesAnalysis* recursiveClauses) {
/* start with an empty sequence */
VecOwn<ram::Statement> res;
std::string relName = translateRelation(&rel);
/* iterate over all clauses that belong to the relation */
for (ast::Clause* clause : getClauses(*program, rel)) {
// skip recursive rules
if (recursiveClauses->recursive(clause)) {
continue;
}
// translate clause
Own<ram::Statement> rule = ClauseTranslator(*this).translateClause(*clause, *clause);
// add logging
if (Global::config().has("profile")) {
const std::string& relationName = toString(rel.getQualifiedName());
const SrcLocation& srcLocation = clause->getSrcLoc();
const std::string clauseText = stringify(toString(*clause));
const std::string logTimerStatement =
LogStatement::tNonrecursiveRule(relationName, srcLocation, clauseText);
const std::string logSizeStatement =
LogStatement::nNonrecursiveRule(relationName, srcLocation, clauseText);
rule = mk<ram::LogRelationTimer>(std::move(rule), logTimerStatement, relName);
}
// add debug info
std::ostringstream ds;
ds << toString(*clause) << "\nin file ";
ds << clause->getSrcLoc();
rule = mk<ram::DebugInfo>(std::move(rule), ds.str());
// add rule to result
appendStmt(res, std::move(rule));
}
// add logging for entire relation
if (Global::config().has("profile")) {
const std::string& relationName = toString(rel.getQualifiedName());
const SrcLocation& srcLocation = rel.getSrcLoc();
const std::string logSizeStatement = LogStatement::nNonrecursiveRelation(relationName, srcLocation);
// add timer if we did any work
if (!res.empty()) {
const std::string logTimerStatement =
LogStatement::tNonrecursiveRelation(relationName, srcLocation);
auto newStmt =
mk<ram::LogRelationTimer>(mk<ram::Sequence>(std::move(res)), logTimerStatement, relName);
res.clear();
appendStmt(res, std::move(newStmt));
} else {
// add table size printer
appendStmt(res, mk<ram::LogSize>(relName, logSizeStatement));
}
}
// done
return mk<ram::Sequence>(std::move(res));
}
/**
* A utility function assigning names to unnamed variables such that enclosing
* constructs may be cloned without losing the variable-identity.
*/
void AstToRamTranslator::nameUnnamedVariables(ast::Clause* clause) {
// the node mapper conducting the actual renaming
struct Instantiator : public ast::NodeMapper {
mutable int counter = 0;
Instantiator() = default;
Own<ast::Node> operator()(Own<ast::Node> node) const override {
// apply recursive
node->apply(*this);
// replace unknown variables
if (dynamic_cast<ast::UnnamedVariable*>(node.get()) != nullptr) {
auto name = " _unnamed_var" + toString(++counter);
return mk<ast::Variable>(name);
}
// otherwise nothing
return node;
}
};
// name all variables in the atoms
Instantiator init;
for (auto& atom : ast::getBodyLiterals<ast::Atom>(*clause)) {
atom->apply(init);
}
}
/** converts the given relation identifier into a relation name */
std::string AstToRamTranslator::getRelationName(const ast::QualifiedName& id) {
return toString(join(id.getQualifiers(), "."));
}
/** generate RAM code for recursive relations in a strongly-connected component */
Own<ram::Statement> AstToRamTranslator::translateRecursiveRelation(const std::set<const ast::Relation*>& scc,
const ast::analysis::RecursiveClausesAnalysis* recursiveClauses) {
// initialize sections
VecOwn<ram::Statement> preamble;
VecOwn<ram::Statement> updateTable;
VecOwn<ram::Statement> postamble;
auto genMerge = [&](const ast::Relation* rel, const std::string& destRel,
const std::string& srcRel) -> Own<ram::Statement> {
VecOwn<ram::Expression> values;
if (rel->getArity() == 0) {
return mk<ram::Query>(mk<ram::Filter>(mk<ram::Negation>(mk<ram::EmptinessCheck>(srcRel)),
mk<ram::Project>(destRel, std::move(values))));
}
for (std::size_t i = 0; i < rel->getArity(); i++) {
values.push_back(mk<ram::TupleElement>(0, i));
}
auto stmt = mk<ram::Query>(mk<ram::Scan>(srcRel, 0, mk<ram::Project>(destRel, std::move(values))));
if (rel->getRepresentation() == RelationRepresentation::EQREL) {
return mk<ram::Sequence>(mk<ram::Extend>(destRel, srcRel), std::move(stmt));
}
return stmt;
};
// --- create preamble ---
/* Compute non-recursive clauses for relations in scc and push
the results in their delta tables. */
for (const ast::Relation* rel : scc) {
/* create update statements for fixpoint (even iteration) */
Own<ram::Statement> updateRelTable =
mk<ram::Sequence>(genMerge(rel, translateRelation(rel), translateNewRelation(rel)),
mk<ram::Swap>(translateDeltaRelation(rel), translateNewRelation(rel)),
mk<ram::Clear>(translateNewRelation(rel)));
/* measure update time for each relation */
if (Global::config().has("profile")) {
updateRelTable = mk<ram::LogRelationTimer>(std::move(updateRelTable),
LogStatement::cRecursiveRelation(toString(rel->getQualifiedName()), rel->getSrcLoc()),
translateNewRelation(rel));
}
/* drop temporary tables after recursion */
appendStmt(postamble, mk<ram::Clear>(translateDeltaRelation(rel)));
appendStmt(postamble, mk<ram::Clear>(translateNewRelation(rel)));
/* Generate code for non-recursive part of relation */
/* Generate merge operation for temp tables */
appendStmt(preamble, translateNonRecursiveRelation(*rel, recursiveClauses));
appendStmt(preamble, genMerge(rel, translateDeltaRelation(rel), translateRelation(rel)));
/* Add update operations of relations to parallel statements */
appendStmt(updateTable, std::move(updateRelTable));
}
// --- build main loop ---
VecOwn<ram::Statement> loopSeq;
// create a utility to check SCC membership
auto isInSameSCC = [&](const ast::Relation* rel) {
return std::find(scc.begin(), scc.end(), rel) != scc.end();
};
/* Compute temp for the current tables */
for (const ast::Relation* rel : scc) {
VecOwn<ram::Statement> loopRelSeq;
/* Find clauses for relation rel */
for (const auto& cl : getClauses(*program, *rel)) {
// skip non-recursive clauses
if (!recursiveClauses->recursive(cl)) {
continue;
}
// each recursive rule results in several operations
int version = 0;
const auto& atoms = ast::getBodyLiterals<ast::Atom>(*cl);
for (size_t j = 0; j < atoms.size(); ++j) {
const ast::Atom* atom = atoms[j];
const ast::Relation* atomRelation = getAtomRelation(atom, program);
// only interested in atoms within the same SCC
if (!isInSameSCC(atomRelation)) {
continue;
}
// modify the processed rule to use delta relation and write to new relation
Own<ast::Clause> r1(cl->clone());
r1->getHead()->setQualifiedName(translateNewRelation(rel));
ast::getBodyLiterals<ast::Atom>(*r1)[j]->setQualifiedName(
translateDeltaRelation(atomRelation));
if (Global::config().has("provenance")) {
r1->addToBody(mk<ast::ProvenanceNegation>(souffle::clone(cl->getHead())));
} else {
if (r1->getHead()->getArity() > 0) {
r1->addToBody(mk<ast::Negation>(souffle::clone(cl->getHead())));
}
}
// replace wildcards with variables (reduces indices when wildcards are used in recursive
// atoms)
nameUnnamedVariables(r1.get());
// reduce R to P ...
for (size_t k = j + 1; k < atoms.size(); k++) {
if (isInSameSCC(getAtomRelation(atoms[k], program))) {
auto cur = souffle::clone(ast::getBodyLiterals<ast::Atom>(*r1)[k]);
cur->setQualifiedName(translateDeltaRelation(getAtomRelation(atoms[k], program)));
r1->addToBody(mk<ast::Negation>(std::move(cur)));
}
}
Own<ram::Statement> rule = ClauseTranslator(*this).translateClause(*r1, *cl, version);
/* add logging */
if (Global::config().has("profile")) {
const std::string& relationName = toString(rel->getQualifiedName());
const SrcLocation& srcLocation = cl->getSrcLoc();
const std::string clauseText = stringify(toString(*cl));
const std::string logTimerStatement =
LogStatement::tRecursiveRule(relationName, version, srcLocation, clauseText);
const std::string logSizeStatement =
LogStatement::nRecursiveRule(relationName, version, srcLocation, clauseText);
rule = mk<ram::LogRelationTimer>(
std::move(rule), logTimerStatement, translateNewRelation(rel));
}
// add debug info
std::ostringstream ds;
ds << toString(*cl) << "\nin file ";
ds << cl->getSrcLoc();
rule = mk<ram::DebugInfo>(std::move(rule), ds.str());
// add to loop body
appendStmt(loopRelSeq, std::move(rule));
// increment version counter
version++;
}
if (cl->getExecutionPlan() != nullptr) {
// ensure that all required versions have been created, as expected
int maxVersion = -1;
for (auto const& cur : cl->getExecutionPlan()->getOrders()) {
maxVersion = std::max(cur.first, maxVersion);
}
assert(version > maxVersion && "missing clause versions");
}
}
// if there was no rule, continue
if (loopRelSeq.size() == 0) {
continue;
}
// label all versions
if (Global::config().has("profile")) {
const std::string& relationName = toString(rel->getQualifiedName());
const SrcLocation& srcLocation = rel->getSrcLoc();
const std::string logTimerStatement = LogStatement::tRecursiveRelation(relationName, srcLocation);
const std::string logSizeStatement = LogStatement::nRecursiveRelation(relationName, srcLocation);
auto newStmt = mk<ram::LogRelationTimer>(
mk<ram::Sequence>(std::move(loopRelSeq)), logTimerStatement, translateNewRelation(rel));
loopRelSeq.clear();
appendStmt(loopRelSeq, std::move(newStmt));
}
/* add rule computations of a relation to parallel statement */
appendStmt(loopSeq, mk<ram::Sequence>(std::move(loopRelSeq)));
}
auto loop = mk<ram::Parallel>(std::move(loopSeq));
/* construct exit conditions for odd and even iteration */
auto addCondition = [](Own<ram::Condition>& cond, Own<ram::Condition> clause) {
cond = ((cond) ? mk<ram::Conjunction>(std::move(cond), std::move(clause)) : std::move(clause));
};
Own<ram::Condition> exitCond;
VecOwn<ram::Statement> exitStmts;
for (const ast::Relation* rel : scc) {
addCondition(exitCond, mk<ram::EmptinessCheck>(translateNewRelation(rel)));
if (ioType->isLimitSize(rel)) {
Own<ram::Condition> limit =
mk<ram::Constraint>(BinaryConstraintOp::GE, mk<ram::RelationSize>(translateRelation(rel)),
mk<ram::SignedConstant>(ioType->getLimitSize(rel)));
appendStmt(exitStmts, mk<ram::Exit>(std::move(limit)));
}
}
/* construct fixpoint loop */
VecOwn<ram::Statement> res;
if (preamble.size() > 0) {
appendStmt(res, mk<ram::Sequence>(std::move(preamble)));
}
if (!loop->getStatements().empty() && exitCond && updateTable.size() > 0) {
appendStmt(res,
mk<ram::Loop>(mk<ram::Sequence>(std::move(loop), mk<ram::Exit>(std::move(exitCond)),
mk<ram::Sequence>(std::move(exitStmts)), mk<ram::Sequence>(std::move(updateTable)))));
}
if (postamble.size() > 0) {
appendStmt(res, mk<ram::Sequence>(std::move(postamble)));
}
if (res.size() > 0) {
return mk<ram::Sequence>(std::move(res));
}
fatal("Not Implemented");
}
/** make a subroutine to search for subproofs */
Own<ram::Statement> AstToRamTranslator::makeSubproofSubroutine(const ast::Clause& clause) {
auto intermediateClause = mk<ast::Clause>(souffle::clone(clause.getHead()));
// create a clone where all the constraints are moved to the end
for (auto bodyLit : clause.getBodyLiterals()) {
// first add all the things that are not constraints
if (!isA<ast::Constraint>(bodyLit)) {
intermediateClause->addToBody(souffle::clone(bodyLit));
}
}
// now add all constraints
for (auto bodyLit : ast::getBodyLiterals<ast::Constraint>(clause)) {
intermediateClause->addToBody(souffle::clone(bodyLit));
}
// name unnamed variables
nameUnnamedVariables(intermediateClause.get());
// add constraint for each argument in head of atom
ast::Atom* head = intermediateClause->getHead();
size_t auxiliaryArity = auxArityAnalysis->getArity(head);
auto args = head->getArguments();
for (size_t i = 0; i < head->getArity() - auxiliaryArity; i++) {
auto arg = args[i];
if (auto var = dynamic_cast<ast::Variable*>(arg)) {
// FIXME: float equiv (`FEQ`)
intermediateClause->addToBody(mk<ast::BinaryConstraint>(
BinaryConstraintOp::EQ, souffle::clone(var), mk<ast::SubroutineArgument>(i)));
} else if (auto func = dynamic_cast<ast::Functor*>(arg)) {
TypeAttribute returnType = functorAnalysis->getReturnType(func);
auto opEq = returnType == TypeAttribute::Float ? BinaryConstraintOp::FEQ : BinaryConstraintOp::EQ;
intermediateClause->addToBody(
mk<ast::BinaryConstraint>(opEq, souffle::clone(func), mk<ast::SubroutineArgument>(i)));
} else if (auto rec = dynamic_cast<ast::RecordInit*>(arg)) {
intermediateClause->addToBody(mk<ast::BinaryConstraint>(
BinaryConstraintOp::EQ, souffle::clone(rec), mk<ast::SubroutineArgument>(i)));
}
}
// index of level argument in argument list
size_t levelIndex = head->getArguments().size() - auxiliaryArity;
// add level constraints, i.e., that each body literal has height less than that of the head atom
const auto& bodyLiterals = intermediateClause->getBodyLiterals();
for (auto lit : bodyLiterals) {
if (auto atom = dynamic_cast<ast::Atom*>(lit)) {
auto arity = atom->getArity();
auto atomArgs = atom->getArguments();
// arity - 1 is the level number in body atoms
intermediateClause->addToBody(mk<ast::BinaryConstraint>(BinaryConstraintOp::LT,
souffle::clone(atomArgs[arity - 1]), mk<ast::SubroutineArgument>(levelIndex)));
}
}
return ProvenanceClauseTranslator(*this).translateClause(*intermediateClause, clause);
}
/** make a subroutine to search for subproofs for the non-existence of a tuple */
Own<ram::Statement> AstToRamTranslator::makeNegationSubproofSubroutine(const ast::Clause& clause) {
// TODO (taipan-snake): Currently we only deal with atoms (no constraints or negations or aggregates
// or anything else...)
//
// The resulting subroutine looks something like this:
// IF (arg(0), arg(1), _, _) IN rel_1:
// return 1
// IF (arg(0), arg(1), _ ,_) NOT IN rel_1:
// return 0
// ...
// clone clause for mutation, rearranging constraints to be at the end
auto clauseReplacedAggregates = mk<ast::Clause>(souffle::clone(clause.getHead()));
// create a clone where all the constraints are moved to the end
for (auto bodyLit : clause.getBodyLiterals()) {
// first add all the things that are not constraints
if (!isA<ast::Constraint>(bodyLit)) {
clauseReplacedAggregates->addToBody(souffle::clone(bodyLit));
}
}
// now add all constraints
for (auto bodyLit : ast::getBodyLiterals<ast::Constraint>(clause)) {
clauseReplacedAggregates->addToBody(souffle::clone(bodyLit));
}
int aggNumber = 0;
struct AggregatesToVariables : public ast::NodeMapper {
int& aggNumber;
AggregatesToVariables(int& aggNumber) : aggNumber(aggNumber) {}
Own<ast::Node> operator()(Own<ast::Node> node) const override {
if (dynamic_cast<ast::Aggregator*>(node.get()) != nullptr) {
return mk<ast::Variable>("agg_" + std::to_string(aggNumber++));
}
node->apply(*this);
return node;
}
};
AggregatesToVariables aggToVar(aggNumber);
clauseReplacedAggregates->apply(aggToVar);
// build a vector of unique variables
std::vector<const ast::Variable*> uniqueVariables;
visitDepthFirst(*clauseReplacedAggregates, [&](const ast::Variable& var) {
if (var.getName().find("@level_num") == std::string::npos) {
// use find_if since uniqueVariables stores pointers, and we need to dereference the pointer to
// check equality
if (std::find_if(uniqueVariables.begin(), uniqueVariables.end(),
[&](const ast::Variable* v) { return *v == var; }) == uniqueVariables.end()) {
uniqueVariables.push_back(&var);
}
}
});
// a mapper to replace variables with subroutine arguments
struct VariablesToArguments : public ast::NodeMapper {
const std::vector<const ast::Variable*>& uniqueVariables;
VariablesToArguments(const std::vector<const ast::Variable*>& uniqueVariables)
: uniqueVariables(uniqueVariables) {}
Own<ast::Node> operator()(Own<ast::Node> node) const override {
// replace unknown variables
if (auto varPtr = dynamic_cast<const ast::Variable*>(node.get())) {
if (varPtr->getName().find("@level_num") == std::string::npos) {
size_t argNum = std::find_if(uniqueVariables.begin(), uniqueVariables.end(),
[&](const ast::Variable* v) { return *v == *varPtr; }) -
uniqueVariables.begin();
return mk<ast::SubroutineArgument>(argNum);
} else {
return mk<ast::UnnamedVariable>();
}
}
// apply recursive
node->apply(*this);
// otherwise nothing
return node;
}
};
// the structure of this subroutine is a sequence where each nested statement is a search in each
// relation
VecOwn<ram::Statement> searchSequence;
// make a copy so that when we mutate clause, pointers to objects in newClause are not affected
auto newClause = souffle::clone(clauseReplacedAggregates);
// go through each body atom and create a return
size_t litNumber = 0;
for (const auto& lit : newClause->getBodyLiterals()) {
if (auto atom = dynamic_cast<ast::Atom*>(lit)) {
size_t auxiliaryArity = auxArityAnalysis->getArity(atom);
auto relName = translateRelation(atom);
// construct a query
VecOwn<ram::Expression> query;
// translate variables to subroutine arguments
VariablesToArguments varsToArgs(uniqueVariables);
atom->apply(varsToArgs);
auto atomArgs = atom->getArguments();
// add each value (subroutine argument) to the search query
for (size_t i = 0; i < atom->getArity() - auxiliaryArity; i++) {
auto arg = atomArgs[i];
query.push_back(translateValue(arg, ValueIndex()));
}
// fill up query with nullptrs for the provenance columns
for (size_t i = 0; i < auxiliaryArity; i++) {
query.push_back(mk<ram::UndefValue>());
}
// ensure the length of query tuple is correct
assert(query.size() == atom->getArity() && "wrong query tuple size");
// create existence checks to check if the tuple exists or not
auto existenceCheck = mk<ram::ExistenceCheck>(relName, std::move(query));
auto negativeExistenceCheck = mk<ram::Negation>(souffle::clone(existenceCheck));
// return true if the tuple exists
VecOwn<ram::Expression> returnTrue;
returnTrue.push_back(mk<ram::SignedConstant>(1));
// return false if the tuple exists
VecOwn<ram::Expression> returnFalse;
returnFalse.push_back(mk<ram::SignedConstant>(0));
// create a ram::Query to return true/false
appendStmt(searchSequence, mk<ram::Query>(mk<ram::Filter>(std::move(existenceCheck),
mk<ram::SubroutineReturn>(std::move(returnTrue)))));
appendStmt(searchSequence, mk<ram::Query>(mk<ram::Filter>(std::move(negativeExistenceCheck),
mk<ram::SubroutineReturn>(std::move(returnFalse)))));
} else if (auto neg = dynamic_cast<ast::Negation*>(lit)) {
auto atom = neg->getAtom();
size_t auxiliaryArity = auxArityAnalysis->getArity(atom);
auto relName = translateRelation(atom);
// construct a query
VecOwn<ram::Expression> query;
// translate variables to subroutine arguments
VariablesToArguments varsToArgs(uniqueVariables);
atom->apply(varsToArgs);
auto atomArgs = atom->getArguments();
// add each value (subroutine argument) to the search query
for (size_t i = 0; i < atom->getArity() - auxiliaryArity; i++) {
auto arg = atomArgs[i];
query.push_back(translateValue(arg, ValueIndex()));
}
// fill up query with nullptrs for the provenance columns
for (size_t i = 0; i < auxiliaryArity; i++) {
query.push_back(mk<ram::UndefValue>());
}
// ensure the length of query tuple is correct
assert(query.size() == atom->getArity() && "wrong query tuple size");
// create existence checks to check if the tuple exists or not
auto existenceCheck = mk<ram::ExistenceCheck>(relName, std::move(query));
auto negativeExistenceCheck = mk<ram::Negation>(souffle::clone(existenceCheck));
// return true if the tuple exists
VecOwn<ram::Expression> returnTrue;
returnTrue.push_back(mk<ram::SignedConstant>(1));
// return false if the tuple exists
VecOwn<ram::Expression> returnFalse;
returnFalse.push_back(mk<ram::SignedConstant>(0));
// create a ram::Query to return true/false
appendStmt(searchSequence, mk<ram::Query>(mk<ram::Filter>(std::move(existenceCheck),
mk<ram::SubroutineReturn>(std::move(returnFalse)))));
appendStmt(searchSequence, mk<ram::Query>(mk<ram::Filter>(std::move(negativeExistenceCheck),
mk<ram::SubroutineReturn>(std::move(returnTrue)))));
} else if (auto con = dynamic_cast<ast::Constraint*>(lit)) {
VariablesToArguments varsToArgs(uniqueVariables);
con->apply(varsToArgs);
// translate to a ram::Condition
auto condition = translateConstraint(con, ValueIndex());
auto negativeCondition = mk<ram::Negation>(souffle::clone(condition));
// create a return true value
VecOwn<ram::Expression> returnTrue;
returnTrue.push_back(mk<ram::SignedConstant>(1));