-
Notifications
You must be signed in to change notification settings - Fork 217
/
Copy pathCCOps.td
1755 lines (1463 loc) · 57.9 KB
/
CCOps.td
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
/********************************************************** -*- tablegen -*- ***
* Copyright (c) 2022 - 2025 NVIDIA Corporation & Affiliates. *
* All rights reserved. *
* *
* This source code and the accompanying materials are made available under *
* the terms of the Apache License 2.0 which accompanies this distribution. *
******************************************************************************/
#ifndef CUDAQ_OPTIMIZER_DIALECT_CC_OPS
#define CUDAQ_OPTIMIZER_DIALECT_CC_OPS
include "mlir/Interfaces/InferTypeOpInterface.td"
include "mlir/IR/SymbolInterfaces.td"
include "cudaq/Optimizer/Dialect/Common/Traits.td"
include "cudaq/Optimizer/Dialect/CC/CCDialect.td"
include "cudaq/Optimizer/Dialect/CC/CCInterfaces.td"
include "cudaq/Optimizer/Dialect/CC/CCTypes.td"
include "cudaq/Optimizer/Dialect/Quake/QuakeTypes.td"
def AnyPointerType : Type<CPred<"$_self.isa<mlir::LLVM::LLVMPointerType,"
"cudaq::cc::PointerType>()">, "any pointer type">;
def AnyCallableType : Type<CPred<"$_self.isa<cudaq::cc::CallableType, "
"mlir::FunctionType>()">, "any callable type">;
def AnyAggregateType : Type<CPred<"$_self.isa<cudaq::cc::StructType, "
"cudaq::cc::ArrayType, mlir::ComplexType>()">,
"any aggregate type">;
//===----------------------------------------------------------------------===//
// Base operation definition.
//===----------------------------------------------------------------------===//
class CCOp<string mnemonic, list<Trait> traits = []> :
Op<CCDialect, mnemonic, traits>;
//===----------------------------------------------------------------------===//
// Local Scope.
//===----------------------------------------------------------------------===//
def cc_ScopeOp : CCOp<"scope",
[AutomaticAllocationScope, RecursiveMemoryEffects, NoRegionArguments,
DeclareOpInterfaceMethods<RegionBranchOpInterface,
["getNumRegionInvocations",
"getRegionInvocationBounds"]>]> {
let summary = "A compound statement in which allocations are scoped.";
let description = [{
A ScopeOp is used to delineate the scope of local allocations, such as
for variables declared in a compound statement. All such allocations that
appear in the context of the ScopeOp are dead when the ScopeOp exits.
For a C++ variable, this means that the variable may require a call to a
destructor as well as deallocation. For example, after inserting calls to
dtors the LLVM IR intrinsics `llvm.stacksave` and `llvm.stackrestore` may
be added to reclaim stack space, or a call to `free` may be inserted to
deallocate any compiler-generated heap allocations.
For a CUDA-Q variable, cc.scope will, at minimum add calls to
deallocate any quantum references created inside the ScopeOp's region. It
may also be desirable to autogenerate adjoint code.
A ScopeOp that contains no allocations has no semantics and can be inlined
into the parent Region. This transformation is done in canonicalization.
A ScopeOp may contain a single-entry, multiple-exit CFG with multiple
basic blocks in its region. A ContinueOp is the terminator that exits a
ScopeOp.
Example:
```mlir
cc.scope {
%alloc = cc.alloca i32
...
}
// %alloc is deallocated at this point
```
}];
let results = (outs Variadic<AnyType>:$results);
let regions = (region AnyRegion:$initRegion);
let hasCustomAssemblyFormat = 1;
let hasCanonicalizer = 1;
let builders = [
OpBuilder<(ins
CArg<"llvm::function_ref<void(mlir::OpBuilder &, mlir::Location)>",
"nullptr">)>
];
let extraClassDeclaration = [{
using BodyBuilderFn =
llvm::function_ref<void(mlir::OpBuilder &, mlir::Location)>;
bool hasAllocation(bool quantumAllocs = true);
}];
}
//===----------------------------------------------------------------------===//
// Generalized Loop.
//===----------------------------------------------------------------------===//
def cc_LoopOp : CCOp<"loop",
[AutomaticAllocationScope, RecursiveMemoryEffects,
DeclareOpInterfaceMethods<LoopLikeOpInterface>,
DeclareOpInterfaceMethods<RegionBranchOpInterface>]> {
let summary = "generalized loop construct";
let description = [{
A LoopOp is a generalized C-like or Python loop structure. It can be used to
capture the semantics of C's `for`, `while`, and `do while` statements and
Python's for-else statement. A LoopOp is at its core a gated backedge with
up to four distinct phases. Each phase is a Region in the LoopOp. A LoopOp
has the following (maximal) structure.
Example:
```mlir
cc.loop while {
<while-code>
} do {
<do-code>
} step {
<step-code>
} else {
<else-code>
}
```
The following show how statements in the surface syntax are lowered to the
cc.loop construct.
- C/C++ `for` statement:
```c++
for (<init-code>; <while-code>; <step-code>) {
<do-code>
}
```
The above C++ `for` loop (C-style) is lowered to the following ScopeOp and
LoopOp.
```mlir
cc.scope {
<init-code>
cc.loop while {
<while-code>
cc.condition ...
} do {
<do-code>
} step {
<step-code>
}
cc.continue
}
```
- C/C++ `while` statement:
```c++
while (<while-code>) {
<do-code>
}
```
The above C++ `while` loop is lowered to the following LoopOp. Note that
the LoopOp's step region is left empty.
```mlir
cc.loop while {
<while-code>
cc.condition ...
} do {
<do-code>
}
```
- C/C++ `do while` statement:
```c++
do {
<do-code>
} while (<while-code>);
```
The above C++ `do while` loop is lowered to the following LoopOp. Once
again, the LoopOp's step region is left empty. The semantics of this form of
LoopOp are identical to a C `do while` loop. The body of the loop will be
executed exactly one time before the control condition is evaluated.
```mlir
cc.loop do {
<do-code>
} while {
<while-code>
cc.condition ...
}
```
- Python `for else` statement:
```python
for x in <iterable-expr>:
<do-code>
else:
<else-code>
```
The `<iterable-expr>` will be decomposed into separate steps of
`<init-code>`, `<while-code>`, and `<step-code>` by the Python bridge.
The above python loop, properly decomposed, is lowered to the following
MLIR code.
```mlir
cc.scope {
<init-code>
cc.loop while {
<while-code>
cc.condition ...
} do {
<do-code>
} step {
<step-code>
} else {
<else-code>
}
cc.continue
}
```
}];
let arguments = (ins
Variadic<AnyType>:$initialArgs,
BoolAttr:$post_condition
);
let results = (outs Variadic<AnyType>:$results);
let regions = (region
SizedRegion<1>:$whileRegion,
AnyRegion:$bodyRegion, // 1 or more blocks
AnyRegion:$stepRegion, // 0 or 1 blocks
AnyRegion:$elseRegion // 0 or more blocks
);
let hasCanonicalizer = 1;
let hasCustomAssemblyFormat = 1;
let hasVerifier = 1;
let builders = [
// Generalized C++ loop statements
OpBuilder<(ins "mlir::ValueRange":$iterArgs, "bool":$postCond,
"llvm::function_ref<void(mlir::OpBuilder &, mlir::Location, "
"mlir::Region &)>":$whileBuilder,
"llvm::function_ref<void(mlir::OpBuilder &, mlir::Location, "
"mlir::Region &)>":$bodyBuilder,
CArg<"llvm::function_ref<void(mlir::OpBuilder &, mlir::Location, "
"mlir::Region &)>",
"nullptr">:$stepBuilder)>,
OpBuilder<(ins "mlir::TypeRange":$results, "mlir::ValueRange":$iterArgs,
"bool":$postCond,
"llvm::function_ref<void(mlir::OpBuilder &, mlir::Location, "
"mlir::Region &)>":$whileBuilder,
"llvm::function_ref<void(mlir::OpBuilder &, mlir::Location, "
"mlir::Region &)>":$bodyBuilder,
CArg<"llvm::function_ref<void(mlir::OpBuilder &, mlir::Location, "
"mlir::Region &)>",
"nullptr">:$stepBuilder)>,
// Python's for-else
OpBuilder<(ins "mlir::ValueRange":$iterArgs,
"llvm::function_ref<void(mlir::OpBuilder &, mlir::Location, "
"mlir::Region &)>":$whileBuilder,
"llvm::function_ref<void(mlir::OpBuilder &, mlir::Location, "
"mlir::Region &)>":$bodyBuilder,
"llvm::function_ref<void(mlir::OpBuilder &, mlir::Location, "
"mlir::Region &)>":$stepBuilder,
"llvm::function_ref<void(mlir::OpBuilder &, mlir::Location, "
"mlir::Region &)>":$elseBuilder)>,
OpBuilder<(ins "mlir::TypeRange":$results, "mlir::ValueRange":$iterArgs,
"llvm::function_ref<void(mlir::OpBuilder &, mlir::Location, "
"mlir::Region &)>":$whileBuilder,
"llvm::function_ref<void(mlir::OpBuilder &, mlir::Location, "
"mlir::Region &)>":$bodyBuilder,
"llvm::function_ref<void(mlir::OpBuilder &, mlir::Location, "
"mlir::Region &)>":$stepBuilder,
"llvm::function_ref<void(mlir::OpBuilder &, mlir::Location, "
"mlir::Region &)>":$elseBuilder)>
];
let extraClassDeclaration = [{
using RegionBuilderFn = llvm::function_ref<void(mlir::OpBuilder &,
mlir::Location, mlir::Region &)>;
bool hasArguments() { return getOperands().size(); }
static constexpr llvm::StringRef postCondAttrName() {
return llvm::StringLiteral("post_condition");
}
bool isPostConditional() {
return getOperation()
->getAttrOfType<mlir::IntegerAttr>(postCondAttrName())
.getInt();
}
mlir::Block *getWhileBlock() { return &getWhileRegion().front(); }
mlir::Block::BlockArgListType getWhileArguments() {
return getWhileBlock()->getArguments();
}
mlir::Block *getDoEntryBlock() { return &getBodyRegion().front(); }
mlir::Block::BlockArgListType getDoEntryArguments() {
return getDoEntryBlock()->getArguments();
}
bool hasStep() { return !getStepRegion().empty(); }
mlir::Block *getStepBlock() {
// The step region is expected to have 0 or 1 block.
return hasStep() ? &getStepRegion().front() : nullptr;
}
mlir::Block::BlockArgListType getStepArguments() {
if (hasStep())
return getStepBlock()->getArguments();
return {};
}
bool hasPythonElse() { return !getElseRegion().empty(); }
mlir::Block *getElseEntryBlock() {
return hasPythonElse() ? &getElseRegion().front() : nullptr;
}
mlir::Block::BlockArgListType getElseEntryArguments() {
return hasPythonElse() ? getElseEntryBlock()->getArguments() :
mlir::Block::BlockArgListType{};
}
mlir::OperandRange
getSuccessorEntryOperands(std::optional<unsigned> index);
bool hasBreakInBody();
}];
}
//===----------------------------------------------------------------------===//
// If statement.
//===----------------------------------------------------------------------===//
def cc_IfOp : CCOp<"if",
[DeclareOpInterfaceMethods<RegionBranchOpInterface,
["getNumRegionInvocations",
"getRegionInvocationBounds"]>,
RecursiveMemoryEffects, LinearTypeArgsTrait]> {
let summary = "if-then-else operation";
let description = [{
An IfOp is a C-like if statement that supports single-entry, multiple-exit
code blocks for both the true (then) and false (else) execution cases. The
else region may be left empty only if the IfOp does not return any results
to the parent operation.
Example:
```mlir
cc.if (%cond) {
^bb0:
...
^bb2:
...
^bb3:
...
cc.continue // exits then region
^bb4:
cf.cond_br ..., ^bb0, ^bb2
} else {
^bb5:
...
}
```
}];
let arguments = (ins
I1:$condition,
Variadic<AnyQLinearType>:$linearArgs
);
let results = (outs Variadic<AnyType>:$results);
let regions = (region
AnyRegion:$thenRegion,
AnyRegion:$elseRegion
);
let builders = [
OpBuilder<(ins "mlir::TypeRange":$resultTypes, "mlir::Value":$cond,
"llvm::function_ref<void(mlir::OpBuilder &, mlir::Location, "
"mlir::Region &)>":$thenBuilder,
CArg<"llvm::function_ref<void(mlir::OpBuilder &, mlir::Location, "
"mlir::Region &)>", "nullptr">:$elseBuilder)>
];
let hasCustomAssemblyFormat = 1;
let hasVerifier = 1;
let extraClassDeclaration = [{
using RegionBuilderFn = llvm::function_ref<void(mlir::OpBuilder &,
mlir::Location, mlir::Region &)>;
bool hasResults() { return getResults().size(); }
// A cc.if must have a valid then region.
bool hasThen() { return !getThenRegion().empty(); }
mlir::Block *getThenEntryBlock() { return &getThenRegion().front(); }
mlir::Block::BlockArgListType getThenEntryArguments() {
return getThenEntryBlock()->getArguments();
}
bool hasElse() { return !getElseRegion().empty(); }
mlir::Block *getElseEntryBlock() {
return hasElse() ? &getElseRegion().front() :
static_cast<mlir::Block*>(nullptr);
}
mlir::Block::BlockArgListType getElseEntryArguments() {
return hasElse() ? getElseEntryBlock()->getArguments() :
mlir::Block::BlockArgListType{};
}
}];
}
//===----------------------------------------------------------------------===//
// Terminators for control-flow operations.
//===----------------------------------------------------------------------===//
def cc_ConditionOp : CCOp<"condition",
[Pure, Terminator, ParentOneOf<["LoopOp"]>,
DeclareOpInterfaceMethods<RegionBranchTerminatorOpInterface>]> {
let summary = "Conditional branch in a where region's basic block.";
let description = [{
A ConditionOp is used as the terminator of the basic block in the where
region of a LoopOp. It takes, at minimum, an `i1` value as the control
condition. If the value is true, a branch to the body of the loop is taken.
If the value is false, the parent LoopOp exits.
Any additional arguments to the ConditionOp are forwarded as block
arguments to the body or the result of the parent LoopOp accordingly.
Example:
```mlir
cc.loop while {
...
cc.condition %1 (%2, %3 : i32, !quake.wire)
} do {
^bb0(%0 : i32, %1 : !quake.wire):
...
}
```
}];
let arguments = (ins
I1:$condition,
Variadic<AnyType>:$results
);
let builders = [OpBuilder<(ins), [{ /* nothing to do */ }]>];
let assemblyFormat = [{
$condition ( `(` $results^ `:` qualified(type($results)) `)` )? attr-dict
}];
let hasVerifier = 1;
}
def cc_ContinueOp : CCOp<"continue", [Pure, ReturnLike, Terminator,
ParentOneOf<["LoopOp", "ScopeOp", "IfOp"]>]> {
let summary = "Continue branch.";
let description = [{
A ContinueOp is a generalized exit terminator for the dialect operations
with regions.
In the body region of a loop op, a ContinueOp has the standard C semantics.
If the LoopOp has a step region, control is first transferred to the entry
block of the step region and from there to the next iteration of the loop,
which starts at the while region. If the LoopOp does not have a step
region, control is transferred to the while region's entry block.
In the step region of a LoopOp, a ContinueOp is an unconditinal branch from
the step region to the while region's entry block.
In the parent op is a ScopeOp or IfOp, a ContinueOp is an unconditional
branch exiting the parent op and returning control to the parent's parent.
Example:
```mlir
%0 = cc.scope -> (!quake.wire) {
...
cc.continue %4 : !quake.wire
}
```
}];
let arguments = (ins Variadic<AnyType>:$operands);
let builders = [OpBuilder<(ins), [{ /* nothing to do */ }]>];
let assemblyFormat = [{
($operands^ `:` qualified(type($operands)))? attr-dict
}];
}
def cc_BreakOp : CCOp<"break",
[Pure, ReturnLike, Terminator, ParentOneOf<["LoopOp"]>]> {
let summary = "Break branch.";
let description = [{
A BreakOp can be used in a LoopOp's body region (only). A BreakOp is a
terminator. Semantically, a BreakOp is an unconditional, immediate branch
from the body of the parent LoopOp to the parent's parent operation. When
a BreakOp is reached, no other operations in the parent LoopOp (from any
region) will be executed. Any arguments to the BreakOp will be forwarded as
the results of the parent LoopOp.
Example:
```mlir
%w = cc.loop while ((%arg0 = %0) -> !quake.wire) {
...
} do {
...
^bb6:
cc.break %4 : !quake.wire
...
}
```
}];
let arguments = (ins Variadic<AnyType>:$operands);
let builders = [OpBuilder<(ins), [{ /* nothing to do */ }]>];
let assemblyFormat = [{
($operands^ `:` qualified(type($operands)))? attr-dict
}];
}
def cc_ReturnOp : CCOp<"return", [Pure, ReturnLike, Terminator,
ParentOneOf<["mlir::func::FuncOp", "CreateLambdaOp"]>]> {
let summary = "Return (exiting) branch.";
let description = [{
A ReturnOp returns control from the current activation of a λ expression to
the enclosing dynamic scope, the calling function.
In callable expressions, the ReturnOp is always ends the execution of the
callable.
```mlir
%lambda = cc.create_lambda {
^entry(%arg0 : i32):
...
cc.return
} : !cc.callable<(i32) -> ()>
...
cc.call_callable %lambda, %20 : (!cc.callable<(i32) -> ()>, i32) -> ()
```
}];
let arguments = (ins Variadic<AnyType>:$operands);
let builders = [OpBuilder<(ins), [{ /* nothing to do */ }]>];
let assemblyFormat = [{
($operands^ `:` qualified(type($operands)))? attr-dict
}];
let hasVerifier = 1;
let hasCanonicalizer = 1;
let extraClassDeclaration = [{
/// Return true if the cc.return is directly owned by a func.func's region.
/// If it is in a region of some other op, returns false.
bool ownedByFuncOp() {
if (auto *region = getOperation()->getParentRegion())
return isa<mlir::func::FuncOp>(region->getParentOp());
return false;
}
}];
}
//===----------------------------------------------------------------------===//
// Global transfers of control.
//===----------------------------------------------------------------------===//
def cc_UnwindBreakOp : CCOp<"unwind_break", [
ParentOneOf<["IfOp", "ScopeOp"]>, JumpWithUnwind]> {
let summary = "Non-local break (exiting) branch with unwind semantics.";
let description = [{
An UnwindBreakOp may imply unwinding the stack frame for the current
activation. In the following example the break at `(1)` is _not_ a branch
to the Op `%exit`. Instead it unwinds the various scopes, `S1, S2, S3, S4`,
consecutively and in the specified order before exiting the loop as in
`(2)`. Note that this is _not_ the same semantics as `cc.return` or
`cc.unwind_return`.
Because an UnwindBreakOp is terminating the current innermost loop, its
arguments are the return values for the loop, if present.
```mlir
func.func @example() -> (i32, i32) {
%0 = ... : f64
%ival = cc.loop while ((%arg0 = %0) -> f64) {
...
} body {
^bb0(%arg0 : f64):
... // (S4)
cc.scope { // (S3)
cc.if ... {
cc.scope { // (S2)
cc.loop ... {
cc.scope { // (S1)
cc.if ... {
...
cc.unwind_break %val : f64 // (1)
}
}
}
}
}
} step {
^bb0(%arg0 : f64):
...
}
}
%exit = ...
}
```
An UnwindBreakOp is clearly not pure. It is also not a terminator. Note
that it cannot be a ReturnLikeOp because it's arguments do not correspond
to the nearest enclosing structured Op in any way. MLIR's builtin
verification does not support Ops with non-local return semantics.
}];
let arguments = (ins Variadic<AnyType>:$operands);
let assemblyFormat = [{
($operands^ `:` qualified(type($operands)))? attr-dict
}];
let builders = [OpBuilder<(ins), [{ /* nothing to do */ }]>];
let hasVerifier = 1;
let hasCanonicalizer = 1;
}
def cc_UnwindContinueOp : CCOp<"unwind_continue", [
ParentOneOf<["IfOp", "ScopeOp"]>, JumpWithUnwind]> {
let summary = "Non-local continue branch with unwind semantics.";
let description = [{
An UnwindContinueOp may imply unwinding the stack frame for the current
activation. In the following example the continue at `(1)` is _not_ a branch
to the Op `%next_iter`. Instead it unwinds the various scopes, `S1, S2, S3,
S4`, consecutively and in the specified order before exiting the loop as
in `(2)`. Note that this is _not_ the same semantics as `cc.return` or
`cc.unwind_return`.
Because an UnwindContinueOp is jumping to the next iteration of the current
innermost loop, its arguments are the return values for the loop's backedge,
if present.
```mlir
func.func @example() -> (i32, i32) {
%0 = ... : f64
%ival = cc.loop while ((%arg0 = %0) -> f64) {
...
} body {
^bb0(%arg0 : f64):
... // (S4)
cc.scope { // (S3)
cc.if ... {
cc.scope { // (S2)
cc.loop ... {
cc.scope { // (S1)
%0 = cc.if ... -> i32 {
...
cc.unwind_continue %val : f64 // (1)
}
}
}
}
}
} step {
^bb0(%arg0 : f64):
%next_iter = ...
...
}
}
}
```
An UnwindContinueOp is clearly not pure. It is also not a terminator. Note
that it cannot be a ReturnLikeOp because it's arguments do not correspond
to the nearest enclosing structured Op in any way. MLIR's builtin
verification does not support Ops with non-local return semantics.
}];
let arguments = (ins Variadic<AnyType>:$operands);
let assemblyFormat = [{
($operands^ `:` qualified(type($operands)))? attr-dict
}];
let builders = [OpBuilder<(ins), [{ /* nothing to do */ }]>];
let hasVerifier = 1;
let hasCanonicalizer = 1;
}
def cc_UnwindReturnOp : CCOp<"unwind_return", [
ParentOneOf<["LoopOp", "IfOp", "ScopeOp"]>, JumpWithUnwind]> {
let summary = "Non-local return (exiting) branch with unwind semantics.";
let description = [{
An UnwindReturnOp may imply unwinding the stack frame for the current
activation. In the following example the return at `(1)` is _not_ a branch
to the block `^exit`. Instead it unwinds the various scopes, `S1, S2, S3,
S4`, consecutively and in the specified order before exiting the
function as in `(2)`. Note that this is _not_ the same semantics as
`cc.return`.
Because an UnwindReturnOp is terminating the current function, its
arguments are the return values for the function, if present. Returning a
pointer returned by an `alloca` operation has undefined semantics. The
compiler may raise an error if such a case exists.
```mlir
func.func @example() -> i32 {
... // (S4)
cc.scope { // (S3)
cc.if ... {
cc.scope { // (S2)
cc.loop ... {
cc.scope { // (S1)
cc.if ... {
...
cc.unwind_return %val : i32 // (1)
}
}
}
}
}
}
...
^exit:
func.return %result : i32 // (2)
}
```
An UnwindReturnOp is clearly not pure. It is also not a terminator. Note
that it cannot be a ReturnLikeOp because it's arguments do not correspond
to the nearest enclosing structured Op in any way. MLIR's builtin
verification does not support Ops with non-local return semantics.
}];
let arguments = (ins Variadic<AnyType>:$operands);
let assemblyFormat = [{
($operands^ `:` qualified(type($operands)))? attr-dict
}];
let builders = [OpBuilder<(ins), [{ /* nothing to do */ }]>];
let hasVerifier = 1;
}
//===----------------------------------------------------------------------===//
// Memory operations and initializations.
//===----------------------------------------------------------------------===//
def cc_PoisonOp : CCOp<"poison", [Pure]> {
let summary = "Explicit poison value";
let description = [{
A PoisonOp is used to create an LLVM poison value. A poison value occurs
in CC when the IR violates its own semantics, such as accessing the 10th
element of a constant array which only has 3 elements.
}];
let results = (outs AnyType:$inputType);
let assemblyFormat = "type($inputType) attr-dict";
}
def cc_UndefOp : CCOp<"undef", [Pure]> {
let summary = "Explicit undefined value.";
let description = [{
An UndefOp is used to create an undefined value of a specified type. This
op will be translated to LLVM IR as an undefined instruction.
Example:
```mlir
%structValue = cc.undef !cc.struct<{i32, i8}>
```
}];
let results = (outs AnyType:$inputType);
let assemblyFormat = "type($inputType) attr-dict";
}
def cc_AllocaOp : CCOp<"alloca", [
MemoryEffects<[MemAlloc<AutomaticAllocationScopeResource>]>]> {
let summary = "Allocate a dynamic block of memory on the stack.";
let description = [{
The AllocaOp is similar to the C library `alloca()` function. It allocates
a block of memory on the stack. The memory is undefined/poison until it is
explicitly initialized.
The number of bytes to be allocated is computed by the size of the
`elementType` (which may not have a non-positive size) times `seqSize` if
present or `1` if `seqSize` is omitted.
The result is a pointer to the first element in the allocated sequence of
`seqSize` elements of `elementType`. Each subsequent element (if any) will
be at the next succeeding naturally aligned memory location.
}];
let arguments = (ins
TypeAttr:$elementType,
Optional<AnySignlessInteger>:$seqSize
);
let results = (outs cc_PointerType:$address);
let hasCanonicalizer = 1;
let hasCustomAssemblyFormat = 1;
let builders = [
OpBuilder<(ins "mlir::Type":$elementType, "mlir::Value":$seqSize), [{
auto resTy = cudaq::cc::PointerType::get(seqSize ?
cudaq::cc::ArrayType::get(elementType) : elementType);
return build($_builder, $_state, resTy, elementType, seqSize);
}]>,
OpBuilder<(ins "mlir::Type":$elementType), [{
return build($_builder, $_state, elementType, mlir::Value{});
}]>
];
}
def cc_LoadOp : CCOp<"load",
[TypesMatchWith<"result type matches element type of pointer value",
"ptrvalue", "result",
"$_self.cast<cudaq::cc::PointerType>().getElementType()">]> {
let summary = "Load a value from a pointer into a virtual register.";
let description = [{
A LoadOp is used to load a value from a memory location, specified by a
pointer, into a virtual register.
Example:
```mlir
%1 = cc.load %0 : !cc.ptr<i32>
```
}];
let arguments = (ins
Arg<cc_PointerType,"pointer to memory location",[MemRead]>:$ptrvalue
);
let results = (outs AnyType:$result);
let assemblyFormat = [{
$ptrvalue `:` qualified(type($ptrvalue)) attr-dict
}];
}
def cc_StoreOp : CCOp<"store",
[TypesMatchWith<"type of value matches element type of pointer",
"ptrvalue", "value",
"$_self.cast<cudaq::cc::PointerType>().getElementType()">]> {
let summary = "Store a virtual register value to a memory location.";
let description = [{
A StoreOp is used to store the value from a virtual register to a memory
location, specified by a pointer.
Example:
```mlir
cc.store %value, %pointer : !cc.ptr<f64> {cpp_variable="my_double"}
```
}];
let arguments = (ins
AnyType:$value,
Arg<cc_PointerType,"pointer to memory location",[MemWrite]>:$ptrvalue
);
let assemblyFormat = [{
$value `,` $ptrvalue `:` qualified(type($ptrvalue)) attr-dict
}];
}
//===----------------------------------------------------------------------===//
// Aggregate operations.
//===----------------------------------------------------------------------===//
def cc_AddressOfOp : CCOp<"address_of", [Pure,
DeclareOpInterfaceMethods<SymbolUserOpInterface>]> {
// Note: should be used to get a pointer to a global object as well, but we
// haven't added globals to the dialect yet.
let summary = "Creates a pointer pointing to a function";
let description = [{
An AddressOfOp is used to get the address of a function by its symbol name.
Example:
```mlir
%fp = cc.address_of @my_void_function : !cc.ptr<() -> ()>
```
}];
let arguments = (ins FlatSymbolRefAttr:$global_name);
let results = (outs cc_PointerType:$res);
let assemblyFormat = [{
$global_name `:` qualified(type($res)) attr-dict
}];
}
def cc_GlobalOp : CCOp<"global", [IsolatedFromAbove, Symbol]> {
let summary = "Create a global constant or variable";
let description = [{
A GlobalOp is used to create a global variable or constant that can be
referenced by symbol using the AddressOfOp. The type of this op is always
implicitly a cc::PointerType.
For example, this op may be used to define arrays of doubles, which may in
turn be used as initial state vectors for quantum memory (VeqType).
}];
let arguments = (ins
TypeAttr:$global_type,
SymbolNameAttr:$sym_name,
OptionalAttr<AnyAttr>:$value,
OptionalAttr<StrAttr>:$sym_visibility,
UnitAttr:$constant,
UnitAttr:$external
);
let hasCustomAssemblyFormat = 1;
let builders = [
OpBuilder<(ins
"mlir::Type":$type, "mlir::StringRef":$name,
"mlir::Attribute":$value, "bool":$constant, "bool":$external), [{
return build($_builder, $_state, type, name, value,
mlir::StringAttr{}, constant, external);
}]
>];
let extraClassDeclaration = [{
cudaq::cc::PointerType getType() {
auto globalTy = getGlobalType();
return cudaq::cc::PointerType::get(globalTy);
}
//===------------------------------------------------------------------===//
// SymbolOpInterface Methods
//===------------------------------------------------------------------===//
bool isDeclaration() { return getExternal(); }
}];
}
def cc_ExtractValueOp : CCOp<"extract_value", [Pure]> {
let summary = "Extract a value from an aggregate value.";
let description = [{
This will translate to LLVM's extract_value instruction. It makes a copy of
a subvalue that is part of a larger aggregate value.
Example:
```mlir
%i = cc.extract_value %r [1, 0] : (!cc.struct<{i32, !cc.struct<{i16, f32,
i64}>}>) -> i16
```
}];
let arguments = (ins
AnyAggregateType:$aggregate,
Variadic<AnyInteger>:$dynamicIndices,
DenseI32ArrayAttr:$rawConstantIndices
);
let results = (outs AnyType);
let assemblyFormat = [{
$aggregate `[` custom<ExtractValueIndices>($dynamicIndices,
$rawConstantIndices) `]` `:` functional-type(operands, results) attr-dict
}];
let hasFolder = 1;
let hasVerifier = 1;
let hasCanonicalizer = 1;
let builders = [
OpBuilder<(ins "mlir::Type":$resultType, "mlir::Value":$aggregate,
"mlir::ValueRange":$indices,
CArg<"mlir::ArrayRef<mlir::NamedAttribute>", "{}">:$attrs)>,
OpBuilder<(ins "mlir::Type":$resultType, "mlir::Value":$aggregate,
"mlir::ArrayRef<cudaq::cc::ExtractValueArg>":$indices,
CArg<"mlir::ArrayRef<mlir::NamedAttribute>", "{}">:$attrs)>,
OpBuilder<(ins "mlir::Type":$resultType, "mlir::Value":$aggregate,
"std::int32_t":$index,
CArg<"mlir::ArrayRef<mlir::NamedAttribute>", "{}">:$attrs)>,
OpBuilder<(ins "mlir::Type":$resultType, "mlir::Value":$aggregate,
"mlir::Value":$index,
CArg<"mlir::ArrayRef<mlir::NamedAttribute>", "{}">:$attrs)>
];
let extraClassDeclaration = [{
static constexpr std::int32_t kDynamicIndex =
std::numeric_limits<std::int32_t>::min();
static std::int32_t getDynamicIndexValue() { return kDynamicIndex; }
bool indicesAreConstant() { return getDynamicIndices().empty(); }
}];