-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathhqir.d
More file actions
7335 lines (6554 loc) · 206 KB
/
hqir.d
File metadata and controls
7335 lines (6554 loc) · 206 KB
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
import core.exception: AssertError;
import std.conv: ConvOverflowException, text, to;
import std.stdio: File, stderr;
import std.array: Appender, appender, array, join;
import std.string: endsWith;
import std.format: format;
import std.functional: partial;
import std.algorithm: map, filter, canFind, count, all, any, fold;
import std.range: iota, zip, repeat;
import std.utf: byCodeUnit;
import std.bigint: BigInt, toDecimalString;
import std.traits: EnumMembers;
import std.algorithm.mutation: swap, reverse;
import std.math: frexp, isFinite;
import std.meta: AliasSeq;
import util.maybe;
import ast_sem = ast.semantic_;
import ast_exp = ast.expression;
import ast_ty = ast.type;
import ast_decl = ast.declaration;
import ast_scope = ast.scope_;
import ast_lex = ast.lexer;
import ast_conv = ast.conversion;
import ast_low = ast.lowerings;
import ast.lexer: Tok, TokenType;
import ast.expression: Id, Expression, UnaryExp, BinaryExp;
import ast.semantic_: typeForDecl;
import ast.reverse: knownLength;
mixin("alias ast_ty_Nt = ast_ty.\u2115t;");
mixin("alias ast_ty_Zt = ast_ty.\u2124t;");
mixin("alias ast_ty_Qt = ast_ty.\u211at;");
mixin("alias ast_ty_R = ast_ty.\u211d;");
mixin("alias ast_ty_C = ast_ty.\u2102;");
mixin("alias ast_ty_NumericType_Nt = ast_ty.NumericType.\u2115t;");
mixin("alias ast_ty_NumericType_Zt = ast_ty.NumericType.\u2124t;");
mixin("alias ast_ty_NumericType_Qt = ast_ty.NumericType.\u211at;");
mixin("alias ast_ty_NumericType_R = ast_ty.NumericType.\u211d;");
mixin("alias ast_ty_NumericType_C = ast_ty.NumericType.\u2102;");
mixin("alias ast_conv_ZtoFixedConversion = ast_conv.\u2124toFixedConversion;");
mixin("alias ast_conv_UintToNConversion = ast_conv.UintTo\u2115Conversion;");
mixin("alias ast_conv_IntToZConversion = ast_conv.IntTo\u2124Conversion;");
static immutable string opComma = ",";
static immutable string opConcat = "~";
static immutable string opDefine = ":=";
static immutable string opAssign = "\u2190";
static immutable string opConcatAssign = opConcat ~ opAssign;
alias Unit = void[0];
enum unit = Unit.init;
alias IdMap(T) = T[Id];
alias IdSet=IdMap!Unit;
static size_t regCtr = 0;
static size_t lambdaCtr = 0;
static immutable size_t MAX_UNROLL_LENGTH = 16;
private string mangleName(ast_exp.Identifier id) {
auto b = appender!string;
bool first = true;
bool esc = false;
foreach(c; id.name.byCodeUnit) {
if((!first && c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_') {
b.put(c);
} else {
esc = true;
if(!first) b.put('.');
b.put("0123456789abcdef"[c >> 4]);
b.put("0123456789abcdef"[c & 15]);
}
first = false;
}
if(!esc) return id.name;
return b[];
}
private bool isReturnLambda(ast_decl.FunctionDef parent, ast_decl.FunctionDef child) {
if(Id.s!"artificial" !in parent.attributes) return false;
if(parent.body_.s.length != 1) return false;
auto ret = cast(ast_exp.ReturnExp)parent.body_.s[0];
if(!ret) return false;
auto lam = cast(ast_exp.LambdaExp)ret.e;
if(!lam) return false;
return lam.fd is child;
}
static immutable string HEX = "0123456789abcdef";
private void escapeStr(Appender!string* o, string val) {
o.put('"');
foreach(c; val) {
if(c == '"' || c == '\\') {
o.put('\\');
}
if(c >= 32 && c <= 126) {
o.put(c);
continue;
}
o.put('\\');
if(c < 128) {
o.put('x');
} else {
if(c < (1 << 16)) {
o.put('u');
} else {
o.put('U');
o.put(HEX[c >> 28]);
o.put(HEX[(c >> 24) & 15]);
o.put(HEX[(c >> 20) & 15]);
o.put(HEX[(c >> 16) & 15]);
}
o.put(HEX[(c >> 12) & 15]);
o.put(HEX[(c >> 8) & 15]);
}
o.put(HEX[(c >> 4) & 15]);
o.put(HEX[c & 15]);
}
o.put('"');
}
private static ast_lex.Location locEnd(ast_lex.Location loc) {
if(!loc.rep) return loc;
return ast_lex.Location(loc.rep[$-1..$], loc.line + cast(int) loc.rep[0..$-1].byCodeUnit.count!(c => c == '\n'));
}
final class CReg {
string name;
immutable size_t index;
this() scope @safe {
this.index = regCtr++;
}
override string toString() const @safe {
if(name) {
return format("$%s.%d", name, index);
} else {
return format("$%d", index);
}
}
private:
string asStr;
}
final class QReg {
string name;
immutable size_t index;
this() scope @safe {
this.index = regCtr++;
}
override string toString() const @safe {
if(name) {
return format("%%%s.%d", name, index);
} else {
return format("%%%d", index);
}
}
}
static immutable string ctypeBitvec = "builtin.bitvec";
static immutable string ctypeQtArray = "builtin.qtypes";
static immutable string ctypeSilqRational = "silq.rational";
static immutable string ctypeSilqComplex = "silq.complex";
static immutable string ctypeSilqTuple = "silq.tuple";
static immutable string ctypeSilqArray = "silq.array";
static immutable string ctypeSilqQFunc = "silq.qfunc";
static immutable string ctypeRTTI = "silq.rtti";
static immutable string opCond = "cond";
static immutable string opAbort = "abort";
static immutable string opCallAsClassicalIndirect = "call_as_classical";
static immutable string opCallClassicalIndirect = "classical_call";
static immutable string opCallMeasureIndirect = "call";
static immutable string opCallMfreeIndirect = "mfree_call";
static immutable string opCallQfreeIndirect = "qfree_call";
static immutable string opCallMfreeRevIndirect = "mfree_call_rev";
static immutable string opCallQfreeRevIndirect = "qfree_call_rev";
private string opCallClassical(string name) {
if(!name.ptr) return opCallClassicalIndirect;
assert(name.length > 0);
return format("classical_call[%s]", name);
}
private string opCallMeasure(string name) {
if(!name.ptr) return opCallMeasureIndirect;
assert(name.length > 0);
return format("call[%s]", name);
}
private string opCallMfree(string name) {
if(!name.ptr) return opCallMfreeIndirect;
assert(name.length > 0);
return format("mfree_call[%s]", name);
}
private string opCallQfree(string name) {
if(!name.ptr) return opCallQfreeIndirect;
assert(name.length > 0);
return format("qfree_call[%s]", name);
}
private string opCallMfreeRev(string name) {
if(!name.ptr) return opCallMfreeRevIndirect;
assert(name.length > 0);
return format("mfree_call_rev[%s]", name);
}
private string opCallQfreeRev(string name) {
if(!name.ptr) return opCallQfreeRevIndirect;
assert(name.length > 0);
return format("qfree_call_rev[%s]", name);
}
static immutable string opAllocError = "qfree_call[qbuiltin.error]";
static immutable string opAllocQubit = "qfree_call[silq_builtin.alloc_qubit]";
static immutable string opAllocBitvec = "qfree_call[qbuiltin.alloc_bitvec]";
static immutable string opAllocUint = "qfree_call[silq_builtin.alloc_uint]";
static immutable string opAllocUnit = "qfree_call[qbuiltin.alloc_unit]";
static immutable string opAllocQubit0 = "qfree_call[qbuiltin.alloc_0]";
static immutable string opAllocQubit1 = "qfree_call[qbuiltin.alloc_1]";
static immutable string opDeallocError = "qfree_call_rev[qbuiltin.error]";
static immutable string opDeallocQubit0 = "qfree_call_rev[qbuiltin.alloc_0]";
static immutable string opDeallocQubit1 = "qfree_call_rev[qbuiltin.alloc_1]";
static immutable string opDeallocBitvec = "qfree_call_rev[qbuiltin.alloc_bitvec]";
static immutable string opDeallocUnit = "qfree_call_rev[qbuiltin.alloc_unit]";
static immutable string opInplaceNot = "qfree_call[qbuiltin.X]";
static immutable string opLiftedNot = "qfree_call[qbuiltin.lifted_X]";
static immutable string opDup = "qfree_call[qbuiltin.dup]";
static immutable string opUndup = "qfree_call_rev[qbuiltin.dup]";
static immutable string opMeasureQubit = "call[qbuiltin.measure_qubit]";
static immutable string opMeasureBitvec = "call[qbuiltin.measure_bitvec]";
static immutable string opMeasureUint = "call[silq_builtin.measure_uint]";
static immutable string opForget = "autoforget";
static immutable string opCSplit = "csplit";
static immutable string opQSplit = "qsplit";
static immutable string opCMerge = "cmerge";
static immutable string opQMerge = "qmerge";
static immutable string opCat = "qfree_call[qbuiltin.cat]";
static immutable string opUncat = "qfree_call_rev[qbuiltin.cat]";
static immutable string opIndexDupI = "qfree_call[silq_builtin.cindex_i]";
static immutable string opIndexDupD = "qfree_call[silq_builtin.cindex_d]";
static immutable string opSliceI = "qfree_call[silq_builtin.cslice_i]";
static immutable string opSliceD = "qfree_call[silq_builtin.cslice_d]";
static immutable string opIndexSwapI = "qfree_call[silq_builtin.cswap_i]";
static immutable string opIndexSwapD = "qfree_call[silq_builtin.cswap_d]";
private string opPack(size_t n) {
if(n == 0) return opAllocUnit;
return "qfree_call[qbuiltin.pack]";
}
private string opUnpack(size_t n) {
if(n == 0) return opDeallocUnit;
return "qfree_call_rev[qbuiltin.pack]";
}
struct QCapture {
CReg qtype;
QReg qreg;
}
final class Value {
CReg _creg = null;
QReg _qreg = null;
FunctionInfo funcInfo;
CReg[] funcCapR;
QCGen qfuncQcg;
CReg[] qfuncCapT;
QReg[] qfuncCapR;
@property
bool hasQuantum() {
if(qfuncQcg) return true;
return !!_qreg;
}
@property
bool hasClassical() {
return !!_creg;
}
@property
CReg creg() {
return _creg;
}
@property
QReg qreg() {
auto qcg = qfuncQcg;
if(!qcg) return _qreg;
_qreg = qcg.pack(qfuncCapT, qfuncCapR);
funcInfo = null;
funcCapR = null;
qfuncQcg = null;
qfuncCapT = null;
qfuncCapR = null;
if(!_qreg) {
// quantum component suddenly disappeared?
// We cannot change hasQuantum after initialization, so create an empty one.
_qreg = qcg.allocUnit();
}
return _qreg;
}
override string toString() {
if(funcInfo) return format("func[%s]", funcInfo.prettyName);
return format("(%s,%s)", _creg, _qreg);
}
static Value newReg(CReg creg, QReg qreg) {
auto v = new Value();
v._creg = creg;
v._qreg = qreg;
return v;
}
static Value newFunction(ScopeWriter sc, FunctionInfo fi, Value[] captures) {
auto cCapR = appender!(CReg[]);
auto qCapT = appender!(CReg[]);
auto qCapR = appender!(QReg[]);
foreach(i, cap; fi.captures) {
auto val = captures[i];
if(cap.hasClassical) {
cCapR.put(val.creg);
} else if(val.hasClassical) {
assert(0, "Capture has no classical component but argument does");
}
if(val.hasQuantum) {
assert(cap.hasQuantum, "Capture has no quantum component but argument does");
assert(val.qreg);
qCapT.put(sc.getQType(typeForDecl(cap.innerDecl), val));
qCapR.put(val.qreg);
} else if(cap.hasQuantum) {
qCapT.put(sc.ctx.qtUnit);
qCapR.put(null);
}
}
auto v = new Value();
v._creg = sc.ccg.funcPack(fi.indirectName, cCapR[]);
v.funcInfo = fi;
v.funcCapR = cCapR[];
auto qtype = sc.ccg.qtTuple(qCapT[]);
if(qtype is sc.ctx.qtUnit) {
foreach(val; captures) {
if(val.hasQuantum) sc.qcg.deallocUnit(val.qreg);
}
return v;
}
v._creg = sc.ccg.qfuncPack(v._creg, qtype);
v.qfuncQcg = sc.qcg;
v.qfuncCapT = qCapT[];
v.qfuncCapR = qCapR[];
return v;
}
void setName(ast_exp.Identifier name) {
if(_creg && !_creg.name) _creg.name = mangleName(name);
if(_qreg && !_qreg.name) _qreg.name = mangleName(name);
}
}
private bool valueIsZero(Expression exp) {
if (auto m = exp.asIntegerConstant(true)) {
return m.get() == 0;
}
return false;
}
private bool typeHasClassical(Expression ty) {
assert(ty);
if(ast_ty.isEmpty(ty)) return true;
if(!ast_ty.hasClassicalComponent(ty)) return false;
if(auto tupTy = cast(ast_ty.TupleTy) ty) {
return tupTy.types.any!(typeHasClassical);
}
if(auto vecTy = cast(ast_ty.VectorTy) ty) {
return !valueIsZero(vecTy.num) && typeHasClassical(vecTy.next);
}
if(auto intTy = ast_ty.isFixedIntTy(ty)) {
return intTy.isClassical;
}
return true;
}
private bool typeHasQuantum(Expression ty) {
assert(ty);
if(!ast_ty.hasQuantumComponent(ty)) return false;
if(auto tupTy = cast(ast_ty.TupleTy) ty) {
return tupTy.types.any!(typeHasQuantum);
}
if(auto vecTy = cast(ast_ty.VectorTy) ty) {
return !valueIsZero(vecTy.num) && typeHasQuantum(vecTy.next);
}
if(auto arrTy = cast(ast_ty.ArrayTy) ty) {
return typeHasQuantum(arrTy.next);
}
if(auto intTy = ast_ty.isFixedIntTy(ty)) {
if(intTy.isClassical) return false;
return !valueIsZero(intTy.bits);
}
return true;
}
private bool typeHasQDep(Expression ty) {
assert(ty);
if(!ast_ty.hasClassicalComponent(ty)) return false;
if(!ast_ty.hasQuantumComponent(ty)) return false;
if(auto tupTy = cast(ast_ty.TupleTy) ty) {
return tupTy.types.any!(subty => typeHasQDep(subty));
}
if(auto vecTy = cast(ast_ty.VectorTy) ty) {
return !valueIsZero(vecTy.num) && typeHasQDep(vecTy.next);
}
if(auto arrTy = cast(ast_ty.ArrayTy) ty) {
return typeHasQuantum(arrTy.next);
}
if(ast_ty.isFixedIntTy(ty)) {
return false;
}
return true;
}
private bool productTyIsMoved(ast_ty.ProductTy ty) {
final switch(ty.captureAnnotation) {
case ast_ty.CaptureAnnotation.none:
case ast_ty.CaptureAnnotation.const_:
return false;
case ast_ty.CaptureAnnotation.moved:
return true;
case ast_ty.CaptureAnnotation.once:
case ast_ty.CaptureAnnotation.spent:
assert(0, "TODO mixed const/moved captures");
}
}
private void putRet(FunctionInfo fi, ref CReg[] cRet, ref QReg[] qRet, Value v) {
if(!fi || fi.retHasClassical) {
cRet = [v.creg];
} else {
assert(!v.creg);
}
if(!fi || fi.retHasQuantum) {
qRet = [v.qreg];
} else {
assert(!v.qreg, format("callee returns no quantum component but caller wants it"));
}
}
private enum ConvertFlags {
noop = 0,
check = 1,
classical = 2,
quantum = 4,
}
private ConvertFlags qpromoteFlags(Expression ty) {
if(!typeHasQuantum(ty)) {
return ConvertFlags.noop;
}
if(auto tupTy = cast(ast_ty.TupleTy) ty) {
return tupTy.types.fold!((v, sub) => v | qpromoteFlags(sub))(ConvertFlags.noop);
}
if(auto vecTy = cast(ast_ty.VectorTy) ty) {
if(valueIsZero(vecTy.num)) return ConvertFlags.noop;
return qpromoteFlags(vecTy.next);
}
if(auto arrTy = cast(ast_ty.ArrayTy) ty) {
return qpromoteFlags(arrTy.next);
}
if(auto prodTy = cast(ast_ty.ProductTy) ty) {
return ConvertFlags.classical;
}
return ConvertFlags.classical | ConvertFlags.quantum;
}
private ConvertFlags conversionFlags(ast_conv.Conversion conv) {
assert(conv);
if(cast(ast_conv.NoOpConversion) conv || cast(ast_conv.AnnotationPun) conv || cast(ast_conv.TypeConversion) conv || cast(ast_conv.ExplosionConversion) conv) {
return ConvertFlags.noop;
}
if(cast(ast_conv_UintToNConversion) conv || cast(ast_conv_IntToZConversion) conv) {
return ConvertFlags.noop;
}
if(cast(ast_conv.NumericConversion) conv) {
auto r = ConvertFlags.classical;
if(conv.from == ast_ty_Nt() && conv.to == ast_ty_Zt()) r = ConvertFlags.noop;
return r;
}
if(auto nConv = cast(ast_conv.NumericCoercion) conv) {
auto r = ConvertFlags.classical;
if(conv.from == ast_ty_Zt() && conv.to == ast_ty_Nt()) r = ConvertFlags.noop;
if(nConv.needsCheck) r |= ConvertFlags.check;
return r;
}
if(cast(ast_conv.QuantumPromotion) conv) {
assert(!typeHasQuantum(conv.from));
return qpromoteFlags(conv.to);
}
if(auto tConv = cast(ast_conv.TransitiveConversion) conv) {
return conversionFlags(tConv.a) | conversionFlags(tConv.b);
}
if(auto tupConv = cast(ast_conv.TupleConversion) conv) {
return tupConv.elements.fold!((v, sub) => v | conversionFlags(sub))(ConvertFlags.noop);
}
if(auto vecConv = cast(ast_conv.VectorConversion) conv) {
auto r = conversionFlags(vecConv.next);
if(vecConv.checkLength) r |= ConvertFlags.check;
return r;
}
if(auto arrConv = cast(ast_conv.ArrayConversion) conv) {
return conversionFlags(arrConv.next);
}
if(auto arrConv = cast(ast_conv.ArrayToVectorConversion) conv) {
auto r = ConvertFlags.classical;
if(arrConv.checkLength) r |= ConvertFlags.check;
return r;
}
if(auto arrConv = cast(ast_conv.VectorToArrayConversion) conv) {
return ConvertFlags.classical;
}
if(auto funcConv = cast(ast_conv.FunctionConversion) conv) {
// annotation conversions are no-op
auto r = conversionFlags(funcConv.dom) | conversionFlags(funcConv.cod);
return r != ConvertFlags.noop ? ConvertFlags.classical : ConvertFlags.noop;
}
if(auto fConv = cast(ast_conv.FixedToVectorConversion) conv) {
auto t = ast_ty.isFixedIntTy(conv.from);
assert(t);
auto r = t.isClassical ? ConvertFlags.classical : ConvertFlags.noop;
if(fConv.checkLength) r |= ConvertFlags.check;
return r;
}
if(auto fConv = cast(ast_conv.VectorToFixedConversion) conv) {
auto t = ast_ty.isFixedIntTy(conv.to);
assert(t);
auto r = t.isClassical ? ConvertFlags.classical : ConvertFlags.noop;
if(fConv.checkLength) r |= ConvertFlags.check;
return r;
}
auto r = ConvertFlags.noop;
if(typeHasClassical(conv.to)) r |= ConvertFlags.classical;
if(typeHasQuantum(conv.to)) r |= ConvertFlags.quantum;
return r;
}
struct PureOpKey {
string op;
CReg[] args;
}
class ExprInfo {
immutable size_t id;
Expression expr;
this(size_t id, Expression expr) {
this.id = id;
this.expr = expr;
}
}
struct CondC {
CReg reg;
bool value = true;
CondC invert(){ return CondC(reg, !value); }
bool opCast(T:bool)(){ return !!reg; }
}
struct CondQ {
QReg reg;
bool value = true;
CondQ invert(){ return CondQ(reg, !value); }
bool opCast(T:bool)(){ return !!reg; }
}
struct CondAny {
union {
CReg _creg;
QReg _qreg;
};
bool value;
bool isQuantum;
this(CReg r, bool value = true) scope @safe nothrow {
assert(r);
this._creg = r;
this.value = value;
this.isQuantum = false;
}
this(QReg r, bool value = true) scope @safe nothrow {
assert(r);
this._qreg = r;
this.value = value;
this.isQuantum = true;
}
this(CondC c) scope @safe nothrow {
assert(c.reg);
this(c.reg, c.value);
}
this(CondQ c) scope @safe nothrow {
assert(c.reg);
this(c.reg, c.value);
}
bool opCast(T:bool)(){ return this !is CondAny.init; }
@property
bool isClassical() const pure @safe nothrow {
return !isQuantum;
}
@property
CReg creg() pure @trusted nothrow {
assert(!isQuantum);
return _creg;
}
@property
QReg qreg() pure @trusted nothrow {
assert(isQuantum);
return _qreg;
}
@property
CondQ qcond() pure @safe nothrow {
return CondQ(qreg, value);
}
@property
CondC ccond() pure @safe nothrow {
return CondC(creg, value);
}
CondAny invert() @safe nothrow {
return isQuantum ? CondAny(qreg, !value) : CondAny(creg, !value);
}
string toString(){ return text("CondAny(",isClassical?text(ccond):text(qcond),")"); }
}
class RTTI {
ScopeWriter sc;
ExprInfo ei;
CReg _packed;
CReg _qtypeF;
CReg _promoteF;
CReg _measureF;
this(ScopeWriter sc, ExprInfo ei) {
this.sc = sc;
this.ei = ei;
}
static RTTI builtin(Writer ctx, CReg qtypeF, CReg promoteF, CReg measureF) {
auto r = new RTTI(null, null);
r._qtypeF = qtypeF;
r._promoteF = promoteF;
r._measureF = measureF;
r._packed = ctx.literalBox(ctypeRTTI, [qtypeF, promoteF, measureF]);
return r;
}
@property
CReg qtypeF() {
if(_qtypeF) return _qtypeF;
auto f = _packed ? sc.ccg.boxIndex(ctypeRTTI, 3, _packed, 0) : sc.genQTypeFunc(ei.expr);
_qtypeF = f;
return f;
}
@property
CReg promoteF() {
if(_promoteF) return _promoteF;
auto f = _packed ? sc.ccg.boxIndex(ctypeRTTI, 3, _packed, 1) : sc.genPromoteFunc(ei.expr);
_promoteF = f;
return f;
}
@property
CReg measureF() {
if(_measureF) return _measureF;
auto f = _packed ? sc.ccg.boxIndex(ctypeRTTI, 3, _packed, 2) : sc.genMeasureFunc(ei.expr);
_measureF = f;
return f;
}
@property
CReg packed() {
if(_packed) return _packed;
auto p = sc.ccg.boxPack(ctypeRTTI, [this.qtypeF, this.promoteF, this.measureF]);
_packed = p;
return p;
}
}
struct CondRetValue {
CReg condC;
QReg condQ;
bool hasClassical(){ return !!condC; }
bool hasQuantum(){ return !!condQ; }
bool hasAny(){ return hasClassical||hasQuantum; }
this(CReg condC) {
this.condC = condC;
}
this(QReg condQ) {
this.condQ = condQ;
}
this(CReg condC, QReg condQ) {
this.condC = condC;
this.condQ = condQ;
}
static CondRetValue makeConst(bool val, ScopeWriter w) {
return CondRetValue(val ? w.ctx.boolTrue : null);
}
CondRetValue toQuantum(ScopeWriter w) {
if(hasClassical && hasQuantum) {
return CondRetValue(w.qcg.cmerge(CondC(condC), condQ, w.qcg.withCond(CondAny(condC)).allocQubit(1)));
}
if(hasQuantum) {
return this;
}
if(hasClassical) {
return CondRetValue(w.qcg.allocQubit(condC));
}
return CondRetValue(w.qcg.allocQubit(0));
}
CondRetValue dup(ScopeWriter w) {
return CondRetValue(condC, condQ ? (condC ? w.qcg.withCond(CondAny(condC, false)) : w.qcg).dup(condQ) : null);
}
CondRet asCondRet() { return CondRet(CondC(condC), CondQ(condQ)); }
}
struct CondRet {
CondC condC;
CondQ condQ;
bool isAnd = false;
bool opCast(T:bool)(){ return !!condC||!!condQ; }
this(CondAny cond) {
if(cond.isQuantum) {
condQ = cond.qcond;
} else {
condC = cond.ccond;
}
}
this(CondC condC) {
this.condC = condC;
}
this(CondQ condQ) {
this.condQ = condQ;
}
this(CondC condC, CondQ condQ, bool isAnd = false) {
this.condC = condC;
this.condQ = condQ;
this.isAnd = isAnd;
}
void forget(ScopeWriter sc) {
assert(!isAnd);
if(!condQ) return;
if(condC) {
sc.qcg.withCond(CondAny(condC.invert())).forget(condQ.reg);
} else {
sc.qcg.forget(condQ.reg);
}
}
CondRet invert() {
return CondRet(condC.invert(), condQ.invert, !isAnd);
}
RetValue valMerge(RetValue v0, RetValue v1, ScopeWriter w) {
assert(!isAnd);
assert(v0.classicalRet && !v0.quantumRet);
assert(v1.classicalRet || v1.quantumRet);
assert(!!v1.classicalRet == !!condC);
assert(!!v1.quantumRet == !!condQ);
auto v = v0.classicalRet;
if(condQ) {
assert(v1.quantumRet);
auto wg = w;
if(condC) {
wg = w.withCond(w.nscope, CondAny(condC.invert()));
}
v = wg.valMerge(CondAny(condQ), v, v1.quantumRet);
}
if(condC) {
assert(v1.classicalRet);
v = w.valMerge(CondAny(condC), v, v1.classicalRet);
}
return RetValue(v);
}
ScopeWriter addToScope(ast_scope.NestedScope nscope, ScopeWriter w) {
assert(isAnd);
if(condC) w = w.withCond(nscope, CondAny(condC));
if(condQ) w = w.withCond(nscope, CondAny(condQ));
return w;
}
CondRetValue asCondRetValue(ScopeWriter w) {
CReg creg = null;
if(condC) {
creg = w.ccg.cond(condC, w.ctx.boolFalse, w.ctx.boolTrue); // TODO: this is overkill
}
QReg qreg = null;
if(condQ) {
auto wg = w.qcg;
if(condC) {
wg = wg.withCond(CondAny(condC.invert()));
}
auto rF = wg.withCond(CondAny(condQ.invert())).allocQubit(0);
auto rT = wg.withCond(CondAny(condQ)).allocQubit(1);
qreg = wg.qmerge(condQ, rF,rT);
if(creg) {
qreg = wg.addCond(CondAny(creg, false), qreg);
qreg = w.qcg.withCond(CondAny(creg, false))
.removeCond(CondAny(condC.invert()), qreg);
}
}
return CondRetValue(creg, qreg);
}
bool isQuantum() { // TODO: remove
assert(!!condC ^ !!condQ);
return !!condQ;
}
RetValue updateRetCond(RetValue retv, CondRet previous, ScopeWriter w) {
if(this is previous) {
return retv;
}
auto cret = retv.classicalRet, qret = retv.quantumRet;
assert(!!cret == !!condC && !!qret == !!condQ);
if(!previous) {
if(cret && condC) {
cret = w.valAddCond(CondAny(condC), cret);
}
if(qret && condQ) {
if(condC) {
qret = w.valAddCond(CondAny(condC.invert()), qret);
qret = w.withCond(w.nscope, CondAny(condC.invert())).valAddCond(CondAny(condQ), qret);
} else {
qret = w.valAddCond(CondAny(condQ), qret);
}
}
return RetValue(cret, qret);
}
assert(!!condC == !!previous.condC);
assert(!!condQ == !!previous.condQ);
if(condC && condQ) {
assert(cret && qret);
cret = w.withCond(w.nscope, CondAny(previous.condC))
.valAddCond(CondAny(condC), cret);
cret = w.withCond(w.nscope, CondAny(condC))
.valRemoveCond(CondAny(previous.condC), cret);
qret = w.withCond(w.nscope, CondAny(previous.condC.invert()))
.withCond(w.nscope, CondAny(previous.condQ))
.valAddCond(CondAny(condC.invert()), qret);
qret = w.withCond(w.nscope, CondAny(previous.condC.invert()))
.withCond(w.nscope, CondAny(previous.condQ))
.withCond(w.nscope, CondAny(condC.invert()))
.valAddCond(CondAny(condQ), qret);
qret = w.withCond(w.nscope, CondAny(previous.condC.invert()))
.withCond(w.nscope, CondAny(condC.invert()))
.withCond(w.nscope, CondAny(condQ))
.valRemoveCond(CondAny(previous.condQ), qret);
qret = w.withCond(w.nscope, CondAny(condC.invert()))
.withCond(w.nscope, CondAny(condQ))
.valRemoveCond(CondAny(previous.condC.invert()), qret);
return RetValue(cret, qret);
}
assert(!!cret ^ !!qret);
auto ret = cret ? cret : qret;
auto cond = condC ? CondAny(condC) : CondAny(condQ);
auto pcond = previous.condC ? CondAny(previous.condC) : CondAny(previous.condQ);
auto wRet = w;
if(previous) {
wRet = wRet.withCond(wRet.nscope, pcond);
}
Value retUnreachable, retReachable;
wRet.valSplit(cond, retUnreachable, retReachable, ret);
wRet.withCond(wRet.nscope, cond.invert()).valDeallocError(retUnreachable);
if(previous) {
auto wRet2 = w.withCond(w.nscope, cond);
retUnreachable = Value.newReg(retUnreachable.creg, retReachable.hasQuantum ? wRet2.withCond(wRet.nscope, pcond.invert()).qcg.allocError() : null);
ret = wRet2.valMerge(pcond, retUnreachable, retReachable);
} else {
ret = retReachable;
}
if(cret) {
return RetValue(ret);
} else {
return RetValue(null, ret);
}
}
RetValue mergeRet(CondAny cond, RetValue r0, RetValue r1, ScopeWriter w) {
Value cret = null;
if(condC) {
assert(r0.classicalRet && r1.classicalRet);
auto wc = w.withCond(w.nscope, CondAny(condC));
cret = wc.valMerge(cond, r0.classicalRet, r1.classicalRet);
}
Value qret = null;
if(condQ) {
assert(r0.quantumRet && r1.quantumRet);
auto wcq = w;
if(condC) wcq = wcq.withCond(wcq.nscope, CondAny(condC.invert()));
wcq = wcq.withCond(wcq.nscope, CondAny(condQ));
qret = wcq.valMerge(cond, r0.quantumRet, r1.quantumRet);
}
return RetValue(cret, qret);
}
ScopeWriter genMerge(CondAny cond, ScopeWriter w0, ScopeWriter w1, ScopeWriter w) {
assert(isAnd);
if(condC) {
w = w.withCond(w.nscope, CondAny(condC));
}
if(condQ) {
w = w.withCond(w.nscope, CondAny(condQ));
}
w.genMerge(cond, w0, w1);
return w;
}
RetValue allocUnreachableRet(RetValue reachable, ScopeWriter w) {
Value cret = null, qret = null;
if(reachable.classicalRet) {
assert(!!condC);
cret = Value.newReg(
reachable.classicalRet.creg,
reachable.classicalRet.hasQuantum ? w.qcg.withCond(CondAny(condC)).allocError() : null
);
}
if(reachable.quantumRet) {
assert(!!condQ);
qret = Value.newReg(
reachable.quantumRet.creg,
reachable.quantumRet.hasQuantum ?
(condC ? w.qcg.withCond(CondAny(condC.invert())) : w.qcg)
.withCond(CondAny(condQ)).allocError() : null
);
}
return RetValue(cret, qret);
}
ScopeWriter replaceCondRet(CondRet previous, ScopeWriter w) {
assert(condC || condQ);
assert(!isAnd && !previous.isAnd);
auto ithis = invert();
assert(ithis.isAnd);
auto w1 = w;
if(ithis.condC) {
w1 = w1.withCond(w.nscope, CondAny(ithis.condC));